1

When I began implementing a class in my system (let's call it A), I realized I needed some kind of object that does something. So I needed a new class (let's call it B), but I made it a private static class of A.

Now, B is still only ever used by A, but A grew much bigger. Including the code for B, it's 320 LoC long.

The question is, should I move B outside of A, into a separate package-private class? It's still only ever used by A, but since A is getting big I think I should split it into smaller parts.

Stephen
  • 8,868
  • 3
  • 31
  • 43
Aviv Cohn
  • 21,538

2 Answers2

1

The size of class A doesn't really matter, provided it follows the following criteria:

  1. It's only responsible for one thing
  2. It groups logically related functionality

As long as that criteria is fulfilled, you do not need to split up the functionality into separate classes. The difficulty is in determining whether the class is actually responsible for more than one thing.

I tend to avoid private classes as they clutter up code. The only reason I would create a private class usually is for a data container for temporary data which is only used by that class. In pretty much every other circumstance I would create classes separately from each other.

Stephen
  • 8,868
  • 3
  • 31
  • 43
0

I try to avoid inner classes in general unless they are simple lambdas, listeners with one or two lines of code, etc.

Once an inner class has a life of its own and performs more complex functions, I refactor it into its own top-level class. I will use either a standard interface or create my own for the class that used to enclose it (A). I then construct the B class and pass in a reference to the interface that A now implements and is used by B.

While A and B are tightly coupled, they probably do not need to be. Severing that coupling and using interfaces and references rather than an implicit outer-class this pointer/reference now means B is one step closer to being reusable. There is now an abstraction between them.

Often the reason for introducing another class is that the enclosing class needs to do additional work that it cannot do itself. That additional work is likely (in my experience) to violate the Single Responsibility Principle. Moving it into an inner class is one step toward fixing that, but is (in my opinion) a suboptimal fix. Refactoring as I mentioned above will fix the tight coupling and "multiple responsibility" concerns.

One final reason to split into multiple top-level classes is it makes the source files shorter. This has nothing to do with OOP principles and is purely aesthetic.