best practices. contents bad practices good practices

38
Best Practices

Upload: emory-glenn

Post on 03-Jan-2016

266 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Best Practices. Contents Bad Practices Good Practices

Best Practices

Page 2: Best Practices. Contents Bad Practices Good Practices

Contents

• Bad Practices• Good Practices

Page 3: Best Practices. Contents Bad Practices Good Practices

Bad PracticesBad Practices

Page 4: Best Practices. Contents Bad Practices Good Practices

Duplicate Code!

• Every time you need to make a change in the routine, you need to edit it in several places.

–Called “Shotgun Surgery”.

• Follow the “Once and Only Once” rule.

• Don’t copy-paste code!

Page 5: Best Practices. Contents Bad Practices Good Practices

Accessible Fields

• Fields should always be private except for constants.

• Accessible fields cause tight coupling.

• Accessible fields are corruptible.

• If a field needs to be accessed, use “get” and “set” convention.

Page 6: Best Practices. Contents Bad Practices Good Practices

Using Magic Numbers

• Magic numbers are not readable, and can lead to “Shotgun Surgery”.

for (int i = 1; i =< 52; i++) {j = i + randomInt(53 - i) – 1swapEntries(i, j)

}• 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: Best Practices. Contents Bad Practices Good Practices

Temporary Fields

• If a variable need not be shared across methods, 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: Best Practices. Contents Bad Practices Good Practices

Initializing Strings with “new”

• Don’t:String str = new String(“This is bad.”);

• Do:String str = “This is good.”;

Page 9: Best Practices. Contents Bad Practices Good Practices

Using floats and doubles for currency calculations

• Binary numbers cannot exactly represent decimals.

• Use BigDecimal for currency calculations.– ...using the constructor that takes a

String as a parameter.

Page 10: Best Practices. Contents Bad Practices Good Practices

Returning null

• Causes NullPointerExceptions.

• Instead, return…– empty objects

– custom-made “Null Objects”

Page 11: Best Practices. Contents Bad Practices Good Practices
Page 12: Best Practices. Contents Bad Practices Good Practices
Page 13: Best Practices. Contents Bad Practices Good Practices

Subclassing for Functionality

• Implementation inheritance is difficult to debug.

• Ask yourself: “Is this a kind of…?”

• Alternatives:– Prefer interface inheritance.– Prefer composition over inheritance.

Page 14: Best Practices. Contents Bad Practices Good Practices

Empty Catch Block

• No indication that an exception has occurred!

Page 15: Best Practices. Contents Bad Practices Good Practices

Using Exceptions Unexceptionally

• Use exceptions only for exceptional conditions.

• Bad:try {

obj = arr[index];} catch (ArrayIndexOutOfBoundsException) {

// do something}

• Good:if (index < 0 || index >= arr.size()) {

// do something} else {

obj = arr[index];}

Page 16: Best Practices. Contents Bad Practices Good Practices

Excessive Use of Switches

• Use of “if” and “switch” statements usually a sign of a breach of the “One Responsibility Rule”.

• Consider polymorphism instead.

Page 17: Best Practices. Contents Bad Practices Good Practices

instanceof

• If you’re using instanceof often, it probably means bad design.

• Consider adding an overridden method in supertype.

• instanceof should only be used – as validation prior to casting– when you have to used a poorly-written library

Page 18: Best Practices. Contents Bad Practices Good Practices

Static Methods

• Static methods are..– ...procedural

• They break encapsulation - the method should be part of the object that needs it

– ...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: Best Practices. Contents Bad Practices Good Practices

System.exit

• Only use in stand-alone applications.• For server applications, this might shut down

the whole application container!

Page 20: Best Practices. Contents Bad Practices Good Practices

Good PracticesGood Practices

Page 21: Best Practices. Contents Bad Practices Good Practices

Validate Your Parameters

• The first lines of code in a method should check if the parameters are valid:

void myMethod(String str, int index, Object[] arr) { if (str == null) {

throw new IllegalArgumentException(“str cannot be null”);

} if (index >= arr.size || index < 0) { throw new IllegalArgumentException(“index exceeds

bounds of array”); } …}

Page 22: Best Practices. Contents Bad Practices Good Practices

Create Defensive Copies

• Create local copies, to prevent corruption.

void myMethod (List listParameter) {List listCopy = new ArrayList(listParameter);listCopy.add(somevar);...

}

Page 23: Best Practices. Contents Bad Practices Good Practices

Modify Strings with StringBuilder

• String objects are immutable.– You may think you’re changing a

String, but you’re actually creating a new object.–Danger of OutOfMemoryErrors.– Poor peformance.

• StringBuilder is mutable.– All changes are to the same object.

Page 24: Best Practices. Contents Bad Practices Good Practices

Favor Immutability

• If your objects don’t change… easier to debug.

• Fields are private and final.

• No setters, only getters.

Page 25: Best Practices. Contents Bad Practices Good Practices

Prefer “final” for Variables

• Usually, variables / parameters do not need to change.

• Get into the habit of using final by default, and make a variable not final only when necessary.

Page 26: Best Practices. Contents Bad Practices Good Practices

Declare Variable Just Before Use

• Easier to read and refactor.

Page 27: Best Practices. Contents Bad Practices Good Practices

Initialize Variables Whenever Possible

• Helpful in debugging, makes it clear what initial value is.

• Makes sure you don’t use the variable before it’s ready for use.

Page 28: Best Practices. Contents Bad Practices Good Practices

Follow Code Conventions

• Improves readability– For other programmers.– For yourself.

• Readability means… –…less bugs.–…easier to debug.

Page 29: Best Practices. Contents Bad Practices Good Practices

Refer to Objects by Interfaces

• Maintainability - changes in implementation need only be done at a single point in code

• Polymorphism – implementation can be set at runtime.

// bad:ArrayList list = new ArrayList();list.add(somevar);

// good:List list = new ArrayList();list.add(somevar);

Page 30: Best Practices. Contents Bad Practices Good Practices

Consider Using Enums instead of Constants

• Constants:–Not typesafe–No namespace

• You often need to prefix constants to avoid collisions

– Brittleness• When you change the order, you need to change

a lot of code.– Printed values are uninformative

Page 31: Best Practices. Contents Bad Practices Good Practices

Buffer I/O Streams

• Requesting OS for I/O resources is expensive.• Buffering provides significant increase in

performance.

Page 32: Best Practices. Contents Bad Practices Good Practices

Close Your I/O Streams

• If you don’t close, other applications may not be able to use the resource.

• Close using the “finally” block in a try-catch.

Page 33: Best Practices. Contents Bad Practices Good Practices

Design Close to Domain

• Code is easily traceable if it is close to the business it is working for.

• If possible, name and group your packages according to the use cases.– Easy to tell client %completion of feature.– If user reports a bug, easier to find where it is.

Page 34: Best Practices. Contents Bad Practices Good Practices

If You Override equals() Override hashcode()

• Always make sure that when equals() returns true, the two object have the same hashcode.

• Otherwise, data structures like Sets and Maps may not work.

• There are many IDE plug-ins and external libraries that can help you with this.

Page 35: Best Practices. Contents Bad Practices Good Practices

Write Self-Documenting Code

• Comments are important, but…

• …even without comments your code should be easily readable.

• Ask yourself: “If I removed my comments, can someone else still understand my code?”

Page 36: Best Practices. Contents Bad Practices Good Practices

Use Javadoc Liberally

• Provide as much documentation about your code as possible.

Page 37: Best Practices. Contents Bad Practices Good Practices

Bubble-Up Exceptions

• If code is not part of the user interface, it should not handle its own exceptions.

• It should be bubbled-up to presentation layer…

• Show a popup?• Show an error page?• Show a commandline message?• Just log to an error log?

Page 38: Best Practices. Contents Bad Practices Good Practices

References

• “Effective Java” by Joshua Bloch• Refactoring by Martin Fowler• http://javapractices.com