I know it's the common thing and maybe the best practice to pass a parameter to a set method, but in this case the new field I'm adding is depending on the value of another field in the same object, here is an example of code:
abstract public class BaseContent {
protected String sentiment;
protected Double sentimentScore;
public String getSentiment() {
return sentiment;
}
/**
* Set sentiment value depending on sentimentScore value:
* If less than 0, set sentiment as negative.
* If more than 0, set sentiment as positive.
* If equals to 0, set sentiment as neutral.
*/
public void setSentiment() {
if (sentimentScore != null) {
if (sentimentScore < 0) {
sentiment = "negative";
} else if (sentimentScore > 0) {
sentiment = "positive";
} else {
sentiment = "neutral";
}
}
}
I thought about creating only a getter method and have this functionality there, but that will force me to update the value of the new field in the same getter method, also I don't care about saving the new value in the database if that helps.
I might be having wrong thoughts so please give me your opinion on this!
CodePudding user response:
If String sentiment
field is transient, then it may be just removed and computed in the getter as suggested in the comments:
public abstract class BaseContent {
protected Double sentimentScore;
/**
* Return sentiment value depending on sentimentScore value
* If less than 0, set sentiment as negative.
* If more than 0, set sentiment as positive.
* If equals to 0, set sentiment as neutral.
*/
public String getSentiment() {
return Optional.ofNullable(sentimentScore)
.map(sc -> switch((int)Math.signum(sc)) {
case -1 -> "negative";
case 0 -> "neutral";
case 1 -> "positive";
default -> "unknown";
})
.orElse("unknown");
}
public void setSentiment(Double score) {
this.sentimentScore = score;
}
}
CodePudding user response:
Thanks for the suggestions, adding the functionality to the setter of the field that it's depending on (sentimentScore
) solved it, after getting the model from the database, the mapper looks for the setter of that field and runs it.