8

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.

guyfleeman
  • 463
  • 7
  • 22

2 Answers2

11

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.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • 1
    The only reason I avoided a nested package was because that package would only contain one Class. I was under the impression that packages should contain many related classes. For this reason I went with inner classes. Is this approach okay? – guyfleeman Nov 24 '13 at 21:09
  • 3
    @guyfleeman - A separate package containing just one class which in turn contains just one static method is not malformed - is is merely young. :) – OldCurmudgeon Nov 24 '13 at 21:14
  • 1
    Even if I have no intention of adding to it in the near future? – guyfleeman Nov 24 '13 at 21:15
  • 3
    Your intentions will change ... give it time. Besides - you should write your code to outlive you. – OldCurmudgeon Nov 24 '13 at 21:17
0

I think, the majority of the cases are:

  • Anonymous inner classes extracted into inner classes for better readability (i.e. java.util.ArrayList.SubList, JCF and Guava are full of these).
  • Small classes or interfaces related mostly to the enclosing class (i.e. java.util.Map.Entry).

I think it's the first time I see an utility inner class, but it's all up to the author. :-)

Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68