Boolean Logic, Conditionals, If, else, then..etc, in Code is BAD
Conditional blocks in code, generally mean a developer merged something. A developer took two separate concerns, and squashed them together.
And now the compiler can't tell what data the method or model needs, because it depends. So now a developer has to read your method, or your (hopefully) well written documentation, to figure it out.
In methods, this is also highlighted by the presence of "behavior modifiers". Booleans or enums in the method signature that make the function, have another function....
In state encapsulations, these are usually fields that have different constraints or usages or meanings or requirement status, based on the value of other fields. I call this "Conditional Relevance" or "Conditional Meaning". Essentially the developer is saying that this object is one of two or more different objects and should be handled differently depending on what values are set on one or more of its various fields.
The problem is there again, that now the compiler can't tell. The compiler can't tell if a field is nullable or not. The developer has to read the docs.
The way you fix this is simple. Separate the things.
With methods, separate out an overload or a decorator or adapter as the case may be.
With models, use declarative polymorphism and encapsulation. This way, whenever holding onto an entity, you know that every field on there is relevant. There is no guesswork. And so does the compiler. If a different set of fields are relevant, then you have an entirely different model, with only those fields listed. And then you swap out the entire set of fields together and atomically.
Conditional blocks should generally be relegated to filters or assertions. This means they serve only to exit the function or stream early. They should not deeply fork or branch execution in a function such that it becomes many functions in one. Because generally there is only one actual, and deterministic code path for entering a function with a given behavior modifier, but the compiler can no longer see that and neither can the developer ( easily ).
When reviewing code, if you see "if, else if, else..etc " consider it a red flag. This is confirmed if the blocks are taking into account an input parameter which has no purpose other than to guide the function as to what conditional fork it should follow. you've basically encoded a hidden set of functions within your function, effectively duplicating the work of the programming language you are programming in with regard to how methods are defined. This has already been done for you. Define methods the way they are meant to defined so that your compiler can do its job.
Comments
Post a Comment