index

goals: self documenting

The objective: code that is more readable because it's succinct.

Using conventions, short functions, and system wide abbreviations sets the stage. Self-documenting code completes the arcology pattern.

Guidelines:

Carefully decoupled small classes.

assert


Using assert() well is an excellent jedi trick.
// Instead of this: 
return 4/step; // step always > 0 

// Use this: 
assert(step>0); 
return 4/step;
It's the specification, documented and enforced-- the mental model of how this code is supposed to work.

Done pervasively it offers relief from bug-hunting, by dropping you right at the problem and telling you what it is.

It's also an insurance policy against future changes. Right now, that pointer may be guaranteed non-null, but if a future change alters that, best to find out right away.

Write asserts as you write the code.

const variables


Bim: Here's that book I borrowed. Thanks, I enjoyed it.
Reader: Did you.. write in my book?
Bim: Only a little.


"const" = "read only."

Lock intermediate results, so Reader can spend attention elsewhere.
const doub rad = sqrt(x*x + y*y); // "rad" not changing.
Combined with short functions it is a powerful element of self documenting code.

const member functions


Separate functions that build from those that consume. Prevent unexpected changes to the data's internal state by consumers.
void  make(); // not const, changes state. 
void  load(); // not const, changes state. 
bool valid() const; 
int   size() const; 
void  save() const; 
void  dump() const;

Isolate code with interior classes

class Threaded { 
public: 
  static void Run(ThreadCB, int N, void*v=0); 
  static int numCPUs(); 
private: 
  static void* _Run(void*); 
  static int find_free(vector<int>&, vector<pthread_t>&); 
  struct ARGS { 
    ThreadCB CB; 
    int i, N, channel; 
    void *v; 
    vector<int>*log; 
  }; 
};
Placing ARGS inside the class tells the reader (and requires) that it can only be used in a restricted context.

Lined-up columns


The reader can absorb lots of class functionality when it's laid out cleanly:
class   layoutUI: public layoutui_, public plug { 
public: layoutUI(); 
  PCOPY(layoutUI); // plugin copy. 
  GFUNC(layoutUI); // declare geom   CB. 
  OFUNC(layoutUI); // declare origin CB. 
  // ...more implementation. 
};

nedwaves.com 2017 [171108]