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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With