Thread.dumpStack()

To print a stack trace in Java, without throwing an exception, call Thread.dumpStack(). The output will go to System.err. This could be redirected to a log file or some other output stream:

PrintStream logFile;

// ...

System.setErr(logFile);
Thread.dumpStack();

Principles of design

Donald Norman’s key principles of design:

  1. Make it easy to determine what actions are possible at a particular moment.
  2. Make things visible – the conceptual model of the system, the alternative actions and the results of actions.
  3. Make it easy to evaluate the current state of the system.
  4. Follow natural mappings between intentions and the required actions; between actions and the resulting effect; and between the information that is visible and the interpretation of the system state.

In other words, the user should be able to figure out what to do without much instruction. He should also be able to tell what is going on. The reason for the design should be a simple explanation, even if that is required. If the explanation leaves the user confused, the design has failed. The interesting observation that Don Norman makes is this: when we are not able to figure out how to make a call from the latest smartphone or cannot locate a simple formatting command in a word processor, it is not because we are dumb, it is just another case of bad product design.

Human Interface

Is it possible to build a useful personal computer that has no operating system, no user applications, not even a mouse (or some other pointing device)? It is! Jef Raskin explains this radical approach to computer design in The Humane Interface: New Directions for Designing Interactive Systems. He demonstrated that this idea is both practical and commercially viable by building the Canon Cat. Tests proved that users were more productive on this new computer than they were on traditionally designed systems.

PS: Another interesting fact about the Canon Cat: Its entire software system was developed in Forth, another masterpiece of great design!

Type inference

An appetizer for those preparing to delve into the depths of type inference.

Consider the following function that takes an argument ‘x’ of some type and returns the result of applying the addition operator on it:

f (x) : x + x

We want to find out the type of x and the type of f (which is the type of the value returned by f). The first step is to assign placeholder types to each expression:

Expression      Type
----------      ----
x                tx
x + x            t0
f (x) : x + x    tf

Next, we generate some equations based on the above types assignments:

1. t0 = tx + tx
2. tf = t0

We can now solve these equations systematically. This process is called unification. The first equation is easy to solve, as our simple language specification dictates that the addition operator can be applied only to integers. (This is true also for OCaml, a much more complicated language that employs type inference!):

t0 = tx + tx
   = (int + int) -> int
hence,
tx = int

Please take note of how we replaced parts of the equation with information we already had. This is called substitution. As the type of the second equation is the same as the first, we have now inferred the types of the argument of f and its return value. So we can write down the type signature of the function f as:

int -> int

Internal iteration as an idiom

You must be familiar with the Iterator pattern. It allows clients to sequentially access a collection, without knowing anything about its underlying representation. Iteration can be external or internal. In the first form, which is the most common, the client decides when to access the next element, what to do with it and when to stop the iteration:

// Java like pseudo-code. For simplicity, values in the collection are
// assumed to be integers.

int sum = 0;
// Iterate over a list of integers and
// find their sum.
Iterator it = list.iterator();
while (it.hasNext()) {
     sum += it.next();
}
print(sum);

The iterator object itself can be made to iterate over the sequence and perform an operation on each element. This is called internal iteration.

// An interface to specify operations on individual elements.
interface Operation {
    public void execute(int i);
}

// For internal iteration to work, the Iterator class
// should have a method that accepts an Operation and
// calls its execute(int) on each element.
class Iterator {
    // .....
    public void iterate(Operation opr) {
         while (hasNext()) {
             execute(next());
         }
    }
 }

Given the above definitions, it is easy to apply an Operation over a sequence and get back some aggregate result:

class Summation implements Operation {
    public void execute(int i) {
        sum += i;
    }

    public int getSum() {
        return sum;
    }

    private int sum;
}

// To find the sum of all ints in a list:
Operation s = new Summation();
list.iterator().iterate(s);
print(((Summation)s).getSum());

In the general OOP world, design patterns are considered arcane. Good knowledge and great care is required to implement the objects that comprise a pattern. Programmers need to be familiar with advanced language concepts like templates to implement patterns effectively. This is not the case with functional languages. Programmers who start with a functional language, learn most of the design patterns while mastering the basic idioms of the language itself and they do this unawares! To make the point clear, let us see how a programmer learning Scheme, one of the simplest of all functional languages, familiarizes himself with the iterator pattern, while learning two basic concepts of the language: higher-order functions and closures. Higher-Order functions are often introduced using map, which applies a procedure on all elements of a list. This is how the internal iterator we just saw, is implemented using a closure and map, in just a few lines of code:

;; Returns a closure that keeps an accumulated sum.
(define (make-accumulator)
  (let ((sum 0))
     (lambda (n)
       (set! sum (+ sum n))
       sum)))

 ;; Iterate a list and find the sum
 (define a (make-accumulator))
 (map a '(1 2 3 4 5))
 (a 0) ;; => 15

Ragas & Scales

Musical modes in Indian Classical music are called Ragas. People often equate Ragas with Scales. This is wrong. A scale just provide a set of allowable pitches. Ragas are built on top of Scales. They also contain information such as melodic patterns and emotions. This is important to musical systems, such as Carnatic music, that are entirely based on melody. European classical composers don’t depend much on modes, they tend to built their music on top of raw scales. This is because they use harmony to evoke emotions and micro-tones (which are an important constituent of modes), are difficult to harmonize. An analogy might help to understand how the European and Indian compositional techniques differ. Imagine you are preparing a letter using a Word Processor. You can start from an ‘empty document’. In addition to the content, you have to decide on the layout, font types and other embellishments that should go to the design of the document. This is like composing music using a raw scale. You have the set of notes as specified by the Scale and the rest is left to your imagination. But most word processors come with ‘templates’ that provide the basic layout and design for various types of documents. You can just select a ‘letter’ template and improve on that, which of course, require knowledge about what you are trying to accomplish. (If you choose a ‘love letter’ template for a business letter, you won’t be running your business for long!). Templates makes your job much easier. If you choose the right template and respect the patterns set by it, you will be able to produce a professional looking document. Composing a melody based on a Raga is like preparing a letter using a ‘template’. Oriental music systems provide a rich collection of modes that cater to the widest spectrum of human emotions. The composer should know which mode to choose (and its scope) to create a composition with a particular feeling. To conclude, Ragas are not the same as Scales. The similar concept in western music is called ‘Musical Modes’, which lost popularity once European composers started emphasizing harmony.

Note: Just like Indian Classical music, Arabic music has a vast array of modes. A mode in Arabic music is called a Maqam. I must admit: “Arabic music has an enchanting charm!”