How to match on type OR method annotation only once - aop

I want to have a Guice interceptor that intercepts calls either to a class that is annotated, or a method that is annotated. I'd like to be able to combine both, ie. override the class annotation with a method annotation with different properties.
I have this working like this:
// Intercept all METHODS annotated with #MyAnnotation
bindInterceptor(
Matchers.any(),
Matchers.annotatedWith(company.MyAnnotation),
new TracingInterceptor());
// Intercept all methods in CLASSES annotated with #MyAnnotation
bindInterceptor(
Matchers.annotatedWith(company.MyAnnotation),
Matchers.any(),
new TracingInterceptor());
However when I annotate a class like this:
#MyAnnotation
class MyClass {
#MyAnnotation
public void myMethod() {}
}
The interceptor gets called twice, which is bad!
Is there any way to avoid triggering the interceptor twice, but having the same behaviour?

You can achieve this by making your binders mutually exclusive, like this:
// Intercept all METHODS annotated with #MyAnnotation in classes not annotated with #MyAnnotation
bindInterceptor(
Matchers.not(Matchers.annotatedWith(company.MyAnnotation)),
Matchers.annotatedWith(company.MyAnnotation),
new TracingInterceptor());
// Intercept all methods not annotated with #MyAnnotation in CLASSES annotated with #MyAnnotation
bindInterceptor(
Matchers.annotatedWith(company.MyAnnotation),
Matchers.not(Matchers.annotatedWith(company.MyAnnotation)),
new TracingInterceptor());
// Intercept all METHODS not annotated with #MyAnnotation in CLASSES annotated with #MyAnnotation
bindInterceptor(
Matchers.annotatedWith(company.MyAnnotation),
Matchers.annotatedWith(company.MyAnnotation),
new TracingInterceptor());

Related

How does Guice inject classes without an #Inject-annotated constructor?

I'm trying to understand how DI is used in our codebase (Kotlin). We are using google guice for dependency injection.
Here is a sample class:
class ServiceClass #Inject construct(
private val depA: DepA,
private val depB: DepB
) { ........ }
In Module class:
#Provides
fun provideDepA(): DepA {
//constructs DepA object and returns it
}
DepB class:
class DepB { .... }
As far as I know for the variables annotated with #Inject, Google Guice will look to resolve those dependencies using module class. So it makes sense how DepA object is injected.
But what about DepB? How are we able to inject DepB without specifying it anywhere?
Guice bindings that are not declared in modules are known as Just-in-time Bindings, and by default Guice is willing to call constructors that take zero arguments:
Guice Wiki: JustInTimeBindings
Guice can create bindings for concrete types by using the type's injectable constructor. Guice considers a constructor injectable if:
(recommended) The constructor is explicitly annotated with #Inject (both com.google.inject.Inject and javax.inject.Inject are supported).
or, the constructor takes zero arguments, and
the constructor is non-private and defined in a non-private class (Guice supports private constructor only when it is defined in a private class, however, private constructors are not recommended because they can be slow in Guice due to the cost of reflection).
the injector has not opted in to require explicit #Inject constructor, see explicit #Inject constructors section below.
If you haven't required explicit bindings and you have a public no-arg constructor, Guice will call it as if you had marked it with #Inject. This is in contrast to Dagger, which will only call #Inject-annotated constructors:
Dagger Dev Guide
If your class has #Inject-annotated fields but no #Inject-annotated constructor, Dagger will inject those fields if requested, but will not create new instances. Add a no-argument constructor with the #Inject annotation to indicate that Dagger may create instances as well.
...
Classes that lack #Inject annotations cannot be constructed by Dagger.
In both Guice and Dagger you can construct the objects yourself in #Provides methods, and in Guice you can also use a Module to explicitly bind to a constructor with arguments and without an #Inject constructor.

Benefit of non-empty method of non-abstract class and abstract method of abstract method?

I don't understand why we use abstract method (abstract class) while we can use empty method of non-abstract class and then we override it. Does it sound fine? I am seeking to clarify this issue.
I give 2 examples
public abstract class MyClass {public abstract void foo();}
public MyChildClass extends MyClass {public void foo() {//..TODO}}
public class MyClass {public void foo(){//empty}}
public class MyChildClass extends MyClass {public void foo() {//..TODO}}
Which one is better?
I'll start by saying that you should try to use interfaces instead of abstract classes. Abstract classes couple the subclass to the implementation of the superclass. In a language like Java, the subclass can override any method even if the superclass did not intend to do so, and most people don't qualify their methods with "do not override" all the time.
At the lowest level, abstract methods give you two concrete protections at compile time:
They force you to override the method in a subclass
They disallow the creation of the abstract class
Before listing the use cases for abstract methods, I'll just say that "common functionality" is NOT a good reason for an abstract base class. If you need common functionality, just create a class that has the common methods, and let the various classes call these functions as they see fit.
So when would you use an abstract class? Here are some examples:
Template Method
In the template method pattern, you have all of your functionality, but there's just one internal aspect that's polymorphic, so you have subclasses that override that particular aspect.
For example, if you're implementing a cache, but the cache invalidation policy is polymorphic, you may have an abstract invalidate() method that is called internally by other methods, but it's up to subclasses to implement invalidate().
If there is a preferred default cache invalidation policy, then invalidate() could implement that default. But if that default is downright destructive in some cases, then it shouldn't be a default - it should be abstract, and the code that creates the cache should be forced to explicitly choose the invalidation policy.
This can also be achieved by passing an Invalidator class to the constructor (Strategy pattern), but if the invalidation logic needs to call methods of the cache, it's better to make those method protected and call them from a subclass (i.e. Template Method pattern).
Default implementation of other methods
In languages where interfaces cannot have default methods (e.g. Java 7), you can emulate it using abstract classes. All the interface methods will be abstract, but the default methods would be regular public methods.
Common Interface and Functionality
This is just a more generic version of the template method pattern. The difference is that the polymorphic methods are part of the API.
If your common functionality has a lot of overlap with the functionality you want to expose, and you don't want mountains of boilerplate code, you use an abstract class. For example:
interface File {
abstract Buffer read(int size);
abstract void write(Buffer buf);
abstract long getSize();
abstract void setSize();
// ... get/set creation time, get/set modification time, get
// file type etc.
abstract long getOwner();
abstract void setOwner(long owner);
}
abstract class AbstractFile extends File {
DataMap dataMap;
MetadataMap metaMap;
protected getDiskMap() { return dataMap; }
protected getMetaMap() { return metaMap; }
public Buffer read(int size) { /* loop here */ }
public void write(Buffer buf) { /* loop here */ }
public long getSize() { /* logic */ }
public void setSize() { /* logic */ }
// ... implementation of get/set creation time, get/set modification
// time, get file type etc.
}
abstract class HardDriveFile extends AbstractFile {
OwnershipMap ownerMap;
abstract long getOwner() { /* logic */ }
abstract void setOwner(long owner) { /* logic */ }
}
abstract class ThumbDriveFile extends AbstractFile {
// thumb drives have no ownership
abstract long getOwner() { return 0; }
abstract void setOwner(long owner) { /* no-op */ }
}
abstract class SomeOtherfile extends AbstractFile {
...
}
If we cut the middleman and have HardDriveFile and ThumbDriveFile (and possibly other types of files) implement File and spell out all the common methods, each calling a method of some common class, we would get mountains and mountains of boilerplate. So we inherit from an abstract base class, that has the abstract methods we want to specialize (e.g. based on the existence of an ownership map).
The naive thing to do would be to combine File and AbstractFile into a single class, which is where you'd get the abstract methods getOwner() and setOwner(), but it's better to hide abstract classes behind actual interfaces, to prevent the coupling between consumers of an API and the abstract class.

Is calling an interface nested inside an abstract generic class bad programming practice

Using the code below as an example
public abstract class Foo<T,V>{
// ...some methods
public interface IFoo<S,U>{
S doSomething(U input);
}
}
class MyClass implements Foo.IFoo<String, Integer>{}
Is calling the interface like that bad OOP or there is nothing wrong with that. Note the interface has different generic parameters from the abstract class.

Under what scenarios a developer should inherit constructors and destructors of a parent class into child class?

As all private and public attributes and methods are inherited into a child class from its parent class then why would constructors and destructors be inherited into a child class?
Is there a real life scnario?
In most programming languages constructors and descructors are not inherited automatically. Usually base class can provide one set of constructors and child class can provide another set of constructors.
I think that in most cases abstract derived class should provide the same set of constructor as base class do (i.e. "inherit" constructors from the base class), but concrete derived class can resolve some of base class's constructor arguments and provide more usable set of constructors:
Consider following case. Let suppose we have a base class called BaseWCFProxy that requires string as endpoint name:
abstract class BaseWCFProxy
{
public BaseWCFProxy(string endpointName)
{}
}
class ConcreteProxy : BaseWCFProxy
{
public ConcreteProxy() : base("ConcreteProxyEndPoint") {}
}
But you decide to add additional abstract class between BaseProxy and ConcreteProxy than you should provide the same set of constructors as base class:
class DualChannelBaseProxy : BaseWCFProxy
{
public DualChannelBaseProxy(string enpointName) : base(endpointName) {}
}
So the rule of thumb is: if you write a abstract child you should consider to "inherit" all base classes constructors. If you write a concrete child you can provide separate set of constructors that would be appropriate for your clients.
P.S. We don't have the same issue with destructors because there is no such notion like destructors overloading. And they're inherited by default: i.e. descendant can provide some additional logic but it definitely should call base version.

Abstract class and methods

i have Abstract class
Public class Abstract baseClass
{
public abstract string GetString();
public abstract string GetString1();
}
public class DerivedClass : baseClass
{
public override string GetString()
{
return "test data";
}
public override string GetString1()
{
throw new NotImplementedException();
}
}
In above line of code, i have to implement both abstract method in derived class. But due to some reason i don't want to implement all methods, just one of them like GetString() only. How can it be done?
Thanks
If DerivedClass is going to offer common functionality to other classes, you can mark it as abstract, implement one of the methods here, and then inheritors will only have to implement the remaining method.
If you aren't going to support the other method in a given implementation, you still have to expose the method in your class, but similar to what you have here, you would typically throw a NotSupportedException. For void methods, you could simply return (do nothing).
Finally, if you want to separate out the things that have both methods and those that have only one, you can use interfaces.
public interface IBase
{
string GetString();
}
public interface IBasePlus : IBase
{
string GetStringPlus();
}
You can have one class that implements IBasePlus, but you can supply this to methods that take a parameter of type IBase, in which case you won't see the extra method.
Generally, if you don't implement all the abstract methods then your new class is also an abstract class. To get a concrete class, you need all the methods to be implemented. If you only want/need to implement a subset of the methods, consider using multiple interfaces (one interface with GetString and another with GetString1) rather than an abstract class. Then you can just implement the interfaces with the methods you want to use in the class.
Take the abstract keyword off the other method and provide a default implementation in the base class