Automatic #Binds in Dagger when there is one implementation per interface - dagger-2

When using Dagger 2, very often I'm applying the following pattern:
Create interface, let's call it LoginService
Create the only one implementation - LoginServiceImpl with the constructor injection:
class LoginServiceImpl implements LoginService {
#Inject LoginServiceImpl() {}
}
Bind the implementation to the interface:
#Binds
abstract LoginService bindStatisticsService(LoginServiceImpl impl);
Always depend on the interface - LoginService in this case.
Is there a possibility to avoid the #Binds annotated method? Is there a simpler (with the less amount of boilerplate code) way to tell Dagger - this class is the only one implementation of the interface, always bind it for example in some annotation on the interface itself?
I've read the documentation and unfortunately haven't found anything like that, but maybe someone knows some trick which can solve my problem.

I don't think that's possible, even hypothetically.
Dagger can't really tell that there's only one implementation, and the only way it could would be to search for every class on the (compilation) classpath to try to find all sorts of possible implementation. That would be slow at best, but Java allows classloading from custom classloaders, so you aren't ever really guaranteed to get a full list of available classes. Even if you were to claim that Dagger should just match against the first appropriate assignable type it sees (because you know that there's only one), Dagger may not have a way to identify where to find that implementation type.
Ultimately it's going to be difficult to improve on a single-line #Binds statement that identifies the fully-qualified class of the binding key (your.package.name.LoginService) and target (your.package.name.LoginServiceImpl).

Related

Play framework controller test - No implementation for <classname> was bound

I would like to write test for a controller class. The controller class takes a service object as constructor parameter. Added the #Inject annotation to the constructor of the service class.
class AssociateService #Inject()(configuration: Configuation){...}
The constructor parameter of the service class is a custom configuration object also created for the application. I added the #Inject to the constructor of the config class as well. Now I'm getting these types of error messages:
No implementation for "className" was bound.
Could not find a suitable constructor in java.lang.Integer. Classes must have either one (and only one) constructor annotated with #Inject or a zero-argument constructor that is not private.
The configuration class has several constructor parameters, those are "basic" types (Int, Boolean) and one parameter is a custom class type (className).
How should I do this binding or is it just enough to annotate something else?
And why it says that constructor error message?
As far as I know, there are two ways with tests and guice, with trade offs:
Don't using field injections, using only constructor injections and fields assignment in constructor for injected parameters. This approach enables very simple solution for testing, just don't use dependency injection in tests. But all your classes must have ability to be created with new operator in test cases...
Ps. You can define optional constructor and use field injections, of course, but it is not very clear solution.
Creating correct module with injectable interfaces binding to its implementations for every test or group of similar tests. Sometimes this approach takes a lot of unnecessary working hours.
You must design your software to maintain testability. Sometimes not every line of code in project need to be tested, sometimes not every code is testable, you must separate it from important parts of your software, that requires testing. If you design your software with single responsibility principe so writing tests is much easer...

What is an Interface

With reference to UML diagrams, what is an interface? and can someone explain in more simpler words. I cant understand anything from googling it.
An interface is like a template design for a class that contains no data or implemetnation; only definitions for methods, properties etc. These are abstract and cannot be instantiated but can be inherited from at which point all specified methods etc must be implemented by the concrete class inheriting the interface.
An interface is a design item describing a behaviour.
Classes implementing the interface will/must behave according to its definition.
Interfaces are used to promote loose coupling and the base of many IoC patterns (Inversion of Control)
A Interface is just a description of a class nothing concrete.
You use it to create a new class "with the same description" without knowing the concrete implementation.
In one word: it's a contract. Every class that implements this contract (interface) will have to implement the methods defined on it.

In Scala, plural object name for a container of public static methods?

I've written a Scala trait, named Cache[A,B], to provide a caching API. The Cache has the following methods, asyncGet(), asyncPut(), asyncPutIfAbsent(), asyncRemove().
I'm going to have a few static methods, such as getOrElseUpdate(key: A)(op: => B). I don't want methods like this as abstract defs in the Cache trait because I don't want each Cache implementation to have to provide an implementation for it, when it can be written once using the async*() methods.
In looking at Google Guava and parts of the Java library, they place public static functions in a class that is the plural of the interface name, so "Caches" would be the name I would use.
I like this naming scheme actually, even though I could use a Cache companion object. In looking at much of my code, many of my companion objects contain private val's or def's, so users of my API then need to look through the companion object to see what they can use from there, or anything for that matter.
By having a object named "Caches" is consistent with Java and also makes it clear that there's only public functions in there. I'm leaning towards using "object Caches" instead of "object Cache".
So what do people think?
Scala's traits are not just a different name for Java's interfaces. They may have concrete (implemented) members, both values (val and var) and methods. So if there's a unified / generalized / shared implementation of a method, it can be placed in a trait and need not be replicated or factored into a separate class.
I think the mistake starts with "going to have a few static methods". Why have static methods? If you explain why you need static methods, it will help figure out what the design should be.

When to use an abstract class with no interface?

Whenever I create an abstract class I tend to create an interface to go along with it and have other code refer to the interface and not the abstract class. Usually when I don't create an interface to start with I regret it (such as having to override all implimented methods to stub the class for unit testing or later down the line new classes don't need any of the implimentation and override everything also finding themselves unable to extend any other class).
At first I tried to distinguish when to use an interface and when to use an abstract class by considering is-a vs able-to but I still would end up suffering later down the line for not making an interface to start with.
So the question is when is it a good idea to only have an abstract class and no interface at all?
When you wish to "give" some base class functionality to derived classes but when this functionality is not sufficient to instantiate a usable class, then go for abstract classes.
When you wish that some classes completely implement a set of methods (a public contract), then it is a convenient to define such contract with interfaces and enforce them onto classes by making them inherit this interface.
In short:
With abstract classes you give some common base functionality to derived classes. No further actions are necessary unless abstract class has some stubs (which have to be implemented down there).
With interfaces you require derived classes to implement a set of functions and you do not pass along any implementation.
So the question is when is it a good idea to only have an abstract class and no interface at all?
When you do not wish to enforce any public contract (a set of methods/properties defined by an interface).
Also when you do not plan to use certain coding techniques like casting object to an interface type (run-time polymorphism) or limit allowed input (some method argument will only accept object of types which implement certain interfaces).
Well, the main case it is useful to have only an abstract class without any interface is to mark a certain type. It is useful to be able to check if an object "is-a" something. These interface "mark" an objet to be of a certain type. Depending on the language you use, different design patterns apply ...
These sort of abstract classes exist in java. You can also use them in C++ with RTTI.
my2c

What is an empty interface used for

I am looking at nServiceBus and came over this interface
namespace NServiceBus
{
public interface IMessage
{
}
}
What is the use of an empty interface?
Usually it's to signal usage of a class. You can implement IMessage to signal that your class is a message. Other code can then use reflection to see if your objects are meant to be used as messages and act accordingly.
This is something that was used in Java a lot before they had annotations. In .Net it's cleaner to use attributes for this.
#Stimpy77 Thanks! I hadn't thought of it that way.
I hope you'll allow me to rephrase your comment in a more general way.
Annotations and attributes have to be checked at runtime using reflection. Empty interfaces can be checked at compile-time using the type-system in the compiler. This brings no overhead at runtime at all so it is faster.
Also known as a Marker Interface:
http://en.wikipedia.org/wiki/Marker_interface_pattern
In java Serializable is the perfect example for this. It defines no methods but every class that "implements" it has to make sure, that it is really serializable and holds no reference to things that cannot be serialized, like database connections, open files etc.
In Java, empty interfaces were usually used for "tagging" classes - these days annotations would normally be used.
It's just a way of adding a bit of metadata to a class saying, "This class is suitable for <this> kind of use" even when no common members will be involved.
Normally it's similar to attributes. Using attributes is a preferred to empty interfaces (at least as much as FxCop is aware). However .NET itself uses some of these interfaces like IRequiresSessionState and IReadOnlySessionState. I think there is performance loss in metadata lookup when you use attributes that made them use interfaces instead.
An empty interface acts simply as a placeholder for a data type no better specified in its interface behaviour.
In Java, the mechanism of the interface extension represents a good example of use. For example, let's say that we've the following
interface one {}
interface two {}
interface three extends one, two {}
Interface three will inherit the behaviour of 'one' and 'two', and so
class four implements three { ... }
has to specify the two methods, being of type 'three'.
As you can see, from the above example, empty interface can be seen also as a point of multiple inheritance (not allowed in Java).
Hoping this helps to clarify with a further viewpoint.
They're called "Mark Interfaces" and are meant to signal instances of the marked classes.
For example... in C++ is a common practice to mark as "ICollectible" objects so they can be stored in generic non typed collections.
So like someone over says, they're to signal some object supported behavior, like ability to be collected, serialized, etc.
Been working with NServiceBus for the past year. While I wouldn't speak for Udi Dahan my understanding is that this interface is indeed used as a marker primarily.
Though I'd suggest you ask the man himself if he'd had thoughts of leaving this for future extension. My bet is no, as the mantra seems to be to keep messages very simple or at least practically platform agnostic.
Others answer well on the more general reasons for empty interfaces.
I'd say its used for "future" reference or if you want to share some objects, meaning you could have 10 classes each implementing this interface.
And have them sent to a function for work on them, but if the interface is empty, I'd say its just "pre"-work.
Empty interfaces are used to document that the classes that implement a given interface have a certain behaviour
For example in java the Cloneable interface in Java is an empty interface. When a class implements the Cloneable interface you know that you can call run the clone() on it.
Empty interfaces are used to mark the class, at run time type check can be performed using the interfaces.
For example
An application of marker interfaces from the Java programming language is the Serializable interface. A class implements this interface to indicate that its non-transient data members can be written to an ObjectOutputStream. The ObjectOutputStream private method writeObject() contains a series of instanceof tests to determine writeability, one of which looks for the Serializable interface. If any of these tests fails, the method throws a NotSerializableException.
An empty interface can be used to classify classes under a specific purpose. (Marker Interface)
Example : Database Entities
public interface IEntity {
}
public class Question implements IEntity {
// Implementation Goes Here
}
public class Answer implements IEntity {
// Implementation Goes Here
}
For Instance, If you will be using Generic Repository(ex. IEntityRepository), using generic constraints, you can prevent the classes that do not implement the IEntity interface from being sent by the developers.