Can u please clarify my doubt regarding the concept behind AOP & INHERITANCE concept in
OOP ?
We can use the same services through inheritance also .Then why we will go for AOP in spring framework?
Aspects are for intercepting calls and injecting logic. For instance, you may have an existing service class and you may want to log all incoming calls to that class -- then you would "simply" use AOP to intercept the incoming calls and perform logging in the interceptor.
See also http://en.wikipedia.org/wiki/Aspect-oriented_programming
Inheritance is just when you create a class that is more specific than an existing class. You may have a BusinessService and inherit a ScalableBusinessService from that, or a B2BIntegrationBusinessService... The inheriting class thus inherits methods and properties from the parent, and adds its own methods or overrides existing (virtual) methods. This is a totally different thing than injecting logic with AOP.
See also http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
Related
I read so many bad things about singleton pattern (What is so bad about singletons?), however, #Singleton is used everywhere in this Micronaut doc to illustrate inversion of control https://docs.micronaut.io/1.3.0.M2/guide/index.html#ioc
When is it appropriate to use #Singleton? For example, if I have a UserInfoService that has getUserInfo, createUserInfo, updateUserInfo method, is it a good idea to use #Singleton?
Another separate question is when do I use #Prototype, because if I don't use any annotation for a function/class, isn't it by default a prototype (as in I initiate a new instance of it in another class/function)?
When is it appropriate to use #Singleton? For example, if I have a
UserInfoService that has getUserInfo, createUserInfo, updateUserInfo
method, is it a good idea to use #Singleton?
UserInfoService should almost certainly be a stateless singleton.
Another separate question is when do I use #Prototype, because if I
don't use any annotation for a function/class, isn't it by default a
prototype (as in I initiate a new instance of it in another
class/function)?
If you initiate a new instance, then the annotation doesn't matter. The annotation only affects instances that the Micronaut container creates for you. For #Singleton the container creates a single instance and injects the same instance at all injection points that require it. For #Prototype the container creates a new instance for each injection point.
All of this is about application design more than it is about Micronaut. Micronaut provides a simple mechanism for you to declaratively express (by way of #Singleton or #Prototype) whether or not you want the same instance to be shared or not but the issue is really about application design. In general you should prefer stateless singletons. If for some reason you have a bean that must be stateful and you have good reasons to not want to share instances from different contexts, then #Prototype might be appropriate.
I hope that helps.
Let's be 100% clear that the GoF Singleton design pattern and the #Singleton annotation are two different things.
Consider that the Singleton design pattern requires you to change your code. You must write the code in such a way as to prevent multiple instantiations.
On the other hand, you can add the #Singleton annotation to any class you like, without modifying its code to prevent instantiation; and as #Jeff-Scott-Brown points out, you can instantiate this Micronaut "Singleton" repeatedly by simply calling its constructor.
The #Singleton annotation does not exhibit those negative consequences you've read about in the Singleton design pattern, because it doesn't implement the Singleton design pattern. The term is overloaded to mean two different things here.
On a related note the #Prototype annotation doesn't follow the GoF Prototype design pattern either. Spring prototype following prototype design pattern
As Jeff Scott Brown covers most parts of your question, your have to be careful to the nuance between Singleton scope in Spring and singleton pattern.
Some of the main differences between these 2 are
Singleton pattern ensures one instance of a particular class of per
class loader.
Spring Singleton is “per container per bean”.
Hope that helps.
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.
From a picture, Can i use inheritance instead of implement an interface?
I mean change from "ConcreteStrategyA and ConcreteStrategyB implements Strategy Interface" to "ConcreteStrategyA and ConcreteStrategyB extends Strategy Class"
Is it still work well or have some problem?
If it still work well my next question is "Why most people prefer to use interface?"
Well technically from a Design pattern perspective with the Strategy pattern, the concrete Strategies need to implement (I mean write code for, not the interface implements thing) a common contract which the Strategy Context is aware of. This is the primary backbone of Strategy pattern philosophy. The adherence to the common contract is what allows the Strategy context to replace the concrete strategies based on some runtime feature. This pattern ideology is what we loosely call Polymorphism in OOP parlance.
Now in Java you can implement his polymorphic strategy either as an interface or as inheritance. For interface you have given the example in the question itself. For inheritance as long as the contract holds between subclasses (something like a base abstract class with an abstract contract which subclasses implement to provide concrete strategy implementations) you can implement Strategy pattern in inheritance as well.
Now thinking about it from OOP perspective. For OOP inheritance is something which a subclass inherits from a super class. The subclass automatically owns and thus demonstrates that inherited generic behavior but it has a choice to make that behavior more specific to its own type. Thus multiple subclasses can override the same behavior and make bits of it more specific to their use. But this chain becomes cumbersome to manage when it gets too long or when subclasses try to inherit the behaviors which don't apply to them logically.
Thus it makes more sense to implement Strategy pattern using interfaces as against inheritance.
Absolutely. Inheritance is most often used with an abstract base class, when you want your derived strategies to share some common code.
People prefer to use interfaces or abstract classes over concrete base classes because :
With a Dependency Inversion approach, a class needs loose coupling to its Strategy. It only needs to know that the Strategy fulfills a contract, but doesn't want to know about its implementation details. Interfaces and abstract classes are an elegant and minimal way to define a contract without specifying the implementation.
It doesn't make sense to instantiate the base Strategy class most of the time, because it's a general, abstract concept -- in fact, it's better if you forbid instantiating it.
There are no technical problems.
However, a class can only extend one base class but it can implement multiple interfaces. So if you want to, let's say, change your inheritance structure in the future it is easier if you choose to implement an interface instead.
As you know a design pattern is "a general solution to a commonly occurring problem". It just describe a general solution without indications concerning implementation details.
If your problem requires a class in place of the interface, there is nothing wrong replacing it with a concrete (or abstract) class.
Using an interface in the pattern UML is a way to say: "you have to expose this set of public methods".
So, no problem using your approach. As an alternative you could leave the Strategy interface and implement it in a StrategyImpl class, then you can inherit this class in your ConcreteStrategyA and ConcreteStrategyB classes.
It's good practice for a class' implementation to be defined by interfaces. If a class has any public methods that aren't covered by any interfaces then they have the potential to leak their implementation.
E.g. if class Foo has methods bar() and baz() but only bar() is covered by an interface then any use of baz() doesn't use an interface.
It feels like to get cleaner code it would make sense to either:
create extra interfaces if the class has to have those methods (eg a separate interface to cover the behavior of baz() above)
or ideally refactor (eg using more composition) so the class doesn't need to have so many methods (put baz() in another class)
Having methods not covered by an interface feels like a code smell. Or am I being unrealistic?
I consider it as "overusing" the interface.
Interface can give you access only to limited functionality, therefore it is good for gathering more classes with similar functionality into one List<Interface> and using them, for example.
Or if you want to keep loose coupling principle, you rather give another component some interface than the whole class(es).
Also some classes should have restricted access to another classes, which can be done with interfaces too.
However high cohesion principle (which is usually connected to loose coupling) does not prevent you from using class itself, if two classes are and should be "strong" connected to each other.
I don't think that's the purpose of interfaces. If you actually talk about the 'is-a' and 'has-a' relationship between classes, not necessarily a class needs to cover all public methods in interfaces. That's like taking the concept too far.
A class can have methods which describe it's behavior but then, there are some methods that do not exactly describe the classes' behavior but rather describe what else the class can do.
In case if a question arises about SRP regarding the 'can-do' behaviors, it is possible that the class can use a component to execute those behaviors rather than implementing within itself.
For e.g., I have a class DataGrid, why would I need to have an interface called IDataGrid which exposes all the public methods. But may be there is an additional functionality that the DataGrid can do, which is export the data. In that case I can have it implement IExportData, and implement the ExportData method, which in turn does not export the data but uses a component, say DataExportHelper, that actually does the job.
The DataGrid only passes the data to the component.
I don't think SRP will be violated in the above example.
EDIT:
I am a .Net developer, so would like to give you and example from MS library classes. For e.g., the class System.Windows.Window does not implemnt any interface that has Close() method. And I don't see why it should be a part of any presenter.
Also, it is possible that something might look seem like a code smell but not necessarily it might be wrong. Code smell itself does not mean there is a problem but that there is a possibility of problem.
I have never come across any principle or guideline in software design which mentions that all the public members of a class need to be exposed in some or the other interface. May be doing that just for the sake of it might be a bad design.
No, I would definitely not consider methods not covered by an interface a code smell.
It seems like this might be dependent on the object infrastructure you are building in, but in the infrastructures I'm familiar with, the real point of interfaces is to provide a manageable form of multiple inheritance. I consider the overuse of multiple inheritance a notable smell.
In .NET at least, abstract classes are explicitly the preferred construct for exposing abstraction (not interfaces). The .NET design guidelines say: Do favor defining classes over interfaces., with rationale described here http://msdn.microsoft.com/en-us/library/vstudio/ms229013(v=vs.100).aspx.
Even in COM (where any externally visible functionality had to be defined in an interface) there are perfectly good reasons to have non-exposed functions: limiting the visibility of implementation details. COM was originally defined in C (not C++) which lacked the richer set of access modifiers that newer languages have, but the concepts were there: published interface members were public, everything else was internal.
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.