Wednesday, February 6, 2008

Methods That Look Like Vars

A couple of years ago, Tim Sweeney of Epic Games (makers of Unreal) gave a presentation on "The Next Mainstream Programming Language". See here for Cedric Beust's take.

One of the points brought out by Cedric is that evaluation should be "lenient by default". Here's a simple example in Java:

public class Numbers {
public static final int FIRST = 1;
public static final int SECOND = FIRST + 1;

The order of definitions matters a lot. You can't put the SECOND before the first. (And try circular dependencies across classes for some fun.) Well, if we used methods rather than constants, the order of appearance doesn't matter:

public class Numbers {
public static int second() {
return first() + 1;
public static int first() {
return 1;

Mr. Unreal Tournament says that the lack of dependency on definition order is better than than supposed performance gains.

Well, both examples are bulky due to Java syntax, but the methods version is obviously more work than the constants. Well, say we had a language where defining methods is as easy as defining constants. There are several such languages, and Scala happens to be one of them. This corresponds roughly to the second Java example:

object Numbers {
def second = first + 1
def first = 1

So remember, according to Mr. Sweeney, Scala's 'def' is your friend. (Unlike in Groovy where 'def' makes vars or methods, 'def' only makes methods in Scala.)

That said, I'm not super hip on all out functional programming. Immutable and semi-functional have their uses, but I'm not on the big time functional side of the Scala crowd. At least not for now.

No comments:

Post a Comment