I made the following code example to learn how to use a generics method signature.
In order to get a Display() method for both Customer and Employee, I actually began replacing my IPerson interface with an Person abstract class.
But then I stopped, remembering a podcast in which Uncle Bob was telling Scott Hanselman about the Single Responsibility Principle in which you should have lots of little classes each doing one specific thing, i.e. that a Customer class should not have a Print() and Save() and CalculateSalary() method but that you should have a CustomerPrinter class and a CustomerSaver class and a CustomerSalaryCalculator class.
That seems an odd way to program. However, getting rid of my interface also felt wrong (since so many IoC containers and DI examples use them inherently) so I decided to give the Single Responsibility Principle a try.
So the following code is different than I have programmed in the past (I would have made an abstract class with a Display() method and got rid of the interface) but based on what I have heard about decoupling and the S.O.L.I.D. principles, this new way of coding (the interface and the PersonDisplayer class) I think this is the right way to go.
I would like to hear if others think the same way on this issue or have experienced positive or negative effects of this (e.g. an unwieldy number of classes each doing one particular thing, etc.).
using System;
namespace TestGeneric33
{
class Program
{
static void Main(string[] args)
{
Container container = new Container();
Customer customer1 = container.InstantiateType<Customer>("Jim", "Smith");
Employee employee1 = container.InstantiateType<Employee>("Joe", "Thompson");
Console.WriteLine(PersonDisplayer.SimpleDisplay(customer1));
Console.WriteLine(PersonDisplayer.SimpleDisplay(employee1));
Console.ReadLine();
}
}
public class Container
{
public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
{
T obj = new T();
obj.FirstName = firstName;
obj.LastName = lastName;
return obj;
}
}
public interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
}
public class PersonDisplayer
{
private IPerson _person;
public PersonDisplayer(IPerson person)
{
_person = person;
}
public string SimpleDisplay()
{
return String.Format("{1}, {0}", _person.FirstName, _person.LastName);
}
public static string SimpleDisplay(IPerson person)
{
PersonDisplayer personDisplayer = new PersonDisplayer(person);
return personDisplayer.SimpleDisplay();
}
}
public class Customer : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
}
public class Employee : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int EmployeeNumber { get; set; }
}
}