Is it time we introduce getters for variables??????
Let me explain:
Some Context:
We always order booleans by their computation complexity ( cheapest to evaluate first ).
This is to avoid evaluating expensive parts of a boolean when the results of that computation is already known.
Example:
if (module.cheapToCompute() && module.expensiveToCompute()) {
// ....
}
Making it readable is not always possible...
Ok, I'm lying, it is always possible but it's not always convenient.
Example: Let's check if a user can see a special resource
if (resource.everyoneCanSee || user.auth?.checkAdminRights() || user.auth?.getSpecialRights().includes('seeRessources')) {
// ....
}
As you can see It's not quite scannable... Let's refactor and make it more readable. I'm going to sparkle intermediate variables here and there.
const hasAdminRight = user.auth?.checkAdminRights();
const hasSpecialRights = user.auth?.getSpecialRights().includes('seeRessources');
const canSeeResource = resource.everyoneCanSee || hasAdminRight || hasSpecialRights
if (canSeeResource) {
// ...
}
That's now super easily scannable and maintainable.
But the problem is that we are evaluating all those variables and it's expensive.
Proposal:
Why not using a getter instead of directly reading the variable?
How does it work? The rule is simple, the get
keyword should work exactly like const
. Expect it is evaluated only the second time we try to access it. In other words, it should defer reading the variable to the next time it tries to reference it.
Here is an example usage of the get
keyword:
get hasAdminRight = user.auth?.checkAdminRights(); <-- get variable created here
get hasSpecialRights = user.auth?.getSpecialRights().includes('seeRessources'); <-- get variable created here
const canSeeResource = resource.everyoneCanSee || hasAdminRight || hasSpecialRights // <-- they get evaluated here
if (canSeeResource) {
// ...
}
The code is now self documenting AND we evaluate the minimum.
Thanks!
Let know if that's dumb.