tshad said:
In addition to the other suggestions - this looks like a situation to
me, where you actually detect an invalid state during object
construction. In that case, I would probably throw an exception in the
constructor.
How do you do that?
If you are already in the constructor, what tells it to send back the
null and not to create the object in the first place (or at least
destroy what it has already created).
I didn't say I'd "send back null", but I'd throw an exception in this
case. Like this:
public Role() {
connectionString = ConfigurationSettings.AppSettings["x"];
if (connectionString == "")
throw new InvalidOperationException("Role can't be created
without a valid connection string.");
}
But what does the code that called it get back?
Role newRole = new Role();
I did explain that in my original post, didn't I? Here's what I said:
I see the distinguishing factors like this: if the condition is part of
your normal application flow logic, you'll want to detect and handle it
without exceptions - but you need to do that "from the outside", meaning
not from the constructor. A factory method may be fine for that. But if
the condition is something that shouldn't occur unless something went
wrong, I'd rather throw an exception from the constructor - no need to
introduce additional management code in the form of factory methods or
other "outside" checks for this error situation.
So, to elaborate: the code that calls the constructor by using the new
keyword doesn't get anything back in this case, because an exception has
been thrown. Apparently you don't know what throwing exceptions is
about - it might help you to read up on this at this (MSDN) link:
http://shrinkster.com/8ds
Throwing an exception in a situation like this is the right thing to do,
as I see it, because neither the constructor code itself nor the code
calling into that code are likely to be able to do anything about the
problem, nor are they responsible for the problem in the first place.
IOW, the problem is not part of the normal application logic and there's
no step-by-step plan of what to do in this case.
Obviously, I'm basing this on assumptions about the sample code you were
showing, but the fact that no connection string can be read from the
application settings sounds pretty much like a global error to me. So I
throw an exception because at this point I simply don't care who, if
anybody, is going to catch it. The exception, so to speak, is the tool
that I use to make sure this error condition can not be ignored under any
normal circumstances - if no part of my code ever catches it, it'll
surface in the debugger or a framework error message to the end user.