What is the terminology for what this method attempts?
سؤال
I don't know:
- if this works.
- if it's a good idea.
- what it is called in order to find out more about it.
But I think the intent is fairly apparent.
public static class DebugLogic
{
public static bool ThrowIfNull = false;
public static T OrNew<T>(this T obj) where T : class
{
if (obj != null) return obj;
else if (ThrowIfNull) throw new ArgumentNullException(//to do...);
else return Activator.CreateInstance<T>();
}
}
Intended usage:
var customer = order.Sale.OrNew().Customer.OrNew().Name
What am I doing? Is this insane or helpful? It seems helpful.
المحلول
I think the idea of having an OrNew
method is fine. Especially if you're striving to make a fluent interface. However I would change 3 things about it
- Don't have a hidden flag that controls the behavior (
ThrowIfNull
). This makes it impossible for someone to read anOrNew
call an understand what it does. - Use a
new
constraint in favor of the less safeActivator.CreateInstance<T>()
call - I'd call it something other than
DebugLogic
. Generally (but not always) extension method containers end with theExtensions
.
For example
public static class LogicExtensions {
public static T OrNew<T>(this T obj) where T : class, new() {
if (obj != null) {
return obj;
}
return new T();
}
}
نصائح أخرى
The name of this operation is clearly: DefaultIfNull
لا تنتمي إلى StackOverflow