Always use comments for your class, methods and variables
One of the best practice is using comments wherever posible. It will make your more understandable not only for you, but also for other developers who use your code.
The another advantage of using the comments is Java Doc. You can generate the Java Doc with a click of your mouse in any IDE which supports it like Eclipse.
Here are the few examples how to use comments in a better way.
Class Comments:
/**
* This class is used to perform operations on database at back-end.
* 1. Updating the database
* 2. Retrieving the data from database
*/
public class DatabaseOperations{
...
}
Method Comments:
/**
* This method is used to updating the database with the data
* given in the form of xml as a parameter.
* @params strXMLQuery the operation to be performed - in the form of xml.
* @returns boolean ...
*/
public boolean DatabaseUpdate(String strXMLQuery){
...
}
Variable Comments:
/** Status of the email with the database*/
private static final boolean DATABASE_STATE_EMAIL;
Always use meaning full names for your classes, methods and variables
Using meaningful names to your methods or variables not only simplyfies your coding tasks but also it makes your code more readable and undestandable.
For example, to declare a method which performs uploading a file from client machine to server, rather than declaring it as upload() declare it as uploadFileToServer() which conveys better meaning and simplifies the task of writing other methods which uses this method.
Do not extend a line to more than acceptable number of characters
The source files should be more readable in order to improve your productivity. One of such activity is writing code in a way such that no line shoud exxtend more than the screen width. i.e you should not drag the horizontal scrollbar in order to see the entire line.
For this you should follow strict line width. Say, Maximum 80 characters per line. If the line exceeds this width, simply devide that line into two parts. That can be done in two ways.
- Simplify your code so that one line of code can be written in two lines.
- Wrap the line to second line.
The first way will increase the ease in your code but at the same time you should be very careful. Using this technique excessively will make your code unmanageable.
boolean result = ((test1 != var1 && test2 == var2) || test3 > var3) && test4 == var4)
The above code can be written as below
boolean flag1 = (test1 != var1 & test2 == var2)
boolean flag2= flag1 || (test3 > var3)
boolean result = flag2 && (test4 == var4)
The second technique is far simpler and recomonded. For example, to write
String strResult = (null != strVar1 && null != strVar2 && strVar1.equalsIgnoreCase(strVar2)) ? true : false;
Simply expand it to multiple line as below..
boolean strResult = (null != strVar1 &&
null != strVar2 &&
strVar1.equalsIgnoreCase(strVar2)
) ? true : false;
Use a formatter like jelopy, if posible, to format the java files
Formatting the code using a tool will save lots of time as well as makes the code beautiful so that we can easily understand the code whenever we see it. The tools like Jaloppy are very useful in this aspect. They are not only freeware but also very powerful.
Always use Constants on left side while comparing with variables
Using variables on left side in a comparision will lead to unpredictable results in some cases. For example the code below explains how it is.
intResult = strVar01.equals(CONST_VAR02);
Tips while using multiple comparisions
Is it always suggested that before performing any opertions on an Object, first check posible errors which can be avoided. Say for example, you are comparing a string value to check whether it is empty or null. It is good to test for null first before empty value. This will avoid the null pointer exceptions.
If you use to test the empty value first, if the value is null then there is a probability to occur the error. If you test null value before that then this case can be avoided.
Example:
boolResult = (null == strVar01 strVar01.equals(""))?true:false;
Never use generic exception to catch exceptions
Always use the speccific exception for the perticular operation so that you can easily debug the error and easily solve if any bug is detected. This will drastically reduce the maintainability. It is a good habit to catch exceptions like null pointer exception wherever possible.
Example:
try{
intResult = Integer.parseInt(strVar01);
}catch(NullPointerException objNullPointerException){
//Do what you want to do..
}
Standard
Customization
Controller
Rich UI Components for the View Tier
Event Driven
Six phases in the life cycle of a JSF application
- Restore View Phase
- Apply Request Values Phase and Process Events
- Process Validations Phase and Process Events
- Update Model Values Phase and Process Events
- Invoke Application Phase and Process Events
- Render Response Phase
Restore View Phase
Apply Request Values Phase
- During this phase the request values of the components will be extracted by calling the decode method of the components and the new values retrieved will be stored locally to process further validations and conventions, if any. If the conversion of the new value fails, the error message will be queued in the FacesContext instance.
- If any events attached to any component, the corresponding event listener will get invoked during this phase. If the immediate flag set on any particular component, the associated event listener, validations and conversions will get executed during this phase itself. If any validation or conversion failed during the phase, the corresponding message will be queued in the FacesContext instance and the message will gets displayed during the Render Response phase.
- If the renderResponse method called on the current FacesContext instance during this phase, the implementation skips to the Render Response phase. This will be helpful in situations like when you want to skip executing the business logic when the data entered is invalid etc.
Process Validations Phase
- In this phase all validations attached to the components will get executed. Error messages for all failed validations will gets queued in the FacesContext instance and will get displayed during the Render Response phase.
- Any events that are queued for this phase will be processed and the corresponding event listener gets invoked. Similar to the Apply Request Values Phase, if any method during this phase (like validate, event handler methods) call the renderResponse method on the FacesContext instance, the executions will skips to the Render Response phase. This is true with the next phase as well.
- If you want to skip the current execution during any phase and render a different page (no jsf page) on a different web application, you can simply call the responseComplete method on the FaceContext instance.
Update Model Values Phase
- If the execution of the applications successfully completes the third phase means that the request data is valid and can be assigned to the model. So the data will be applied to the model and if any conversion fails, the application will skips to Render Response phase.
- Again, if any updateModes method or event listener method calls the renderResponse method, the executions skips to the last phase. Also any events registered will be broadcasted to the corresponding event listeners.
Invoke Application Phase
- This is the phase where you execute the actual business logic. The JavaServer Faces controller will invoke the application to to handle the form submissions. The component values validated, converted and applied to the model and you can use the model in your business logic.
- You can specify the next view to be rendered in this phase by returning the corresponding view mapping. See the navigation rules declaration in faces-config.xml file.
Render Response Phase
- This is the last phase of the JSF page execution life cycle. In this phase the result view will be rendered with the generated components and their corresponding values existing with the model.
-
J2SE 1.4 or higher (Depending on the version used)
-
Servlet 2.x
-
JSP 2.x
<listener><listener-class>com.sun.faces.config.ConfigureListener</listener-class></listener><context-param><param-name>javax.faces.CONFIG_FILES</param-name><param-value>/WEB-INF/faces-config.xml</param-value></context-param><servlet><servlet-name>Faces Servlet</servlet-name><servlet-class>javax.faces.webapp.FacesServlet</servlet-class><load-on-startup>0</load-on-startup></servlet><servlet-mapping><servlet-name>Faces Servlet</servlet-name><url-pattern>*.jsf</url-pattern></servlet-mapping>
<application><resource-bundle><base-name>com.yourcompany.app.resources.messages</base-name><var>msg</var></resource-bundle></application>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %><%@taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<managed-bean><managed-bean-name>BeanName</managed-bean-name><managed-bean-class>com.yourcompany.yourapp.beanpackage.BeanName</managed-bean-class><managed-bean-scope>request</managed-bean-scope></managed-bean>
<navigation-rule><navigation-case><from-outcome>NavigationRuleName</from-outcome><to-view-id>/path/pageName.jsf</to-view-id></navigation-case></navigation-rule>
"I am developer 1
You are developer 2"
public class Main {
public static void main(String[] args){
System.out.println("I am --> "+Programmers.Developer1.getMyName());
System.out.println("You are --> "+Programmers.Developer2.getMyName());
}
}
class Programmers{
static class Developer1{
static String getMyName(){
return "Developer 1";
}
}
static class Developer2{
static String getMyName(){
return "Developer 2";
}
}
}
requirements has changed and he has to print the below message.
"I am developer 2
You are developer 1"
The specifications/rules are given as below:
1) The solution should be done with minimal changes
2) No modifications are allowed to the Main, Developer1 and Developer2 classes
Try if you can do it. Else watch this space for the answer soon...