c# - Guard clause for properties that are possibly forgotten to be assigned a value -
we have message being passed method.
class message { public int transactionid { get; set; } public bool iscredit { get; set; } // debit when false public decimal amount { get; set; } } class servicebus { public iservice theservice { get; set; } public void somethinghappen() { var message = new message { transactionid = 7, amount = 6 // forgot assign iscredit }; theservice.dosomething(message); } } class service { public void dosomething(message message) { // before proceeding else, wanted put // guard clause if not assigned, e.g., iscredit } } can't check if iscredit forgotten assigned of value, unassigned boolean defaults false, means it's debit, assignment of iscredit = false; not detected unassigned, indicates debit instead.
so suggested use drcrflag starts value of 1.
public enum drcrflag { debit = 1, credit = 2 } that way, dosomething method can have guard clause checks if message's iscredit property forgotten assigned checking if enum zero.
public void dosomething(message message) { // before proceeding else, wanted put // guard clause if forgotten assigned, e.g., iscredit if (message.drcrflag == 0) throw new argumentexception("drcrflag unassigned"); } however, the data contract broken on client apps rely on boolean property. changing boolean drcrflag not possible.
so suggested use nullable boolean, break existing client app, welcome changing boolean nullable boolean more changing of boolean enum.
this can implemented:
class message { public int transactionid { get; set; } public bool? iscredit { get; set; } // debit when false public decimal amount { get; set; } } public void dosomething(message message) { // before proceeding else, wanted put // guard clause if forgotten assigned, e.g., iscredit if (message.iscredit == null) throw new argumentexception("iscredit unassigned"); } is right way guard against unassigned variable?
should actions validate values being passed it?
another approach declare private member miscredit of type bool?. in getter, can check value of private variable , throw exception if null. way public property remain bool type.
Comments
Post a Comment