Defensive programming and exception handling
Asked Answered
D

2

11

A couple days ago, I have following theoretical questions on the exam: (a) Explain what is meant by defensive programming when dealing with exceptional circumstances that may occur during the execution of a program. You may refer to examples seen in class or use pseudo code to describe the steps taken to prevent certain circumstances from occurring when trying to read a file for example. [5 marks]

(b) Briefly describe in general terms what is meant by exception handling in Java and how this differs from defensive programming. [5 marks]

I always thought that defensive programming is the whole paradigm of programming and that exception handling is the part of it. During exam I write that in "defensive programming", programmer try to find out all possible problems before executing the logic code, and later on return error value(example 0) from this function, whereas in exception handling the potential errors occurs and are caught by special mechanism, in which these errors are directly being interpreted. Is it right? What should be correct answers?

Desolate answered 22/9, 2011 at 17:58 Comment(1)
Someone has voted to close as off topic. WTF? It's a shame that the question is couched in terms of "what should i write in an exam?", but in what way is this not a question about programming?Generate
G
2

Defensive programming, to me, means writing code to handle cases that you do not think will, or even can, happen, because you have a belief that your own beliefs are unreliable.

For example (not compiled or tested, terms and conditions apply):

private String findSmallestString(Collection<String> strings) {
    if (strings == null || strings.isEmpty()) return null;
    Iterator<String> stringsIt = strings.iterator();
    try {
        String smallestString = stringsIt.next();
        while (stringsIt.hasNext()) {
            String candidateString = stringsIt.next();
            if (candidateString == null) continue;
            if (candidateString.compareTo(smallestString) < 0) {
                smallestString = candidateString;
            }
        }
        return smallestString;
    }
    catch (NoSuchElementException e) {
        return null;
    }
}

In there, arguably defensive features include:

  • The null-or-empty guard clause at the top; this is a private method, so you should be in a position to ensure that it is never called with a null or empty collection
  • The try-catch for NoSuchElementException; you can prove that the code it contains will never throw this exception if the iterator fulfils its contract.
  • The nullity guard clause on the strings (other than the first!) coming out of the iterator; again, since this is a private method, you should probably be able to ensure that the collection parameter contains no nulls (and what would you be doing putting nulls in collections anyway?)

Not everyone would agree that the null checks are defensive. The try-catch is, to the point of being completely pointless.

For me, the acid test of defensive programming is that you don't think the defence will ever be used.

Generate answered 22/9, 2011 at 18:14 Comment(0)
G
2

For me defensive programming is assuming the worst case: that your users are complete crazy people and you must defend yourself and your program from their crazy inputs. I believe there is a lot of wisdom within this quote:

Every day, the software industry is making bigger and better fool-proof software, and every day, nature is making bigger and better fools. So far nature is winning

And never forget that your users are not only your clients. If you are responsible of a library API your users might be other department. In that case one of the most stellar complains I ever heard in my life was:

Even after we deleted all failed unit tests, the program did not work

Gauldin answered 22/9, 2011 at 18:20 Comment(1)
Succinctly and powerfully put. However, i would go further: assuming your users are crazy people who make crazy inputs is not defensive, it's normal; assuming that you yourself is a crazy person who makes crazy inputs is defensive.Generate

© 2022 - 2024 — McMap. All rights reserved.