How to avoid copy-paste of exceptionness function?
I have fo开发者_JS百科llowing functionality in few different classes C1, D2, F34:
class C1
{
void SomeFunc
{
Statement1();
Obj = GetObj();
Statement2(Obj);
}
IMyObj Obj{get;private set;}
}
public static class MyObjExt
{
public static void Statement2(this IMyObj obj)
{
... do validation of 'obj';
... throw exception if object state is wrong
}
}
Classes C1, D2, F34 aren't member of same hierarchy.
so I would like to avoid copy paste of them.
I could do something like this:
static MyObj MyFunc()
{
Statement1();
IMyObj obj = GetObj();
Statement2(obj);
return obj;
}
class C1
{
void SomeFunc
{
Obj = MyFunc();
}
IMyObj Obj{get;private set;}
}
but if "Statement2" function throws an exception obj member will left uninitialized...
How could I avoid copy-paste?
I have a little bit more complicated solution:
class Extender
{
static IMyObj MyFunc(out IMyObj obj)
{
Statement1();
obj = GetObj();
Statement2(obj);
}
}
class C1
{
void SomeFunc
{
IMyObj obj=null;
try
{
MyFunc(out obj);
}
finally
{
Obj = obj;
}
}
IMyObj Obj{get;private set;}
}
But I not sure if it will and must work. Is this good or bad approach?
If you think it is good - please vote, if no - please point "why"?
Thanks a lot!
EDIT: Added 'SomeFunc' implementation after modification.
精彩评论