Groovy #7 – if there is no if

The most minimal high level programming language just needs three statements:

assignment

if

goto

All other syntaxes can be replaced with a combination of these. As programming languages evolved, goto bore the ignominy of being the first to lose favor with the programmer-theorists. It was replaced with various sophisticated constructs like for, while, do, switch, subroutines and functions.

The next one is the ‘if’ condition. With the applications growing in complexity, the if-s also drive the cyclomatic complexity. But to some extent, OOP languages eliminate if conditions at a higher-level.

Without the inheritance feature, a procedural language programmer would have to rely on if condition to make the above work. Obviously the if condition is still there somewhere down the line (compiler will have to determine the type of the object to know which method to invoke), but its not in the reviewed code. Yet, the above looks like an elaborate code-trap to just avoid one if condition.

By induction, can ‘if’ conditions be fully replaced by abstractions? Lets look a simple Groovy example, which uses the metaprogramming technique to do something like that.

Since if conditions evaluate to true/false and are automatically represented as Boolean in Groovy, by providing a missingMethod override implementation for the anonymous closure and calling that closure, the “if” keyword vanishes from code. The above construct is now equivalent to a if..elseif..elseif..elseif.. construct.

How is this helpful? The above constructs can actually be written in a configuration file by a business owner or it could even be in a excel spreadsheet. The core Groovy code just has to slurp the config file, evaluate and execute the statements as if there are no if-s.