Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a lot of hardcoded strings in code

Tags:

c#

When I am looking at my code and I am writing things like..

if (role == "Customer")
{
    bCustomer = true;
}
else if (role == "Branch")
{
    bIsBranch = true;
}

Or

foreach(DataRow as row in myDataSet.Tables[0].Rows)
{
    row["someField"]=somefield.Tostring()
}

Are you guys doing this? When is this ok to do and when shouldn't you be doing this? What if any would be a better approach to write this if any?

Thanks For the Comments: I guess I should add what if (for this example purposes) I am only using this role comparison once? Is it still a better idea to make a whole new class? Also should I have 1 class called "constants" are multiple classes that that hold specific constants, like "roles" class for example?

like image 560
Nick LaMarca Avatar asked Feb 29 '12 15:02

Nick LaMarca


1 Answers

No. Don't use "magic strings". Instead create a static class with constants, or an enum if you can.

For example:

public static class Roles
{
  public const string Customer = "Customer";
  public const string Branch = "Branch";
}

Usage:

if (role == Roles.Customer)
{

}
else if (role == Roles.Branch)
{

}

Here's a good discussion on various solutions.

like image 194
jrummell Avatar answered Sep 21 '22 17:09

jrummell