I am wrapping calls to an API and most of my methods have in their first lines:
if ( !Gree.Authorizer.IsAuthorized() )
{
return;
}
In python I would decorate those methods with something like @login_required
.
What would you use to refactor that type of logic in c#
?
Decorator in C++Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects, called decorators. Using decorators you can wrap objects countless number of times since both target objects and decorators follow the same interface.
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behaviour of function or class. Decorators allow us to wrap another function in order to extend the behaviour of the wrapped function, without permanently modifying it.
You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.
Decorators are a prime-time example of a perfectly implemented feature. It does take a while to wrap your head around, but it's worth it. As you start using them, you'll notice how they don't overcomplicate things and make your code neat and snazzy.
You are looking for a subset of a more general programming methodology called Aspect Oriented Programming.
C# seems to support it through several libraries, and one can also roll out his own, thanks to some of the CLR features. See Aspect Oriented Programming using .NET which covers its basic principles (I am linking the part of the article talking about the specifics of C#, but the rest is equally interesting if you are looking for ready-made solutions like PostSharp, as mentioned in another answer).
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