c# - What is the best way to implement a Must Set Property for a Base class? -


i have simple basic question c# , inheritance.

in below example, i'm showing 2 ways of setting must set properties (captiondisplaytext , firstname):

public abstract class baseclass {     private string _firstname;      protected baseclass(string captiondisplaytext)     {         this.captiondisplaytext = captiondisplaytext;          this._firstname = this.getfirstname();     }      protected string captiondisplaytext { get; private set; }      protected abstract string getfirstname(); }  public class derivedclass : baseclass {    protected derivedclass():base(string.empty)    {     }     protected override string getfirstname()    {        return string.empty;    } } 

approach 1, captiondisplaytext, introduces property , sets in constructor whereas approach 2 introduces abstract method overridden in derived class.

i know approach2 bad if method virtual rather abstract here it's abstract means executed before constructor of base class , fine.

i'm having 10-15 properties/fields have set derived classes i'm thinking approach more maintainable, readable , testable.

i think approach 1 more testable whereas approach 2 more readable. approach 2 testable mock object have implement abstract members anyway.

which way best in view , there third way?

many thanks,

doing logic in constructor not way go if want make class testable. doing this._firstname = this.getfirstname(); introduce test effort, code called if not want first name. in first approach have filled null, indicates not important test.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -