I have following C# code. It works fine; but the GetDestination()
method is cluttered with multiple if
conditions by using is operator.
In
Here's one option:
private static readonly Dictionary DestinationsByType =
new Dictionary
{
{ typeof(Manager), @"\ManagerHome" },
{ typeof(Accountant), @"\AccountantHome" },
// etc
};
private static string GetDestination(Role x)
{
string destination;
return DestinationsByType.TryGetValue(x.GetType(), out destination)
? destination : @"\Home";
}
Note:
class Foo : Manager
); you could do that by going up the inheritance hierarchy if necessaryHere's a version which does deal with both of those points, at the cost of complexity:
private static string GetDestination(Role x)
{
Type type = x == null ? null : x.GetType();
while (type != null)
{
string destination;
if (DestinationsByType.TryGetValue(x.GetType(), out destination))
{
return destination;
}
type = type.BaseType;
}
return @"\Home";
}
EDIT: It would be cleaner if Role
itself had a Destination
property. This could either be virtual, or provided by the Role
base class.
However, it could be that the destination is really not something the Role
should concern itself with - it could be that Role
is part of the business model, and the destination is purely an artifact of one particular application using that business model. In that sort of situation, you shouldn't put it into Role
, as that breaks separation of concerns.
Basically, we can't tell which solution is going to be most suitable without knowing more context - as is so often the way in matters of design.