Programming: Style

From wikinotes

Basics

Readable Code

  • similar code-silhouettes make code easier to skim

Aesthetics

  • similar items should have similar silhouettes
  • do not duplicate comments, easier to maintain/update
  • line up identical values
/*
 * Bad
 */

public class PerformanceTester {
    public static final TcpConnectionSimulator wifi = new TcpConnectionSimulator(
        500, /* Kbps */
        80, /* millisecs latency */
        200, /* jitters */
        1 /* packet loss % */);

    public static final TcpConnectionSimulator t3_fiber =
         new TcpConnectionSimulator(
             45000, /* kbps */
             10, /* millisecs latency */
             0, /* jitter */
             0, /* packet loss */);
    public static final TcpConnectionSimulator cell = new TcpConnectionSimulator(
        100, /* kbps */
        400, /* millisecs latency */
        250, /* jitter */
        5 /* packet loss % */);
    )
}
/*
 * Good
 */

public class PerformanceTester {
    // TcpConnectionSimulator(throughput, latency, jitter, packet_loss)
    //                           [Kbps]     [ms]     [ms]   [percent]

    public static final TcpConnectionSimulator wifi =
        new TcpConnectionSimulator(500,    800,     200,    1);

    public static final TcpConnectionSimulator t3_fiber =
        new TcpConnectionSimulator(4500,    10,       0,    0);

    public static final TcpConnectionSimulator cell =
        new TcpConnectionSimulator(100,    400,     250,    5);
}

Low Cohesion

Law of Demeter

Don't make assumptions about collaborator objects.
Only send messages to collaborators passed in to the object (assignment to field, or instantiation).

class Foo:
  B = B()

  def __init__(self, a):
    self.a = a
    self.a.b = self.B

  @staticmethod
  def bar():
    return "abcdefg"

  @staticmethod
  def a_b_c():
    self.a.b.c
foo = Foo()

foo.a       # ok ('a' passed in initialization)
foo.a.b     # ok ('b' assigned to 'a', but is defined on this class)
foo.bar()   # ok ('bar()' defined on this object
foo.a_b_c() # ok ('a.b.c's 'c' is abstracted by this method, we don't depend on it's behaviour)

foo.a.b.c   # BAD (this object does not bind 'c')
foo.a.c     # BAD (this object does not bind 'c')

References

The Art of Readable Code (p36-43)
https://justinmeiners.github.io/the-skills-programmers-lack/