Java Object Oriented Design Question: update internal state or return new object
This is a design question. The design is pseudo-code and represents a small example but I may add a lot more methods, data, logic in the future.
In this example, I am considering two approaches. In the execute method below, should I return an immutable "data/bean/model" object with the output of the execute method or update the state of the BusinessLogic class.
The both accomplish the same goal, I want the result of execute and either the data should be contained in a bean container or in the internally in the BusinessLogic class.
I am kind of favoring just having the BusinessLogic class because SomeObject is just a useless bean that doesn't do anything.
What are your thoughts?
public class SomeObject {
private String data1;
private String data2;
}
public class BusinessLogic {
private final IWebObject webObject;
/* String data1; String data2 */
public BusinessLogic(final IWebObje开发者_如何学编程ct webObject) {
this.webObject = webObject;
}
// Approach 1
public SomeObject execute() {
return new SomeObject();
}
or
...
...
// Approach 2
public void execute() {
// Do something
this.data1 = "data1";
this.data2 = "data2";
}
public String getData1() { }
public String getData2() { }
} // End of the Class //
My only problem with approach 2 is that data1 and data2 won't be immutable so. I can call execute arbitrarily and change those values.
If the main purpose of the method would be to execute and not return anything, I would personally go with your second approach and keep the data internally inside the BusinessLogic
class.
For the most part, I'd say it depends on the nature of the code that's calling the execute() method. If it's going to just be reading the results as-is, then keeping it in the BusinessLogic class would be fine. If you're going to be passing the results around to different methods, you should put the results in a separate class (you could have BusinessLogic implement an interface that contains just the result methods, but that could blur the line between where the BusinessLogic implementation ends and where the result implementation begins).
To start with, it'd probably be best to keep it internal -- following the "You Ain't Gonna Need It" principle. When the time comes where you can see that you are going to need to pass the results around to other methods and other objects, you can refactor it to suit your needs at the time.
This isn't a general object-oriented design question - it depends on the domain you're trying to model.
- Should
execute
change the state ofBusinessLogic
or not? (Option 2) - How is that class being consumed? Are data1 and data2 used in a different way? In a different context? (Option 1)
- Do data1 and data2 have different lifetimes than BusinessLogic? (Option 1)
精彩评论