Better java with JDeveloper 10g

Better Java with JDeveloper 10g

By Harshad Oak

Java Integrated Development Environments (IDEs) are one of the most talked about things in the Java world today. There are many good development tools being used by Java developers today to make their Java tasks a little easier. NetBeans, JBuilder, Eclipse, IDEA, Websphere Studio, JDeveloper and so on are all competing for essentially the same Java developer?s attention and so each of them are trying to offer that little bit extra that will get users to prefer it over other IDEs. In this article we will look at some tools provided by Oracle JDeveloper 10g that make it stand out from the crowd of other IDEs.

JDeveloper 10g has good Java and J2EE capabilities but in this article we will talk about JDeveloper tools that go beyond standard Java development to give the developer more information about the code he has written and to suggest how that code can be improved. The JDeveloper tools we will discuss are CodeCoach, Memory Profiler, code audit tool and code metrics tool. All these tools are part of JDeveloper 10g and do not require any separate download or installation.

I will first create a simple standalone Java application and then use this application to demonstrate the usage of the following tools.

  • CodeCoach: As the name suggests, this is a tool that coaches the developer into writing good Java code.
  • Memory Profiler: This tool shows the memory consumption of your application.
  • Code Auditing: This is used to audit your code to check if it follows programming standards.
  • Code Metrics tools: This tool provides metrics about the code and can point out where your code exceeds the defined threshold limits.

Sample Application

JDeveloper 10g organizes all content in the form of workspaces and projects. So before you can write Java code for the application, you first need to create a new workspace and a project to work with. Create a new Application Workspace using the File> New option from the menu. Create the Application Workspace with application name as Javapro, package prefix as javapro and Application Template as Java Application [Default].

This will create a new workspace named Javapro and two projects within the workspace with the name Model and View.

The names Model and View come from the Model View Controller (MVC) pattern. So it is expected that the classes associated with the Model be placed in the project named Model and those that represent the View are in the project View. Check out for more information on the MVC pattern.

Now for the project Model, create a Java Class named JavaproTrial in the package javapro.model. Modify this class as shown in Listing 1.

Listing 1: JavaproTrial class

package javapro.model;

import java.io.FileWriter;

import java.io.IOException;

import java.text.SimpleDateFormat; public class JavaproTrial {

public JavaproTrial() { }

public static void main(String[] args) {

JavaproTrial codeCoachTrial = new JavaproTrial();

Object today = fetchTodaysDay();

if (today instanceof String) {

System.out.println("today is a String");

}

try {

FileWriter fw = new FileWriter("testfile.txt");

 for (int i = 0; i < 0; i++) {

     fw.write("Day is >>>" + today);

}

} catch (IOException e) {

//ignored

}

} public static String fetchTodaysDay() {

SimpleDateFormat sfInput = new SimpleDateFormat("EEEEEEEEE"); return sfInput.format(new java.util.Date());

}

}

The JavaproTrial class does not do anything special. It simply formats today?s date and writes the day to a file. This isn?t the ideal code for the task however I have included a few things like instanceof usage to help me easily demonstrate JDeveloper tool features.

Java Optimization

An oft-repeated statement about Java is that ?Java is slow?. Over the years, better hardware, better Java Virtual Machines and other improvements to Java have meant that Java no longer is that slow. However, it still hasn?t quite managed to shake off the tag of being the slow language. So performance is always a top issue on a manager?s mind whenever a new Java project is started. You can find numerous articles, books and tools that suggest ways to make Java better and faster.

Trying to optimize Java by painstakingly going through every line of code once coding is complete, might not be a worthwhile exercise as the performance return might not be worth the time and cost involved. I think the best way to good Java is to lay down unambiguous guidelines and standards right at the beginning and then monitor and modify your code using tools like the ones provided by JDeveloper.

Fix coding errors, introduce best practices, avoid common performance pitfalls, optimize or eliminate resource hungry code and you will soon have a top performing application. You will now look at the CodeCoach tool that will get you started with our optimizing exercise.

Note that you can configure JDeveloper?s Java optimization tools using the Project properties dialog for the project in question.

CodeCoach

CodeCoach is a tool to coach the developer into writing superior quality of Java code and avoid well-known Java pitfalls. You can use CodeCoach with any kind of Java and J2EE project and once you are done executing the code, CodeCoach will present you with suggestions on how the code can be improved as well as things that need to be fixed in the code. You can run CodeCoach by selecting the Run > CodeCoach option from the menu. The kinds of advice that CodeCoach offers are:

Class Advice: Class should be converted to final or static.

Method Advice: Method should be final, private or static.

Field Advice: Field is unused or it should be final, local, private or static.

Local Variable advice: Local Variable is unused or it should be final.

Memory Improvement advice: Advice related to the usage of ArrayList, BitSet, HashMap, Hashtable, StringBuffer, Vector or WeakHashMap.

Miscellaneous advice

So every time you ask CodeCoach to have a look at your code, it evaluates the code based on the types of advice it offers and then presents a report of its findings and recommendations. You can set the level of advice from 1-10, where 1 would mean only a few select types of advice are provided while 10 would mean that all types of advice are provided. You can also configure CodeCoach so that it looks only at classes from a certain package and excludes certain packages.

If you execute CodeCoach on the code in Listing 1 with the level set to 10, the result is as shown in Figure 1.

JDeveloper Code Coach Results

Figure 1: CodeCoach?s suggestions for improving your Java code.

CodeCoach not only picks errors in the code like unnecessary usage of instanceof or unused variables but you can also easily fix most of these errors by right clicking and choosing the Apply Fix To Source option. I would suggest that you use CodeCoach right from the early stages of the project and if you are using it with a big application with multiple code execution flows, try and execute all flows because maximum code coverage will mean better quality of advice from CodeCoach. You will now look at the Code auditing tool that can save you precious man-hours otherwise spent on reviewing Java code.

Code Auditing

Peer review of code is a common and useful practice however it should be focused on finding logic errors that can be picked only by another team member who has a sound understanding of the system. A tool like JDeveloper?s audit tool should pick programmer errors like missing Javadoc comments or non-adherence to naming standards. While CodeCoach analyzed and suggested changes based on how the code performed on execution, the code auditing tool performs a static audit of the code without a need to actually execute the code.

You can use the Run> Audit option from the menu to run the audit tool. The audit tool checks for adherence to programming standards. The level and kind of audit is based on the audit profile you select. The audit tool can check for things like missing Javadoc, non-adherence to naming standards and improper exception handling. For example if you use the audit tool for our example in Listing 1, the result is as shown in Figure 2. What you get are seven low priority Javadoc violations, three medium priority violations and one high priority exception handling violation for the case where you have ignored the IOException that is caught. The audit tool suggests that you either handle the exception or rethrow it.

JDeveloper Audit tool Results

Figure 2 Audit results based on a static analysis of code

You can select the rules that the audit tool should check for as well as create new profiles based on your selection.

Code Metrics

JDeveloper provides a code metrics measurement tool that can be used to perform a quantitative analysis of your code. This tool can be run using the Run > Measure option from the Menu. This can be used to measure the following:

Depth of Inheritance Tree: This shows how tall the inheritance hierarchy is. So in the case of the example in Listing 1, as the class only extends the java.lang.Object class that is at the top of the Java hierarchy, the DIT is 2.

Cyclomatic complexity: This value depicts the branching complexity of a class or method. If your code has got too complex to handle, this value will be able to raise the red flag in time.

Number of Statements: The number of Java statements in a method, class, or other construct.

If you set a rule that no method in an application should be more than ?x? number of lines and inheritance should never be more than ?y? levels, you can easily check that using the metrics tool. This would ensure that a certain quality of code is maintained throughout the application. On using the metrics tool for the code in Listing 1, you will get the results as shown in Figure 3.

JDeveloper Metrics tool Results

Figure 3.Metrics results for the code in Listing 1.

You will now look the various JDeveloper profilers that can help you get a better understanding of how your code actually performs.

Profilers

JDeveloper provides three profilers, namely Event Profiler, Execution Profiler and Memory Profiler. The Event Profiler requires that calls to a Profiler API are inserted in your code and is more useful while developing application using the Oracle Application Development Framework (ADF). The other two profilers are what you will now take up as these can be used easily and are very useful while developing any kind of Java application.

Most profiling tools seem to have a strange ability of overwhelming the user with too much data. This often means that not much is achieved out of an application profiling exercise. That is why you need to be careful and not try to optimize every line of Java code and use every little statistic that the profiler provides. It is usually a small portion of code that takes the most time and consumes the most resources. So it makes sense to optimize these snippets and forget about the rest.

Memory Profiler

Most java performance tuning discussions revolve around optimizing memory usage of Java and ensuring that unnecessary objects do not consume too much memory and slow down the system. To perform any such memory optimization however you first need a report of what the actual memory consumption is. The JDeveloper memory profiler can help you here and display a visual analysis of how your application consumes memory.

Use the Run> Memory Profile option from the menu to use the memory profiler. If you run the memory profiler for the code in Listing 1, the result will be similar to what?s shown in Figure 4. The display will show many details of memory consumed by the application like the number of objects created and the size of objects. The profiler captures snapshots after a specified duration so you can also see how memory consumption changes over the life of the application.

You could check if an unexpected number of instances of a particular class are being created or if a certain class is taking up too much memory. Once you isolate such classes and usages, you could manually review and optimize them. You could also configure the profiler so that only classes from a certain package are monitored while other classes are not.

JDeveloper Memory Profiler

Figure 4 The Memory Profiler results showing the memory consumption for the application.

Execution Profiler

The execution profiler is used to time your application. This profiler will show how much time each method is taking and based on this you would know which methods to focus your optimization efforts on. That would be a feasible approach especially for projects that are running on tight schedules .Having said that, does anybody know of projects that don?t run on tight schedules?

Use the Run> Execution Profile option in the menu to use the execution profiler. Figure 5 shows the results on running the Execution profiler for the code in Listing 1. Note that not only is the time taken by each method shown but also the methods called from that method and the time that those methods took. So the next time you think that a particular flow in the application seems unacceptably slow, try monitoring that flow using the execution profiler and then optimize the methods that are taking the most time.

JDeveloper Execution Profiler

Figure 5 The Execution Profiler that shows the time taken by methods in the application.

Summary

In this article you looked at the CodeCoach, Code Audit, Code Metrics and the profilers provided by JDeveloper 10g. All these tools provide valuable data that can be used to improve the quality of your Java code and develop a high quality application. You can download a fully functional trial of JDeveloper 10g at http://otn.oracle.com. Last but not the least, it is important that you do not leave the code optimization activity late in the project lifecycle as when schedules get very tight, code review and optimization seem to be the first casualty.

BIO:

Harshad authored the books Oracle JDeveloper 10g: Empowering J2EE Development, (Apress, 2004), Pro Jakarta Commons (Apress, 2004) and also coauthored Java 2 Enterprise Edition 1.4 Bible (Wiley & Sons, 2003).

Content Team

The IndicThreads Content Team posts news about the latest and greatest in software development as well as content from IndicThreads' conferences and events. Track us social media @IndicThreads. Stay tuned!

Leave a Reply