Question

I have seen some examples that go like this:

public class Customer
{
 public int ID { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public Address Address { get; set; }
}
public class Address
{
 public string Street { get; set; }
 public string City { get; set; }
}

And I can't still figure out what advantages has over the following:

public class Customer
{
 public int ID { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string Street { get; set; }
 public string City { get; set; } 
}

Any ideas about it?

Cheers.

Was it helpful?

Solution 2

The example you showed is not a nested class, but a property making use of another class through composition.

The main advantage in your example is that the Address is a separate entity (refactored out) and may be used to indicate different classifications of address for a given Customer e.g a Customer may have a Home Address, a Business Address and a Corporate Address which all will be of type Address class.

Achieving above type of classification without having a separate Address class would be difficult otherwise and that's the one reason Address is taken out as a separate class.

As an illustration, your Customer class can be modified as below to show one of the advantages:

public class Customer
{
     public int ID { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public Address HomeAddress { get; set; }
     public Address BusinessAddress { get; set; }
     public Address CorporateAddress { get; set; }
}

Now, as per above example if your Address entity later requires ZipCode also, then you don't need to add 3 zipcodes (1 for Home, 1 for Business and 1 for Corporate); you just add the ZipCode property to the Address class and the 3 properties in Customer class make use of the new property without modifying the Customer class.

OTHER TIPS

Your class is not nested, it just uses composition. Composition is composing a class from one or more other classes. It's advantage is reuse of course.

You can use your Address class in another class or method and you also encapsulate all the logic and data that must be in the Address class.

If you want nested classes then you can write it as:

public class Apple
{
    public int Mass;
    public Worm MyWorm;

    public class Worm
    {
         public string Name;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top