Reputation: 1222
I'm currently doing dev on an inherited Spring boot app, part of it is sending an API POST request with the boolean of whether a soccer match is finished or not (resulted
). I noticed that the design of the class was such:
//parent class
public class Fixture {
private final FixtureType type;
private final Team homeTeam;
private final Team awayTeam;
public Fixture(@JsonProperty("type") final FixtureType type,
@JsonProperty("homeTeam") final Team homeTeam,
@JsonProperty("awayTeam") final Team awayTeam
) {
this.type = type;
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
}
public boolean isResulted() {
return false;
}
/*
other methods
*/
}
//child class
public class Result extends Fixture {
private final Outcome outcome;
public Result(@JsonProperty("type") final FixtureType type,
@JsonProperty("homeTeam") final Team homeTeam,
@JsonProperty("awayTeam") final Team awayTeam,
@JsonProperty("outcome") final Outcome outcome) {
super(type, homeTeam, awayTeam);
this.outcome = outcome;
}
@Override
public boolean isResulted() {
return true;
}
/*
other methods
*/
}
In the Swagger documentation, the request specifies that "resulted": true
needs to be a field in the JSON POST request. Now I can add that field into the constructor, but that would mean changing a load of tests and code that calls this constructor. My solution was to call the isResulted()
method in the constructor itself. I've never done this before, but this works. Is there any reason that this design below would create issues in the long run?
public class Result extends Fixture {
private final boolean resulted;
public Result (){
super();
resulted = isResulted();
}
@Override
@JsonProperty("resulted")
public boolean isResulted() {
return true;
}
}
Upvotes: 0
Views: 259
Reputation: 2824
I don't understand what's the purpose of having a private field that is not used anywhere. I'm also not sure I understand the problem you'd like to have solved.
There's a possible approach that is both more flexible and compatible with your previous code:
public class Result extends Fixture {
private final boolean resulted;
public Result (boolean resulted){
super();
this.resulted = resulted;
}
public Result (){
this(true); // sets the default value
}
@Override
@JsonProperty("resulted")
public boolean isResulted() {
return resulted;
}
}
Upvotes: 1