Java Best Practices
- Avoid creating unnecessary objects and always prefer to do Lazy Initialization, Create object only if needed.
- Never make an instance/object fields of class public, Ensure to give right access specifier based on requirement.
- Try to make classes immutable, This can be achieved by having private constructor and have public static method to get the instance of the class.
- Try to prefer Interfaces instead of Abstract classes
- Always try to limit the scope of Local variable, This can be achieved by declaring variable just before use.
- Use existing libraries instead of writing your own framework from scrach.
- Wherever possible user primitive data types and avoid unnecessary usage of wrapper class .
For eg : use 'int' data type rather than 'Integer' just to hold some integer values.
- Never use String constructor, For eg : String name ="Fortune Minds" is best practice , String name = new String("Fortune Minds") is not a best practice.
Standard Java Naming Conventions
The below list outlines the standard Java naming conventions for each identifier type, Give meaningful name for every identifier you define/create in Java.
Packages: Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:
package com.fm.employee
package mathutil
In software companies and large projects where the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features:
package com.mycompany.utilities
package org.bobscompany.application.userinterface
Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:
class Customer
class Account
Interfaces: Starts with Upper case and follows CamelCase. They tend to have a name that describes an operation that a class can do:
interface Comparable
interface Enumerable
Note that some programmers like to distinguish interfaces by beginning the name with an "I":
interface IComparable
interface IEnumerable
Methods: Names should be in mixed case. Use verbs to describe what the method does:
void calculateTax()
string getSurname()
Variables: Names should be in mixed case. The names should represent what the value of the variable represents: Make sure to give meaningful names
string firstName
int orderNumber
Only use very short names when the variables are short lived, such as in for loops:
for (int i=0; i<20;i++)
{
//i only lives in here
}
Constants: Names should be in uppercase.
static final int DEFAULT_WIDTH
static final int MAX_HEIGHT
No comments:
Post a Comment