I have a question, a little bit theoretical:
Assume, I have the following classes :
interface ReportInterface {
void execute();
}
class Report implements ReportInterface {
private final Repository rep;
Report(Repository ref){
this.rep = ref;
}
public void execute(){
//do some logic
}
}
class ReportWithSetter implements ReportInterface {
private final Repository rep;
private String release;
ReportWithSetter(Repository ref){
rep = ref;
}
public void execute(){
if (release == null) throw IlligalArgumentException("release is not specified");
//do some logic
}
public void setRelease(String release){
this.release=release;
}
}
The second report needs an additional parameter release to work properly, but my interface is defined without parameters for execute
method, so I work around it with a setter method, so it would look like:
ReportWithSetter rep2 = new ReportWithSetter (rep);
rep.setRelease("R1.1");
rep.execute();
So I don't like this additional rep.setRelease
. I looks weird and artificial - a user of this class may be confused, and for example, if I make the class as a singleton bean in Spring, it is a source of potential error, if it is requested for the second time and somebody forgets to trigger rep.setRelease
for the second time. Besides putting it into constructor (I want to make it a spring bean), what would be the best practice to handling this situation?
Assuming you are allowed to change the interface, here are a few solutions I can think of:
Solution #1
or
and then use them for
Report
class asexecute(Optional.empty())
orexecute(null)
.Solution #2
and then use it for
Report
class asexecute()
and forReportWithSetter
class asexecute("R1.1")
.Solution #3
Define both
void execute();
andvoid execute(String release);
in the interface. Then while implementing, throwUnsupportedOperationException
in the method you don't need. For example, inReport
class, you would do:You can also make both these methods as
default
in the interface, so your implementation classes don't have to worry about implementing the unsupported method.Use whichever is most readable and maintainable for you.