Why do we use ENUM - An approach of Deffensive Programming


ENUM is an old topic for .Net framework. I have heard new programmers discussing about ENUM lot of times and they get confused to understand the usage of ENUM. In this article I did not write much about ENUM and it's merits/demerits. I just tried to explain a scenario to represent the importance of ENUM.

Lets assume that we have the following Enum class in our application code base.



public enum EmployeeType
{
Management = 1,
Engineers = 2,
Internee = 3
}



Now in our application depending on EmployeeType different action will be taken. For an example lets consider that we have 4 classes in 3 different layers. Files are:

ApplicationDAO.cs
ApplicationDAL.cs
ViewRecordsUI.cs
UIClass.cs


All these files have the dependency on Employee Type. Lets take a code block from ViewRecords.cs.




var empoloyeeType = (int)dtEmployee["EmployeeType"];
if(employeeType == 1)
{
// Perform Action
}



Now these type of EmployeeType checking is in many places of the application, here in all the 4 classes.

Now what if the value of Manager changes tomorrow. We have to find all the places where the checking have been done and then we have to replace it with the new value. IDE's 'Find & Replace' feature will also not help much, moreover the code can be broken or messed up.

In software development there is a term called "Robustness". In this case will that be called as a Robust Development. Not at all! In defensive programming the code should be written in such a way so that future modification can be implemented easily without impacting the current state.

Thus ENUM comes in the picture. If we write the code block using Enum then it would be:



var empoloyeeType = (int)dtEmployee["EmployeeType"];
if(employeeType == EmployeeType.Management)
{
// Perform Action
}



Now if the value is changed in future, we will just change the value for enum and that's it, no other places need to be changed.



public enum EmployeeType
{
Management = 4, // New Value
Engineers = 2,
Internee = 3
}



And this can be a very good way to do programming. This type of change can be implemented very easily without impacting the current code block.

Now there are so many ways to write and use enum efficiently but my objective was just to let you know why ENUM is used in programming. Hope that clears the doubt. Pass your comment/feedback or thoughts.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: