For the use in a Servlet based application I’ve written a class to store a view name and objects to be rendered. Actually it is more a data structure than a class in the sense of OOP. I wonder if I should expose the members or if should use getters.
public class Result {
private final int status;
private final String view;
private final Map<String, Object> model = new HashMap<String, Object>();
public Result(final int status, final String view) {
this.status = status;
this.view = view;
}
public Result put(final String modelName, final Object modelObject) {
model.put(modelName, modelObject);
return this;
}
}
Should I add getStatus(), getView() and getModel() or should I change the member visibility to “public”? At the moment I don’t know any scenario where it would be useful to have a method to access a member. “Result” is an immutable datastructure and no computations are needed when members are accessed. Would you add getters for the unlikely event that the implementation changes?
Addendum
I read a section related to my question in Robert C. Martins excellent book Clean Code (page 99):
Hybrids
This confusion [about objects and data structures] sometimes lead to
unfortunate hybrid structures that are
half object and half data structure.
They have functions that do
significant things, and they also have
either public variables or public
accessors and mutators that, for all
intents and purposes, make the private
variable public, tempting other
external functions to use those
variables the way a procedural program
would use a data structure.Such hybrids make it hard to add new
functions but also make it hard to add
new data structures. They are the
worst of both worlds. Avoid creating
them. They are indicative of muddled
design whose authors are unsure of –
or worse, ignorant of – whether they
need protection from functions or
types.
I can’t make concrete recommendations as it would depend on how you’re going to be using that class. However…
I often create “lightweight” objects intended as data structures to transport some immutable data. Like you, I make the members
public finaland initialize them in the constructor.The risks associated with accessible, mutable data members aren’t there when they’re final; all you’re losing is the ability to meaningfully subclass the class. Also, you can’t attach functionality to data access. But for a lightweight data transfer object, chances are you won’t be doing that anyway.