Thursday, February 02, 2006

Processing Notes, 1 February 2006

Last night's lecture on genetic algorithms:

Be wary of method argument names: When writing code for students, try not to give method arguments the same names as the outer scoped variables. This is difficult to explain but easy to demonstrate:


void func(int width, int height) {
    // do something with width and height
}
// later
int boxw = getBoxWidth();
int HEIGHT = getAnotherHeight();
func(boxw, HEIGHT);


is more instructive than:


void func(int width, int height) {
    // do something with width and height
}
// later
int width = getBoxWidth();
int height = getAnotherHeight();
func(width, height);


Again this may seem overly subtle, but the former style gives a visual cue to groking variable scopes.

Function side-effects: Methods that return values should have few — ideally zero — side effects. Novice programmers are comfortable with the "formula" metaphor from high school algebra, but side effects will tempt this metaphor to bite back.

And now two more features for Processing to help in teaching programming to designers and architects:

Comparable and casting: High level array sorting and inserts are provided by the Java Comparable interface. Since Java is overly typed, implementing this interface almost always requires casting. Object casting is an absolutely brutal concept to teach. Instead Processing should provide a method in all classes called "toNumber()" which converts an instance into a numeric representation. All classes should by default implement Comparable, and should by default implement "compareTo()" as:


int compareTo(Object o) {
    ProcessingObject processingObject = (ProcessingObject) o; // cry...
    if (toNumber() < processingObject.toNumber()) {
        return -1;
    }
    else if (toNumber() > processingObject.toNumber()) {
        return +1;
    }
    else {
        return 0;
    }
}


Programmers could just override "toNumber()" in their subclasses, and then "Arrays.sort()" would work magically. Sorting by a numeric representation of an instance is by far the most prevalent.

Random array elements: Selecting a random element from an array or Collection is a common idiom, but also a obscure, bug-ridden one. Implementing it requires students to understand zero-based array indexing (as opposed to natural one-based), float to int conversion for the index and pseudo-random numbers. Processing should implement an additional "faux-method" on arrays like "array.randomElement()" that does:

return ar[(int) (random() * ar.length)];

Until next week.

0 Comments:

Post a Comment

<< Home