Twitter icon.
Random notes on software, programming and languages.
By Adrian Kuhn

Archive for the ‘Spartan programming’ Category

One-letter method names, good design?


Friday, November 20th, 2009

Sometime short one-letter names are to be preferred as method names.

Don’t get me wrong. Naming conventions are one of the most important achievements of programming culture in the recent decade. No doubt, generalMatrixMultiplication is more readable than dgemm, but sometimes a simple p just beats the hell out of clumsy System.out.println and friends.

Akira Tanaka refers to this as the “Huffman coding” of API design.

The library design also utilize the usage frequency. For
example, Ruby defines p method which is usable anywhere.
It prints arguments for debugging purpose which is easy to
understand for programmers. The method name p is inconsistent
with other methods because it is too short in the sense
of Ruby naming convention. It is intentional because debug
printings are very common. In general, too short names are
incomprehensible and tends to conflict. But p has no such
problem because almost all Ruby programmers knows it.

This kind of naming convention, assigning short names
for features frequently used, are called “Huffman coding”
which term is borrowed from data compression.

He goes on to provide more example. In particular he proposes an API design life cycle, where method names start with full-length English terms and get shortened as they raise in popularity. There is two ways to shorten method names, either down to a single letter, or even more powerful, to pick an operator as its name.

I’ll gonna apply the same to Smalltalk now. For the full story of Ruby’s core API design, please refer to Akira Tanaka’s recent paper “Language and Library API Design for Usability of Ruby” from the PLATEAU workshop at this year’s OOPSLA.

First we define p as follows

Object >> p
    Transcript show: self; cr.
    ^self

the implementation is taken from Travis Griggs’s Out package. Now we can insert a print statement wherever we need debug output.

Printing is not the pinnacle of debugging, so let’s do the same with breakpoints

Object >> h
    self halt

If you are using Pharo, add h to the methods listed in OBInheritanceFilter >> icon:forNode: to make sure our new breakpoint command is marked with a red flag in the class browser.

Next let’s rename OrderedCollection to List

Smalltalk at: #List put: OrderedCollection.

And introduce the << operator for addition

OrderedCollection >> << element
    self add: element.
    ^self

which allows us to write concise code such as

List new << 'Lorem' << 'ipsum' << 'dolor

Next is string concatenation. Such a basic feature that many languages include string interpolation at their very core. Alas, Smalltalk is a bit dated to that regard (at least unless Pharo includes Lukas’s awesome Helvetia one day) and we are left with String >> #expandMacrosWithArguments:, which shall be Huffman encoded to

String >> e: argument
    ^self expandMacrosWith: argument
String >> e: first e: second
    ^self expandMacrosWith: first with: second
String >> e: first e: second e: third
    ^self expandMacrosWith: first with: second with: third
String >> e: first e: second e: third e: fourth
    ^self expandMacrosWith: first with: second with: third with: fourth

And welcome to Phexample’s expectation failure message

'Expected <1p> but got <2p> (using <3s>)' e: value e: expected e: symbol

And eventually, regular expressions. Again such a basic feature that most languages include regex literals at their very core, and again we have to wait for Lukas’s Helvetia until we get the same awesomeness in Pharo. Until then, let’s pirate Groovy’s r syntax

String >> r
    ^self asRegex
String >> =~ regex
    ^self matchesRegex: regex
RmMatcher >> asRegex
    ^self

And, “Hup hup hup, barbatruc”

| regex |
regex := 'a*wesome'r
'Regex are aaaaaaaaaawesome!' =~ regex

Well then

Gofer new
    squeaksource: 'akuhn';
    addPackage: 'Akuhn-Huffman';
    load

Gofer it!

This is Verbose!


Thursday, September 11th, 2008

Yesterday I came across the following piece of Java code. The code visits an abstract syntax tree and pretty prints it.

public void visitIf(If node) {
    this.builder.append(this.indentation());
    this.builder.append("if ");
    node.condition.accept(this);
    this.builder.append(" then\n");
    this.increaseIndentation();
    node.body.accept(this);
    this.decreaseIndentation();
    this.builder.append(this.indentation());
    this.builder.append("end\n");
}

This is verbose! Way too much syntactic noise. As we know from XP, it is sometimes best to turn the knob to the extremes—so let’s turn the knob from Corporate Java™ to Spartan Programming.

  1. Remove all redundant this references.
  2. Rename builder to $.
  3. Replace the procedural indentation with Class Tab.
public void visitIf(If node) {
    $.append(tab+"if ");
    node.condition.accept(this);
    $.append(" then\n");
    tab.more();
    node.body.accept(this);
    tab.less();
    $.append(tab+"end\n");
}

This is Sparta! Less noise, more readable.

The 6th Rule of Variable Naming


Tuesday, July 29th, 2008

Personally, I take particular care when naming methods. An often neglected detail is that an object’s public method names are almost ever written following the variable name holding an instance of the object. Thus, it is rather pointless to start all methods of a Factory class with the verb create, rather we can omit it and stick to the convention that its instances must be named create!

Factory create = new Factory();
Node n = create.Node();
Edge e = create.Edge();
…

In lack of a better name, I am calling this the Read-Aloud naming convention.

I have first stumbled upon this convention when reading the sources of the Java Compiler. Other occurrences known to me are restricted to the naming of static methods. For example Yossi Gil’s awesome Default class which returns a default value if a given variable is null.

String guess = Defaults.to(answer, "A");

Another example of Read-Aloud naming is the headline of this blog, which refers to the creation of examples in the JExample testing framework.

Stack stack = For.example(StackTest.class, "withManyValues");

PS—if you are looking for the first five rules of variable naming, please refer to Ian Hickman’s recently digged 5 Rules of Variable Naming.

Class Once, Class Separator


Saturday, July 12th, 2008

Every once a while, you stumble upon one of those rare programming gems that immediately make it into your personal utils project. Today, this happened when I stumbled upon class Once and class Separator by Yossi Gil of the Technion.

Let’s start head first, with an example:

Separator s = new Separator(", ");
for (String n : names) {
    System.out.println(s + n);
}

This prints a comma separated list of names, excluding trailing comma—without using any if statement or referring the loop’s underlaying iterable! Wooow, that’s what I call mastering the art of code fu. Moar, pleaze, moar!

The implementation of class Separator is straight forward. It wraps a string that is returned on every call of toString() except for the first call, which returns an empty string.

The class Once is implemented in the same way, but with reversed logic. In the first call of toString(), the initial value is returned. In all subsequent calls, the empty string is returned.

You can find the sources of both classes on the SSDL wiki:


NB for the interested reader, my previous stumble was the internal implementation of List, ListBuffer and Pair in the Java compiler sources.

For.example is Digg proof thanks to caching by WP Super Cache!