3/31/09

How to program well (part 1 of n)

Be sure to clearly define "programming interface" of your function.

Writing a function is a simple part of programming in any language yet it is an essential part of programming and having good functions are very important to produce high quality software. I've seen too many pooly written functions and decided to document what not to do and what to do.

When I say, pooly written function, these are functions with no clear "interface contract". Here, I am not talking about what is inside of the function (ie. implementation). I actually don't care about implementation (well, it should work, but it is really up to programmer to implement the function however he/she sees appropriate). It is more about "interface".

There are several important rules about writing good functions

Function name should have a single action word
A function should do one thing, or a unit of things that is cohernt
Etc..

However, the issue I see most offten with pooly written functions are lack of clear documentation about its arguments.

Function arguments should have acceptable values (or domain)

For instance, if function Foo takes an integer argument, it must clearly state whether 0 is acceptable, negative value is acceptable, whether it has upper/lower limits, etc. Usually function should accompany documetation that describe these details. Amazingly, many professional progammers just don't do this...

Next, function should "enforce" these domains by using Assertions and throwing Exceptoins. I would recommend setting up both, but sometimes throwing exceptions is sufficient, but not doing either is bad. Without this enforcement, problem would occur down the code stream and it is probably more time consuming to toubleshoot. With enforcement of input values at the function entry, it is much easier to understand what went wrong.... client code deviated from "interface contract" (ie. was never supposed to pass negative value, but it did).

(I will update this entry)