java tutorial- do's and don'ts of java programming

54
Dr Java Workshop – By Satyarth Gaur We will cover the following areas: - Top 10 mistakes made by Java programmers – How to avoid them - Core Java- Best Practices – This covers good and bad practices both - How to prepare for Java Interviews and Sun Java Exams

Upload: keshav-kumar

Post on 26-May-2015

1.600 views

Category:

Technology


0 download

DESCRIPTION

Whether you program regularly in Java, and know it like the back of your hand, or whether you’re new to the language or a casual programmer, you’ll make mistakes. The purpose of this webinar is to talk about some Do's and Don'ts of Java programming. The webinar will cover the following areas: - Top 10 mistakes made by Java programmers – How to avoid them - Core Java- Best Practices – This covers good and bad practices both- How to prepare for Java Interviews and Sun Java Exams- Q&A Key learnings from this webinar: - It will benefit both junior and senior java professionals so that they don’t make common errors- Clarity of concepts of Java- Better awareness of best practices of Java

TRANSCRIPT

Page 1: JAVA Tutorial- Do's and Don'ts of Java programming

Dr Java Workshop – By Satyarth Gaur

We will cover the following areas: - Top 10 mistakes made by Java programmers –

How to avoid them   - Core Java- Best Practices – This covers good

and bad practices both- How to prepare for Java Interviews and Sun

Java Exams

Page 2: JAVA Tutorial- Do's and Don'ts of Java programming

Top Ten Errors Java Programmers Make

SATYARTH [email protected]

Page 3: JAVA Tutorial- Do's and Don'ts of Java programming

Accessing non-static member variables from static methods (such as main)

public class StaticDemo { public String my_member_variable = "somedata"; public static void main (String args[]) {

// Access a non-static member from static method

System.out.println ("This generates a compiler error" +

my_member_variable ); } }

Page 4: JAVA Tutorial- Do's and Don'ts of Java programming

Contd..

public class NonStaticDemo{ public String my_member_variable = "somedata";  public static void main (String args[]) { NonStaticDemo demo = new NonStaticDemo();  // Access member variable of demo System.out.println ("This WON'T generate an

error" + demo.my_member_variable ); }}

Page 5: JAVA Tutorial- Do's and Don'ts of Java programming

Mistyping the name of a method when overriding

If you mistype the name, you're no longer overriding a method - you're creating an entirely new method, but with the same parameter and return type.

Page 6: JAVA Tutorial- Do's and Don'ts of Java programming

Comparison assignment (  = rather than == )

Fortunately, even if you don't spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : "Can't convert xxx to boolean", where xxx is a Java type that you're assigning instead of comparing.

Page 7: JAVA Tutorial- Do's and Don'ts of Java programming

Comparing two objects ( == instead of .equals) When we use the == operator, we are actually

comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.

Ex. String Comparison String abc = "abc"; String def = "def";  // Bad way if ( (abc + def) == "abcdef" ) { ….. }

// Good way if ( (abc + def).equals("abcdef") ) { ..... }

Page 8: JAVA Tutorial- Do's and Don'ts of Java programming

Confusion over passing by value, and passing by reference

When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value. That means that a copy of the data type is duplicated, and passed to the function. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only.

Page 9: JAVA Tutorial- Do's and Don'ts of Java programming

Contd.. When you pass a Java object, such as an

array, a vector, or a string, to a function then you are passing by reference.So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent

Page 10: JAVA Tutorial- Do's and Don'ts of Java programming

Writing blank exception handlers public static void main(String args[])

{    try {

// Your code goes here..    }    catch (Exception e)    {

System.out.println ("Err - " + e );    }

}

Page 11: JAVA Tutorial- Do's and Don'ts of Java programming

Forgetting that Java is zero-indexed

If you've come from a C/C++ background, you may not find this quite as much a problem as those who have used other languages. In Java, arrays are zero-indexed, meaning that the first element's index is actually 0

Page 12: JAVA Tutorial- Do's and Don'ts of Java programming

Example Contd.. // Create an array of three stringsString[] strArray = new String[3]; // First element's index is actually 0strArray[0] = "First string"; // Second element's index is actually 1strArray[1] = "Second string"; // Final element's index is actually 2strArray[2] = "Third and final string";

Page 13: JAVA Tutorial- Do's and Don'ts of Java programming

Preventing concurrent access to shared variables by threads The simplest method is to make your variables

private (but you do that already,  right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner. Take the following accessor methods, which provide a safe way to change the value of a counter.

Page 14: JAVA Tutorial- Do's and Don'ts of Java programming

Contd..

public class MyCounter{private int count = 0; // count starts at zero

  public synchronized void setCount(int amount){

count = amount;}

public synchronized int getCount(){

return count;}

}

Page 15: JAVA Tutorial- Do's and Don'ts of Java programming

Capitalization errors While there's no silver bullet for

detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :-

all methods and member variables in the Java API begin with lowercase letters

all methods and member variables use capitalization where a new word begins e.g - getDoubleValue()

Page 16: JAVA Tutorial- Do's and Don'ts of Java programming

Capitalization errors While there's no silver bullet for

detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :-

all methods and member variables in the Java API begin with lowercase letters

all methods and member variables use capitalization where a new word begins e.g - getDoubleValue()

Page 17: JAVA Tutorial- Do's and Don'ts of Java programming

Null pointers

When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown.

The cause of null pointers can be varied, but generally it means that either you haven't initialized an object, or you haven't checked the return value of a function.

Page 18: JAVA Tutorial- Do's and Don'ts of Java programming

Java Best Practices

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

Dr Java Boot Camp – Satyarth GaurDr Java Boot Camp – Satyarth Gaur

Page 19: JAVA Tutorial- Do's and Don'ts of Java programming

Bad PracticesBad Practices

Page 20: JAVA Tutorial- Do's and Don'ts of Java programming

Duplicate Code!

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

• Don’t copy-paste code!

Page 21: JAVA Tutorial- Do's and Don'ts of Java programming

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 22: JAVA Tutorial- Do's and Don'ts of Java programming

Using Magic Numbers

Magic numbers are not readablefor (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 23: JAVA Tutorial- Do's and Don'ts of Java programming

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 24: JAVA Tutorial- Do's and Don'ts of Java programming

Initializing Strings with “new”

Don’t:String str = new String(“This is

bad.”);

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

Page 25: JAVA Tutorial- Do's and Don'ts of Java programming

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 26: JAVA Tutorial- Do's and Don'ts of Java programming

Returning null

Causes NullPointerExceptions.

Instead, return… empty objects custom-made “Null

Objects”

Page 27: JAVA Tutorial- Do's and Don'ts of Java programming
Page 28: JAVA Tutorial- Do's and Don'ts of Java programming
Page 29: JAVA Tutorial- Do's and Don'ts of Java programming

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 30: JAVA Tutorial- Do's and Don'ts of Java programming

Empty Catch Block

No indication that an exception has occurred!

Page 31: JAVA Tutorial- Do's and Don'ts of Java programming

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 32: JAVA Tutorial- Do's and Don'ts of Java programming

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 33: JAVA Tutorial- Do's and Don'ts of Java programming

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 34: JAVA Tutorial- Do's and Don'ts of Java programming

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 35: JAVA Tutorial- Do's and Don'ts of Java programming

System.exit

Only use in stand-alone applications.

For server applications, this might shut down the whole application container!

Page 36: JAVA Tutorial- Do's and Don'ts of Java programming

Good PracticesGood Practices

Page 37: JAVA Tutorial- Do's and Don'ts of Java programming

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 38: JAVA Tutorial- Do's and Don'ts of Java programming

Create Defensive Copies

Create local copies, to prevent corruption.

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

listCopy.add(somevar);...

}

Page 39: JAVA Tutorial- Do's and Don'ts of Java programming

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 40: JAVA Tutorial- Do's and Don'ts of Java programming

Favor Immutability

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

Fields are private and final. No setters, only getters.

Page 41: JAVA Tutorial- Do's and Don'ts of Java programming

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 42: JAVA Tutorial- Do's and Don'ts of Java programming

Declare Variable Just Before Use

Easier to read and refactor.

Page 43: JAVA Tutorial- Do's and Don'ts of Java programming

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 44: JAVA Tutorial- Do's and Don'ts of Java programming

Follow Code Conventions

Improves readability For other programmers. For yourself.

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

Page 45: JAVA Tutorial- Do's and Don'ts of Java programming

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 46: JAVA Tutorial- Do's and Don'ts of Java programming

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 47: JAVA Tutorial- Do's and Don'ts of Java programming

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 48: JAVA Tutorial- Do's and Don'ts of Java programming

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 49: JAVA Tutorial- Do's and Don'ts of Java programming

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.

Page 50: JAVA Tutorial- Do's and Don'ts of Java programming

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 51: JAVA Tutorial- Do's and Don'ts of Java programming

Use Javadoc Liberally

Provide as much documentation about your code as possible.

Page 52: JAVA Tutorial- Do's and Don'ts of Java programming

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 53: JAVA Tutorial- Do's and Don'ts of Java programming

Best Sites for Java Examples,Code Samples,Tutorials and Interview Preparation www.roseindia.net

www.vaannila.com

www.java2s.com

www.javaprepare.com SCJP

Page 54: JAVA Tutorial- Do's and Don'ts of Java programming

Contd.. www.techinterviews.com http://www.jguru.com

www.coderanch.com

SCJP 5 /6 By Kathy Sierra -- E book http://javapractices.com