I'm writing classes that "must be used in a specific way" (I guess all classes must...).
For example, I create the fooManager
class, which requires a call to, say, Initialize(string,string)
. And, to push the example a little further, the class would be useless if we don't listen to it's ThisHappened
action.
My point is, the class I'm writing requires method calls. But it will compile just fine if you don't call those methods and will end up with an empty new FooManager. At some point, it will either not work, or maybe crash, depending on the class and what it does. The programmer that implements my class would obviously look inside it and realize "Oh, I didn't call Initialize!", and it'd be fine.
But I don't like that. What I would ideally want is the code to NOT compile if the method wasn't called; I'm guessing that's simply not possible. Or something that would immediately be visible and clear.
I find myself troubled by the current approach I have here, which is the following:
Add a private boolean value in the class, and check everywhere necessary if the class is initialized ; if not, I will throw an exception saying "The class wasn't initialized, are you sure you're calling .Initialize(string,string)
?".
I'm kind of okay with that approach, but it leads to a lot of code that is compiled and, in the end, not necessary to the end user.
Also, it's sometimes even more code when there are more methods than just an Initiliaze to call. I try to keep my classes with not too many public methods/actions, but that's not solving the problem, just keeping it reasonable.
What I'm looking for here is:
- Is my approach correct?
- Is there a better one?
- What do you guys do/advise?
- Am I trying to solve a non-issue? I've been told by colleagues it's the programmer's to check the class before trying to use it. I respectfully disagree, but that's another matter I believe.
EDIT : About the possible duplicate of this question : those questions are entirely different. I'm not considering wether or not I should call 1 big method vs many small ones. I'm asking for a way to make sure that method is called at all. Wether it's a small Init()
or many calls is irrelevant.
Put it simply, I'm trying to figure out a way to never forget to implement calls when that class is reused later, or by someone else.
initialize
be made late after the object creation ? Would the ctor be too "risky" in the sense it could throw exceptions and break the creation chain ? – Spotted yesterdaynew
if the object isn't ready to be used. Relying on an initialization method is bound to come back to haunt you and should be avoided unless absolutely necessary, at least that's my experience. – Seralize 14 hours ago