I’d like to know what’s the default approach for those times when you need a variable to have been set in order for a given method/another variable initialization to work.
Like this:
Everything works if I initialize var A after var B. But not the other way around. I wrote the constructor, so I’ll do that myself, but I’m not really sure where the code that tests for var B‘s existence should be. Or even if it should exist at all, for I have written the constructor and I initialize the values the order I see fit, but I feel it’s a little insecure because it is not very robust in case anything changes.
Mind you, I’m talking about instance variables, if that helps.
FA
The answer can be influenced by the reason why
amust be set beforeb.Explicit Object Dependencies
If the reason is that
bdepends upona, then the simplest thing to do is to make that dependency explicit at the time thatbis created. For example, ifaandbwere objects then:In this way, it is not possible to initialize the objects out of order. Note that
AandBcould be newly introduced wrapper objects that contain the original operation parameters.Fluent Interface
If the reason is that the operation itself must know the value of
ain order to perform some configuration in preparation for the arrival ofb, then the operation constructor could be replaced by a fluent interface:We must take care to define this fluent interface in such a way that
withBcan only be called afterwithAhas been called. For example:Here,
Chas been introduced to capture that state that is dependent uponaalone prior to the arrival ofb. Note how the constructor ofOperationis not visible to client code and thatwithBcannot possibly be called until afterwithAhas been called.