Saturday 3 November 2012

Formatting Code in eclipse

Eclipse has one beautiful feature to create a new rule to format code in eclipse and then export the same set of rules in XML format and import the same set of rules(XML File) and hence supports quick formatting.
It is used for formatting indentation,braces,white spacing,blank lines,new line,control statement,line wrapping and comment section.

Steps to follow to create a set of rules for formatting the code according to your business requirements are described below:-
  1. Go to Windows(Ctrl + W) -> Preferences(P).Now select Java -> Code Style -> Formatter.
    Formatting in Eclipse
    Formatting in Eclipse
  2. Create a new profile.Click on new and give a name to your profile.
    Creating new Formatting Profile
    Creating new Formatting Profile
  3. Set the rules for formatting by checking the rules that you want to use in your application.
    Create rules for formatting
    Create rules for formatting
    For formatting the width,Select Line Wrapping and set maximum line width and set line breaking policy and indentation policy for Class Declarations,Constructor Declarations,Method declarations,enum Declarations,Function Calls,Expressions,Statements.After setting all the formatting rules,click on apply -> OK.You can see the code after formatting preview in the Preview of the setting.
    Line Wrapping rules for formatting
    Line Wrapping rules for formatting
  4. Click on Export in top right corner to export these settings.Give a name to the file and Click on Save.
    Export these Settings
    Export these Settings
  5. To use these settings throughout the project team,import these settings by importing the XML file created above and click on Apply-> OK.
  6. If you want this setting to be applicable for a particular project.Go to Project Properties,select Formatter from Java Code Style and click on the check-box Enable project specific settings.Select the Active Profile and click on Apply.
    Project Specific Settings
    Project Specific Formatting
  7. Now to apply formatting to the code everytime you save a File,follow following process:-
    Under Preferences, choose Java -> Editor -> Save Actions. Check the "Perform the selected actions on save", and check the "Format source code" box.You can select the profile to be used for formatting from there.

  8. Njoy...:)