Elegant way of reading a child property of an object

前端 未结 11 1233
半阙折子戏
半阙折子戏 2020-12-24 02:19

Say you are trying to read this property

var town = Staff.HomeAddress.Postcode.Town;

Somewhere along the chain a null could exist. What wo

11条回答
  •  误落风尘
    2020-12-24 02:28

    As per encapsulation, it is always the duty of a class to make proper validation (i.e. null-checks) for it's fields (and properties) before returning them. So each object is responsible for its fields, you can choose to return null, empty string, or raise an exception and handle it one level up in the chain. Trying to work around this is like trying to work around encapsulation.

提交回复
热议问题