Pramati Technologies

Java Coding Aids

Overview

Pramati Studio provides features such as automatic code completion, navigation and code transformation. This chapter discusses the following coding aids for Java:

Formatting Java code layout

Studio parses the source code to analyze its structure based on which the formatting rules are applied. To format existing code based on these formatting rules, select File > IDE Options from the main menu. In the IDE Options panel, click Java which is listed under Code Layout.

Studio provides more than 80 Java formatting options categorized under three basic groups:

Select or unselect the options as required and preview the effect in the Preview window. Click Apply to apply settings to the current file; click Save and Close to apply settings to the Editor. Existing code is not effected unless the changes are applied manually. Press Ctrl + Alt + L to invoke formatting or select Code > Reformat from the main menu. Formatting maintains the logical breaks in a program. For example, If two block of code are separated by new lines, formatting will not change the number of new lines unless it is specified as a rule in Java formatting options.

Formatting can be applied on source codes with syntactic errors but the results may not as expected. This is because the parsed structure of the code is an error recovered version which may be different from the intended meaning. To avoid such results, correct the syntactic errors before formatting. Semantic errors do not cause such behavior during formatting.

Defining imports

Take a parameter PackageName and defines the way in which import layout should be in Editor. It is the sequence in which imports are added in a Java file. The sequence of nodes in the list panel is the same sequence for the packages to be added in import declaration of Java and JSP files. ALL_OTHER_IMPORTS option takes care of all packages that are not defined. This node cannot be deleted. It adds packages lexicographically.

BodyDeclaration

This option defines layout for field, constructor, method, classes, and interfaces in a Java or JSP file. Every list node in accepts the following data:

All fields, methods, constructors, and innertypes take care of the default layout. For any addition of body declaration, it follows the layout as defined. For example, if a method is added, it appears after existing methods in the file and before the inner types. The default layout cannot be deleted and is shown gray.

Code completion

In Studio, place the cursor at a suitable position and press Ctrl + Spacebar to view the available completions for various contexts in the Java file. Studio sugg ests all possible fields, methods, classes, and variables to complete the code. Select the suitable option and press Enter to add it to the code. Let us consider the completions provided by Studio for variable type String

Select a variable name; press Enter to insert it in the code; press Tab to replace the word at cursor with the selection. Java code completions available in Studio are:

Code completion is triggered automatically for some characters. For example, typing open bracket `(' after a method, triggers method parameter completion. Typing another character immediately this cancels the popup. If there is only one completion option, it is included in the code automatically. If there are no completion options for a particular request, the popup displays `No suggestions'.

Split string literals

Studio enables the user to split long strings into fragments. A string literal is enclosed in double quotes and represents operator symbols. For example, to split a long, existing print statement into fragments:

    1. Place the cursor at a suitable position within the string.
  1. Press enter. The string is split into two literals. The `quote' and `plus' characters appear automatically.

This simplifies the process of splitting existing strings and enables to complete strings as they are typed.

Online validation of sources

Java Assistant in Studio validates Java files open in Editor for errors and warnings. Validation is based on Java version 1.4 specifications. Any deviation from the specification is considered to be an error. Some events that trigger validation are:

When the code is being typed or modified in Editor, the errors, if any are underlined with a red squiggly. Errors are also displayed in the overview bar.

To view details, place the cursor on the squiggly or on the highlights in the Overview bar.

If Studio can provide any correction, it suggests to press Alt + Enter. Pressing Alt + Enter displays a list of actions or a single action. Select a suitable correction and press Enter to implement the suggestion.

Note: Clicking a highlight in the overview bar also takes the caret to the error statement.
Surrounding elements of code with constructs

Select a block of code and select Code > Surround With from the menu bar or press Ctrl + Alt + T.

Studio provides the following surround with options:

Note: Constructs are numbered from 1 to 9, 0, and A based on mnemonics.

To generate a construct in the code, select a suitable option from the dropdown, press Enter or double click on it. To cancel the operation, press Escape.

For surround with try/catch and try/catch/finally, Studio checks for exceptions thrown by the code fragment and wraps the block into the corresponding statement. For example, for a try/catch statement, the body of catch statement is filled with the corresponding code template

Implementing methods

In Editor, place cursor at the required method and select Code > Implement from the menu bar or press Ctrl + Alt + I. This is to select the accessible abstract methods from the base classes or interfaces to be implemented. It also enables the user to create stubs for these methods inside the class under consideration.

The methods displayed in the list are:

Note: To implement a method, which has been already implemented by a class in the class hierarchy, use the Override option (Code > Override...) from the menu bar instead of Implement.

For example, in CheckingBean.java, place the cursor at setcustomer_name(String customer_name). Pressing Ctrl + Alt + I displays the following methods:

All methods are selected for im plementation. Unselect a method by clicking on it if you do not want to implement it. To reorder, click Method Signature tab. Implement Methods functions in the context of a class. The caret must be placed inside the class during invocation.

This feature is designed to complete the contract of a class and to create concrete implementations. It can also be used for anonymous inner classes and used effectively for generating stubs of listener classes.

The Implements dialog contains the two fields displaying information on:

Select the methods to be implemented and click OK or press Ctrl + Enter. Methods once generated do not reappear in the list. If the method has a valid return type, it returns a default value of the same type as the super. If the method is abstract, a concrete implementation is provided by applying the following code generation rules:

If the return type is of primitive type, false is returned for boolean. For all other primitives, the appropriate primitive typecast from an int value of 0 is returned. The generated method body has a valid return statement, and gets compiled. The user may be required to change the code as per requirements.

Overriding methods

To override a method, place the cursor inside the method and select Code > Override from the menu bar or press Ctrl + Alt + O. It also enables you to generate stubs for these methods inside the class under consideration.

Override Methods panel displays a list of accessible methods from the base classes such as:

The list of methods is displayed against the class name containing them.

Select the methods to be overridden by clicking it; to select all methods in the panel, press Ctrl + A. Click OK or press Ctrl + Enter to generate appropriate method body in the class. Methods once generated do not reappear in the list. Ctrl + Alt + / browses for implementation of interfaces of the method.

If the method has a valid return type, it returns a default value of the same type as the super. If the method is abstract, a concrete implementation is provided by applying the code generation rules as mentioned in the Implement Methods section.

Creating accessor methods for fields

Select Code > Field Get/Set from the menu bar or press Ctrl + Alt + F to select the unimplemented getter and setter methods for all the fields in the class. It also enables the user to create the stubs for these methods inside the class under consideration.

Generate getter/setter methods for fields dialog consists a list of getter and setter methods and the corresponding field names.

Select a method by clicking it; to select all from the list, press Ctrl + A. Click OK or press Ctrl + Enter to generate selected accessor in the code. Methods once generated do not reappear in the list. The generated method follows the JavaBean rules. For a set method, the method body sets the value passed as a method argument to the field. For a get method, the generated method body returns the fields value.

This feature functions only in context of a class, and the caret must be placed inside the class during invocation. When the context is not understood, an error message, "the class under the caret could not be recognized" appears. The preferences set in IDE Options determine whether to generate tabs or spaces.

Javadoc stub generation

Studio enables you to generate Javadoc stubs for methods, fields, constructors, and classes within the Java code. Start a Javadoc and press enter. A new line appears and the Javadoc is closed, automatically. For example, type /** before a method and press enter. This adds @param, @return, or @throws to the Javadoc for the method and closes it. Pressing Enter inside a Javadoc adds the initial indent and * in the new line.

Viewing Javadoc

Studio enables you to view Javadoc for all JDK classes, methods, fields, and all project classes. Pressing Alt + F1 provides inline help for Javadocs.

This eliminates the need to create Javadoc HTMLs and viewing them in browsers. The help is cross-linked and details can be viewed on clicking a link.

Comment or uncomment lines in Java code

Select the lines to be commented in a file and press Ctrl + T. To uncomment that are line-commented, press Ctrl + Shift + T. To block-comment lines of code, press Ctrl + T. To uncomment the block-commented lines, press Ctrl + Shift + T. On Linux, to comment or uncomment, press the same keys as above, release them and press Ctrl.

Source code browsing

Source code browsing allows easy navigation and location of source code for objects in the code. It enables easy development and maintenance of code without the user having to keep track of declarations and references. User can browse through the class hierarchies, classes, functions, variables, types, and constants in the code.

Source code browsing can be invoked on fields, classes, constructors, and methods. It helps user to navigate to the appropriate file. In a simple case, the method being browsed for exists in the same Java file. In complex cases, the right implementation may be buried under a long class hierarchy, hidden by abstractions and overridden methods.

To invoke source code browsing, select Code > Browse Symbol from the main menu or press Ctrl + /. If there are multiple possible destinations, or if source code browsing cannot resolve the context uniquely, a window that enables the user to navigate to the appropriate file, appears. The navigation can be retraced back to the file from where the navigation started by using the keyboard shortcut Alt + Left Arrow. Press Alt + Left Arrow and Alt + Right Arrow to navigate to the previous caret position in the file.

Pressing Ctrl + Alt + / displays the implementation of the selected method for both Remote and Home interfaces.

Note: For large projects, Ctrl + Alt + / will take time.

The following cases demonstrate source code browsing:

    1. Foo foo = new Foo();
      Invoking source code browsing with the cursor placed anywhere inside Foo() takes the user to the line in Foo.java file where the class is declared.
  1. public Foo foo;
    Invoking source code browsing with the cursor placed anywhere inside Foo behaves similar to case 1.
  2. public void foobar()

{

foo.fooMethod();

}

Invoking source code browsing anywhere in the variable foo takes the user to variable foo in case 2 to indicate the declaration of the variable.

  1. foo.fooMethod();

Invoking source code browsing anywhere in the method fooMethod() takes the user to the file, Foo.java and highlights the line where fooMethod is defined. Source code browsing navigates only to the visible method. For example, if fooMethod is an inherited method and is declared in SuperFoo, which is in the class hierarchy of Foo, then cursor moves to the selected fooMethod in SuperFoo. In case of Ctrl + Alt + /, if Foo is a bean interface then the beans that have Foo as an interface are also shown in the popup, allowing navigation based on J2EE framework which goes beyond Java inheritance rules.

Functionality of source code browsing for normal Java classes

Consider for example a normal Java file, where class A extends class B, class B extends class C, class C extends class D, and class D implements interface E. We can have the following implementations of source code browsing:

Using declaration browser

The Declaration Browser enables to view and browse to methods, fields, inner classes in the current file. Select Code > Declaration Browser from the menu bar or press Ctrl + Shift + \ to view all fields, methods and classes for the current Java file.

To search for fields or methods, the user can start typing the initial characters of the required element.

Incremental search ensures that as the user types, the item which starts with the text written is highlighted in the browser. This also limits Up and Down navigation to the methods whose names start with the letters typed in the Search field.

Navigating between methods

Studio allows navigation between methods in the current file. For example, open Checking.java in Editor and place the cursor at the method debit. Select Code > Go To Previous Method from the menu bar or press Alt + Up Arrow on the keyboard to move the caret position from the current method to credit method, irrespective of class boundaries.

Select Code > Go To Next Method from the menu bar or press Alt + Down Arrow to move the caret from the current method to the next method, irrespective of class boundaries. To navigate to the previous/next method depending on class boundaries, press

Search facility

Studio provides the following search facilities in Java sources:

For our example, let us see how Find Usages option works in Studio. Place the cursor at a suitable element in the Java source; select Search > Find Usages from the main menu or press Ctrl + Alt + F7. Choose from option Interface, Method, Fields, Implementing classes, Extending interfaces where Studio should search for the usage of selected element.

Click Find to search for all occurrences of the element; Cancel cancels Find Usage command. Studio highlights `read' and `write' usages with different colors. The overview bar also has horizontal marks with respect to Java usages. Click on a mark or press Ctrl + Shift + F7 to move cursor to a particular usage location. Ctrl+Shift+alt+F7 highlights write usages and a corresponding mark appears in the overview bar.

Viewing search results

Search results are displayed in the output panel in a tree format.

To delete a result, select it in the output panel and press Delete on keyboard. This excludes the result, and also displays the corresponding row in grey color in Editor.

Press Ctrl + Shift + Q, or click Close button to close the tab in the output panel. To rerun the search, press Ctrl + Alt + R, or use the rerun button in the tab.

Note: For Find Usages, rerun does not apply.

Pramati Technologies  © Copyright   TOCPREVNEXTINDEX