Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the One Class, One Responsibility Principle?

I would like to learn about the One Class, One Responsibility principle. I have found some articles about it, but without examples. It would help me if you can give me an example of a class that violates the principle.

I'm familiar with the idea that a method should do only one thing, for instance get and set methods. It must not be the same as One Class, One Responsibility, because set and get methods are both implemented inside a class. So does this mean the class is violating the rule because the class has responsibilities both to set and to get?

What is the One Class, One Responsibility Principle?

like image 597
user1348869 Avatar asked Apr 21 '12 22:04

user1348869


1 Answers

I'm not a 100% expert in this design pattern, but here's how I think of it - if I create an object, it is responsible for exactly one thing. If it needs to do something else, but is related to another object, depending on the situation, I would use inheritance, or interfaces.

It's a concept that seems fairly simple; make sure that a specific object (or method, for that matter) handles one piece of logic. If it handles more, you need another object (or method).

like image 108
Makoto Avatar answered Oct 20 '22 06:10

Makoto