Search code examples
c#oopsolid-principles

Extending base class to include details?


I have a DTO returned by my DAL. For example

public class CustomerDTO
{
    public int CustId {get; set; }
    public int CustType {get; set; }
    .
    . 
    .
    public string GetCustomerTypes{
      get {  if (CustType== 1) 
               return "Special Customer";
             else if(CustType==
}

Now I have multiple properties in my class which are not linked with any table & are just codes representing some attributes like for CustId I can have (1='Special Customer', 2='Defaulter'or 3='New Customer'). Now I need to display their attributes on the DTO.

I can embed my business logic either into SQL statements or my DTO class as I have done above. However, for various columns I end up with a lot of conditional logic. Also, incase I make another DTO, this conditional logic is repeated again.

How can I encapsulate this logic in my class design & avoid repetition?


Solution

  • I'm going to recommend you put these values in the database. You could build separate tables like:

    CREATE TABLE CustomerTypes (
        ID INT PRIMARY KEY IDENTITY(1, 1),
        Name VARCHAR(50) NOT NULL
    )
    

    or you could build one table with a type code in it like:

    CREATE TABLE ListTypes (
        ID INT PRIMARY KEY IDENTITY(1, 1),
        Name VARCHAR(50) NOT NULL,
        TypeCode CHAR(2) NOT NULL
    )
    

    either way, when you gather the DTO from the database, join to those tables and grab that value. So if you built one table it might look like:

    SELECT c.*, ct.Name FROM Customer c
        JOIN CustomerTypes ct ON ct.ID = c.CustType
    

    and if you were to use the more generic table with the type code it might look like this:

    SELECT c.*, lt.Name FROM Customer c
        JOIN ListTypes lt ON lt.ID = c.CustType AND lt.TypeCode = '01'
    

    The reason this approach will work so well for you is because you need the string value, but only for display purposes, and you're going to need it on a lot of types going forward. Further, you're already in the database getting the entity, so let the database do this work. Finally, if you ever wanted to list these values in a combo box and let the user select them, you could bind that combo box from the database rather than statically.

    But in short, this makes your application much easier to modify and expand.