jeudi 8 août 2019

How can a derived class fields be of different type than its base class?

I am trying to learn program designing and good practices. Here my question stems from while working with existing code practice in an organisation. It would be really helpful if anyone can list bad practice/code design/code smell along with how should it be done with inline with principals.

Base Class

// Sits in Data Layer of overall project
public abstract class BaseClassDataService{

   protected string ID {get;set;}
   protected string FieldA {get;set;}
   ....

   protected BaseClassDataService(){}
   protected BaseClassDataService(string id){
    ID= id;
    Populate();
   }

   protected void Populate(){
     // Populate itself from database by executing SQL query..
      FieldA  = data from db (string);
      ... other fields are populated
   }

    protected void Insert()
    {
        // FieldA value (string) is saved to db by executing SQL query..
    }
}

Derived Class

// sits in Business layer of overall project
public class DerivedClassLogicService : BaseClassDataService { 

   public DerivedClassLogicService () : base() {}
   public DerivedClassLogicService (string id) : base(id) {}
   public MyObject FieldA 
   {
       set
       {
          value.DisplayName = "Field A";
          base.ID = value.Value;
       }
   }
}

public class MyObject 
{
   public string Value{ get; set; }
   public string DisplayName { get; set; }
   MyObject (string value, string displayName) {
      Value= value; 
      DisplayName = displayName;
}

Now at line public MyObject FieldA {get;set {base.ID = value.Type}} VisualStudio shows warning that the base class hide FieldA since Derived Class has same named field 'FieldA'.

Warning CS0108 'DerivedClassLogicService.FieldA' hides inherited member 'BaseClassDataService.FieldA'. Use the new keyword if hiding was intended.

so to resolve warning :

public new MyObject FieldA 
{
    set
    {
        value.DisplayName = "Field A";
        base.ID = value.Type;
     }
}

Q1. Is this good practice in terms of code design, if anyone can point out any real disadvantages or advantages of this?

Now, What purpose does this way of setting a different type of object is:

Since string type of FieldA is replaced by MyObject type of FieldA in derived class, its purpose is to enable ONLY saving the value (typeof: string) of FieldA. It is not wanted to save DisplayName to the db.

Q2. Base class is DB layer class, and acts to save data (of primitive type). Is this a good practice ?

I think by doing above, the programmer gets wrong impression that the MyObject is also saved in Db. If anyone can point out more issues than it would be really helpful for me to learn architecture and project design.

Aucun commentaire:

Enregistrer un commentaire