Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# / Object oriented design - maintaining valid object state

Tags:

c#

oop

state

When designing a class, should logic to maintain valid state be incorporated in the class or outside of it ? That is, should properties throw exceptions on invalid states (i.e. value out of range, etc.), or should this validation be performed when the instance of the class is being constructed/modified ?

like image 817
Scott Davies Avatar asked Jul 17 '26 00:07

Scott Davies


2 Answers

It belongs in the class. Nothing but the class itself (and any helpers it delegates to) should know, or be concerned with, the rules that determine valid or invalid state.

like image 167
John Saunders Avatar answered Jul 19 '26 12:07

John Saunders


Yes, properties should check on valid/invalid values when being set. That's what it's for.

like image 24
Adrian Godong Avatar answered Jul 19 '26 13:07

Adrian Godong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!