|
|
|
|
|
by jpochtar
2949 days ago
|
|
I believe the code presented would have benefited from a lambda-based API approach instead of an object-oriented one. In Javascript: // global, since the cached values were apparently global in the original
let cache = {};
let lastCachedTime = 0;
// Utility for fetching potentially cached values, or computing them
// if there's no valid cache entry.
let cached = (id, recompute) => {
// I don't love this policy, but thankfully it's all in one place.
if (lastCachedTime <= lastMidnight() || lastCachedTime <= lastNoon() {
cache = {};
lastCachedTime = Time.now();
}
if (!(id in cache)) {
cache[id] = recompute();
}
return cache[id];
};
// now we get to have a nicely factored, simple, conceptually independent,
// declarative code for the dashboard.
function displayDashboard() {
print("Total Users: " + cached("numContent", => countUsers());
print("Articles written: " + cached("numArticles", => countArticles());
print("Words written: " + cached("numWords", => countWords());
}
This achieves the same "Embedded Design" goal. If you squint, it's actually virtually the same as the DashboardStatComputation/DashboardStat/Dashboard the author comes up with, where each lambda in the displayDashboard function is corresponds to a DashboardStatComputation.I prefer this lambda-based design because it reifies the "form" into a single, callable, function: cached(). If you want to use the idea of cached(), you don't have to subclass anything or know about its implementation details— just call it. (PS. the code's even nicer in CoffeeScript) |
|
I think the OPs problems are mainly coming from the culture/design of Java.