I was reading this answer on SESE about encapsulation and getters/setters. Suppose I favor the use of immutable classes, so if a setter were implemented, it would return the a new object reflecting the change, for example:
//return a new Book reflecting the price change.
public Book updatePrice(double price){}
In the link, the answer suggested I have a method called getDisplayinformation()
that returns a data structure.
(think an array indexed by an enum, a struct, or a methodless class)
Following this advice how would I return a Book with a List of authors?
public final class Author{
private final String id;
private final String firstname;
private final String lastname;
//Constructor
}
public final class Book{
private String bookID;
private final String title;
private List<Author> authorsList;
private double price;
//Constructor
}
Suppose I wanted to return a Map<String,String>
.
public Map<String,String> getDisplayinformation(){
Map<String,String> displayMap = new HashMap<String,String>();
display.put("BookTitle", title);
display.put("ID", bookID);
display.put("Price", price.toString())
//insert authorsList;
return displayMap;
}
The answer you quote got half of it right. Providing getters for fields does break encapsulation, because it makes the caller dependent on some internal structure.
Now, returning a map where the caller needs to know the keys and knows what that information is, is basically not different than providing a getter for that field.
Object-orientation tries to tell us that the functionality needs to be bundled with the data. So, the
Book
has to have some method to present theBook
. I would not call itgetDisplayInformation()
, rather simplydisplay()
. It can return something, and it can take relevant parameters too.The point is, that anything returned by
display()
must be about the presentation, and must not be about the book. Semantics about being a book should be lost at that point, otherwise the caller will be tightly coupled.So, it's ok to return an XML document, JSON document, HTML, a Wicket
Component
, whatever it is you can use for presentation that is independent of theBook
.Or, the method could take an argument to present itself to. Like AWT
Component.paint(Graphics g)
or something.Note: this is actually a controversial subject. Mixed-paradigm development (a mix of procedural and ood) would argue that presentation needs to be separated from objects, while object-orientation argues that data and function belong always together.