What best practices apply to property setters that refer to contained objects that might be null?
I'm working with a class that exposes a contained object's properties for data binding purposes. I ran into a couple lines of code that smell, but I'm not sure the best way to improve them.
Class D开发者_运维知识库river
Public Property License As LicenseInfo
Public Property LicenseState
Set(value As String)
If License Is Nothing Then Exit Property '<-- is there a better way?
License.State = value
End Set
...
End Property
...
End Class
Would it be better to create a new License object here? Are there any best practices that apply to this scenario?
Depends on your business rules, but most commonly :
1.Throw an Exception
999.Instantiate the value to be set, and set it (be weary)
Throwing an exception is usually the best way because if the object doesn't exist, and you create it in a setter, your broker/business flow might be off. Throwing also let's other developers know they're logic is wrong - and they're using your class incorrectly, and that is why it's the #1 choice.
Your code libraries are like a machine - they work best when they're used they way you wrote them to be used (If you use a squatting machine wrong you're going to break your back). So let people know they're using it wrong.
精彩评论