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 ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With