As I grow older and wisereven older as a programmer, I've found that my personal coding style has trended heavily toward minimalism.
I was pleased, then, to find many of the coding conventions I've settled on over the last 20 years codified in Spartan programming.
No, not that sort of Spartan, although it is historically related. The particular meaning of spartan I'm referring to is this one:
(adj) ascetic, ascetical, austere, spartan (practicing great self-denial) "Be systematically ascetic...do...something for no other reason than that you would rather not do it" - William James; "a desert nomad's austere life"; "a spartan diet"; "a spartan existence"
I've tried to code smaller, even going so far as to write no code at all when I can get away with it. Spartan programming aligns perfectly with these goals. You strive for simultaneous minimization of your code in many dimensions:
- Horizontal complexity. The depth of nesting of control structures.
- Vertical complexity. The number of lines or length of code.
- Token count.
- Character count.
- Parameters. The number of parameters to a routine or a generic structure.
- Variables.
- Looping instructions. The number of iterative instructions and their nesting level.
- Conditionals. The number of
if
and multiple branchswitch
statements.
The discipline of spartan programming means frugal use of variables:
- Minimize number of variables. Inline variables which are used only once. Take advantage of
foreach
loops. - Minimize visibility of variables and other identifiers. Define variables at the smallest possible scope.
- Minimize accessibility of variables. Prefer the greater encapsulation of
private
variables. - Minimize variability of variables. Strive to make variables
final
in Java andconst
in C++. Use annotations or restrictions whenever possible. - Minimize lifetime of variables. Prefer ephemeral variables to longer lived ones. Avoid persistent variables such as files.
- Minimize names of variables. Short-lived, tightly scoped variables can use concise, terse names.
- Minimize use of array variables. Replace them with collections provided by your standard libraries.
It also means frugal use of control structures, with early return
whenever possible. This is probably best illustrated with an actual example, starting with raw code and refactoring it using the spartan programming techniques:
- Applying Spartan programming techniques to a C File
- Applying Spartan programming techniques to a Java function
I don't agree with all the rules and guidelines presented here, but I was definitely nodding along with the majority of the page. Minimalism isn't always the right choice, but it's rarely the wrong choice. You could certainly do worse than to adopt the discipline of spartan programming on your next programming project.
(hat tip to Yuval Tobias for sending this link my way)