Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defensive programming and exception handling

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?

like image 537
kuper006 Avatar asked Sep 22 '11 17:09

kuper006


People also ask

What is meant by defensive programming?

Defensive programming is an approach wherein the programmer assumes he is capable of mistakes, and therefore can apply the proper practices to produce higher-quality code.

What is defensive programming example?

Defensive programming is the practice of writing software to enable continuous operation after and while experiencing unplanned issues. A simple example is checking for NULL after calling malloc() , and ensuring that the program gracefully handles the case.

What is exceptional handling in programming?

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.

Why defensive programming is necessary?

It is important for software developers because defensive programming can help them avoid errors in the code, reduce the number of bugs in their programs, and make the programs more secure. This is why it's important for software development.


2 Answers

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.

like image 180
Tom Anderson Avatar answered Oct 21 '22 13:10

Tom Anderson


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

like image 2
SystematicFrank Avatar answered Oct 21 '22 13:10

SystematicFrank