Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the convention for the placement of inner classes in java? [closed]

I have a utility class called Util. Within it I have a MatrixUtil static inner class (among others). Where are inner classes located by convention?

Should MatrixUtil go after Util fields but before Util methods? I was unable to find a java convention on this. Perhaps I missed it in the API...

Anyways, this is the structure I am talking about.

public class Util
{
    public static final Vector3f myField;

    public static class MatrixUtil
    {
        public static void myMatrixUtilMethod()
        {
            return;
        }
    }

    public static float myUtilMethod()
    {
        return;
    }
}

Code works either way but I'd like to know the proper convention for this. Thanks.

like image 264
guyfleeman Avatar asked Nov 24 '13 20:11

guyfleeman


People also ask

What is the naming structure for an inner class in Java?

Local classes, also called inner classes, are defined in a block — a group of statements between balanced braces. For example, they can be in a method body, a for loop, or an if clause. The scope of the local class is restricted within the block just like the local variables.

Can inner class be placed within a method in Java?

In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.

What is convention in Java programming?

Java naming convention is a rule to follow as you decide what to name your identifiers such as class, package, variable, constant, method, etc. But, it is not forced to follow. So, it is known as convention not rule. These conventions are suggested by several Java communities such as Sun Microsystems and Netscape.


1 Answers

I always go for the principle of least surprise.

When a developer opens your source they will probably be placed at the top of the source. So first comes the important stuff.

As they scroll down your source they should next see the less important stuff.

Finally, at the end they should find the unimportant stuff.

I leave to you the decision as to whether the inner class is important or less important or unimportant.

I would certainly consider inner classes pretty close to unimportant especially if they are private - however, if is some kind of factory class that creates and manipulates objects of that type then they could be considered important.

In your case - you seem to be using an inner class to sub-categorize methods - I would not use an inner class to do that, I would use a nested package such as com.....util.matrixutil.

like image 130
OldCurmudgeon Avatar answered Sep 19 '22 05:09

OldCurmudgeon