Download presentation
Presentation is loading. Please wait.
Published byRosanna O’Connor’ Modified over 8 years ago
1
Java Best Practices Java Fundamentals & Object-Oriented Programming MELJUN CORTES, MBA,MPA,BSCS
2
Contents Bad Practices Bad Practices Good Practices Good Practices
3
Bad Practices
4
Duplicate Code! Every time you need to make a change in the routine, you need to edit it in several places.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.Follow the “Once and Only Once” rule. Don’t copy-paste code!Don’t copy-paste code!
5
Accessible Fields Fields should always be private except for constants. Fields should always be private except for 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” and “set” convention. If a field needs to be accessed, use “get” and “set” convention.
6
Using Magic Numbers Magic numbers are not readable, and can lead to “Shotgun Surgery”. Magic numbers are not readable, and can lead to “Shotgun Surgery”. for (int i = 1; i =< 52; i++) { j = i + randomInt(53 - i) – 1 swapEntries(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) – 1 swapEntries(i, j) }
7
Temporary Fields If a variable need not be shared across methods, make it local. 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
Initializing Strings with “new” Don’t: Don’t: String str = new String(“This is bad.”); Do: Do: String str = “This is good.”;
9
Using floats and doubles for currency calculations Binary numbers cannot exactly represent decimals. Binary numbers cannot exactly represent decimals. Use BigDecimal for currency calculations. Use BigDecimal for currency calculations....using the constructor that takes a String as a parameter....using the constructor that takes a String as a parameter.
10
Returning null Causes NullPointerExceptions. Causes NullPointerExceptions. Instead, return… Instead, return… empty objects empty objects custom-made “Null Objects” custom-made “Null Objects”
13
Subclassing for Functionality Implementation inheritance is difficult to debug. Implementation inheritance is difficult 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.
14
Empty Catch Block No indication that an exception has occurred! No indication that an exception has occurred!
15
Using Exceptions Unexceptionally Use exceptions only for exceptional conditions. Use exceptions only for exceptional conditions. Bad: Bad: try { obj = arr[index]; } catch (ArrayIndexOutOfBoundsException) { // do something } Good: Good: if (index = arr.size()) { // do something } else { obj = arr[index]; }
16
Excessive Use of Switches Use of “if” and “switch” statements usually a sign of a breach of the “One Responsibility Rule”. Use of “if” and “switch” statements usually a sign of a breach of the “One Responsibility Rule”. Consider polymorphism instead. Consider polymorphism instead.
17
instanceof If you’re using instanceof often, it probably means bad design. If you’re using instanceof often, it probably means bad design. Consider adding an overridden method in supertype. Consider adding an overridden method in supertype. instanceof should only be used instanceof should only be used as validation prior to casting as validation prior to casting when you have to used a poorly-written library when you have to used a poorly-written library
18
Static 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.
19
System.exit Only use in stand-alone applications. Only use in stand-alone applications. For server applications, this might shut down the whole application container! For server applications, this might shut down the whole application container!
20
Good Practices
21
Validate Your Parameters The first lines of code in a method should check if the parameters are valid: 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) { if (str == null) { throw new IllegalArgumentException(“str cannot be null”); throw new IllegalArgumentException(“str cannot be null”); } if (index >= arr.size || index = arr.size || index < 0) { throw new IllegalArgumentException(“index exceeds throw new IllegalArgumentException(“index exceeds bounds of array”); } …}
22
Create Defensive Copies Create local copies, to prevent corruption. Create local copies, to prevent corruption. void myMethod (List listParameter) { List listCopy = new ArrayList(listParameter); listCopy.add(somevar);...}
23
Modify Strings with StringBuilder String objects are immutable. String objects are immutable. You may think you’re changing a String, but you’re actually creating a new object. You may think you’re changing a String, but you’re actually creating a 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.
24
Favor Immutability If your objects don’t change… easier to debug. If your objects don’t change… easier to debug. Fields are private and final. Fields are private and final. No setters, only getters. No setters, only getters.
25
Prefer “final” for Variables Usually, variables / parameters do not need to change. 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. Get into the habit of using final by default, and make a variable not final only when necessary.
26
Declare Variable Just Before Use Easier to read and refactor. Easier to read and refactor.
27
Initialize Variables Whenever Possible Helpful in debugging, makes it clear what initial value is. Helpful in debugging, makes it clear what initial value is. Makes sure you don’t use the variable before it’s ready for use. Makes sure you don’t use the variable before it’s ready for use.
28
Follow Code Conventions Improves readability Improves 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.
29
Refer to Objects by Interfaces Maintainability - changes in implementation need only be done at a single point in code Maintainability - changes in implementation need only be done at a single point in code Polymorphism – implementation can be set at runtime. Polymorphism – implementation can be set at runtime. // bad: ArrayList list = new ArrayList(); list.add(somevar); // good: List list = new ArrayList(); list.add(somevar);
30
Consider Using Enums instead of Constants Constants: Constants: Not typesafe Not typesafe No namespace No namespace You often need to prefix constants to avoid collisions Brittleness Brittleness When you change the order, you need to change a lot of code. Printed values are uninformative Printed values are uninformative
31
Buffer I/O Streams Requesting OS for I/O resources is expensive. Requesting OS for I/O resources is expensive. Buffering provides significant increase in performance. Buffering provides significant increase in performance.
32
Close Your I/O Streams If you don’t close, other applications may not be able to use the resource. If you don’t close, other applications may not be able to use the resource. Close using the “finally” block in a try- catch. Close using the “finally” block in a try- catch.
33
Design Close to Domain Code is easily traceable if it is close to the business it is working for. 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. If possible, name and group your 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.
34
If You Override equals() Override hashcode() Always make sure that when equals() returns true, the two object have the same 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. 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. There are many IDE plug-ins and external libraries that can help you with this.
35
Write Self-Documenting Code Comments are important, but… Comments are important, but… …even without comments your code should be easily readable. …even without comments your code should be easily readable. Ask yourself: “If I removed my comments, can someone else still understand my code?” Ask yourself: “If I removed my comments, can someone else still understand my code?”
36
Use Javadoc Liberally Provide as much documentation about your code as possible. Provide as much documentation about your code as possible.
37
Bubble-Up Exceptions If code is not part of the user interface, it should not handle its own 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… 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?
38
References “Effective Java” by Joshua Bloch “Effective Java” by Joshua Bloch Refactoring by Martin Fowler Refactoring by Martin Fowler http://javapractices.com http://javapractices.com
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.