Java Reference
In-Depth Information
Chapter 2. Defensive Programming
Defensive programming is carefully guarded programming that helps you to construct re-
liable software by designing each component to protect itself as much as possible: for ex-
ample, by checking that undocumented assumptions remain valid [Goodliffe 2007]. The
guidelines in this chapter address areas of the Java language that can help to constrain the
effect of an error or help to recover from an error.
Java language mechanisms should be used to limit the scope, lifetime, and accessibility
of program resources. Also, Java annotations can be used to document the program, aiding
readability and maintenance. Java programmers should be aware of implicit behaviors and
avoid unwarranted assumptions about how the system behaves.
Agoodoverallprinciplefordefensiveprogrammingissimplicity.Acomplicatedsystem
is difficult to understand, difficult to maintain, and difficult to get right in the first place. If
a construct turns out to be complicated to implement, consider redesigning or refactoring it
to reduce the complexity.
Finally, the program should be designed to be as robust as possible. Wherever possible,
the program should help the Java runtime system by limiting the resources it uses and
by releasing acquired resources when they are no longer needed. Again, this can often
be achieved by limiting the lifetime and accessibility of objects and other programming
constructs. Not all eventualities can be anticipated, so a strategy should be developed to
provide a graceful exit of last resort.
22. Minimize the scope of variables
Scope minimization helps developers avoid common programming errors, improves code
readability by connecting the declaration and actual use of a variable, and improves main-
tainability because unused variables are more easily detected and removed. It may also al-
low objects to be recovered by the garbage collector more quickly, and it prevents viola-
tions of Guideline 37 , “ Do not shadow or obscure identifiers in subscopes .
Noncompliant Code Example
This noncompliant code example shows a variable that is declared outside the for loop.
Click here to view code image
public class Scope {
public static void main(String[] args) {
int i = 0;
Search WWH ::




Custom Search