Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard Methods vs Extensions Methods

Tags:

c#

Assuming the following domain entity :

public enum Role
{
    User = 0,
    Moderator = 1,
    Administrator = 2
}

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public Role Role { get; set; }
}

I need to know if the user can perform "Edit" action. So i've 2 solutions :

Create a CanEdit method inside the User entity

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public Role Role { get; set; }

    public bool CanEdit()
    {
        return Role == Role.Moderator || Role == Role.Administrator;
    }
}

Create a CanEdit Extension Method for User type :

public static class UserExtensions
{
    public static bool CanEdit(this User user)
    {
        return user.Role == Role.Moderator || user.Role == Role.Administrator;
    }
}

Both solution works, but the question is WHEN use standard methods vs using Extensions methods ?

like image 403
Yoann. B Avatar asked Feb 28 '10 20:02

Yoann. B


People also ask

What does extension method mean?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is an advantage of using extension methods?

Extension methods can also help keep your classes and class dependencies clean. For instance, you may need a Bar() method for the Foo class everywhere Foo is used.

What are extension methods in agriculture?

Extension methods comprise the communication techniques between extension workers and target groups. To facilitate farmers' decisions whether or not and how to adopt fish farming. the problems to be solved. Generally speaking, mass media help extension agents to reach large numbers of farmers simultaneously.


1 Answers

Extension methods are simply syntactic sugar for plain, ordinary static methods.

If you control the class structure, you should implement all the necessary functionality within the class. Where extension methods are really useful/necessary is if you don't own the class that you are trying to "extend."

For this example, I think you should put the logic inside the User class. It is a logical function of the user itself; consumers should be able to use the CanEdit() method without having to use or even know about the UserExtensions class.

like image 69
Aaronaught Avatar answered Sep 29 '22 04:09

Aaronaught