[英]How to use Single-Responsibility Principle
I am trying to understand design principles in c++. 我试图理解c ++中的设计原则。
In database I have users. 在数据库中我有用户。
users:
id
name
age
gender
I want to get my users in three ways. 我希望以三种方式吸引用户。
For example, if I use same class for getAllUsers and getFilteredByAge, it means that my class has two responsibility, it is responsible for getting users and also for filtering them. 例如,如果我对getAllUsers和getFilteredByAge使用相同的类,则意味着我的类有两个责任,它负责获取用户以及过滤它们。 Am I right or not? 我是对还是不对? And how Single-Responsibility Principle works in this example, should I split this three in different classes, or is there any better way ? 单一责任原则如何在这个例子中起作用,我应该将这三个分成不同的类,还是有更好的方法?
A good definition for SRP is: SRP的一个很好的定义是:
A module should be responsible to one, and only one, actor. 一个模块应该对一个且只有一个演员负责。
(Clean Architecture) (清洁建筑)
This means that if the person telling you what these functions do is the same, then you can leave them in the same class/module. 这意味着如果告诉您这些函数的功能是相同的,那么您可以将它们保留在同一个类/模块中。
If, let's say, getAllUsers()
is requested by accounting and getUserAtLeastThisOld(int minimumAge)
is requested by HR, then it might be sensible to have them in separate classes. 如果,假设getAllUsers()
请求getAllUsers()
并且HR请求getUserAtLeastThisOld(int minimumAge)
,那么将它们放在单独的类中可能是明智的。
Following are answers to your question 以下是您的问题的答案
Q] If I use same class for getAllUsers and getFilteredByAge, it means that my class has two responsibility? 问]如果我对getAllUsers和getFilteredByAge使用相同的类,这意味着我的班级有两个责任?
A] No,because your class's job is to get users, rather these functions should be overloads and should not be in different classes. 答: 不,因为你的班级的工作是获得用户,而不是这些函数应该是重载而不应该在不同的类中。
Q] it is responsible for getting users and also for filtering them. 问:它负责获取用户并过滤它们。 Am I right or not? 我是对还是不对?
A] I guess No!, filtering is not a different task, it is something that should be applied before retrieving objects. A] 我猜不是!,过滤不是一个不同的任务,它是在检索对象之前应该应用的东西。
Q] how Single-Responsibility Principle works in this example, should I split this three in different classes, or is there any better way ? Q]单一责任原则如何在这个例子中起作用,我应该将这三个分成不同的类,还是有更好的方法?
A] 一种]
In this case I suggest you to have only one class, which should have following functions overloads 在这种情况下,我建议你只有一个类,它应该具有以下函数重载
Note : Now suppose in future you have want to add more functionality to this class for eg compute salary for user, or adding family details for users then in such case you can go for creating another class instead of putting burden on single class... 注意: 现在假设您将来想要为此类添加更多功能,例如为用户计算工资,或者为用户添加家庭详细信息,那么在这种情况下您可以创建另一个类而不是为单个类加重...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.