【问题标题】:Law of Demeter and DAO pattern得墨忒耳定律和 DAO 模式
【发布时间】:2010-09-15 17:21:43
【问题描述】:

这是我的 Spring/Hibernate 网站代码中的一个方法,它举例说明了我的代码库:

public class UserVoteServiceImpl implements UserVoteService {

   @Autowired UserRepository userRepository;

   public static int getUserScore(long userId) {
     return userRepository.findUserById(userId).getScore();
   }
 }

我认为这种方法违反了得墨忒耳法则,因为它调用的是 findUserById() 返回的对象。如何更改此代码以遵守最少知识原则?

【问题讨论】:

    标签: spring dao law-of-demeter


    【解决方案1】:

    我不认为这违反了得墨忒耳法则。如果您传入某个对象,从中获取 userId 并仅使用 userid,这将是违规行为。

    这是一个违规的例子:

    public class UserVoteServiceImpl implements UserVoteService {
    
       @Autowired UserRepository userRepository;
    
       public static int getUserScore(SomeWrapper someWrapper) {
         return userRepository.findUserById(someWrapper.getUserId()).getScore();
       }
     }
    

    但是在方法的实现中委派工作并没有错,对从存储库返回的对象进行调用也没有错。

    (我个人并不热衷于使用服务来包装单个 dao 调用,但这是一个不同的问题。)

    目前我正在开发一个代码库,这些代码库由显然从未听说过 LoD 的人所犯,其中充满了诸如

    之类的东西
    public Thing getThing(Integer id) {
        return new Beta().getGamma().getDelta().getEpsilon().getOmega().getThing(id);
    } 
    

    最初我认为你的例子没有上升到与那个相同的病理水平。但是看了this blog post, which is where I got the above example, of course之后, 我想我建议您将方法更改为

    public class UserVoteServiceImpl implements UserVoteService {
    
       @Autowired UserRepository userRepository;
    
       public User getUser(Long userId) {
         return userRepository.findUserById(userId);
       }
     }
    

    并让调用者从用户那里获得分数。此更改还具有使应用程序的服务接口处理域对象而不是原语的好处。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多