Why are pure inheritance based proxies bad in AoP - aop

I have a problem making method calls between methods in same class and having transaction advice apply.
Spring Framework .NET documentation states that it supports compositional and inheritance based proxies and that you can force spring to create inheritance based proxies (proxies without target) to be instantiated.
However, it turns out that even 'inheritance based proxies' are not what they claim. They do inherit target class rather than it's interface(s), but they still use target object. This leads to the fact that on calls between methods in same class advices are not applied.
Admittedly, Spring makes it available to do this with some effort using InheritanceBasedAopConfigurer but you still have to list objects you want to apply this to and advice you want to apply to them.
Why is Spring jumping through hoops to avoid real inheritance based proxies? What anti-pattern am I missing?

I can see multiple reasons:
1) Implementation more complicated. IoC container manages instance, and to apply pure inheritance based proxies, you need to work on the type. That's what 'InheritanceBasedAopConfigurer' does: it changes the type before container initialization.
2) You need to mark your method as virtual if you want AOP to work. It's not intuitive.
3) Composition based proxies forces design by interface which is a good practice.

Related

Converting the interfaces in hierarchical structure in OOD

I have a question about Facade design pattern. As i started learning design patterns from the book: Elements of re-useable object -oriented-software, there is a good explaination of what it is and how it solves the problem.
This Picture comes from that book:
Problem:
Suppose i add some extra functionality in the subsystem for which Domain is an Facade/interface. With this design, i think it's not possible to add extra functionality in the subsystem without changing the Domain class?
Second, suppose i use an abstract class Domain(to create a hierarchical structure) and delegate all the requests to it's subclasses so that whenever i want to add new functionality , i simply extend my new class/subsystem with Domain(abstract), would that be wrong or still i will have a Facade structure?
Same thing happends in Adapter pattern. We can have different kind of adapter and instead of hard-coding one class , can we create such an hierarchial structure without violating any OOD rule?
The facade as well as the adapter design patterns are part of the so called "wrapper" patterns (along with decorator and proxy). They essentially wrap certain functionality and provide a different interface. Their difference is on their intent:
facade: is used to provide a simple interface to clients, hiding the complexities of the operations it provides behind it
adapter: allows two incompatible interfaces to work together without changing their internal structure
decorator: allows new functionalities to be added to an object statically or dynamically without affecting the behavior of objects of the same class
proxy: a class (proxy) is used to represent and allow access to the
functionality of another class
If your components "in the back" add new functionality and you want your facade to expose this functionality, you would have to adjust your facade to do so.
If you have the Domain class (facade in your scenario) as an abstract class that others extend, you do not have a facade, you have whatever inheritance you created with your classes. Simply put there is no "wrapping" for achieving the intent of the facade pattern.
With this design, I think it's not possible to add extra functionality in the subsystem without changing the Domain class?
True. However, the changes you make may (or may not) affect the client (Process) class. If you add a new method to the Façade, it won't break the "old" clients. Although it's not its explicit intention (which is to hide complexities of a sub-system), Façade can provide a stable interface to its clients that can be extended. When I say interface, I don't mean a Java or C# interface. It's a programming interface.
A real-world example is the JOptionPane Façade in Java/Swing. Check the Java doc at the link I put and you'll see that some of its methods existed in 1.4, some in 1.6, etc. Basically, since this class is part of a Swing library, it had to remain stable so old clients of it's interface would not break. But it was still extended with new functionality by simply adding new methods.
I would say this is how Façades are typically extended, not with sub classing or hierarchy. Hierarchies are difficult to maintain, because they are brittle. If you get the abstraction wrong (the root of the hierarchy), then it affects the entire tree when you need to change it. Hierarchies make sense when the abstraction in the hierarchy is stable (certain).
The Adapter pattern has hierarchy because an Adapter adapts a method to work with several variants of a service that cannot be changed. You can see examples of several stable (abstract) services such as tax calculation, accounting services, credit authorization, etc. at https://stackoverflow.com/a/13323703/1168342.

Implementing .Net DI Compile Time Proxies?

I'm not so much seeking a specific implementation but trying to figure out the proper terms for what I'm trying to do so I can properly research the topic.
I have a bunch of interfaces and those interfaces are implemented by controllers, repositories, services and whatnot. Somewhere in the start up process of the application we're using the Castle.MicroKernel.Registration.Component class to register the classes to use for a particular interface. For instance:
Component.For<IPaginationService>().ImplementedBy<PaginationService>().LifeStyle.Transient
Recently I became interested in creating an audit trail of every class and method call. There's a few hundred of these classes so writing a proxy class for each one by hand isn't very practical. I could use a template to generate the code but I'd rather not blow up our code base with all that.
So I'm curious if there's some kind of on the fly solution. I know nHibernate creates proxy classes at some point which overlay all the entity classes. Can someone give me some guidance on how I might be able to do something similar here?
Something like:
Component.For<IPaginationService>().ImplementedBy<ProxyFor<PaginationService>>().LifeStyle.Transient
Obviously that won't work because I can only use generics to generalize the types of methods but not the methods themselves. Is there some tricky reflection approach I can use to do this?
You are looking for what Castle Windsor calls interceptors. It's an aspect-oriented way to tackle cross-cutting concerns -- auditing is certainly one of them. See documentation, or an article about the approach:
Aspect oriented programming is an approach that effectively “injects” pieces of code before or after an existing operation. This works by defining an Inteceptor wrapping the logic being invoked then registering it to run whenever a particular set/sub-set of methods are called.
If you want to apply it to many registered services, read more about interceptor selection mechanisms: IModelInterceptorsSelector helps there.
Using PostSharp, things like this can be even done at compile time. This can speed the resulting application, but when used correctly, interceptors are not slow.

The delegates need the methods and attributes of the holder class

I have some entity, which depending on internals, may act in two ways. For example, my Connector class can operate as a HttpConnector and as a TCPConnector. The implementation of 'connect' method differs for these two 'engine' classes. Both of them share some common methods of Connector such as "openFileToTransfer(String fileName)" and share common attributes such as "folderWithFiles" etc. I need two find the best OOP design for this problem.
1) first way is delegation. I create Connector with TCPConnectorEngine and it works. The problem is that I need to share some settings and common methods. I dont want to copy paste them of course into each of the classes. I can provide common settings via constructor, which implies coding the same attributes two times, but sharing common methods is harder. May be I can inject Connector instance in each of them, but that looks ugly. May be I can provide a BaseClass for both of my ConnectorEngines, but this looks more complicated.
2) second way is inheritance. I just inherit TCPConnector from Connector and get all I need. But I suppose the 'engine' decision fits better for my task just because it fits better logically. It is really an engine of Connector, its not different types of Connector.. but may be I am wrong?
Which way you would choose and why?
I work with Java, if it matters for the answer.
In pattern terminology, the question boils down to, how to implement a Connection interface properly:
1) Use a facade and then delegate to a strategy.
2) Or use an abstract base class and inherit with concrete implementation.
So in my opinion 2 is a good solution, only in case the internal choreography or protocol of the chil classes is quite similar and they therefore can share a lot of structure and code, which is then captured in the base class.
If the concepts used internally are quite different, I think it is better to implement different strategies, instanciate those in a facade class and delegate to the strategy instances. If you want code reuse, e.g. for the settings, I would keep this concept in a different class, e.g. ConnectionSettings and inject that to the strategy instance from the facade.

Is there a case for parameterising using Abstract classes rather than Interfaces?

I'm currently developing a component based API that is heavily stateful. The top level components implement around a dozen interfaces each.
The stock top-level components therefore sit ontop of a stack of Abstract implementations which in turn contain multiple mixin implementations and implement multiple mixin interfaces.
So far, so good (I hope).
The problem is that the base functionality is extremely complex to implement (1,000s of lines in 5 layers of base classes) and therefore I do not wish for component writers to implement the interfaces themselves but rather to extend my base classes (where all the boiler plate code is already written).
If the API therefore accepts interfaces rather than references to the Abstract implementation that I wish for component writers to extends, then I have a risk that the implementer will not perform the validation that is both required and assumed by other areas of code.
Therefore, my question is, is it sometimes valid to paramerise API methods using an abstract implementation reference rather than a reference to the interface(s) that it implements?
Do you have an example of a well-designed API that uses this technique or am I trying to talk myself into bad-practice?
So far, so good (I hope).
Not quite. Implementing a dozen interfaces isn't a good sign. But I can't tell how to restructure, or is it possible, since I don't know the code.
Therefore, my question is, is it sometimes valid to paramerise API methods using an abstract implementation reference rather than a reference to the interface(s) that it implements?
Rarely, yes. For example (Java):
JSF: javax.faces.context.FacesContext is abstract, but is passed around as parameter.
EL: javax.el.ELContext - ditto.
AWT: java.awt.Image - ditto.
But anyway, I'd say no. It is not good to constrain developers to implementations. They might want to provide a mock that should not perform any of the mentioned validations, or would use dynamic proxies.
Finally, if you are absolutely sure you can't restructure your interfaces, you may go with as little abstract class parameters as possible.

Should every single object have an interface and all objects loosely coupled?

From what I have read best practice is to have classes based on an interface and loosely couple the objects, in order to help code re-use and unit test.
Is this correct and is it a rule that should always be followed?
The reason I ask is I have recently worked on a system with 100’s of very different objects. A few shared common interfaces but most do not and wonder if it should have had an interface mirroring every property and function in those classes?
I am using C# and dot net 2.0 however I believe this question would fit many languages.
It's useful for objects which really provide a service - authentication, storage etc. For simple types which don't have any further dependencies, and where there are never going to be any alternative implementations, I think it's okay to use the concrete types.
If you go overboard with this kind of thing, you end up spending a lot of time mocking/stubbing everything in the world - which can often end up creating brittle tests.
Not really. Service components (class that do things for your application) are a good fit for interfaces, but as a rule I wouldn't bother having interfaces for, say, basic entity classes.
For example:
If you're working on a domain model, then that model shouldn't be interfaces. However if that domain model wants to call service classes (like data access, operating system functions etc) then you should be looking at interfaces for those components. This reduces coupling between the classes and means it's the interface, or "contract" that is coupled.
In this situation you then start to find it much easier to write unit tests (because you can have stubs/mocks/fakes for database access etc) and can use IoC to swap components without recompiling your applications.
I'd only use interfaces where that level of abstraction was required - i.e. you need to use polymorphic behaviour. Common examples would be dependency injection or where you have a factory-type scenario going on somewhere, or you need to establish a "multiple inheritance" type behaviour.
In my case, with my development style, this is quite often (I favour aggregation over deep inheritance hierarchies for most things other than UI controls), but I have seen perfectly fine apps that use very little. It all depends...
Oh yes, and if you do go heavily into interfaces - beware web services. If you need to expose your object methods via a web service they can't really return or take interface types, only concrete types (unless you are going to hand-write all your own serialization/deserialization). Yes, that has bitten me big time...
A downside to interface is that they can't be versioned. Once you shipped the interface you won't be making changes to it. If you use abstract classes then you can easily extend the contract over time by adding new methods and flagging them as virtual.
As an example, all stream objects in .NET derive from System.IO.Stream which is an abstract class. This makes it easy for Microsoft to add new features. In version 2 of the frameworkj they added the ReadTimeout and WriteTimeout properties without breaking any code. If they used an interface(say IStream) then they wouldn't have been able to do this. Instead they'd have had to create a new interface to define the timeout methods and we'd have to write code to conditionally cast to this interface if we wanted to use the functionality.
Interfaces should be used when you want to clearly define the interaction between two different sections of your software. Especially when it is possible that you want to rip out either end of the connection and replace it with something else.
For example in my CAM application I have a CuttingPath connected to a Collection of Points. It makes no sense to have a IPointList interface as CuttingPaths are always going to be comprised of Points in my application.
However I uses the interface IMotionController to communicate with the machine because we support many different types of cutting machine each with their own commend set and method of communications. So in that case it makes sense to put it behind a interface as one installation may be using a different machine than another.
Our applications has been maintain since the mid 80s and went to a object oriented design in late 90s. I have found that what could change greatly exceeded what I originally thought and the use of interfaces has grown. For example it used to be that our DrawingPath was comprised of points. But now it is comprised of entities (splines, arcs, ec) So it is pointed to a EntityList that is a collection of Object implementing IEntity interface.
But that change was propelled by the realization that a DrawingPath could be drawn using many different methods. Once that it was realized that a variety of drawing methods was needed then the need for a interface as opposed to a fixed relationship to a Entity Object was indicated.
Note that in our system DrawingPaths are rendered down to a low level cutting path which are always series of point segments.
I tried to take the advice of 'code to an interface' literally on a recent project. The end result was essentially duplication of the public interface (small i) of each class precisely once in an Interface (big I) implementation. This is pretty pointless in practice.
A better strategy I feel is to confine your interface implementations to verbs:
Print()
Draw()
Save()
Serialize()
Update()
...etc etc. This means that classes whose primary role is to store data - and if your code is well-designed they would usually only do that - don't want or need interface implementations. Anywhere you might want runtime-configurable behaviour, for example a variety of different graph styles representing the same data.
It's better still when the thing asking for the work really doesn't want to know how the work is done. This means you can give it a macguffin that it can simply trust will do whatever its public interface says it does, and let the component in question simply choose when to do the work.
I agree with kpollock. Interfaces are used to get a common ground for objects. The fact that they can be used in IOC containers and other purposes is an added feature.
Let's say you have several types of customer classes that vary slightly but have common properties. In this case it is great to have a ICustomer interface to bound them together, logicaly. By doing that you could create a CustomerHander class/method that handels ICustomer objects the same way instead of creating a handerl method for each variation of customers.
This is the strength of interfaces.
If you only have a single class that implements an interface, then the interface isn't to much help, it just sits there and does nothing.