I used to be really poor at simplifying my code (even my living style), but in the recent months I have tried hard to always keep in mind the idea of making-it-simpler. I switched all my accounts’ screen-names to BeingSimpler, just to remind myself that what needs to be simple then keep it simple. The result of this long-live campaign (so far) is now I can write code with 20-30% lines lesser than before. It doesn’t really mean that writing fewer lines of code is better, and this rule can only be applied to certain circumstances.

I know developers hardcode all the time just to keep things organized in their ways, but our coding world has been deemed to be much universal these days, and every single snippet of code can be delivered or passed along the line for the sake of reusing it. So writing portable, clean and clear code doesn’t only help you maintain it easily, but can also reflect your ability to work collectively or your mentality and approach to code-professionalism.

Too much of the introduction though I know I should keep it simple in this post, but I’m gonna talk more about keep-it-simple or keep-it-simply-organized later on if I have enough time.

So what is the point? I’ve been reading some of my friends’ code at uni, and some of the real-world coders, and some of them have some of the common ways of dealing with coding situations. One of these situations is what I’m trying to stress in this post, which is to deal with switching boolean value efficiently (actually more simply).

Imagine that you have to write a function that checks and switches a certain task from not-completed state to completed state (i.e. FALSE to TRUE). You can have up to two options: 1) switch from not-completed state to completed state and 2) (1) or vice-versa.

For 1) You only want 1 outcome, which is isCompleted holds true whenever you call the method.

public void setComplete() { //switch from not completed to completed
     isCompleted = (!isCompleted) ? !isCompleted : isCompleted;
}

Does it look clean in just a line? Yes it is, and indeed tricky too. I don’t really recommend this way since you can write it  much cleaner and better (to understand) by using if statement, so you won’t play around with assigning variable to itself.

public void setComplete() { //switch from not completed to completed
     if (!isCompleted) isCompleted = true;
}

For 2) You want to have 2 outcomes, depending on the input, as a meaning of switching

public void switchComplete() {
    if (isCompleted)
        isCompleted = false; // if it is completed, then switch it back to be not completed.
    else
        isCompleted = true; // if it is not completed, then switch it to be completed.
}

It looks pretty ordinary and easy to understand. But you can write this in only 1 line instead of 4 lines (with check-style rule applied) or 2 lines (without check-style rule applied). Thus:

public void switchComplete() {
    isCompleted = !isCompleted;
}
Tagged with: