MELJUN CORTES JAVA_BestPractices

download MELJUN CORTES JAVA_BestPractices

of 38

Transcript of MELJUN CORTES JAVA_BestPractices

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    1/38

    Java

    Best Practices

    Java Fundamentals &

    Object-Oriented Programming

    MELJUN CORTES, MBA,MPA,BSCS

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    2/38

    Contents

    Bad Practices

    Good Practices

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    3/38

    Bad Practices

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    4/38

    Duplicate Code

    Every time you need to make a change in theroutine, you need to edit it in several places.

    Called Shotgun Surgery. Follow the Once and Only Once rule.

    Dont copy-paste code!

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    5/38

    Accessible Fields

    Fields should always be private except forconstants.

    Accessible fields cause tight coupling.

    Accessible fields are corruptible.

    If a field needs to be accessed, use getand set convention.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    6/38

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    7/38

    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 stuff

    return x;

    }

    int method() {

    int x = 0;

    ... // do some stuff

    return x;

    }

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    8/38

    Initializing Strings with new

    Dont:

    String str = new String(This is bad.);

    Do:

    String str = This is good.;

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    9/38

    Using floats and doubles forcurrency calculations

    Binary numbers cannot exactlyrepresent decimals.

    Use BigDecimal for currencycalculations.

    ...using the constructor that takes aString as a parameter.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    10/38

    Returning null

    Causes NullPointerExceptions.

    Instead, return

    empty ob jects

    cus tom-made Null Objects

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    11/38

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    12/38

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    13/38

    Subclassing for Functionality

    Implementation inheritance is difficultto debug.

    Ask yourself: Is this a kind of?

    Alternatives:

    Prefer interface inheritance.

    Prefer composition over inheritance.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    14/38

    Empty Catch Block

    No indication that an exception

    has occurred!

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    15/38

    Using ExceptionsUnexceptionally

    Use exceptions only for exceptionalconditions.

    Bad:

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

    // do something}

    Good:

    if (index < 0 || index >= arr.size()) {// do something} else {

    obj = arr[index];}

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    16/38

    Excessive Use of Switches

    Use of if and switch statements

    usually a sign of a breach of theOne Responsibility Rule.

    Consider polymorphism instead.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    17/38

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    18/38

    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.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    19/38

    System.exit

    Only use in stand-alone applications.

    For server applications, this might shut

    down the whole application container!

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    20/38

    Good Practices

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    21/38

    Validate YourParameters

    The first lines of code in a method should check ifthe parameters are valid:

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

    if (str == null) {throw new IllegalArgumentException(str cannot benull);}if (index >= arr.size || index < 0) {

    throw new IllegalArgumentException(index

    exceedsbounds of array);

    }

    }

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    22/38

    Create Defensive Copies

    Create local copies, to preventcorruption.

    void myMethod (List listParameter) {

    List listCopy = new ArrayList(listParameter);

    listCopy.add(somevar);

    ...

    }

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    23/38

    Modify Strings withStringBuilder

    String objects are immutable. You may think youre changing a

    String, but youre actually creating a

    new object. Danger of OutOfMemoryErrors.

    Poor peformance.

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

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    24/38

    Favor Immutability

    If your objects dont changeeasier to debug.

    Fields are private and final.

    No setters, only getters.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    25/38

    Prefer final for Variables

    Usually, variables / parameters do not

    need to change.

    Get into the habit of using f inalby default,and make a variable not final only when

    necessary.

    D l V i bl J t

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    26/38

    Declare Variable Just

    Before Use

    Easier to read and refactor.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    27/38

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    28/38

    Follow Code Conventions

    Improves readability

    For other programmers.

    For you rsel f .

    Readability means

    less bugs.

    easier to debug.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    29/38

    Refer to Objects by Interfaces

    Maintainability - changes in implementation needonly be done at a single point in code

    Polymorphismimplementation can be set atruntime.

    // bad :

    A rrayList l ist = new ArrayL ist();

    l ist .add(somevar);

    // good :

    Lis t l ist = new A rrayList();

    l ist .add(somevar);

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    30/38

    Consider Using Enums insteadof Constants

    Constants:

    Not typesafe

    No namespace

    You often need to prefix constants to avoidcollisions

    Brittleness When you change the order, you need to

    change a lot of code.

    Printed values are uninformative

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    31/38

    Buffer I/O Streams

    Requesting OS for I/O resources is

    expensive.

    Buffering provides significant increase in

    performance.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    32/38

    Close Your I/O Streams

    If you dont close, other applications may

    not be able to use the resource.

    Close using the finally block in a try-

    catch.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    33/38

    If You Override equals()

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    34/38

    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 andMaps may not work.

    There are many IDE plug-ins and external

    libraries that can help you with this.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    35/38

    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 stillunderstand my code?

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    36/38

    Use Javadoc Liberally

    Provide as much documentation aboutyour code as possible.

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    37/38

    Bubble-Up Exceptions

    If code is not part of the user interface, itshould 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?

  • 8/10/2019 MELJUN CORTES JAVA_BestPractices

    38/38

    References

    Effective Java by Joshua Bloch

    Refactoring by Martin Fowler

    http://javapractices.com