views:

298

answers:

9

Specifically, can anyone give me concrete examples of when or when not to use nested classes?

I've known about this feature since forever, but never had a reason to use it.

Thanks.

+15  A: 

When the nested class is only used by the outer class, a great example, no longer necessary, is for an enumerator class for a collection.

another example might be for a enum to replace a true false parameter used by a method within a class, to clarify the call signature...

instead of

public class Product
{
    public void AmountInInventory(int warehouseId, bool includeReturns)
    {
        int totalCount = CountOfNewItems();
        if (includeReturns)
            totalCount+= CountOfReturnedItems();
        return totalCount;
    }
}

and

  product P = new Product();
  int TotalInventory = P.AmountInInventory(123, true);

which leaves it unclear as to what 'true' means, you could write:

public class Product
{
    [Flags]public enum Include{None=0, New=1, Returns=2, All=3 }
    public void AmountInInventory(int warehouseId, Include include)
    {
        int totalCount = 0;
        if ((include & Include.New) == Include.New)
            totalCount += CountOfNewItems();
        if ((include & Include.Returns) == Include.Returns)
            totalCount += CountOfReturns();
        return totalCount;
    }
}


  product P = new Product();
  int TotalInventory = P.AmountInInventory(123, Product.Include.All);

Which makes the parameter value clear in client code.

Charles Bretana
+2  A: 

I've seen cases of nested classes when a special purpose data structure is used only within one class, or a certain exception is thrown and caught only within one class.

Ben S
+11  A: 

The two places where I use nested classes:

  • The nested class is used exclusively by the outer class, and I want completely private scope.

  • The nested class is used specifically to implement an interface defined elsewhere. For example, implementing an enumerator falls into this category.

Reed Copsey
+3  A: 

I sometimes use this for simple helper classes that I need for a function or two inside of the parent class.

Jon B
+3  A: 

For a practical example, see this question asked earlier this morning:
http://stackoverflow.com/questions/1427448/make-an-object-accessible-to-only-one-other-object-in-the-same-assembly

Summary: you can nest an associated data class inside it's business object.

Joel Coehoorn
+1  A: 

I nest classes when I have a helper class which has no need to be visible to any other object in the system. This keeps the visibility as constrained as possible which helps prevent unintended uses of the class

JaredPar
+4  A: 

You really only want to use nested classes when you are sure the nested class doesn't make sense that it would be used anywhere else.

For example, if you needed to create a list of several types of object associated together with functions and member information about that set of objects for a short time (like methods or properties), you could use a nested class to do that. Maybe you need to create a list of all combinations of some type of object, and then mark all combinations that have a certain property. That would be a good case for a nested class.

If you don't need methods on the nested class, you can probably just use a struct but I don't know if IL treats them any differently.

Dale Halliwell
+1  A: 

Following Uncle Bob's 'rules' on cohesion should find that you actually create quite a number of nested (and nested, nested!) classes. These could be made non-nested but only if you have other clients that reference them now.

Chris Arnold
+1  A: 

I'd like to improve on my previous answer!

A specific area where I use nested classes regularly is enabling Interface Injection and Inversion of Control. Example...

public class Worker
{
  private IHelper _helper;

  public Worker()
    : this (new DefaultHelper())
  {
  }
  public Worker(IHelper helper)
  {
    this._helper = helper;
  }

  private class DefaultHelper : IHelper
  {
  }
}
Chris Arnold