Date post: | 13-May-2015 |
Category: |
Technology |
Upload: | meljun-cortes |
View: | 140 times |
Download: | 0 times |
Java Java Best PracticesBest Practices
Java Fundamentals &Java Fundamentals &Object-Oriented ProgrammingObject-Oriented Programming
The Complete Java Boot CampThe Complete Java Boot Camp
MELJUN CORTESMELJUN CORTES
MELJUN CORTESMELJUN CORTES
ContentsContents
Bad PracticesBad Practices Good PracticesGood Practices
Bad PracticesBad Practices
Duplicate Code!Duplicate Code!
• Every time you need to make a change in the Every time you need to make a change in the routine, you need to edit it in several places. routine, you need to edit it in several places.
– Called “Shotgun Surgery”.Called “Shotgun Surgery”.
• Follow the “Once and Only Once” rule.Follow the “Once and Only Once” rule.
• Don’t copy-paste code!Don’t copy-paste code!
Accessible FieldsAccessible Fields
Fields should always be private except for Fields should always be private except for constants.constants.
Accessible fields cause tight coupling.Accessible fields cause tight coupling.
Accessible fields are corruptible.Accessible fields are corruptible.
If a field needs to be accessed, use “get” If a field needs to be accessed, use “get” and “set” convention.and “set” convention.
Using Magic NumbersUsing Magic Numbers
Magic numbers are not readable, and can lead to Magic numbers are not readable, and can lead to “Shotgun Surgery”.“Shotgun Surgery”.
for (int i = 1; i =< 52; i++) {j = i + randomInt(53 - i) – 1swapEntries(i, j)
} Replace with constants.Replace with constants.
final int DECKSIZE = 52;for (int i = 1; i =< DECKSIZE; i++) {
j = i + randomInt(DECKSIZE + 1 - i) – 1swapEntries(i, j)
}
Temporary FieldsTemporary Fields
If a variable need not be shared across methods, If a variable need not be shared across methods, make it local.make it local.
private int x;int method() {
x = 0; // if you forget to initialize, you're dead... // do some stuffreturn x;
}
int method() {int x = 0;... // do some stuffreturn x;
}
Initializing Strings with “new”Initializing Strings with “new”
Don’t:Don’t:String str = new String(“This is
bad.”);
Do:Do:String str = “This is good.”;
Using floats and doubles for Using floats and doubles for currency calculationscurrency calculations
Binary numbers cannot exactly Binary numbers cannot exactly represent decimals.represent decimals.
Use BigDecimal for currency Use BigDecimal for currency calculations.calculations. ...using the constructor that takes a ...using the constructor that takes a
String as a parameter.String as a parameter.
Returning nullReturning null
Causes NullPointerExceptions.Causes NullPointerExceptions.
Instead, return…Instead, return… empty objectsempty objects
custom-made “Null Objects”custom-made “Null Objects”
Subclassing for FunctionalitySubclassing for Functionality
Implementation inheritance is difficult Implementation inheritance is difficult to debug.to debug.
Ask yourself: “Is this a kind of…?”Ask yourself: “Is this a kind of…?”
Alternatives:Alternatives: Prefer interface inheritance.Prefer interface inheritance. Prefer composition over inheritance.Prefer composition over inheritance.
Empty Catch BlockEmpty Catch Block
No indication that an exception No indication that an exception has occurred!has occurred!
Using Exceptions UnexceptionallyUsing Exceptions Unexceptionally
Use exceptions only for exceptional Use exceptions only for exceptional conditions.conditions.
Bad:Bad:try {try {
obj = arr[index];obj = arr[index];} catch (ArrayIndexOutOfBoundsException) {} catch (ArrayIndexOutOfBoundsException) {
// do something// do something}}
Good:Good:if (index < 0 || index >= arr.size()) {if (index < 0 || index >= arr.size()) {
// do something// do something} else {} else {
obj = arr[index];obj = arr[index];}}
Excessive Use of SwitchesExcessive Use of Switches
Use of “if” and “switch” statements Use of “if” and “switch” statements usually a sign of a breach of the usually a sign of a breach of the “One Responsibility Rule”.“One Responsibility Rule”.
Consider polymorphism instead.Consider polymorphism instead.
instanceofinstanceof
If you’re using instanceof often, it If you’re using instanceof often, it probably means bad design.probably means bad design.
Consider adding an overridden method in Consider adding an overridden method in supertype.supertype.
instanceof should only be used instanceof should only be used as validation prior to castingas validation prior to casting when you have to used a poorly-written librarywhen you have to used a poorly-written library
Static MethodsStatic Methods
Static methods are..Static methods are.. ...procedural...procedural
They break encapsulation - the method should be part of the object that needs it
...not polymorphic...not polymorphic You can't have substitution/pluggability.
You can't override a static method because the implementation is tied to the class it's defined in.
Makes your code rigid, difficult to test.
System.exitSystem.exit
Only use in stand-alone applications.Only use in stand-alone applications. For server applications, this might shut For server applications, this might shut
down the whole application container!down the whole application container!
Good PracticesGood Practices
Validate Your ParametersValidate Your Parameters
The first lines of code in a method should check if The first lines of code in a method should check if the parameters are valid:the parameters are valid:
void myMethod(String str, int index, Object[] arr) { void myMethod(String str, int index, Object[] arr) { if (str == null) {if (str == null) {
throw new IllegalArgumentException(“str cannot be throw new IllegalArgumentException(“str cannot be null”);null”);
}} if (index >= arr.size || index < 0) {if (index >= arr.size || index < 0) { throw new IllegalArgumentException(“index throw new IllegalArgumentException(“index
exceeds exceeds bounds of array”);
}} … …}}
Create Defensive CopiesCreate Defensive Copies
Create local copies, to prevent Create local copies, to prevent corruption.corruption.
void myMethod (List listParameter) {void myMethod (List listParameter) {List listCopy = new ArrayList(listParameter);listCopy.add(somevar);...
}}
Modify Strings with StringBuilderModify Strings with StringBuilder
String objects are immutable.String objects are immutable. You may think you’re changing a You may think you’re changing a
String, but you’re actually creating a String, but you’re actually creating a new object.new object.
Danger of OutOfMemoryErrors.Danger of OutOfMemoryErrors. Poor peformance.Poor peformance.
StringBuilder is mutable.StringBuilder is mutable. All changes are to the same object.All changes are to the same object.
Favor ImmutabilityFavor Immutability
If your objects don’t change… easier If your objects don’t change… easier to debug.to debug.
Fields are private and final.Fields are private and final.
No setters, only getters.No setters, only getters.
Prefer “final” for VariablesPrefer “final” for Variables
Usually, variables / parameters do not Usually, variables / parameters do not need to change.need to change.
Get into the habit of using Get into the habit of using finalfinal by default, by default, and make a variable not final only when and make a variable not final only when necessary.necessary.
Declare Variable Just Before Declare Variable Just Before UseUse Easier to read and refactor.Easier to read and refactor.
Initialize Variables Whenever Initialize Variables Whenever PossiblePossible Helpful in debugging, makes it clear what Helpful in debugging, makes it clear what
initial value is.initial value is. Makes sure you don’t use the variable Makes sure you don’t use the variable
before it’s ready for use.before it’s ready for use.
Follow Code ConventionsFollow Code Conventions
Improves readabilityImproves readability For other programmers.For other programmers. For yourself.For yourself.
Readability means… Readability means… ……less bugs.less bugs. ……easier to debug.easier to debug.
Refer to Objects by InterfacesRefer to Objects by Interfaces
Maintainability - changes in implementation need Maintainability - changes in implementation need only be done at a single point in codeonly be done at a single point in code
Polymorphism – implementation can be set at Polymorphism – implementation can be set at runtime.runtime.
// bad:ArrayList list = new ArrayList();list.add(somevar);
// good:List list = new ArrayList();list.add(somevar);
Consider Using Enums instead of Consider Using Enums instead of ConstantsConstants
Constants:Constants: Not typesafeNot typesafe No namespaceNo namespace
You often need to prefix constants to avoid collisions
BrittlenessBrittleness When you change the order, you need to
change a lot of code. Printed values are uninformativePrinted values are uninformative
Buffer I/O StreamsBuffer I/O Streams
Requesting OS for I/O resources is Requesting OS for I/O resources is expensive.expensive.
Buffering provides significant increase in Buffering provides significant increase in performance.performance.
Close Your I/O StreamsClose Your I/O Streams
If you don’t close, other applications may If you don’t close, other applications may not be able to use the resource.not be able to use the resource.
Close using the “finally” block in a try-Close using the “finally” block in a try-catch.catch.
Design Close to DomainDesign Close to Domain
Code is easily traceable if it is close to the Code is easily traceable if it is close to the business it is working for.business it is working for.
If possible, name and group your If possible, name and group your packages according to the use cases.packages according to the use cases. Easy to tell client %completion of feature.Easy to tell client %completion of feature. If user reports a bug, easier to find where it is.If user reports a bug, easier to find where it is.
If You Override equals() If You Override equals() Override hashcode()Override hashcode() Always make sure that when equals() Always make sure that when equals()
returns true, the two object have the same returns true, the two object have the same hashcode.hashcode.
Otherwise, data structures like Sets and Otherwise, data structures like Sets and Maps may not work.Maps may not work.
There are many IDE plug-ins and external There are many IDE plug-ins and external libraries that can help you with this.libraries that can help you with this.
Write Self-Documenting CodeWrite Self-Documenting Code
Comments are important, but…Comments are important, but…
……even without comments your code even without comments your code should be easily readable.should be easily readable.
Ask yourself: “If I removed my Ask yourself: “If I removed my comments, can someone else still comments, can someone else still understand my code?”understand my code?”
Use Javadoc LiberallyUse Javadoc Liberally
Provide as much documentation about Provide as much documentation about your code as possible.your code as possible.
Bubble-Up ExceptionsBubble-Up Exceptions
If code is not part of the user interface, it If code is not part of the user interface, it should not handle its own exceptions.should not handle its own exceptions.
It should be bubbled-up to presentation It should be bubbled-up to presentation layer…layer…
Show a popup? Show an error page? Show a commandline message? Just log to an error log?
ReferencesReferences
““Effective Java” by Joshua BlochEffective Java” by Joshua Bloch Refactoring by Martin FowlerRefactoring by Martin Fowler http://javapractices.comhttp://javapractices.com