Skip to content
Mark Janssen edited this page May 6, 2019 · 4 revisions

Part of Hacking with the Tao.

Group variable declarations where they are used. MinimizeDependencies though might mean you put all declarations at the top of your file so that ??? --- Use asserts for testing invariants that would crash your program or your logic.


Keep your mallocs near your memory usage and be sure to deallocate all your memory, where your done using it, in the exact same amount. You do it just like using a stack: first memory allocated is the last memory de-allocated. That lets others know that you're being responsible. Leave comments at that point explaining the amount of memory allocated and when you can deallocate it.
This can be a fun part of the ally. You get to start with coding how the program should behave and then code it until it passes the tests, ensuring that it is correct.

Consider the Python Program:

 def Factorial(n):
 """Computes the nth Factorial number.  Takes positive integer, returns integer.
    >>> Factorial(0)  
    1
    >>> Factorial(20) #returns arbitrarily-sized ints, not limited to floating point.
    2432902008176640000
 """
     if n==0:     #math's own documented base case, 
         return 1 #specious
     else:
         return n * Factorial(n-1)

See how the language has provided a means to keep documentation right at the code? That's called a DocString. Since it's defined in the language itself, other third-party apps could auto-convert this to printed documentation, to document all your functions.

And see how the DocString examples show testable run-time behavior, including possibly confusing edge cases which could easily get missed if the code were to change? Tools like DocTests (included with Python) make this effortless. Even better tight coupling is to allow context-aware DocTests: At module level, a DocString could define variables for each Class that the module is designed for and must have, and then the DocTests within the Class could use those as pre-defined variables. In other words, SetUp code right where it should be, illuminating the module/class`s purpose.

Lastly, the example shown gives a result with high-information density: it's probability of showing up randomly from an incorrect calculation is extremely low. R3sult: Sweet! Rewrite your code as much as you want, worry-free. Tightly-coupled: documentation <==> code <==> tests. Elegant.

A perfect DocTest case covers:

  • edge-case documentation,
  • correct use-cases conveyed,
  • improbable results tested,
  • limits itself to testing designed-for or documented behaviors, and
  • what exceptions (documented fail cases) are thrown.
These tests can and should be combined if you use a little effort (Brevity).

Left to it`s own, this type of TightCoupling would lead to code bloat, so remember it`s companion.

Clone this wiki locally