2010-09-15 53 views
2

下面是我的春/ Hibernate網站的代碼的方法是體現了我的代碼庫:和DAO得墨忒耳定律模式

public class UserVoteServiceImpl implements UserVoteService { 

    @Autowired UserRepository userRepository; 

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

我相信,這種方法違反了迪米特法則,因爲它使對象上的調用由findUserById()返回。我如何更改此代碼以遵守最低知識原則?

回答

1

我不認爲這是違反德米特法。如果你傳遞了一些對象,將userId關閉,並且僅使用用戶標識符,那將是一種違規行爲。

下面是將違反一個例子:

public class UserVoteServiceImpl implements UserVoteService { 

    @Autowired UserRepository userRepository; 

    public static int getUserScore(SomeWrapper someWrapper) { 
    return userRepository.findUserById(someWrapper.getUserId()).getScore(); 
    } 
} 

但有什麼不對你的方法的實現中工作委派的,並沒有什麼錯與打電話的對象從資源庫中返回。

(我個人不是瘋了有關使用服務包單道呼叫,但是這是一個不同的問題。)

目前我的工作由人民犯下一個代碼庫誰顯然從未聽說過的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); 
    } 
} 

,讓呼叫者將比分扳斷的用戶。這種改變還有讓應用程序的服務接口在域對象中處理的好處,而不是在基元中。