Whenever I'm writing code, I always stub out my methods like this (not necessarily using generics):
public T MyMethod()
{
T result = default(T); // or null
return result;
}
This always puts me in the right place to fill out the logic and make sure that I have a return variable to track throughout the process. After having done this long enough I've found a development pattern arose, and I'm not sure which direction to take. Usually in some relatively trivial operation:
public bool AddRecord(Record r)
{
bool result = false;
if(_collection != null)
{
_collection.Add(r);
result = true;
}
return result;
}
As an aside, I'd generally assign the result of the inner callee to result
but some methods (such as Add
) don't have any result.
This method, as it exists, is fine. But for some systems, I would write it a little different.
public bool AddRecord(Record r)
{
bool result = false;
if(_collection == null)
{
_collection = new List<Record>();
}
_collection.Add(r);
result = true;
return result;
}
And it's here that I ponder what I should do. Always returning true
provides no value to the end user, in my opinion. But then I say, "Well if, in the future, this method grows in complexity, would you want to have to change the method signature and have all callers update their reaction to this? Or would you rather just return true
for now?" to which I tend to favor the latter, unless it's something so trivially straightforward that I have high confidence it will not change (which, in itself, has ~50% chance of being wrong). Another option would be to assume that, although this interior logic can't generate a false-y condition, it could throw an exception. Should my method handle that and return a flag indicating whether an exception was thrown? Thinking about this, I think:
- Eating exceptions is bad, and unless I can do something with the information given to me, I shouldn't do it and I should let the caller handle it.
- Does the caller even care about this exception, or do they only care whether this operation succeeded as a whole?
This leads me to this state where I have a method in which I'm not sure what to do, so I typically return a constant true
and do not eat the exception.
My question is: In the general case, what is the best way to approach this?
I understand that specific cases require specific consideration, and while writing my code I always consider the unique case each method presents. But when I realize a method is not any more unique than another, I'd like have some additional insight as to what I should do. Many thanks in advance for your opinion.
AddRecord()
, how often do you check the return value? – Dan Pichelman Jul 20 '15 at 18:49AddRecord
as one step in it's logic. If it fails, it kicks out, otherwise it continues to the next step. – Will Custode Jul 20 '15 at 18:53