4 ms·
The "makes code easier to read" thing is easier if you have a certain style of programming. Compare (a trivial example): bool isCommentSpam(int id, ICommen
by arjie 13y ago
The "makes code easier to read" thing is easier if you have a certain style of programming. Compare (a trivial example):
bool isCommentSpam(int id, ICommentCache commentCache) {
return commentCache.getCommentById(id).getScore() > THRESHOLD;
}
bool isCommentSpam(int id) {
return Cache.getCommentCache().getCommentById(id).getScore() > THRESHOLD:
}
In the former, you make the fact that the method uses the comment cache explicit. If you were to have another method that deleted a video (and all its associated comments), it would have to ask for a comment cache explicitly in its signature. This would make the fact that these two methods interact with each other explicit and make reasoning easier.
This is perhaps less important than the ease of testing, etc. that you get as well, but I find that I work better with this style.
- shitgoose 13y agoI am not sure how first case is more explicit. Try Ctrl+click (say we are in Eclipse world) on getCommentById(...) in first case and you will see interface signature - bummer. And while you will be pressing Ctrl+Shift+G and trying to guess (just guess because only Spring knows for sure) which implementation is more likely to be used on this particular line, I will jump straight to getCommentCache(...) implementation (2nd example, non-interface) and move miles ahead. EDIT: Not to mention, that passing references to cache object along each method call bloats the code. Now you have references to cache not in 50 cases where cache is used (example #2), but in 5000 cases because each method signature needs to include reference to cache (each method along the call hierarchy until you reach the point where you use cache object).
- arjie 13y agoThat's not what I mean. When you see an instance of explicit `isCommentSpam` used, you know immediately that it is using the CommentCache. Compare: if (isCommentSpam(423)) { doSomething(); } if(isCommentSpam(423, commentCache)) { doSomething(); } See, the fact that the first kind uses the CommentCache is completely opaque to you when you're reading the code. You don't know it does until you actually look inside `isCommentSpam`. The second way, you can trace the flow of information through the program very easily.
- shitgoose 13y agoWell, I see what you are saying, but I still don't think this is a strong case against singletons.