The Country
, State
and City
functions accepts the Integer as Parameter and returns the relevant error code if the validation fails in ValidateNotExist
Class.
Therefore, I have enhanced the ValidateNotExist
class with a slight different implementation (using switch
) and named it as ValidateNotExistImproved
.
But I think, the entire code can be improved further. Can someone help me figure out what mistakes am I doing and how can I improve it?
The entire code is provided with a little explanation for every class.
NotExistErrorCodeConfig
Error codes configuration.
public static class NotExistErrorCodeConfig
{
public const string Country = "COUNTRY_NOT_EXIST";
public const string State = "STATE_NOT_EXIST";
public const string City = "CITY_NOT_EXIST";
}
EntityTypeEnum
Enum Configuration, this is being used in the ValidateNotExistImproved class.
public enum EntityTypeEnum
{
Country = 1,
State = 2,
City = 3
}
ExistsHelper
The actual logic is implemented and it has dedicated functions.
public static class ExistsHelper
{
public static bool Country(int id)
{
return (id > 10) ? true : false;
}
public static bool State(int id)
{
return (id > 10) ? true : false;
}
public static bool City(int id)
{
return (id > 10) ? true : false;
}
}
ValidateNotExist
A helper class, the implementation calls this class. This class is responsible to check the value and return the relevant error message.
public static class ValidateNotExist
{
public static string Country(int id)
{
return (!ExistsHelper.Country(id)) ? NotExistErrorCodeConfig.Country : string.Empty;
}
public static string State(int id)
{
return (!ExistsHelper.State(id)) ? NotExistErrorCodeConfig.State : string.Empty;
}
public static string City(int id)
{
return (!ExistsHelper.City(id)) ? NotExistErrorCodeConfig.City : string.Empty;
}
}
ValidateNotExistImproved
I have combined the three functions into single function but using Switch statement. This is supposed to be improved version of ValidateNotExist.
public class ValidateNotExistImproved
{
public static string Validate(EntityTypeEnum type, int id)
{
string errorCode = string.Empty;
switch (type)
{
case EntityTypeEnum.Country:
errorCode = (!ExistsHelper.Country(id)) ? NotExistErrorCodeConfig.Country : string.Empty;
break;
case EntityTypeEnum.State:
errorCode = (!ExistsHelper.State(id)) ? NotExistErrorCodeConfig.State : string.Empty;
break;
case EntityTypeEnum.City:
errorCode = (!ExistsHelper.City(id)) ? NotExistErrorCodeConfig.City : string.Empty;
break;
default:
break;
}
return errorCode;
}
}
ImplementationClass
The actual implementation class, it returns the same error code.
public class ImplementationClass
{
public ImplementationClass()
{
var error = ValidateNotExist.Country(2); //Throws an error COUNTRY_NOT_EXIST
var extendedError = ValidateNotExistImproved.Validate(EntityTypeEnum.Country, 2); //Throws an error COUNTRY_NOT_EXIST
Console.WriteLine(error);
Console.WriteLine(extendedError);
Console.ReadKey();
}
}