3

Folks, I have two separate classes. One of them makes http requests/receives response to/from a server and the second one converts received JSON objects into my models (separate classes). I'm thinking it would be an idea to include this class for data converting as an inner class of my first class. Wouldn't my first class be extra big because of it and I need to leave everything as is or this is a good common practice to behave like that?

1
  • Have you considered making the second class package-private? Commented Jan 12, 2011 at 20:34

3 Answers 3

4

Inner classes are most commonly used for objects that act directly on the enclosing class. An excellent example of this is iterators. You create a custom implementation of Iterator within your container class, and return an instance of it in your getIterator() or whatever method. This iterator has access to all methods and fields of that container, which may make it easier to implement remove(), for example. Also, that iterator is unique to that class, but it is an implementation of an external, public interface, so it makes sense for it to be hidden as an inner class.

I would apply these questions to your example. If the answer to any of them is no, I'd reccommend making the class stand alone.

  1. Is it unique to your class? That is, can any other class use this converter?
  2. Does it need access to private fields of the enclosing class?
  3. Is it a custom implementation of an existing public interface that should never be accessed in any way but through that interface? If so, there's really no point in making it a public class of it's own. As in the Iterator example, you can return the interface with no hint of the underlying structure. Good encapsulation.

I think your example fails number 2, and probably number 1 too, since it operates on data not specific to the closing class. I don't know about the third; insufficient information. I would not make it an inner class. If you really want to limit access to the class, make it package private (declared with class, not public class)- then it can only be accessed within the package.

0
1

If it is going to over complicate things without giving you a significant improvement somewhere(execution time, etc) then I don't think it's worth it and would leave it as-is.

1

They seem to be doing two completely unrelated things. So they should be independent classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.