| Start |
|---|
| Pitfall - Missing a ‘break’ in a 'switch' case These Java issues can be very embarrassing, and sometimes remain undiscovered until run in production. Fallthrough behavior in switch statements is often useful; however, missing a “break” keyword when such behavior is not desired can lead to disastrous results. If you have forgotten to put a “break” in “case 0” in the code example below, the program will write “Zero” followed by “One”, since the control flow inside here will go through the entire “switch” statement until it reaches a “break”. For example: In most cases, the cleaner solution would be to use interfaces and move code with specific behaviour into separate implementations (composition over inheritance) If a switch-statement is unavoidable it is recommended to document "expected" fallthroughs if they occur. That way you show fellow developers that you are aware of the missing break, and that this is expected behaviour. |
| Pitfall - Leaving out braces: the "dangling if" and "dangling else" problems The latest version of the Oracle Java style guide mandates that the "then" and "else" statements in an This is not actually required by Java language syntax. Indeed, if the "then" part of an or even However there are dangers in ignoring Java style rules and leaving out the braces. Specifically, you significantly increase the risk that code with faulty indentation will be misread. The "dangling if" problem: Consider the example code from above, rewritten without braces. This code seems to say that the calls to The "dangling else" problem A second problem appears when we add The code above seems to say that If the code was written according to the Java style rules, it would actually look like this: To illustrate why that is better, suppose that you had accidentally mis-indented the code. You might end up with something like this: But in both cases, the mis-indented code "looks wrong" to the eye of an experienced Java programmer. |
| Pitfall - Declaring classes with the same names as standard classes Sometimes, programmers who are new to Java make the mistake of defining a class with a name that is the same as a widely used class. For example: Then they wonder why they get unexpected errors. For example: If you compile and then attempt to run the above classes you will get an error: Someone looking at the code for the When we declare a version of instead of and the Lesson: Do not define classes that have the same name as existing classes in |
| Pitfall - Ignoring method visibility Even experienced Java developers tend to think that Java has only three protection modifiers. The language actually has four! The package private (a.k.a. default) level of visibility is often forgotten. You should pay attention to what methods you make public. The public methods in an application are the application’s visible API. This should be as small and compact as possible, especially if you are writing a reusable library (see also the SOLID (opens new window) principle). It is important to similarly consider the visibility of all methods, and to only use protected or package private access where appropriate. When you declare methods that should be private as public, you expose the internal implementation details of the class. A corollary to this is that you only unit test (opens new window) the public methods of your class - in fact you can only test public methods. It is bad practice to increase the visibility of private methods just to be able to run unit tests against those methods. Testing public methods that call the methods with more restrictive visibility should be sufficient to test an entire API. You should never expand your API with more public methods only to allow unit testing. |
| Pitfall - Octal literals Consider the following code snippet: A Java beginner might be surprised to know that the above program prints the wrong answer. It actually prints the sum of the numbers 1 to 8. The reason is that an integer literal that starts with the digit zero ('0') is interpreted by the Java compiler as an octal literal, not a decimal literal as you might expect. Thus, |
| Pitfall - Using '==' to test a boolean Sometimes a new Java programmer will write code like this: An experienced programmer would spot that as being clumsy and want to rewrite it as: However, there is more wrong with Here the programmer has mistyped The lesson here is to get out of the habit of using Note: A possible alternative to |
| Pitfall - Misplaced semicolons and missing braces This is a mistake that causes real confusion for Java beginners, at least the first time that they do it. Instead of writing this: they accidentally write this: and are puzzled when the Java compiler tells them that the In other cases, there will be no be compilation errors, but the code won't do what the programmer intends. For example: only prints "Hello" once. Once again, the spurious semicolon means that the body of the Another variation: This will give a "Cannot find symbol" error for In those examples, there is a straight-forward solution: simply delete the spurious semicolon. However, there are some deeper lessons to be drawn from these examples: If the programmer followed the style rules then the That looks odd to an experienced eye. If you auto-indented that code, it would probably look like this: which should stand out as wrong to even a beginner. |
| Pitfall - Wildcard imports can make your code fragile Consider the following partial example: Suppose that when when you first developed the code against version 1.0 of Now when you recompile If you are familiar with the codebase, this probably is just a minor inconvenience. If not, then you have some work to do to address this problem, here and potentially elsewhere. The problem here is the wildcard imports. On the one hand, using wildcards can make your classes a few lines shorter. On the other hand: The lesson is that it is a bad idea to use wildcard imports in code that needs to be long lived. Specific (non-wildcard) imports are not much effort to maintain if you use an IDE, and the effort is worthwhile. |
| Pitfall: Using 'assert' for argument or user input validation A question that occasionally on StackOverflow is whether it is appropriate to use The simple answer is that it is not appropriate. Better alternatives include:
This is what the Java Language Specification (JLS 14.10, for Java 8) (opens new window) advises on this matter: Typically, assertion checking is enabled during program development and testing, and disabled for deployment, to improve performance.
Because assertions may be disabled, programs must not assume that the expressions contained in assertions will be evaluated. Thus, these boolean expressions should generally be free of side effects. Evaluating such a boolean expression should not affect any state that is visible after the evaluation is complete. It is not illegal for a boolean expression contained in an assertion to have a side effect, but it is generally inappropriate, as it could cause program behavior to vary depending on whether assertions were enabled or disabled.
In light of this, assertions should not be used for argument checking in public methods. Argument checking is typically part of the contract of a method, and this contract must be upheld whether assertions are enabled or disabled.
A secondary problem with using assertions for argument checking is that erroneous arguments should result in an appropriate run-time exception (such as |
| Pitfall - Overloading instead of overriding Consider the following example: This code is not going to behave as expected. The problem is that the
These mistakes mean that we have declared accidental overloads, and these won't be used if However, there is a simple way to deal with this (from Java 5 onwards). Use the When we add an |
Pitfall of Auto-Unboxing Null Objects into Primitives The pitfall here is that Java is incapable of comparing primitive types against RemarksThis topic is about specific aspects of the Java language syntax that are either error prone or that that should not be used in certain ways. |
Read Article
https://develop.horje.com/learn/1434/reference