Friday, 8 July 2016

Logic in getters and setters

Setters:
  • used to set a (new) value of a property
  • expected to be fast
  • value can be validated (e.g. null check, range check etc...); failed validation CAN throw exception
  • event which publishes information that property's value has been changed can be fired; event handlers are not under publisher's control and they CAN throw exception


Getters:
  • return value of the property
  • expected to be fast
  • expected to be idempotent (i.e. no destructive actions should be performed there)
  • expected to cause no side effects on the object (no changing values)
  • MUST NOT throw exception (otherwise would break principle of least surprise)
  • use memoisation (lazy computation/evaluation)



References:
Property Design (MSDN)
http://stackoverflow.com/questions/495864/logic-in-get-part-of-property-good-practice
http://stackoverflow.com/questions/2923116/is-it-a-good-practice-to-implement-logic-in-properties
http://stackoverflow.com/questions/1488472/best-practices-throwing-exceptions-from-properties

Post a Comment