When developing a class (in C# but I suppose this question is somewhat language independent) what is the correct way to deal with dependencies between properties?
For example where I want to create a property B whose value is derived in some way from the value of property A. Property B is undefined and should not be called if property A has not been set. Throwing an exception in B’s getter if A has not been set hardly seems like an elegant way of handling this. Simply returning some default value from property B is not something I want to do.
One way is to enforce initialization of A through the constructor, but let’s assume that a default constructor with no arguments is required so this is not an option.
Throwing an
InvalidOperationExceptionin this case seems entirely proper to me:Now granted it talks about a method rather than a property, but I think it’s still fine.
If you want an example from the framework,
IEnumerator.Currentis specified to throwInvalidOperationExceptionif it’s called before the first element or after the last one. (C#-generated iterators don’t do that in fact, but that’s a different matter 🙂It sounds like it’s a bug in the calling code to do this… they’re using the object improperly. The correct way to indicate a bug is to throw an exception.