Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

My professor keeps referring to this Java example when he speaks of "robust" code:

if (var == true) {
    ...
} else if (var == false) {
    ...
} else {
    ...
}

He claims that "robust code" means that your program takes into account all possibilities, and that there is no such thing as an error - all situations are handled by the code and result in valid state, hence the "else".

I am doubtful, however. If the variable is a boolean, what is the point of checking a third state when a third state is logically impossible?

"Having no such thing as an error" seems ridiculous as well; even Google applications show errors directly to the user instead of swallowing them up silently or somehow considering them as valid state. And it's good - I like knowing when something goes wrong. And it seems quite the claim to say an application would never have any errors.

So what is the actual definition of "robust code"?

share|improve this question
8  
2  
This would only hold in a not-strongly-typed language. In a strongly typed language a variable of type boolean (not some integer posing as a boolean), can only be true or false, there is no third option... –  Marjan Venema Aug 27 '11 at 8:38
    
There was another question, what is elegant code, which got closed as a duplicate of "what is good code" -- a rather presumptuous decision, I think, but this question's likely to be closed as well. This question should demonstrate that there are multiple aspects to what constitutes "good code", so there's no sense closing either this question or the question about elegant code. –  Rei Miyasaka Aug 27 '11 at 12:33
6  
ask him how would you test coverage on the 3rd case, because robust code should surely require testing, and if you don't manage to test the 3rd case, you wouldn't be able to find any bugs that might lurk in there. –  gbjbaanb Aug 27 '11 at 13:53
    
@Marjan - in a not-strongly-typed language one would most likely just write: if (var) { } else { } –  kevin cline Aug 27 '11 at 14:16
show 2 more comments

11 Answers

up vote 14 down vote accepted

what is the point of checking a third state when a third state is logically impossible?

What about a Boolean? that allows for a NULL state that is neither true nor false. Now what should the software do? Some software has to be highly crash-resistant like pacemakers. Ever seen someone add a column to a database that was a Boolean and initialize the current data to NULL initially? I know I've seen it.

Here are a few links that discuss what it means to be robust in terms of software:

If you think there is one universally agreed upon definition of "robust" here, good luck. There can be some synonyms like bomb-proof or idiot-proof. The Duct Tape Programmer would be an example of someone that usually writes robust code at least in my understanding of the terms.

share|improve this answer
add comment

I think the professor might be confusing "error" and "bug". Robust code should certainly have few/no bugs. Robust code may, and in a hostile environment, must, have good error management (be it exception handling or rigorous return status tests).

I agree that the professor's code example is silly, but not as silly as mine.

// Assign 3 to x
var x = 3;
x = 3;   // again, just for sure
while (x < 3 or x > 3) { x = 3; }  // being robust
if (x != 3) { ... }  // this got to be an error!
share|improve this answer
add comment

For the sake of my discussion a Bool can have 2 states, True or False. Anything else is non-conformance to the programming langugae specification. If your tool chain is non-conformant to it's specification, you are hosed no matter what you do. If a developer created a type of Bool that had more than 2 states, it's the last thing he would ever do on my codebase.

Option A.

if (var == true) {
    ...
} else if (var == false) {
    ...
} else {
    ...
}

Option B

if (var == true) {
    ...
} else {
    ...
}

I assert Option B is more robust.....

Any twit can tell you to handle unexpected errors. They are usually trivally easy to detect once you think of them, The example your professior has given is not something that could happen, so it's a very poor example.

A is impossible to test without convoluted test harnesses. If you can't create it, how are you going to test it. If you have not tested the code, how do you know it works. If you don't know it works, then you are not writing robust software. I think they still call that a Catch22 (Great movie, watch it sometime).

Option B is trivial to test.

Next problem, ask you professor this question "What do you want me to do it about it if a Boolean is neither True nor False?" That should lead into an a very interesting discussion.....

Most cases, a core dump is approriate, at worst it annoys the user or costs a lot of money. What say the module is the Space shuttle realtime reentry calculation system, any answer, no matter how inaccurate, cannot be worse than aborting, which will kill the users, so what to do, you know the answer is might be wrong, go for the 50/50, or abort and go fo the 100% failure. If I a crew member, i'd take the 50/50.

Option A kills me Option B gives me an even chance of survival.

But wait - it's a simulation of the space shuttle reentry - then what, abort so you know about it, sound like a good idea? - NOT - because you need to test with the code you plan to ship

Option A is better for simluation, but cann't be deployed. It's useless Option B is the deployed code so the simulation performs the same as the live systems.

Lets say this was a valid concern, the better solution would be to isolate the error handling from the application logic.

if (var != true || var != false) {
    errorReport("Hell just frose over, var must be true or false")
}
......
if (var == true){
 .... 
} else {
 .... 
}

Futher reading - Therac-25 Xray machine, Ariane 5 Rocket failure and others (Link has many broken links but enough info that Google will help)

share|improve this answer
    
"..unexpected errors. They are usually trivally easy to detect once you think of them" - but when you think of them, they're no longer unexpected. –  gbjbaanb Aug 27 '11 at 13:51
add comment

I personally describe a code as 'robust' which has this one, important attributes:

  1. If my mom sits in front of it and work with it, she can't break the system

Now, by break I mean either getting the system into an unstable state, or causing an UNHANDLED exception. You know, sometimes for a simple concept, you can make a complex definition and explanation. But I'd prefer simple definitions. Users are pretty good at finding robust applications. If the user of your application send you many requests about bugs, about state loss, about unintuitive workflows, etc., then there is something wrong with your programming.

share|improve this answer
add comment

Actually your code is not more robust but LESS robust. The final else is simply dead code that you can't test.

In critical software such as in spacecrafts, dead code and more generally untested code is forbidden: If a cosmic ray produces a single event upset that in turn makes your dead code being activated, anything is possible. If the SEU activates a portion of robust code, the (unexpected) behaviour stays under control.

share|improve this answer
add comment

There is no agreed upon definition of Robust Code, as for many things in programming it's more or less subjective...

The example your professor gives depends on the language:

  • In Haskell, a Boolean can be either True or False, there is no third option
  • In C++, a bool can be true, false, or (unfortunately) come from some dubious cast that put it in an unknown case... This should not happen, but may, as a result of a previous error.

However, what your professor is advising obscures the code by introducing extraneous logic for should-not-happen events in the middle of the core program, so I will point you, instead, toward Defensive Programming.

In university case, you could even augment it by adopting a Design By Contract strategy:

  • establish invariants for classes (eg, size is the number of items in the data list)
  • establish pre-conditions and post-conditions for each function (eg, this function may only be invoked with a being less than 10)
  • Test each of those at the entry and exit points of each of your functions

Example:

class List:
  def __init__(self, items):
    self.__size = len(items)
    self.__data = items

  def __invariant(self):
    assert self.__size == len(self.__data)

  def size(self):
    self.__invariant()

    return self.__size

  def at(self, index):
    """index should be in [0,size)"""
    self.__invariant()
    assert index >= 0 and index < self.__size

    return self.__data[index]

  def pushback(self, item):
    """the subsequent list is one item longer
       the item can be retrieved by self.at(self.size()-1)"""
    self.__invariant()

    self.__data.append(item)
    self.__size += 1

    self.__invariant()
    assert self.at(self.size()-1) == item
share|improve this answer
    
But the professor specifically said that it was Java, and specifically did NOT say what the type of var is. If it is Boolean, it can be true, false, or null. If something else, it can be unequal to both true and unequal to false. Yes, overlap between robust, defensive, and paranoid. –  Andy Canfield Aug 27 '11 at 12:48
add comment

Robust code is simply code that handles failures well. No more, no less.

Of failures, there are many types: incorrect code, incomplete code, unexpected values, unexpected states, exceptions, resource exhaustion, .... Robust code handles these well.

share|improve this answer
add comment

I would consider the code you gave as an example of defensive programming (at least as I use the term). Part of defensive programming is to make choices that minimise assumptions made about the behaviour of the rest of the system. For example, which of these is better:

for (int i = 0; i != sequence.length(); ++i) {
    // do something with sequence[i]
}

Or:

for (int i = 0; i < sequence.length(); ++i) {
    // do something with sequence[i]
}

(In case you're having trouble seeing the difference, check the loop test: the first uses !=, the second uses <).

Now, under most circumstances, the two loops will behave in exactly the same way. However, the first (comparing with !=) makes an assumption that i will be incremented only once per iteration. If it skips the value sequence.length() then the loop could continue beyond the bounds of the sequence and cause an error.

You can therefore make an argument that the second implementation is more robust: it does not depend on assumptions about whether loop body changes i (note: actually it still makes the assumption that i is never negative).

To give some motivation for why you might not want to make that assumption, imagine that the loop is scanning a string, doing some text processing. You write the loop and everything is fine. Now your requirements change and you decide you need to support escape characters in the text string, so you change the loop body such that if it detects an escape character (say, backslash), it increments i to skip the character immediately following the escape. Now the first loop has a bug because if the last character of the text is backslash, the loop body will increment i and the loop will continue on beyond the end of the sequence.

share|improve this answer
add comment

what is the point of checking a third state when a third state is logically impossible?

There is a point and a good one of checking third state. The point is, it is logically possible as perfectly clearly explained in another answer.

Now that we're done with the simple part...

...the choice of words of your professor though feels rather questionable to me.

Questionable. Softly speaking.

keeps referring to this Java example when he speaks of "robust" code

Hm. Hmmmmmm. Given amount of bugs I've seen (and made myself) in a mess of ifelseifelse-s like in this Java example I would call it anything but "robust".

Your professor would better stick with straightforward wording takes into account all possibilities instead of throwing loud (and frankly, lame) value judgements at it.

Robust ha. Ask him to find out some long-living real Java project, get bugs statistics and analyze correlation to code like this.

  • ifelseifelse would probably be the last thing I'd want to see in a code managing crash-resistant pacemaker - and the more possibilities it takes into account the less I want it there.
     
    Oh and if I find that this code ingeniously hides null Boolean case under an else that makes an impression of dead code then I'll have a heart attack before installing that damn pacemaker

Code in this example takes into account all logical possibilities, fine. But the one it blatantly ignores lies beyond formal logic - a possibility that programmer reading code might get it wrong and screw it. Code like this is fragile - way too easy to break to call it robust.

share|improve this answer
add comment

Your professor is trying to make a point by leaving out the type of var. His robust code does not make the assumption that var is of type Bool and provides for a way out.

share|improve this answer
add comment

Robust means it's resistant to breakage/failure because it makes few assumptions and is decoupled: it's self contained, self defining, and portable.

This generally translates into short functions that get their data from parameters passed in by the caller, and use interfaces rather than concrete implementations

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.