Returning a Data Structure to Display information

2019-08-06 07:41发布

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;
}

1条回答
戒情不戒烟
2楼-- · 2019-08-06 08:04

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 the Book. I would not call it getDisplayInformation(), rather simply display(). 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 the Book.

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.

查看更多
登录 后发表回答