Naming your variables, every time

I am rushing through the “Functional Programming Principles in Scala” by Martin Odersky on Coursera during my little career break. I signed up and didn’t do anything for six weeks so I’ve been doing a week per day to catch up. Overall the course is excellent. I think the assignments have lots of “aha!” moments, which can be infuriating, but overall I like the approach. The Coursera tools are nice – I especially like that during the “quiz” parts of the lectures you can copy out the function prototypes the instructor gives into your Scala worksheet. The Scala/Eclipse integration leaves much to be desired though (I confirmed with a pro Scala developer that there is no great tool set).

Academic programming can occasionally be hard to look at. A fundamental problem in all programming is naming your variables. Everyone on the planet can agree this is important. While Martin does not make any egregious errors I think there is room for improvement. Let’s take a look at some minor examples from the course:

In natural numbers (lecture 4.2) the Successor to a number takes a link back to its predecessor.  He uses

class Succ(n: Nat) extends Nat {

The ‘n’ is the name of the persistent field for this instance, so you end up with something like

def +(that: Nat): Nat = new Succ(n + that)

As opposed to the much more readable (in my opinion):

class Succ(pred: Nat) extends Nat { ...
def +(that: Nat): Nat = new Succ(pred + that)

Similarly in real numbers (lec 2.5) he uses

class Rational(x: Int, y: Int) {

as opposed to:

class Rational(n: Int, d: Int) {

in the tweet set assignment (A3) we use binary trees, where left is smaller and right is bigger. So we get:

class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet
...
def contains(x: Tweet): Boolean =
if (x.text < elem.text) left.contains(x)
else if (elem.text < x.text) right.contains(x)
else true

‘left’ and ‘right’ are kind of useless right? Why not:

class NonEmpty(elem: Tweet, smaller: TweetSet, larger: TweetSet) extends TweetSet
...
def contains(x: Tweet): Boolean =
if (x.text < elem.text) smaller.contains(x)
else if (elem.text < x.text) larger.contains(x)
else true

‘elem’ is not a great name either. I couldn’t think of anything clearly superior. Anyone have a better idea?

It’s a small criticism. Just something I noticed while working the examples.