mybatis3中PerpetualCache中的equals和hashCode方法在第一行先判断getId() == null, 有点不能理解, 为什么要这个判断, 不是不可能为null吗。
代码如下:
@Override
public boolean equals(Object o) {
if (getId() == null) {
throw new CacheException("Cache instances require an ID.");
}
if (this == o) {
return true;
}
if (!(o instanceof Cache)) {
return false;
}
Cache otherCache = (Cache) o;
return getId().equals(otherCache.getId());
}
@Override
public int hashCode() {
if (getId() == null) {
throw new CacheException("Cache instances require an ID.");
}
return getId().hashCode();
}
黄舟2017-04-18 09:40:01
The underlying framework method cannot know all the usage of the application layer. It is very likely that some people do not follow the rules. In order to ensure the correctness of the program, it is necessary to make some defensive code.
PHP中文网2017-04-18 09:40:01
id determines the uniqueness of the cache, hashCode, equals method determines the uniqueness reference
ringa_lee2017-04-18 09:40:01
When working collaboratively, you cannot judge the caller. Our verbal agreement can easily be broken by someone. In order to avoid someone doing such a thing, parameter checking is a very meaningful and necessary behavior. This also facilitates troubleshooting
ringa_lee2017-04-18 09:40:01
What if getId()==null, you have reversed the cause and result, because it is not allowed to be null, so there is an if judgment. If it is null, a custom exception is thrown to tell you that it cannot be null
ringa_lee2017-04-18 09:40:01
This is the strategy implementation of DBC.
DBC is divided into three types:
1.Post-conditions postcondition represents the result that will definitely be obtained by calling a method. Similar to assertions, if the language does not support assertions, then we must write assertions ourselves, which is test-driven.
2.Pre-conditions precondition, which guarantees in advance that the post-condition must meet the pre-condition.
The preconditions must be met, and the postconditions must be realized. Through the combination of the preconditions and postconditions of the contract, there will be no hidden functional obligations, so that things are clearly laid out. Only in this way can the design be implemented into code to ensure normal object calls.
3. Class invariant class invariant represents the assertion of the object state, which should be satisfied after performing any operation. The invariant still strictly defines the integrity of the aggregate.