Java Code compared to Scala Code (1) - Magic Number Constants

Feb 6, 2011 17:45 · 355 words · 2 minutes read Scala Java

I am working on a private Java project right now that I started some years ago. It is already 95% done (isn’t that true for all projects?), so it is still faster to finish it in Java than rewriting it in Scala. However, now that I have done a lot of Scala lately I notice how much more verbose and klunky Java is compared to Scala. As I get into a discussion now and then with Java programmers about the Scala vs. Java issue, I though I’d just blog the real world examples where Java really annoys me every time I encounter them and how I would do it in Scala. Just the two code versions, and maybe a little comment. Just compare the two and judge for yourself.

In this example I have to define a couple of constants that are magic numbers in a binary format I am working with. Which of the two do you like better?

The Original in Java

public class MagicNumbers {

    private MagicNumbers() {}

    public static final int TONE_DATA_1             = 0x00;
    public static final int OPERATION_DATA_1        = 0x01;
    public static final int MULTI_CHANNEL_MODE_DATA = 0x02;
    public static final int TUNE                    = 0x40;
    public static final int MASTER_TUNE             = 0x00;
    public static final int KEY_TRANSPOSE           = 0x01;
    public static final int MODE_CHANGE             = 0x50;
    public static final int CARD_BANK_CHANGE        = 0x51;
    public static final int OPEN                    = 0x70;
    public static final int CLOSE                   = 0x71;
    public static final int OK                      = 0x72;
    public static final int ERROR                   = 0x73;
    public static final int DATA                    = 0x74;
}

The Scala version

object MagicNumbers {
    val TONE_DATA_1             = 0x00
    val OPERATION_DATA_1        = 0x01
    val MULTI_CHANNEL_MODE_DATA = 0x02
    val TUNE                    = 0x40
    val MASTER_TUNE             = 0x00
    val KEY_TRANSPOSE           = 0x01
    val MODE_CHANGE             = 0x50
    val CARD_BANK_CHANGE        = 0x51
    val OPEN                    = 0x70
    val CLOSE                   = 0x71
    val OK                      = 0x72
    val ERROR                   = 0x73
    val DATA                    = 0x74
}

My 2 ¢

//should be 1
public static final int HOW_MANY_FRAKING_KEYWORDS_DO_YOU_FRAKING_NEED = 4;
//should be 0
public static final int USELESS_CONSTRUCTOR_BOILERPLATE_COUNT = 1;
//should be 0
public static final int SUPERFLUOUS_SEMICOLON_COUNT = 13