I've just started dipping my feet into OOP.
Is it considered bad practice to have classes that reference attributes that depend on another function being called and thus may not exist (version 1)? I'm self-taught so trying to gauge what is considered better quality. Any mistakes are easily fixed by just making sure I call functions in order?
I could make the function
add_extra_attribute explicitly take a variable (something like version 2), but this would be more verbose and making
add_new_attribute work together could be more confusing.
Cheers for reading!
class test: def __init__(self): self.attribute = 'hello' def add_attribute(self): self.new_attribute = self.attribute + 'there' def add_extra_attribute(self): self.extra_attribute = self.new_attribute + 'you' t = test() t.add_attribute() #if I comment this out it will AttributeError t.add_extra_attribute()
class test: def __init__(self): self.attribute = 'hello' def add_attribute(self): self.new_attribute = self.attribute + 'there' def add_extra_attribute(self, new_attribute): self.extra_attribute = self.attribute + new_attribute + 'you' t = test() t.add_attribute() t.add_extra_attribute('there')
This is called temporal coupling1, 2, 3. Call the methods in the correct order and everything is fine. But nothing in the API hints that this is needed so this design is most effective at hazing the new coder.
If torturing the younger generation isn't for you then please do subject us to the more verbose option that makes it's dependencies clear. Some might argue that the entire practice of functional programming exists just to squeeze these evil timing issues out of our code.
You can fix this even in OOP centric languages. Just make us pass in what is needed. Sometimes that's called reference passing. Sometimes people want to feel fancy and call it Dependency Injection. Whatever you call it I like it when error messages tell me a clear story about what I forgot.
External links referenced by this document: