What is the best design approach for attributes that are not directly related to an entity?

Revnic Robert-Nick :

I want to create a mini-application in Java which simulates a library. I created a class called Book which the following attributes:

public class Book {
    private final String ISBN;
    private String title;
    private String author;
    private String domain;
    private int numberOfPages;
}

I want to add two more attributes: stock and price. But these attributes are not directly related to a real book (like ISBN or title) so I don't know exactly where to add them: in Book or in another class...

One idea would be to create a new class called BookView (not sure if it's the best name) and to add the attributes like this:

public class BookView {
    private Book book;
    private short stock;
    private float price;
}

Another idea would be to extend the Book and create a BookWithDetails child class which adds the stock and the price, but I'm not sure the inheritance comes in handy for this scenario:

public BookWithDetails extends Book {
    private short stock;
    private float price;
}

What is the best approach for situations like these?

0xCursor :

In your scenario, it seems like creating a class similar to BookView, as shown in your post, would be the best option:

public class BookManager {
    private short stock;
    private float price;
    private Book book;
}

This way, the manager class keeps the extra information about the price and quantity of the book separated from the actual book itself.

Because the fields are declared as private, you should add setter and getter methods to retrieve the values of the fields. As an example of some getter methods:

public short getStock() {
    return stock;
}

public float getPrice() {
    return price;
}

public Book getBook() {
    return book;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=80512&siteId=1