Play Framework dependency injection Object vs #Singleton Class - scala

Play Framework 2.4 has support for Google Guice Dependency Injection
What is the advantage of using
#Singleton class A
instead of
object A
for singletons?

I can see three advantages of using #Singleton class over object if A has no dependencies:
If you wanted to test A, and declare it as #Singleton class you have the option of subclassing it to mock out some of the functions in your test, whereas this is not possible with an object.
If you use object, it is very tempting for clients of A to reference it directly, leading to a strongly coupled system, but using #Singleton class forces them to think about where A is instantiated, probably leading to a more decoupled design.
If you later change your mind, and allow multiple instances of A, the refactoring will be much easier to do if you chose to use #Singleton class.
If A has dependencies, however, using #Singleton class allows them to be dependency injected on construction, whereas with an object this is only possible if you declare the dependencies as mutable (eg: a var with getter/setter methods) .

Related

Constructor Parameters vs Abstract Members (Class vs Abstract Class)

When should I use an abstract class vs a regular class? More specifically, I'm trying to understand when constructor parameters should be preferred over abstract members.
For example:
sealed trait Client
abstract class BaseService {
def client: Client
}
class Service extends BaseService {
val client = ???
}
vs
sealed trait Client
class BaseService(client: Client) {}
class Service extends BaseService(client = ???)
As far as I can tell, both are valid.
As #Luis Miguel said, use abstract classes when you want to declare a common set of methods that need to be implemented by the sub-classes and/or share some limited functionality that will be used by all child classes.
Below, I'm listing some reasons why I considered you should pass your dependencies to the constructor rather than defining them in your classes/base-classes.
Use dependency injection
(IMHO) It is better to give the constructor the dependencies it needs to function properly AKA dependency injection.
Avoid tight coupling
When you declare a dependency inside your class or in your constructor, you are tightly coupling your Service with that specific implementation of the dependency, which is not ideal and is considered an antipattern.
Program to interfaces, not implementations
Injecting the dependencies gives you greater flexibility as you are not coupled to a specific implementation. This is true as long as your code relies on an interface/trait/abstract-class (consequently avoiding tight coupling).
When your class relies on an interface/trait/abstract-class can be very powerful as you can be passing a mock, a no-op, or different strategies of the client. So make sure you "Program to interfaces, not implementations".

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...

When should I use a regular class in Scala?

It seems to me that I can make just about anything using object, trait, abstract class and in rare occasions, case class. Most of this is in the form object extends trait. So, I'm wondering, when should I, if ever, use a plain, standard class?
This is not a right place to ask this question
Looks like you are new Scala
Class is a specification for something(some entity) you want to model . It contains behavior and state
There is only one way to declare so called regular class using keyword class
Both trait and abstract class are used for inheritance.
trait is used for inheritance (generally to put common behavior in there). trait is akin to interface in Java. multiple inheritance possible with traits but not abstract class.
A class can extends one class or abstract class but can mixin any number of traits. Traits can have behavior and state.
case class is a nothing but a class but compiler produces some boilerplate code for us to make things easy and look good.
object is used when you want to declare some class but you want to have single instance of the class in the JVM (remember singleton pattern).
If an object performs stateful computations on its members i.e. its members are declared with vars;
Or, even if its member are only declared with vals but those vals store mutable data structures which can be edited in place, then it should be an ordinary (mutable) class akin to a Java mutable object.
The idiomatic way of using Case classes in Scala is as immutable types i.e. all the constructor arguments are vals. We could use vars but then we lose the advantages of case classes like equality comparisons will break over time.
Some advise from Programming in Scala by Odersky et al on deciding between using traits, abstract classes and concrete classes:
If the behavior will not be reused, then make it a concrete class. It is not reusable behavior after all.
If it might be reused in multiple, unrelated classes, make it a trait.
Only traits can be mixed into different parts of the class hierarchy.
If you want to inherit from it in Java code, use an abstract class.
Since traits with code do not have a close Java analog, it tends to be
awkward to inherit from a trait in a Java class. Inheriting from a
Scala class, meanwhile, is exactly like inheriting from a Java class.
As one exception, a Scala trait with only abstract members translates
directly to a Java interface, so you should feel free to define such
traits even if you expect Java code to inherit from it. See Chapter 29
for more information on working with Java and Scala together.
If you plan to distribute it in compiled form, and you expect outside
groups to write classes inheriting from it, you might lean towards
using an abstract class. The issue is that when a trait gains or loses
a member, any classes that inherit from it must be recompiled, even if
they have not changed. If outside clients will only call into the
behavior, instead of inheriting from it, then using a trait is fine.
If efficiency is very important, lean towards using a class. Most Java
runtimes make a virtual method invocation of a class member a faster
operation than an interface method invocation. Traits get compiled to
interfaces and therefore may pay a slight performance overhead.
However, you should make this choice only if you know that the trait
in question constitutes a performance bottleneck and have evidence
that using a class instead actually solves the problem.
If you still do not know, after considering the above, then start by
making it as a trait. You can always
change it later, and in general using a trait keeps more options open.

Constructor and Unit Testing

I have a class XmlRecord. This class will deal with reading/writing to an xml file. At the moment, I have the following for that class:
class XmlRecord {
private val _file = new File("file.xml")
}
I want this class to somehow create the file if it doesn't exist. I know how to achieve this but I'm unsure how to design it in an Object Orientated way. I think I have two options:
Do I add a code to the constructor (or a call to a private method) that will create this file automatically if it doesn't exist. My problem with this method is that how do I unit test this as this code is effectively private code? Would I have to inject the File dependency so it could be mocked during testing?
Do I get the constructor to return an exception or implement a public method for the class so that the caller can use it to check if a file needs to be created? If so, the caller would then call another public method that would create the file. Again I think I would need to inject the dependency.
I hope that makes sense. I'm just trying to get a better grasp on designing my classes.
The presence of abstractions to accomplish DIP have other design
implications in an Object Oriented program:
All member variables in a class must be interfaces or abstracts.
All concrete class packages must connect only through interface/abstract classes packages.
No class should derive from a concrete class.
No method should override an implemented method.[5]
All variable instantiation requires the implementation of a Creational pattern as the Factory Method or the Factory pattern, or the more complex use of a Dependency Injection framework.
Dependency inversion principle

Scala dependency injection using singleton

I'm new to Scala and I'm trying to figure out the best approach for dependency injection. I have Java background and I used to use both Guice and Spring IoC.
I used to use a provider class with the #Provider annotation to chose implementation or use beans.xml in Spring and just use the #Inject annotation (or in Spring, #Autowired) to inject instances of a class into my services.
In Scala, I read about the cake pattern but it seems rather complicated to me. All I want to achieve is what I already have in Java: get a singleton of an interface type with specific implementation.
My question is whether using Scala object type would be sufficient.
Example:
trait TestDI { }
class Impl1 extends TestDI { }
class Impl2 extends TestDI { }
object TestDI extends Impl1 { }
So I'd just use TestDI in my service which would actually use the implementation of Impl1. So my initial interface (trait) and the singleton object would have the same name.
I think either Macwire or Scaldi matches Guice style quite closely. I like Macwire because it's standard Scala based framework based on macros, no other magical sauce is used (like byte manipulation).
Other ways to do DI are described in my answer here:
Scala - write unit tests for objects/singletons that extends a trait/class with DB connection