I made the following code example to learn how to use the generics method signature.
To get the Display () method for the client and employee, I actually started replacing my IPerson interface with the abstract class Person >.
But then I stopped, remembering the podcast in which Uncle Bob told Scott Hanselm about the principle of single responsibility , in which you should have many small classes, each of which does one specific thing, that is, that the Client class should not have Print () and Save () and the CalculateSalary () method , but you must have the CustomerPrinter class and the CustomerSaver class and the CustomerSalaryCalculator class .
This seems like a weird way of programming. However, getting rid of my interface also feels bad (since many IoC containers and DI examples use them inherently), so I decided to try the principle of single responsibility.
So, the following code is different from the one I programmed in the past (I would have made an abstract class using the Display () method and got rid of the interface), but based on what I have heard about the decoupling and SOLID principles, this new way coding (interface and PersonDisplayer class) I think this is the right way .
I would like to hear if others think differently on this issue or experience positive or negative consequences of this (for example, a cumbersome number of classes, each of which does one 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; } } }
c # design-patterns solid-principles
Edward Tanguay Mar 18 '09 at 17:11 2009-03-18 17:11
source share