Business Logic that depends on string values

215 Views Asked by At

In one of my projects I am working on I am using Entity Framework 4.1 (Code First). I have a relationship between two entities like the following:

public class Project
{
    public int Id { get; set; }

    // snip...

    // Foreign Key
    public string ProjectId { get; set; }

    // navigation proeprty
    public virtual ProjectType ProjectType { get; set; }
}

public class ProjectType
{
    public string Id { get; set; }

    public virtual ICollection<Project> Projects { get; set; }
}

Right now I business logic that depends on what type of project is being created/edited so I have code like this:

if( "P".Equals(project.ProjectTypeId) )
    // logic goes here

Is there some other way to do this that doesn't rely on me comparing string values?

3

There are 3 best solutions below

1
On BEST ANSWER

I'd personally prefer converting ProjectTypeId to an enum type.

var projectType = Enum.Parse(typeof(ProjectType), project.ProjectTypeId);
switch(projectType)
{
    case ProjectType.P: // logic goes here
    case ProjectType.N:
        break;
    default: throw new ArgumentOutOfRangeException("That wasn't a valid project type");
}

I'm assuming that you have a fixed number of ProjectTypes, and that your code is supposed to be aware of all of them. This approach gives you a single "source of truth" to look at when you need to see all the ProjectTypes that can be used. I prefer this over other options like a class with string constants because:

  1. It's easier to "fail fast" if you discover that the project has an invalid project type.
  2. You can pass ProjectTypes around as strongly-typed parameters to utility functions and such.
0
On

I know this has already been answered, but we use a slightly different approach than enums:

public static class ProjectType
{
    public const string P = "P";
    public const string N = "N";
}

You still have a single source of truth. Like enums, consts are defined at compile time. So your client code would look like this:

if( ProjectType.P.Equals(project.ProjectTypeId) )
    // logic goes here

It essentially does the same thing, but without the need for Enum.Parse.

0
On

I agree with Austin that you should really have something like..

public class Project
{
public int Id { get; set; }

// snip...      

// Foreign Key      
public string ProjectId { get; set; }      

// navigation proeprty      
public virtual IProjectType ProjectType { get; set; }      

}

public class ProjectTypeA : IProjectType
{ public string Id { get; set; }

public virtual ICollection<Project> Projects { get; set; } 

}

public class ProjectTypeB : IProjectType
{ public string Id { get; set; }

public virtual ICollection<Project> Projects { get; set; } 

}

Then you can have something like

if (p.ProjectType is ProjectTypeB ) {}

or for link

var projects = from p in Project.ofType select p;