Spring AOP or AspectJ way for selecting parents of a given class - aspectj

I have a pointcut definition in Spring AOP, which selects a certain set of classes, let say A. Is there a possibility to select the parent classes of all classes in A? I would prefer a solution in Spring AOP, but I would be also thankful for a predicate definition in AspectJ that would do the job.

You can easily select A and all sub classes for A with A+ , but as class A might have many root classes (parent for parent for parent .... Object) I think you can't create selector for this case. But you can create general pointcup and check inside aspect's advice call, if it's one of parent class for A . BUT it will reduce performance a bit as you add aspect's call / check. I don't know your requirements , but if it's acceptable try this.

Related

Best practices for Eclipse 4 DI

I'd like to know what the best practices are for Eclipse 4 dependency injection.
After reading about this subject on the internet, I came up with the following strategy.
requirements
Share the data model of the application (e.g. company, employee, customer, ...) so that framework objects (view parts, handlers, listeners, ...) can access it with as little coupling as possible.
proposed strategy
I've used the lifeCycleURI plugin property to register a handler which is triggered at application startup. Such handler creates an "empty" top-level data model container object and place it into the EclipseContext. It is also discarded when application stops.
All Eclipse framework classes (view parts, handlers) use the classic DI to get such data model object injected.
Button listeners created with the class constructor can't have the data model object injected in them. So I thought they could be created with ContextInjectionFactory.make() to have injection performed. This would couple the class which creates the listener with CIF, but the great advantage is that injection works out of the box.
This is the best solution I've found yet to leverage E4 DI with as little coupling as possible. The weak spot is in my opinion this coupling with CIF. My question would be whether any strategy exist to remove even this coupling, or alternate solutions for the same requirements.
You can create a service class in your project, let's say ModelService.
Add #creatable and #singleton annotations to that class :
#creatable
#singleton
class ModelService{
}
And let DI do its job using following syntax in your parts/handlers/etc ..
#Inject ModelService modelService;
Then you can implement methods in your service like 'createBaseModel()', updateModel() and so on.
This creates a low coupling solution : you can also implement ModelService in a separate plugin and define it as a OSGi service.
for that solution, you can read this Lars Vogel article.

MVVM Dependency Injection

I'm in the process of teaching myself the MVVM pattern by dividing the pattern into its core facets and learning those facets one by one.
My question is related to dependency injection. What is it, and why/when should I use it? I've looked at Jason Dolinger's excellent MVVM intro video and I see he uses Unity. This might be strange to ask but how would I implement dependency injection WITHOUT using Unity? I basically want to understand the concept of dependency injection and how to use it without having to implement other frameworks/tools (for now).
Thanks.
I think it's good that you want to understand DI without using a framework, the concept is not terribly difficult to wrap your head around.
Let's say you want to use some form of transportation.
interface ITransportation
{
Transport();
}
An initial implementation of a method that uses a form of transportation might look like this:
public void Move()
{
ITransportation car = new Car();
car.Transport();
}
The problem with that method is that it is now dependent on a Car class. We should pass our transportation object in for added flexibility. This is inversion of control and is closely related to DI.
public void Move(ITransportation tr)
{
tr.Transport();
}
As you can see, we don't need to know anything about a specific DI framework. You might also want to check out the ninject DI by hand tutorial.
Just to extend #Andy's answer
Dependency Injection is one of the forms of the Dependency Inversion Principle
To achieve the decoupling of dependencies (as typically found in layered architecture),
DI is commonly used for instantiation scenarios such as basic new() and patterns like Factory method. In addition to being able to inject a new dependency instance every time (e.g. like factory), containers can also be set up to inject named instances, singleton instances, etc - i.e. IoC containers usually also take on the responsibility of managing the lifespans of objects as well.
One potential 'mindset shift' is that dependencies now potentially become publicly visible on concrete classes, since DI typically injects via constructors or public Get / Set properties. This may seem strange if you are used to using OO encapsulation, where dependencies of a class are seen as implementation and should be hidden from the 'outside' i.e. class method signatures.
However, by implementing Interface / Concrete class separation (as you should, not only for decoupling but also for testing / mocking purposes), the injection constructors / property injection methods will not be on the interface, so encapsulation is again in place.
Re : "Doing DI by hand" without Unity etc
What you would need to do is to code your own IoC container, which then is responsible for 'building up' instances of classes - during each 'build up', you would scan the class for dependencies (which are configured in the container, e.g. by config, by attributes, or simply just by convention, e.g. all public settable properties, or any class parameters on a constructor will be assumed to be dependencies). You would then create (if necessary) and inject this 'dependency' instance onto the object (e.g. by using reflection). And then recursively, all dependencies of these dependencies need to be built up etc. You would then also need to provide lifespan management for each of the objects, e.g. Singletons etc.

Class design 'dilemma'

I never did proper class design, so bear with me.
Let's say we have a Project class. Then let's say we have a ProjectGroup class that has the same members as the Project class, plus a list of Projects.
Should ProjectGroup be the superclass of Project or is ProjectGroup a specialization of Project and the former should be a subclass of the latter?
I won't bother you with theory, because you're probably in a hurry to get a quick answer. So here it goes:
If your two classes are actually implying they should be related by inheritance then ProjectGroup should inherit from Project class. This is how it would look like in C#:
public class ProjectGroup: Project ...
If they are not, but they use some common class members (that define their state and some functionality over that state), then I'd write an interface and implement it in both classes. C# code again:
public interface ICommonState ...
public class Project: ICommonState ...
public class ProjectGroup: ICommonState
{
IEnumerable<ICommonState> projects
...
}
Edit
If your classes are actually Project and ProjectGroup and they both have properties like ID and Name in common (for instance), they still shouldn't be inherited. They just happen to have properties with the same name, but they are basically different entities.
They could both either
implement an ICommonEntity interface - use it when they have the same state+functionality but functionality behaves differently in each of them
inherit from CommonEntity class - use it when functionality is completely identical; this way you'll follow the DRY (don't repeat yourself) philosophy
So your component may be an interface or a class (when using composite pattern).
Direct inheritance between two classes is more suitable where entities imply on being in relation to each other. Like User and Person classes. They can be inherited either way. Depending on the business scenario.
class User: Person
This would be the case where you have an application with contacts. Some of them are also users of this very same application.
class Person: User
This would be a web site where you can register as a user. In case you fill up some personal details as well your user data becomes of type Person.
It sounds like you might want the Composite pattern. Both LeafProject and CompositeProject implement the Project interface, and CompositeProject also holds a collection of Project instances.
if the member list of projects is unique to projectgroup and does not apply to all types of projects, then make project your super/base class and derive projectgroup from project.

AspectJ problem

Hi I am new to AspectJ and I would like to find out if creating variants of a class using Aspects - I will create another instance of the class as well?
I am guessing that the question is, if I am adding aspects would a new class be created.
The answer is no, as the weaving, either when compiling or at run-time, using AspectJ, will add the changes to the classes that are affected by the aspects, so there is no new class created, it is just that the byte code for the original class and the final class are different.
What do you mean by variants?
If you are asking if AspectJ instantiates copies of your class, the answer is no.
AspectJ uses a design pattern called proxy to intercept calls to your class.

Is there any reason to not use my IoC as a general Settings Repository?

Suppose that the ApplicationSettings class is a general repository of settings that apply to my application such as TimeoutPeriod, DefaultUnitOfMeasure, HistoryWindowSize, etc... And let's say MyClass makes use of one of those settings - DefaultUnitOfMeasure.
My reading of proper use of Inversion of Control Containers - and please correct me if I'm wrong on this - is that you define the dependencies of a class in its constructor:
public class MyClass {
public MyClass(IDataSource ds, UnitOfMeasure default_uom) {...}
}
and then call instantiate your class with something like
var mc = IoC.Container.Resolve<MyClass>();
Where IDataSource has been assigned a concrete implementation and default_uom has been wired up to instantiate from the ApplicationSettings.DefaultUnitOfMeasure property. I've got to wonder however, if all these hoops are really that necessary to jump through. What trouble am I setting myself up for should I do
public class MyClass {
public MyClass(IDataSource ds) {
UnitOfMeasure duom = IoC.Container.Resolve<UnitOfMeasure>("default_uom");
}
}
Yes, many of my classes end up with a dependency on IoC.Container but that is a dependency that most of my classes will have anyways. It seems like I maybe should make full use of it as long as the classes are coupled. Please Agile gurus, tell me where I'm wrong.
IoC.Container.Resolve("default_uom");
I see this as a classic anti-pattern, where you are using the IoC container as a service locater - the key issues that result are:
Your application no longer fails-fast if your container is misconfigured (you'll only know about it the first time it tries to resolve that particular service in code, which might not occur except for a specific set of logic/circumstances).
Harder to test - not impossible of course, but you either have to create a real (and semi-configured) instance of the windsor container for your tests or inject the singleton with a mock of IWindsorContainer - this adds a lot of friction to testing, compared to just being able to pass the mock/stub services directly into your class under test via constructors/properties.
Harder to maintain this kind of application (configuration isn't centralized in one location)
Violates a number of other software development principles (DRY, SOC etc.)
The concerning part of your original statement is the implication that most of your classes will have a dependency on your IoC singleton - if they're getting all the services injected in via constructors/dependencies then having some tight coupling to IoC should be the exception to the rule - In general the only time I take a dependency on the container is when I'm doing something tricky i.e. trying to avoid a circular dependency problems, or wish to create components at run-time for some reason, and even then I can often avoid taking a dependency on anything more then a generic IServiceProvider interface, allowing me to swap in a home-bake IoC or service locater implementation if I need to reuse the components in an environment outside of the original project.
I usually don't have many classes depending on my IoC container. I usually try to wrap the IoC stuff in a facade object that I inject into other classes, usually most of my IoC injection is done only in the higher layers of my application though.
If you do things your way you can't test MyClass without creating a IoC configuration for your tests. This will make your tests harder to maintain.
Another problem is that you're going to have powerusers of your software who want to change the configuration editing your IoC config files. This is something I'd want to avoid. You could split up your IoC config into a normal config file and the IoC specific stuff. But then you could just as well use the normal .Net config functionality to read the configuration.
Yes, many of my classes end up with a dependency on IoC.Container but that is a dependency that most of my classes will have anyways.
I think this is the crux of the issue. If in fact most of your classes are coupled to the IoC container itself chances are you need to rethink your design.
Generally speaking your app should only refer to the container class directly once during the bootstrapping. After you have that first hook into the container the rest of the object graph should be entirely managed by the container and all of those objects should be oblivious to the fact that they were created by an IoC container.
To comment on your specific example:
public class MyClass {
public MyClass(IDataSource ds) {
UnitOfMeasure duom = IoC.Container.Resolve<UnitOfMeasure>("default_uom");
}
}
This makes it harder to re-use your class. More specifically it makes it harder to instantiate your class outside of the narrow usage pattern you are confining it to. One of the most common places this will manifest itself is when trying to test your class. It's much easier to test that class if the UnitOfMeasure can be passed to the constructor directly.
Also, your choice of name for the UOM instance ("default_uom") implies that the value could be overridden, depending on the usage of the class. In that case, you would not want to "hard-code" the value in the constructor like that.
Using the constructor injection pattern does not make your class dependent on the IoC, just the opposite it gives clients the option to use the IoC or not.