Is there any difference between AOP and Meta-Programming?
Can we say that meta-programming techniques(IL-weaving, dynamic sub-classing etc.) are mechanisms to achieve AOP which is more about separation of cross-cutting concerns from main application code concerned with actual business requirements?
As I see it, metaprogramming is just a way to make AOP work without explicit support for it.
AOP could be implemented without metaprogramming, if your platform specifically supported it. And metaprogramming can be used for many other things than just AOP.
Related
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#?
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).
You can use any AOP tool for C# such as this one.
With PostSharp, software developers can encapsulate implementation
patterns into classes called aspects, and apply these aspects to their
code using custom attributes.
I'm not familiar with python but it seems you are looking for "attributes" (MSDN), (which are pretty similar to Java annotations).
In particular, .NET provides the "AuthorizeAttribute", which does exactly what you want (and maybe a little more). While you are not under .NET, this may still shed some light in the implementatino you are trying to achieve.
I've been searching a bit for some performance tests about typical AOP tasks. I've not been able to find any though, could you help me?
I'm mostly thinking about Castle, Unity and perhaps PostSharp, even though it might be too expensive for my project.
I haven't seen any quantitative comparisons, too, so this answer is probably far from being complete.
It is difficult to compare performance of Castle or Unity with PostSharp - Castle and Unity use runtime weaving by dynamic proxying and PostSharp adds overhead at compile stage. So if performance is crucial for you, compiled solutions like PostSharp will always be better. Generating AOP proxies in runtime means dynamic generating IL code and heavy reflection use.
So performance tests that could make sense have to compare solutions using the same technique - you can try to compare Castle Dynamic Proxy and Unity Interception proxy implementation.
I don't know the former well, but in case of latter, there are still three different scenarios to compare - transparent proxies (MarshalByRefObject), interface proxies and subclassing proxies - each with its own set of usage scenarios and its own performance overheads. From what I've read, transparent proxy is horribly slow and shouldn't be used in AOP scenarios. Interface and subtyping proxies generates some IL on the fly and this is the same what Castle DP does so I believe the differences shouldn't be so big (but again, no quantitative results here).
If you are looking for a light weight AOP tool, there is a article "Add Aspects to Object Using Dynamic Decorator" (http://www.codeproject.com/KB/architecture/aspectddecorator.aspx). It is thin and flexible.
It describes an approach to adding aspects to object at runtime instead of adding aspects to class at design time. The advantage of this approach is that you decide if you need an aspect when you use an object.
Most of today's AOP tools define aspects at class level at class design time. And you don't have the flexibility when you use an object of the classes.
If performance is crutial in your project, make sure your usage of the AOP is performance oriented because the overhead of an AOP Framework is rarely poor unless the usage is not compliant.
For example, if you use DynamicProxy, you have the choice to call the backing treatment using reflection or calling Proceed() method. It alter differently performance.
Another example : most of AOP Framework give you the MethodInfo to your "advice". The way how they get this metedata can alter your performance because GetMethodFromHandle can be very bad in extremely concurrency treatments (dictionary access with a lock).
Another important thing to keep in mind : use the adapted overlod for Advice method because if AOP Framework have to prepare too much informations (argument, methodinfo, ...) You will pay it (performance overhead). Unfortunely, sometimes there is no good user end interface to implement a performant advice event if interception was perfect.
For more details, in the post when-is-aop-code-executed, I give my feedback about performance issue of AOP Framework.
In C++, I often needed NVI to get consistency in my APIs. I don't see it used as much among others in C#, though. I wonder if that is because C#, as a language, offers features that makes NVI unnecessary? (I still use NVI in C#, though, where needed.)
C# poses a problem with NVIs by taking away multiple inheritance. While I do think that multiple inheritance generates more evil than good, it is necessary (in most cases) for NVI. The simplest thing that jumps to mind: a class in C# cannot implement more than one NVI. Once one discovers this unpleasant aspect of C#/NVI tandem, it becomes much easier to give up NVIs than C#.
And by the way, speaking about aspects. That's a very interesting concept, and it's aim is exactly the same as that of NVIs, only it attempts to look at the "true essense" of the issue and address it "properly", so to say. Take a look.
And as far as .NET Framework goes, there is a mechanism to do just that: inject code that is "orthogonal", so to say, to the main logic at hand. I'm talking about all that MarshalByRef/TransparentProxy business, I'm sure you've heard of it. It does seriously impact performance, though, so no big luck here.
There have also been numerous attempts to implement the same concept through other techniques, from building facades to the dirty business mentioned above to post-processing of MSIL.
The latter approach happens to appeal to yours truly the most, since it can be made transparent (by incorporating needed steps into one's build routine), it doesn't affect performance (more than is absolutely necessary to actually execute the "orthogonal" code) and it does not involve some kind of "hacking" or reverse engineering, since MSIL is open and well documented.
Here one can find these points discussed in more detail, as well as more information and links to actual tools. Using Google for the same purpose is also acceptable. :-)
Good luck.
I think the explanation is simply that in C#, "traditional" Java-style OOP is much more ingrained, and NVI runs counter to that. C# has a real interface type, whereas NVI relies on the "interface" actually being a base class. That's how it's done in C++ anyway, so it fits naturally there.
In C#, it can still be done, and it is still a very useful idiom (far more so, I'd say, than "normal" interfaces), but it requires you to ignore a built-in language feature.
Many C# programmers just wouldn't think of a NVI class as being "a proper interface". I think this mental resistance is the only reason why it's less common in C#.
Trey Nash in his book Accelerated C# promotes the NVI pattern as a canonical form in C#.
I don't know who wrote the article you reference (More C++ Idioms/Non-Virtual Interface), but I feel the author missed the point.
...
Interface vs Abstract classes
I'd argue that, philosophically, there's little difference (in C#) between a fully abstract class (ie no implementation whatsoever) versus an interface. On the surface, they both can provide a signature of methods that can be performed and require something else to implement that functionality.
With C# you would always program to an interface if what you need is an interface. You only use an (abstract) base class because you also want implementation reuse as well.
Many code bases combine these and program to the interface in addition to providing a class hierarchy as a default implementation for the interface.
NVI for Interfaces in C
If your only motivation to use NVI in C++ would be to have an interface, then no, you're not going to use this in C# because the language / CLR provides interfaces as a first-class feature.
NVI and object hierarchies
In my mind, NVI has never been about interfaces. It's always been an excellent way to implement the template method pattern.
The usefulness manifests itself in code lifecycle maintenance (ease of change, extension, etc), and provides a simpler model of inheritance.
My opinion: Yes, NVI is very useful in C#.
I think NVI is as useful in C# as it is in C++. I see it used very frequently at my company.
Is the recent movement towards anonymous methods/functions by mainstream languages like perl and C# something important, or a weird feature that violates OO principles?
Are recent libraries like the most recent version of Intel's Thread Building Blocks and Microsofts PPL and Linq that depend on such things a good thing, or not?
Are languages that currently reject anonymous methods/functions, like Java, making wise choices in sticking with a purely OO model, or are they falling behind by lacking a fundamental programming feature?
The expressive power of lambda expressions combined with fluent APIs like LINQ far outweigh any perceived violation of pure OO principles.
Object Orientation is a design philosophy, not a set of commandments on stone tablets.
Since lambda functions increase the power/expressiveness of the language many-fold, refusing them merely on "it violates pure OO model" is rather self-defeating: the overall goal is to design good software, NOT to design OO code.
Plus, I'm not quite certain that correctly written lambda functions "violate OO model" per se. More like are outside of the model.
No inherent violation of OO pronciples anyway.. Not that I can see...
Encapsulation, Inheritence and Polymorphism being the canonical list, AM are not inconsistent with any of the three... They are a method, not a Type... So just like a full .Net 1.1 representation of a Method Delegate, they can be written to use or abuse any of the three OO principles.
C# has always had delegates; its always had event handling. The CLR 2.0 (and C# 2.0) introduced the concept of anonymous delegates to meet a variety of needs that could probably have been solved with design patterns in any OO technology. They've just made it official that functions are "first-class objects" in these technologies.
I dare say that the mixture of functional and object features in a technology like C# has become so useful that its hard to imagine writing applications without the benefits of both worlds.
Java's not "sticking with a purely OO model" out of principle; the Java community just can't agree on what functional additions to the language should look like or whether they're worth the additional complexity in the syntax. According to James Gosling:
Closures were left out of Java
initially more because of time
pressures than anything else. In the
early days of Java the lack of
closures was pretty painful, and so
inner classes were born: an
uncomfortable compromise that
attempted to avoid a number of hard
issues. But as is normal in so many
design issues, the simplifications
didn't really solve any problems, they
just moved them.
(From "Understanding the closures debate", which is a pretty good overview of the state of the functional programming debate in the Java community as of last summer. The consensus seems to have been to punt on it for now.)
Python has always had them.
A function is a class of objects with a really narrow interface and not many attributes.
Python function objects have a number of built-in attributes, and you can always add more if you want.
Callbacks are a fundamental part of OO. It rather makes sense to have good syntactical support for the common case of a single-method callback object. Exactly how that is implemented is another matter.
How would it violate OO principles?
It doesn't violate encapsulation: A class is still in full control of which functions get access to its private members.
It doesn't interfere with inheritance or polymorphism either.
It only violates OO principles if you're a Java programmer and define "OO principles as "can be implemented in Java"
Luckily, no one outside the world of Java, have ever used such a definition of OOP.
It may be said to violate Java's philosophy, which I'd say is a good thing, because Java's philosophy is essentially "start with a broken and mangled version of OOP, and stay there, without ever adding to it or evolving it in any meaningful way". That's not a philosophy that deserves to stay unbroken.
But it doesn't violate the principles of OOP.
I've been using some basic AOP style solutions for cross-cutting concerns like security, logging, validation, etc. My solution has revolved around Castle Windsor and DynamicProxy because I can apply everything using a Boo based DSL and keep my code clean of Attributes. I was told at the weekend to have a look at PostSharp as it's supposed to be a "better" solution. I've had a quick look at PostSharp, but I've been put off by the Attribute usage.
Has anyone tried both solutions and would care to share their experiences?
Couple of minor issues with PostSharp...
One issue I've had with PostSharp is that whilst using asp.net, line numbers for exception messages are 'out' by the number of IL instructions injected into asssemblies by PostSharp as the PDBs aren't injected as well :-).
Also, without the PostSharp assemblies available at runtime, runtime errors occur. Using Windsor, the cross-cuts can be turned off at a later date without a recompile of code.
(hope this makes sense)
I only looked at castle-windsor for a short time (yet) so I can't comment on that but I did use postsharp.
Postsharp works by weaving at compile time. It ads a post-compile step to your build where it modifies your code. The code is compiled as if you just programmed the cross cutting concerns into you code. This is a bit more performant than runtime weaving and because of the use of attributes Postsharp is very easy to use. I think using attributes for AOP isn't as problematic as using it for DI. But that's just my personal taste.
But...
If you already use castle for dependency injection I don't see a good reason why you shouldn't also use it for AOP stuff. I think though the AOP at runtime is a bit slower than at compile time it's also more powerful. AOP and DI are in my opinion related concepts so I think it's a good idea to use one framework for both. So I'll probably look at the castle stuff again next project I need AOP.