通过子关系访问对象的最佳模式
本文关键字:最佳 模式 对象 访问 关系 | 更新日期: 2023-09-27 18:29:57
哪一个更好?为什么?
CurrentCustomer.Company.Employees.Select(x=>x.Name);
或者:
CurrentCustomer.GetCompanyEmployeeNames();
其他示例:
CurrentCustomer.Company.Employees.where(x=>x.Post==EmpPosts.Manager).Select(x=>x.Name);
或者:
CurrentCustomer.GetCompanyManagerNames();
//And Comany has :
//GetManagerEmployeeNames();
//And Employee has
//GetManagerNames(); And GetEmployeeNames(); methods
...
德米特定律,又名受保护变异体。它是面向对象开发的GRASP原则之一。
第二个更好,因为它允许实现发生变化。
换句话说,当你公开第一个接口时,如果不更改所有使用它的代码,你就无法更改它。其他人写了数百行使用你的代码,而你却被卡住了。
在secod方法中,您隐藏实现,以便在未来的版本中更改它,并且客户端代码不会更改。