3 ms·
You can also sometimes combine the techniques in the article above to skip booleans entirely. Instead of passing in a `bool primeMember` that gets used in a cal
by kqr 4y ago
You can also sometimes combine the techniques in the article above to skip booleans entirely. Instead of passing in a `bool primeMember` that gets used in a calculation like
deliveryTime = 3;
if (primeMember) {
deliveryTime = 1;
}
you can pass in a `Membership memberType` value that contains the required information, so the above conditional turns into just the assignment
deliveryTime = memberType.deliveryTime;
This is more amenable to extension and contraction: you can add or remove different classes of delivery times without changing the logic in which it's used.
You can even use private constructors and public static fields to create a list of "constants" containing the known member types, like the `Membership.REGULAR` and `Membership.PRIME`, retaining the property of the code not being able to use an invalid membership type.
This can be used also for more complicated conditionals like the one in the article, by having a factory method that copies the right "constant" composite value based on whatever logic is desired.
- AgentOrange1234 4y agoThis assignment-then-conditional-reassignment is admirably compact and, in languages like C/Java might well be the most elegant way to handle this. On the downside, this breaks single-assignment, binding style variables. That is, now deliveryTime can’t be final/val/const. I wish I had a better solution. Lisp did this so well with if/cond/etc as expressions.