I my class hierarchy looks like this:
P
I : P
O : P
I have this method. The goal of this method is to return a new object of type I
or O
depending on a certain condition.
public P GetP()
{
this.Session.Begin();
var pDetail = GetPDetail();
if (pDetail == null)
{
this.Session.Close();
return null;
}
switch (pDetail.Code)
{
case "1":
var i = new I();
i.PDetail = pDetail;
FillBaseP(i);
FillI(i);
this.Session.Close();
return i;
case "3":
var o = new O();
o.PDetail = pDetail;
FillBaseP(o);
FillO(o);
this.Session.Close();
return o;
default:
throw new Exception("Code is invalid");
}
}
I'm looking to rewrite this in a more logical way. Both case "1"
and case "3"
are doing some of the same work.
If I'm constantly checking type like If(var is O)
or If(var is I)
I feel as though I'm doing something wrong. Is this the case?
pDetail.Code
, then call a standard "create" method? (I'm not sure how extensible you need this to be). \$\endgroup\$