Making your Scala code more concise (and your intent more clear)

I was trying to write some code last night while I was very tired, and while the code itself isn't difficult in any way, the thought process I went through demonstrates how your code can become more concise as your understanding of Scala evolves, so I thought I'd share the experience here.

While working on my Sarah application, I was rewriting the Brain class, and I started off writing a method that looked like this:

def inSleepMode: Boolean = {
    if (awarenessState == AWARENESS_STATE_AWAKE) {
        return false
    else
        return true
    }
}

Step 1

While that method isn't horrible, it sure does require a lot of screen real estate to express a simple idea (a common problem for me when coding while I'm tired). As that thought crossed my mind, I thought "Shorten up the 'return false' and 'return true' code", you don't need those return statements:

def inSleepMode: Boolean = {
    if (awarenessState == AWARENESS_STATE_AWAKE) false else true
}

Step 2

Next I thought, "You don't need to declare the Boolean return type, that's obvious":

def inSleepMode = {
    if (awarenessState == AWARENESS_STATE_AWAKE) false else true
}

Step 3

Then I thought, "Huh, I don't need those curly braces any more":

def inSleepMode = if (awarenessState == AWARENESS_STATE_AWAKE) false else true

As you can see from this example, I've gone from seven lines of initial code down to a simple one-line function. As the code became much shorter -- essentially becoming a ternary operator expression -- my intent also became more clear. As a result, I decided to make a subtle change and rename my method from inSleepMode to isSleeping:

def isSleeping = if (awarenessState == AWARENESS_STATE_AWAKE) false else true

Step 4

If you prefer, you can take one more step here and shorten your method up to just this:

def isSleeping = awarenessState != AWARENESS_STATE_AWAKE

I've seen some programmers not take this last step because they think the previous version is easier to read, but I like it better this way.

At this point my code became so clear I recognized some other problems I had in my class and logic, but since that has nothing to do with this example, I'll stop here.

Summary

I hope this example of the thought process in making your Scala code more concise has been helpful. For me, being as tired as I am when I just went through this, it was funny to observe how my brain went from one simple step to the next, and in the end it resulted in much more concise and readable code, and I could see at a glance what my intent was.