Search code examples
javaclasstell-dont-askhygiene

Is creating a lot of private classes bad style?


I am doing a project in Java which has a lot of methods that require multiple return objects. For this I have to keep creating private classes which encapsulate the return objects. The objects make sense as a FontResult in my code will return the font name and the font size for example but constantly creating new objects for each return type I require feels wrong and somehow like I am trying to circumvent how Java should be written. Is this wrong or is it fine to do it like this? Should I be structuring my code in more of a tell-dont-ask approach?

An example is as follows:

String test = "hello";
StringResult result = getInformation(test);
int length = result.length;

private StringResult getInformation(String test) {
  int length = test.length();
  char firstChar = text.charAt(0);
}

private class StringResult {
  int length;
  char firstChar;

  StringResult(int length, char firstChar) {
    this.length = length;
    this.firstChar = firstChar;
  }
} 

Solution

  • While it is occasionally necessary to have something like "multiple return objects", it is often a sign indicating that you are passing around too much information. Some possible situations:

    1. You pass a lot of data from one object to the other so that the objects are very tightly coupled -> you should probably have just one class.

    2. You are passing around information that nobody uses -> Erase it.

    3. you are passing around information between methods inside a class which really should be a private field of the class.