SRP (Single Responsibility) and encapsulation

Single Responsibility is one of key principles in writing good code, I believe. So when you change a method or a class, you should have only one reason to change it. But at the same time, you don’t want to reveal too much details. You want to encapsulate the internals and nicely abstract your business logic.

This morning, I had a brief chat with a colleague about method encapsulation. I was saying the method was hiding too much and he called it encapsulation. This kind of chat happens often among developers. We didn’t come to conclusion and I thought about it afterward. This is my thought.

A method should do only one thing

For example,

  • contentStore.remove(doc)
  • metaDataStore.remove(doc)
  • raise(new UiDocumentDeletedEvent(doc))

The 3 lines of code are written separately and each call does only one thing. In my opinion, contentStore.remove() method shouldn’t hide the following two call inside its method call. contentStore.remove() should do only one thing it’s good at, which is removing the document from ContentStore.

Encapsulation

However, what if the 3 operations happen together very often. if it does, I think it’s the time to introduce a facade object (facade pattern) or a command and command handler. The command handler can have those 3 objects as dependencies and call them in sequence.

public class DocumentRemovedCommandHandler : IHandle<DocumentRemovedCommand> 
{
    ...
    public void Handle(DocumentRemovedCommand command)
    {
        _contentStore.remove(doc);
        _metaDataStore.remove(doc);
        _event.raise(new UiDocumentDeletedEvent(doc));
    }
}

So, in conclusion, use facade or command, if you want to perform a group of operations. Otherwise, do one thing at a time, well.

SRP (Single Responsibility) and encapsulation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s