Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have a behavior-rich domain entity that adheres to Open-Closed Principle?

The Open-Closed Principle states:

software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

I'm designing a domain right now and including quite a bit of behavior in my domain entities. I'm using domain events and injecting dependencies into methods so make sure my entities aren't coupled to outside influences. However, it occurrs to me that, if the client wants more functionality later on, I will have to violate OCP and crack open these domain entities to add the features. How can a behavior-rich domain entity live in harmony with the Open-Closed Principle?

like image 209
Byron Sommardahl Avatar asked Sep 04 '12 01:09

Byron Sommardahl


1 Answers

It's useful to keep the open-closed principle (OCP) in mind when designing classes, but it's not always practical or desirable to make classes "closed for modification" right away. I think the single responsibility principle (SRP) is much more useful in practice -- as long as a class only does one thing, it is okay to modify it if the requirements for that one thing change.

Moreover, SRP leads to OCP over time; if you find yourself changing a class often, you would eventually refactor it so that the changing portion is isolated in a separate class, thus making the original class more closed.

like image 108
casablanca Avatar answered Nov 08 '22 14:11

casablanca