0.4 C
New York
Thursday, March 21, 2024

Keep away from utilizing enums within the area layer in C#


When engaged on functions, you’ll typically have to symbolize a gaggle of constants within the enterprise logic and even within the area layers. Nevertheless, you must keep away from utilizing enumeration varieties, or enums, within the area layer and as a substitute use options resembling document varieties.

Why? On this article, we’ll clarify the downsides of utilizing enumerations within the area layer.

Create a console utility challenge in Visible Studio

First off, let’s create a .NET Core console utility challenge in Visible Studio. Assuming Visible Studio 2022 is put in in your system, observe the steps outlined under to create a brand new .NET Core console utility challenge.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new challenge.”
  3. Within the “Create new challenge” window, choose “Console App (.NET Core)” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new challenge” window, specify the title and site for the brand new challenge.
  6. Click on Subsequent.
  7. Within the “Extra info” window proven subsequent, select “.NET 8.0 (Lengthy Time period Assist)” because the framework model you want to use.
  8. Click on Create.

We’ll use this .NET 8 console utility challenge to work with the code examples proven within the subsequent sections of this text.

What’s incorrect with enums?

Whereas enumeration varieties can present flexibility in sustaining a set of fixed values in your utility, they typically introduce tight coupling between the area mannequin and the code that makes use of it, thus limiting your capability to evolve the area mannequin.

Contemplate the next enum used to outline consumer and administrator roles.

public enum Roles
{
    Person,
    Administrator,
    Reviewer,
    SuperAdmin
}

You can even use an enum to outline a gaggle of constants as proven within the following code snippet.

public enum Roles
{
    Person = 1,
    Administrator = 2,
    Reviewer = 3,
    SuperAdmin = 4
}

Downside 1: Encapsulation smells

Now, suppose it’s essential to know whether or not a selected function pertains to an administrator function. The next code snippet illustrates an extension methodology named IsAdmin that checks if a selected function is an Administrator or a SuperAdmin.

public static class RolesExtensions

           roles == Roles.SuperAdmin;

This lands us on the primary drawback with utilizing enums within the area layer. Though you’ll be able to function on the enum utilizing extension strategies, your code breaks the encapsulation precept as a result of the logic for querying the mannequin and the mannequin you created are separate. In different phrases, the logic that checks the mannequin just isn’t throughout the identical class. That is an anti-pattern, and a mannequin of this kind is usually often known as an anaemic mannequin.

Downside 2: Spaghetti code

One other drawback with enums: You would possibly typically want to make use of specific casts in your utility’s code to retrieve a worth from an enumeration. The next line of code illustrates this.

int function = (int)Roles.Person;

Specific casts should not a great strategy. They’re all the time expensive by way of efficiency, they usually indicate that you just’ve used incompatible varieties in your utility, or that the categories haven’t been correctly outlined. Utilizing enums in your area layer may result in utilizing specific casts all through your utility, cluttering up the code and making it more durable to learn and preserve.

Downside 3: Naming constraints

Keep in mind, you can’t embrace house characters within the names of enumeration constants in C#. Therefore, the next code just isn’t legitimate in C#.

public enum Roles
{
    Admin,
    Tremendous Admin
}

You’ll be able to make the most of attributes to beat this limitation.

utilizing System.ComponentModel.DataAnnotations;
public enum Roles
{
    Admin,
    [Display(Name = "Super Admin")]
    SuperAdmin
}

Nevertheless, you’ll run into issues when your utility wants to supply assist for various locales.

Use document varieties as a substitute of enums

A greater different is to make use of document varieties. You’ll be able to make the most of document varieties to create an immutable kind as proven within the code snippet given under.

public document Roles(int Id)
{
    public static Roles Person { get; } = new(1);
    public static Roles Administrator { get; } = new(2);
    public static Roles Reviewer { get; } = new(3);
    public static Roles SuperAdmin { get; } = new(4);
}

An immutable object is an object that, as soon as instantiated, can’t be altered. Therefore information possess intrinsic thread-safety and immunity to race situations. Immutable objects additionally make your code extra readable and simpler to keep up.

A major advantage of utilizing document varieties is preserving encapsulation as a result of any extension methodology you write might be part of the mannequin itself. Keep in mind, you can’t embrace any strategies inside an enum. 

Additional, information make it simple to supply significant names, as the next code illustrates.

public document Roles(int Id, string Identify)
{
    public static Roles Person { get; } = new(1, "Person");
    public static Roles Administrator { get; } = new(2, "Administrator");
    public static Roles Reviewer { get; } = new(3, "Reviewer");
    public static Roles SuperAdmin { get; } = new(4, "Tremendous Admin");
    public override string ToString() => Identify;
}

Now you can entry the constants of the Roles document in a lot the identical manner you’ll be able to entry enumeration constants.

Roles admin = Roles.Administrator;
Roles consumer = Roles.Person;
Roles reviewer = Roles.Reviewer;
Roles superAdmin = Roles.SuperAdmin;

Whenever you invoke the ToString() methodology, the title of the fixed might be displayed on the console window as proven in Determine 1.

record constants IDG

Determine 1: Displaying the title of the document fixed on the console window.

Alternatively, you would use a category as a substitute of a document kind after which outline the constants you want. Nevertheless, I’d all the time choose a document kind for efficiency causes. File varieties are light-weight varieties attributable to which they’re much quicker than lessons. A document is itself a reference kind but it surely makes use of its personal built-in equality verify, which checks by worth and never by reference.

Copyright © 2024 IDG Communications, Inc.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles