Search code examples
javaoopobject-oriented-analysis

Should CRUD methods be part of the object or a service layer?


I was going through some object oriented design problems for learning and I came across this problem where a Book object is needed in a book catalog. This is the Book object that is suggested in the solution to the problem.

public class Book {

    private long ID;
    private String details; 
    private static Set<Book> books;

    public Book(long iD, String details) { ... }    

    public static void addBook(long iD, String details){
        books.add(new Book(iD, details));
    }

    public void update() { }

    public static void delete(Book b) { books.remove(b); }

    public static Book find(long id){
        for (Book b : books)        
            if(b.getID() == id) return b;   
        return null;

    }
}

In one way this Book object looked quite good to me since it contains all the methods that are needed to modify/get info about the book object as well as the data about the book. So when going with the definition of OOP this looks great since that is what an object should be.

But the way I had been doing stuff in my 1-2 years of programming career I always thought that creating, deleting. modifying an object should be done via a service layer, essentially a BookService class in this case which contains methods to create Books, update books and delete books from the database using the Book object which doesn't contain these CRUD methods.

The first approach looks great in theory while the next one is great in practice as I know from whatever experience I have. Are there flaws/pitfalls of the second approach? Which approach should be preferred ?

PS: I am not sure if such questions are accepted and I would gladly delete/edit it if they aren't but I don't find a better place to get the answer :(


Solution

  • In case you are implementing a console application with study purpose, it`s not a big deal if you implement CRUD logic into the model..but i do not think that this is the case.

    This model Book which you have implemented must have only object properties plus getter and setters. The other CRUD methods which you implemented must be in a external layer. A external layer may be a SERVICE or a DAO, it depends.. But you have to know that it is not a good practice if you write some extra logic in model classes like now.