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,

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.

[sourcecode language="csharp"]
public class DocumentRemovedCommandHandler : IHandle<DocumentRemovedCommand>
{
...
public void Handle(DocumentRemovedCommand command)
{
_contentStore.remove(doc);
_metaDataStore.remove(doc);
_event.raise(new UiDocumentDeletedEvent(doc));
}
}
[/sourcecode]

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