我经常可以在一些遗留代码中见到一些类明确的违反了SRP(Single Responsibility Principle)原则,这些类通常以“Utils”或“Manager”后缀结尾,但有时这些类也没有这些特征,它仅仅是多组方法的组合体。另一个关于上帝类的特征是这些类中的方法被用注释分隔为不同的分组。
久而久之,这些类被转换为那些没有人愿意进行归并到合适类的方法的聚集地,对这些类进行重构的方法是将类中的代码按照职责分享到不同的类中。
1: public class CustomerService
2: {
3: public decimal CalculateOrderDiscount(IEnumerable<Product> products, Customer customer)
4: {
5: // do work
6: }
7:
8: public bool CustomerIsValid(Customer customer, Order order)
9: {
10: // do work
11: }
12:
13: public IEnumerable<string> GatherOrderErrors(IEnumerable<Product> products, Customer customer)
14: {
15: // do work
16: }
17:
18: public void Register(Customer customer)
19: {
20: // do work
21: }
22:
23: public void ForgotPassword(Customer customer)
24: {
25: // do work
26: }
27: }
要重构上面的代码是很简单的,只要将相关的方法按职责分享到对应的类中即可,这会降低代码的颗粒度并减少未来维护代码的成本。下面是重构后的版本,它将上面
的代码按职责分离为了两个类。
1: public class CustomerOrderService
2: {
3: public decimal CalculateOrderDiscount(IEnumerable<Product> products, Customer customer)
4: {
5: // do work
6: }
7:
8: public bool CustomerIsValid(Customer customer, Order order)
9: {
10: // do work
11: }
12:
13: public IEnumerable<string> GatherOrderErrors(IEnumerable<Product> products, Customer customer)
14: {
15: // do work
16: }
17: }
18:
19: public class CustomerRegistrationService
20: {
21:
22: public void Register(Customer customer)
23: {
24: // do work
25: }
26:
27: public void ForgotPassword(Customer customer)
28: {
29: // do work
30: }
31: }