c# - Where should exceptions been thrown? -
i have class looks following way:
public class stackoverflowquestion { private string _question; public string question { { return _question; } set { _question = value; } } public stackoverflowquestion(string question) { _question = question; } public override string tostring() { return _question; } } now, value "question" isn't allowed null or empty , user should notified via argumentnullexception - should been thrown? according 'fail-fast' principle -> everywhere.
public class stackoverflowquestion { private string _question; public string question { { return _question; } set { if(!string.isnullorempty(value)) _question = value else throw new argumentnullexception("value"); } } public stackoverflowquestion(string question) { if(!string.isnullorempty(question)) _question = question; else throw new argumentnullexception("question"); } public override string tostring() { if(!string.isnullorempty(_question)) return _question; else throw new argumentnullexception("_question"); } } now ridiculous , extremely repetitive. seems right: if value set through .ctor, fails directly after short check. when set through property, fails directly after short check.. expects exceptions on setter? , when output string, expect string, not exception should have happend long ago, again: if it's wrong, should fail asap, if 'soon' quite late.
so, should exception handling been done? asking 'best-practice', or taste thing?
since _question private, there's no need check whether null in tostring() (unless you're sanity checking own code).
you can avoid check in constructor having constructor use property setter. thus, i'd recommend:
public class stackoverflowquestion { private string _question; public string question { { return _question; } set { if(string.isnullorempty(value)) // make more transparent when thrown through constructor, might // preferable throw real error message "question: cannot null or empty" throw new argumentexception("value"); this._question = value; } } public stackoverflowquestion(string question) { this.question = question; } public override string tostring() { return this.question; } } a few things note: 1. should throw argumentexception rather argumentnullexception empty strings (if want can 2 checks , still throw argumentnullexception nulls). 2. while approach uses less code, 1 disadvantage error message users worse when pass null constructor, since failure happens 2 levels deep instead of one.
Comments
Post a Comment