meljun cortes java best practices

38
Java Java Best Best Practices Practices Java Fundamentals & Java Fundamentals & Object-Oriented Programming Object-Oriented Programming MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCS MBA,MPA,BSCS

Upload: meljun-cortes

Post on 15-Jul-2015

65 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: MELJUN CORTES Java best practices

Java Java Best Best PracticesPractices

Java Fundamentals &Java Fundamentals &Object-Oriented ProgrammingObject-Oriented Programming

MELJUN CORTES, MELJUN CORTES, MBA,MPA,BSCSMBA,MPA,BSCS

Page 2: MELJUN CORTES Java best practices

ContentsContents Bad PracticesBad Practices Good PracticesGood Practices

Page 3: MELJUN CORTES Java best practices

Bad Bad PracticesPractices

Page 4: MELJUN CORTES Java best 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!

Page 5: MELJUN CORTES Java best practices

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.

Page 6: MELJUN CORTES Java best practices

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)

}

Page 7: MELJUN CORTES Java best practices

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;

}

Page 8: MELJUN CORTES Java best practices

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.”;

Page 9: MELJUN CORTES Java best practices

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.

Page 10: MELJUN CORTES Java best practices

Returning nullReturning null

Causes NullPointerExceptions.Causes NullPointerExceptions.

Instead, return…Instead, return…

empty objectsempty objects

custom-made “Null Objects”custom-made “Null Objects”

Page 11: MELJUN CORTES Java best practices
Page 12: MELJUN CORTES Java best practices
Page 13: MELJUN CORTES Java best practices

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.

Page 14: MELJUN CORTES Java best practices

Empty Catch BlockEmpty Catch Block

No indication that an exception No indication that an exception has occurred!has occurred!

Page 15: MELJUN CORTES Java best practices

Using Exceptions Using Exceptions UnexceptionallyUnexceptionally

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];}}

Page 16: MELJUN CORTES Java best practices

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.

Page 17: MELJUN CORTES Java best practices

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

Page 18: MELJUN CORTES Java best practices

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.

Page 19: MELJUN CORTES Java best practices

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!

Page 20: MELJUN CORTES Java best practices

Good Good PracticesPractices

Page 21: MELJUN CORTES Java best practices

Validate Your Validate Your ParametersParameters 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”);

}} … …}}

Page 22: MELJUN CORTES Java best practices

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);...

}}

Page 23: MELJUN CORTES Java best practices

Modify Strings with Modify Strings with StringBuilderStringBuilder

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.

Page 24: MELJUN CORTES Java best practices

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.

Page 25: MELJUN CORTES Java best practices

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.

Page 26: MELJUN CORTES Java best practices

Declare Variable Just Declare Variable Just Before UseBefore Use Easier to read and refactor.Easier to read and refactor.

Page 27: MELJUN CORTES Java best practices

Initialize Variables Initialize Variables Whenever PossibleWhenever Possible 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.

Page 28: MELJUN CORTES Java best practices

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.

Page 29: MELJUN CORTES Java best practices

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);

Page 30: MELJUN CORTES Java best practices

Consider Using Enums instead Consider Using Enums instead of Constantsof Constants

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

Page 31: MELJUN CORTES Java best practices

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.

Page 32: MELJUN CORTES Java best practices

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.

Page 33: MELJUN CORTES Java best practices

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.

Page 34: MELJUN CORTES Java best practices

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.

Page 35: MELJUN CORTES Java best practices

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?”

Page 36: MELJUN CORTES Java best practices

Use Javadoc LiberallyUse Javadoc Liberally Provide as much documentation about Provide as much documentation about

your code as possible.your code as possible.

Page 37: MELJUN CORTES Java best practices

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?

Page 38: MELJUN CORTES Java best practices

ReferencesReferences ““Effective Java” by Joshua BlochEffective Java” by Joshua Bloch Refactoring by Martin FowlerRefactoring by Martin Fowler http://javapractices.comhttp://javapractices.com