Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to create an inner class for simple functionality?

There are some different opinions about simple inner classes, so I was wondering if there is a general consensus on what is good, and when to use private inner classes.

Here's an example that I found, and for which I think it's unnecessary to create an inner class. How good/bad practice is this?

private static class InternalCounter {
  int count;

  public InternalTabManager() {
    count = 0;
  }

  public int increment() {
    return count++;
  }
}

Mind you that in this particular case, one instance is kept in the surrounding class to keep track of a count.

like image 271
Steven De Groote Avatar asked Mar 30 '12 12:03

Steven De Groote


2 Answers

Yeah, in this case it does seem very unnecessary but if you have a case where there is some significant functionality and you know that no other class will ever need your inner class and it makes no sense to create a class more globally available then do use an inner class.

like image 98
Sachin Kainth Avatar answered Nov 06 '22 23:11

Sachin Kainth


It depends on the context. If this class could've been replaced with only a single static int, then I see no need to create an inner class.

On the other hand, this code would allow the parent class objects to share a reference to mutable int (using java.lang.Integer wouldn't be possible because is immutable).

The general advice/practice/pattern in this case are Keep It Simple and You Ain't Gonna Need it - if you don't need particular behaviour, don't make your code more complex than absolutely necessary.

So, if the question is: "Is it good practice to create an inner class for simple functionality, when it could have been solved in a simpler way" then the answer is NO.

like image 26
surfen Avatar answered Nov 06 '22 23:11

surfen