How to mark logical sections of code in Java comments?

JavaComments

Java Problem Overview


Java classes are generally divided into logical "blocks". Is there a convention to mark these sections? Ideally, it would be supported by the major IDEs.

I personally use this method:

//// Section name here ////

However, some editors seem to have problems with this.

As an example, in Objective-C code you can use this method:

#pragma mark -
#pragma mark Section name here

This will result in a menu in XCode that looks like this:

alt text

Java Solutions


Solution 1 - Java

For intellij/android studio there is an amazing solution.
Start with:
//region Description
and end with:
//endregion

The shortcut for that is in the menu you can open with Command+Alt+T (Mac) or Ctrl+Alt+T (Windows)

You can also add your own line for additional visual separation if you need it. The region can be contracted and expanded at will with the +/- buttons like any function. You can also navigate between regions with Command+Alt+Period (Ctrl+Alt+Period)

Source.

Example:

//region Parceler Implementation
//---------------------------------------------------------------------------------------
@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeParcelable(this.die, 0);
    dest.writeParcelable(this.dieSprite, 0);
}

private DieVm(Parcel in) {
    this.die = in.readParcelable(Die.class.getClassLoader());
    this.dieSprite = in.readParcelable(Sprite.class.getClassLoader());
}

public static final Parcelable.Creator<DieVm> CREATOR = new Parcelable.Creator<DieVm>() {
    public DieVm createFromParcel(Parcel source) {
        return new DieVm(source);
    }

    public DieVm[] newArray(int size) {
        return new DieVm[size];
    }
};
//---------------------------------------------------------------------------------------
//endregion

Solution 2 - Java

I personally use 80-chars line separators, like this :

public class Client {

	//================================================================================
	// Properties
	//================================================================================

	private String name;
	private boolean checked;

	//================================================================================
	// Constructors
	//================================================================================

	public Client() {
	}

	public Client(String name, boolean checked) {
		this.name = name;
		this.checked = checked;
	}

	//================================================================================
	// Accessors
	//================================================================================

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean isChecked() {
		return checked;
	}

	public void setChecked(boolean checked) {
		this.checked = checked;
	}

}

Of course, this may seem a bit overkill for such a small POJO, but believe me, it proved very useful in some huge projects where I had to browse through big source files and quickly find the methods I was interested in. It also helps understand the source code structure.

In Eclipse, I have created a set of custom templates (Java -> Editor -> Templates in Eclipse's Preferences dialog) that generate those bars, eg.

  • sepa (SEParator for Accessors)
  • sepp (SEParator for Properties)
  • sepc (SEParator for Constructors)
  • etc.

I also modified the standard "new class" template (Java -> Code Style -> Code Templates in Eclipse Preferences screen)

Also, there is an old Eclipse plugin called Coffee-bytes, which enhanced the way Eclipse folds portions of code. I don't know if it still works, but I remembed one could define arbitrary foldable zones by adding special comments, like // [SECTION] or something. It might still work in recent Eclipse revisions, so take a look.

Solution 3 - Java

Eclipse defines an @category javadoc annotation (scroll to section marked "Category support") which enables filtering by category in the outline view. Not exactly what you want. I'm suprised nobody has written an Eclipse plugin which offers a view like your screen shot.

Solution 4 - Java

I liked that also when i was using xcode. For eclipse i use ctrl+o (quick outline) to navigate through a Java class.

Solution 5 - Java

Using unnecessary comments/markers in the code to help working may not be a good practice. I have little idea about xcode and java development but all major IDE's support finding the members with out any special markers like eclipse shows the methods and members using outline view which can be triggered using ctrl+O, Intellij (which I prefer using more on mac and had a community edition too) has the same outline concept and can be quickly accessed using (ctrl + f12). So my point here is don't use any unnecessary mark up in the code as all (or atleast good/sane) IDE's can do it automatically.

Solution 6 - Java

I would use javadoc; or use the following as a simple "separator" (single or 3 lines):

/** RecyclerOnItemClickListener */

/** 
 * RecyclerOnItemClickListener
 */

So that in IDE it appears in a different color other than the unobtrusive commented grey.

Solution 7 - Java

As far as I know there is no such thing as a supported specification for grouping class members together. You can use what-ever comment convention you like, but chances are it will not be supported by any tool.

It is better to group related members into separate class via inheritance or aggregation. This is considered a good OOP style

Solution 8 - Java

In addition to Andrey's answer provided, to use //region //endregion, we insert [BigAscii letters][1] in major code sections. When scrolling fast, it really stands out. One drawback of this approach is that I cannot search for it so you'd need to add a search term just below the "banner" like I do below.

> Blockquote

//    _      _____          _____                  _   _
//   | |    |  __ \   /\   |  __ \      /\        | | | |
//   | |    | |  | | /  \  | |__) |    /  \  _   _| |_| |__
//   | |    | |  | |/ /\ \ |  ___/    / /\ \| | | | __| '_ \
//   | |____| |__| / ____ \| |       / ____ \ |_| | |_| | | |
//   |______|_____/_/    \_\_|      /_/    \_\__,_|\__|_| |_|
//
//   Search here with: LDAP Auth

[1]: http://patorjk.com/software/taag/#p=display&c=c%2B%2B&f=Big&t=LDAP Auth

Solution 9 - Java

A modern IDE allows you to view your code in many different ways, and even reorganize it. Eclipse even allows you to view the definition of the code you have the cursor on in another panel.

Any automatic reorganizing of your code, will cause such markup to break down.

If you want grouping then consider putting things belonging together in the same class, and things not belonging together in different classes.

Solution 10 - Java

If you can cluster your methods, do another class specifically for that concept that you want to capture in a section. Go ahead, creating files is free.

Solution 11 - Java

For IntelliJ i do like:

        public void ________________INIT__________________() {};

looking pretty in file structure!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrederikView Question on Stackoverflow
Solution 1 - JavaAndrey PetrovView Answer on Stackoverflow
Solution 2 - JavaOlivier CroisierView Answer on Stackoverflow
Solution 3 - JavabasszeroView Answer on Stackoverflow
Solution 4 - JavakukudasView Answer on Stackoverflow
Solution 5 - JavaTeja KantamneniView Answer on Stackoverflow
Solution 6 - Javasuperarts.orgView Answer on Stackoverflow
Solution 7 - JavaartembView Answer on Stackoverflow
Solution 8 - JavaManabu TokunagaView Answer on Stackoverflow
Solution 9 - JavaThorbjørn Ravn AndersenView Answer on Stackoverflow
Solution 10 - JavaLay GonzálezView Answer on Stackoverflow
Solution 11 - Javauser170317View Answer on Stackoverflow