Search code examples
solid-principles

Simple objects - what is the right design by Single Responsibility and Encapsulation principles


I'm planning some simple application and want to follow the single responsibility and encapsulation principles.

The main players are:

The API class - which expose the ability to save user:

class API{
    ....
    public void saveUser(id, name, address){
        //save the received user in the DB
    }
    ....
}

The DBConnector class - which expose the ability to save user data into the DB.

The User class - which represent a user.

In the old way the saveUser method would look like:

IDBConnector connector = DBConnectorFactory.getDBConnector();
User user = new User(id, name, address);
connector.saveUser(user);

By the new principles it seems like the right way would be:

User user = new User(id, name, address, DBConnectorFactory.getDBConnector());
user.save();

Is this correct?

Should User handle the DB saving?

If not, can you offer a better way?


Solution

  • If your class both contain data (user) and know how to persist, then it is doing more then one thing. Put another way. It has more then one reason to change. If the database change, the user would have to change (and all your other persisted business objects)

    One solution:

    public interface Persister {
        void persist(User user);
    }
    

    The database part of your application would then implement the interface as you sketched out. The creation if the user is done in the application part. This post also holds the interface. That way your main application is separated from the persistence layer. It knows nothing about it. Instead your database is "plugged in".

    (I'm aware that the interface us pretty stupidly named. The main idea though, is the separation of concern, to fulfill single responsibility)