10 Java programming experiences are listed here
1 string constants are placed in front
The string constant is placed on the left side of the Equals () comparison item to prevent accidental nullpointerexception.
// Bad if (Variable.equals ("literal"// goodif ("literal". Equals (variable)) {...}
2 Don't believe-1
// Bad if (String.IndexOf (character)! =-1) {...} // Good if (String.IndexOf (character) >= 0) { ... }
3 Avoidance of accidental assignment
If there is a constant in your expression, place it on the left side of the equation. So when you're going to add another =, it's not easy to go wrong.
// Ooops if (variable = 5// Better (because causes an error)if (5 = variable) {...} // Intent (remember. Paranoid JavaScript: = = =)if (5 = = = variable) {...}
4 checking for null and length
Whenever you have a collection, an array, or something else, make sure it exists and is not empty
// Bad if (Array.Length > 0) {...} // Good if null && array.length > 0) {...}
Of course, you can also use Collections.isempty () to judge
5 All methods are declared with final
You can tell me any opening and closing principle you want, but that's nonsense. I don't believe you (can inherit my class correctly), nor do I trust myself (not accidentally inheriting my class). So all but the interface (specifically for inheritance) should be strictly final
// Bad Public void // good. Don ' t touch. Public Final void Donttouch () {...}
6 All variables and parameters are declared with final
// Bad void input (String importantmessage) { = "..."; = Importantmessage = "LOL accident"// goodfinalvoid input ( Final string importantmessage) { final string answer = "...";}
7 overload don't believe in generics
// Bad<T>voidBad (T value) {Bad (collections.singletonlist (value));}<T>voidBad (list<t>values) { ...} //GoodFinal<T>voidGood (FinalT value) { if(Valueinstanceoflist) Good ((list<?>) value); ElseGood (collections.singletonlist (value));} Final<T>voidGood (FinalList<t>values) { ...}
8 always add default to the switch statement
// BadSwitch(value) { Case1:foo (); Break; Case2:bar (); Break;} //GoodSwitch(value) { Case1:foo (); Break; Case2:bar (); Break; default: Throw NewThreaddeath ("that ' ll teach them");}
9 Use curly braces to separate each case block of a switch
//Bad , doesn ' t compileSwitch(value) { Case1:intj = 1; Break; Case2:intj = 2; Break; J Repeating Definition}//GoodSwitch(value) { Case1: { Final intj = 1; Break; } Case2: { Final intj = 2; Break; } //Remember: default: Throw NewThreaddeath ("that ' ll teach them");}
Java interview (5)