Tied up with injection implemented with setter functions - java

I'm trying to use Scala as part of an existing Java application and now I run into an issue with dependencies injected with a setter method (no DI frameworks in this part of code). How is this handled in a Scala way?
In Scala both val and var require to be initialized when declared but I can't do that, since the Java setters inject objects that implement a certain interface and interfaces are abstract and can not be instantiated.
class ScalaLogic {
var service // How to initialize?
def setService (srv: OutputService) = {
service = srv
}
Is there a way to initialize the var service so that I can later assign a dependency into it? It should be lexically scoped to be visible in the whole class.

You can initialize to a default (null) using an underscore.
class ScalaLogic {
var service: OutputService = _
def setService (srv: OutputService) = {
service = srv
}
}
The nice thing about the underscore (as opposed to just using null) is that it works with both primitives and objects, so parameterized classes work like this:
class ScalaLogic[T] {
var service: T = _
def setService (srv: T) = {
service = srv
}
}

One of the many meanings of the underscore is to mark a variable as uninitialized. So if you want an uninitialized field, initialize it with _ .
To have getters and setters for a field annotate it with #BeanProperty. The compiler will generate the Java-Style getter and setter for you.
import reflect.BeanProperty
class ScalaLogic {
#BeanProperty
var service: OutputService = _
}
By the way, the canonical reference to Dependency Injection in Scala is the summary by Jonas Bonér. This article does not cover setter-based injection, though, if I recall correctly.

Try using class Option. This is the moral equivalent of using null in Java. Declare the service like so:
var service: Option[MyInterface] = None
and use
service.get()
or pattern matching
service match {
case None => ...
case Some[MyInterface] => ...
}

Related

In PHP dependency injection how to instantiate a class according to the parameters defined in constructor

When programming with Magento (PHP), I practiced DI when overriding classes. I can freely add any parameters in any order as I wish in the constructor functions to inject service dependencies, something as below:
class X
{
protected $service_a = null;
protected $service_b = null;
...
public function __construct(ServiceA $a, ServiceB $b, ... )
{
$this->service_a = $a;
$this->service_b = $b;
...
}
}
Somehow, in somewhere, when class X is instantiated, the system could automatically detect the parameter definition in the constructor of class X. Does not matter how do I modify the definition, the system always pass the correct services to the constructor. In Angular, the same story.
My question is how to make it possible in PHP and javascript??? If I define my own class, I have to instantiate it according to the constructor definition. How do they make the process (detect the parameter in constructor) done automatically?

Spring injected references in Kotlin

In Kotlin, a variable must be initialized at declaration time, and cannot be null unless it has ? appended to the type name. So a bean reference intended to be injected by Spring would have to be declared as:
#AutoWired
var someService: SomeService? = null
The nuisance is obviously that from here on everywhere someService is used, some kind of null-safety logic has to be specified, be it ?: or a straight-up null check.
Of course we can do:
#AutoWired
var someService = new SomeService()
But that's not always possible, and the throwaway instance is just confusing.
My question is, is there anyway to tell Kotlin that this variable will be initialized and actually not be null?
You have two options.
1) use constructor injection
Constructor injection is in my opinion the best way because it clearly declares that the dependencies must be set to construct the object.
2) declare your field as lateinit
Read more on tht topic in the doc:
https://kotlinlang.org/docs/reference/properties.html
Late-Initialized Properties
Normally, properties declared as having a non-null type must be
initialized in the constructor. However, fairly often this is not
convenient. For example, properties can be initialized through
dependency injection, or in the setup method of a unit test. In this
case, you cannot supply a non-null initializer in the constructor, but
you still want to avoid null checks when referencing the property
inside the body of a class.
public class MyTest {
lateinit var subject: TestSubject
#SetUp fun setup() {
subject = TestSubject()
}
#Test fun test() {
subject.method() // dereference directly
}
}
The Spring project official recommendation is to use constructor injection.
In Kotlin it will look something like this:
#Service
class GobblinMetricsConsumer(
private val graphiteClient: GraphiteClient,
private val parserService: JsonParserService,
private val kafkaConfigurationProperties: KafkaConfigurationProperties
) {
// code will go here
}

Change persistence layer dynamically (upon runtime) with as few changes as possible

I am searching for a design pattern/way to exchange a (persistence) layer of my application dynamically (preferably even at runtime).
Why?
I'd like to be able to decide whether to save certain data to XML or a database on a "per instance"-basis. So I may decide that one project uses XML as a backend and another uses a database. I want to be flexible here and to be able to easily add another "driver" for e.g. Json or whatever.
Now assume the following setup:
We have a controller and we want to manage some data. We can choose between a SQL and XML implementation.
One possible (working) solution:
BasicController.scala
val myPersistenceLayer: PersistenceLayer = SQLPersistenceLayer
val apples: Seq[Apple] = myPersistenceLayer.getApples()
trait PersistenceLayer
{
def getApples(): Seq[Apple]
def getBananas(): Seq[Banana]
}
object SQLPersistenceLayer extends PersistenceLayer
{
override def getApples(): Seq[Apple] = {...}
override def getBananas(): Seq[Banana] = {...}
}
This is a rather nasty solution as one would have to add methods for each new Model (think fruit! ;)) not only in the trait, but also in every implementation. I like my single responsibility so I'd rather delegate that to the models instead, like:
trait PersistenceLayer
{
def getAll(model: Model): Seq[Model] = { model.getAll() }
}
trait Model
{
def getAll(): Seq[Model]
}
package "SQL"
class Apple extends Model
{
def getAll(): Seq[Apple] = { // do some SQL magic here }
}
package "XML"
class Apple extends Model
{
def getAll(): Seq[Apple] = { // do some XML magic here instead }
}
Now the big problem here is, even if I implement a concrete PersistenceLayer, like so:
object SQLPersistenceLayer extends PersistenceLayer {}
how could I tell the application to use the model of the right package?
If I use the SQLPersistenceLayer upon:
val apples = myPersistenceLayer.get(Apple)
I would need to import the right "Apple" class, which defeats the whole purpose because then I could just remove all other classes, import the right one and just use a generic "getAll()" method on it.
So again I would need to change the implementation at multiple lines, which is what I want to avoid.
I thought about something like giving a string with the package-name, like
val package = "sql" and in the controller to import it from the right package, but this is not really feasible and not really easy to accomplish and it's a rather nasty hack for something I'm obviously missing.
To make a long story short: I want to be able to switch the package to use for my persistence needs dynamically. In some dynamically typed languages I could come up with a solution, but not in Scala or any statically typed language, so I guess I'm not knowing a certain design pattern here
** Edit **
A thought occurred (ya, sometimes it happens ;)) and now I'm wondering whether something like this could lead to what I want:
namespace tld.app.persistence
trait PersistenceLayer
{
proteced val models: mutable.HashMap[String, Model] = new mutable.HashMap[String, Model]
def registerModel(key: String, model: Model): Unit =
{
models.remove(key)
models.put(key, model)
}
def get(model: String): Seq[Future[Model]] =
{
val m: Model = models.getOrElse(model, throw new Exception("No such model found!"))
m.get
}
}
trait Model
{
def get(): Seq[Future[Model]]
}
namespace tld.app.persistence.sql
object SQLPersistenceLayer extends PersistenceLayer
class Person extends Model
{
def get(): Seq[Future[Model]] =
{
// ... query the database
}
}
namespace tld.app.persistence.xml
object XMLPersistenceLayer extends PersistenceLayer
class Person extends Model
{
def get(): Seq[Future[Model]] =
{
// ... read in from the appropriate xml-file
}
}
object Settings
{
var persistenceLayer: PersistenceLayer = SQLPersistenceLayer // Default is SQLPersistenceLayer
}
Somewhere in the application:
Settings.persistenceLayer.get("person")
// Then a user-interaction happens
Settings.persistenceLayer = XMLPersistenceLayer
Settings.persistenceLayer.get("person")
The persistenceLayer normally stays the same, but the user can decide upon changing it. I'll have a deeper look at it, as soon as I can find time. But maybe somebody immediately spots a problem with that approach.
DI allows you to wire an implementation at compile time. There are many ways to do DI in Scala (Cake Pattern, Reader Monad, DI frameworks, etc).
If you want to wire the dependency on application startup then regular dependency mechanisms would work. You would just create an instance of desired dependency (SQL, XML) based on some condition and pass it to the code.
If you want to keep switching between dependencies during your application execution, i.e. sometimes you save to SQL, other times to XML then you can use something similar to Lift Injector, see also my answer here - option 2.
You can use runtime reflection to accomplish it. You need to specify and create class/object at runtime which you'll be passing to Persistency layer and then just call generic getAll method.
For details of reflection library -> http://docs.scala-lang.org/overviews/reflection/overview.html
It would be better to make companion object Apple which has getAll method implemented differently for each persistency layer.
Then access Apple objects with reflection by using full package name
val apple:sql.Apple = //Reflection library object access
val apple:xml.Apple = //Reflection library object access
val apples = myPersistenceLayer.get(apple)
I think you can achieve module-based inclusion with implicits + TypeTags with something along these lines
object SqlPersistence {
implicit def getAll[T: TypeTag](): Seq[T] = {/* type-based sql implementation*/}
}
object JsonPersistence {
implicit def getAll[T: TypeTag](): Seq[T] = {/* type-based json implementation*/}
}
object PersistenceLayer {
def getAll[T](implicit getter: Unit => Seq[T]): Seq[T] = getter
}
// somewhere else ...
import SqlPersistence._
PersistenceLayer.getAll[Apple]
The advantage is that you can decide on your persistence layer at the spot by bringing a corresponding import. The major downside is the same: you need to decide on your persistence layer with every call and make sure that it is what you think. Also, from my personal experience compiler is less helpful with tricky implicit corner cases, so there is a potential to spend more time debugging.
If you set your persistence layer once for an app, then DI would do fine, e.g. cake pattern. But then again, you either need to have a method per class or resort to reflection. Without reflection, it may look like that:
trait PersistenceLayer {
def getApples(): Apples
}
trait SqlPersistenceLayer extends PersistenceLayer {
override def getApples() = // sql to get apples
}
trait Controller {
this: PersistenceLayer =>
def doMyAppleStuff = getApples()
}
// somewhere in the main ...
val controller = new Controller with SqlPersistence {}
controller.doMyAppleStuff
Something similar is strategy pattern if that helps.
I think the repository pattern is your solution.
EDIT:
ok. thanks for "-1" thats ok because i did not explained my idea behind...
my example is only one of many others. so i hope that this is usefull for someone out there
i will try to explain my idea about using the repository and factory pattern.
for this i made a github repository with the example code: https://github.com/StefanHeimberg/stackoverflow-32319416
my setup ist nearly the same as in your question. but the difference is the following:
i did not use scala. but the concept would be the same...
my settings contains only a "flag" for the repository factory.
the "model" objects are persistence ignorance. that means the do not know how the are persisted. this is the concern of the repositories
i made dependency injection by hand cause this should be sufficient for the example
i have no "Controller" but i have "Application Services"...
the decition about the implementation used is made inside the factory on each call to the create() method.
the domain layer does not know anything about the used infrastructure implementation. the application layer is orchestrating the domain service and the infrastructure services (in my example only the repositories)
if you have any DI Container then the factory could by a Producer or soething else... depends on DI Container
package structure:
i have also made a simple integration test
public class AppleServiceIT {
private Settings settings;
private AppleService appleService;
#Before
public void injectDependencies() {
settings = new Settings();
final JdbcAppleRepository jdbcAppleRepository = new JdbcAppleRepository();
final JsonAppleRepository jsonAppleRepository = new JsonAppleRepository();
final AppleRepositoryFactory appleRepositoryFactory = new AppleRepositoryFactory(jdbcAppleRepository, jsonAppleRepository);
appleService = new AppleService(settings, appleRepositoryFactory);
}
#Test
public void test_findAppleById() {
// test with jdbc
settings.setRepositoryType(RepositoryTypeEnum.JDBC);
assertEquals("JDBC-135", appleService.findAppleById(135l).getMessage());
// test with json
settings.setRepositoryType(RepositoryTypeEnum.JSON);
assertEquals("JSON-243", appleService.findAppleById(243l).getMessage());
}
#Test
public void test_getApples() {
// test with jdbc
settings.setRepositoryType(RepositoryTypeEnum.JDBC);
assertEquals(2, appleService.getApples().size());
// test with json
settings.setRepositoryType(RepositoryTypeEnum.JSON);
assertEquals(3, appleService.getApples().size());
}
}

Is it safe to define a method that has the same name as the class in scala?

I am trying to introduce Scala into my Android project, which uses Guice for DI. For Guide to work, I need to add the #Inject annotation to the constructor I would like Guice to use. In my case I created a Scala class and I need to use it in my Java code.
scala:
class scalaClass1(a: String) {
var myA = a
#Inject
def this() = { this("test") }
}
This looks alright, correct? But in another case the constructor does not have any parameters, so I tried
scala:
class scalaClass2() {
var myA: String = null
#Inject
def this() = { this() }
}
And I got an syntax error. Something like recursive definition. Then I tried this:
scala:
class scalaClass2() {
var myA: String = null
#Inject
def scalaClass2() = { this }
}
The code compiled and the app works well on my phone. I have no idea why. I browsed in google, but I could not find any definition/explanation about having a method that has the same name as the class. Why this works? Is there any better solution to my problem?
If you need to to apply #Inject to a constructor without parameters you can use this:
class scalaClass2 #Inject () {
// whatever
}
Note the mandatory empty parentheses. You need them to apply an annotation on the primary constructor. But in this particular case you don't even need #Inject; see below.
In your second example (when you define def this() = { this() }) you are getting an error because you can't define multiple constructors with the same signature, and that's exactly what you are doing - you define primary constructor without parameters and immediately you define secondary constructor, again without parameters.
And in the third example you're really defining a method named scalaClass2 which returns this. It is perfectly valid, but it is not a constructor. As far as I remember, Guice does not need #Inject annotation on parameterless constructor when it is the only constructor in the class, so you can inject scalaClass2 or ask it from Guice, who will create it for you. But you don't really need scalaClass2 method; Guice may call it as a part of method injection procedure but it won't do anything.
Firstly, according to convention class names should start with upper case and methods with lower. But if we would not follow them I would say it is not safe.
Consider having a companion object to the class with apply method defined.
class Person(val name: String, val age: Int)
object Person {
def apply(name: String, age: Int) = new Person(name, age) }
and then create a method with same name and list parameters:
def Person(lastName: String, score: Int): String = s"${lastName} got ${score} points in last game"
Now if you want to make use of object apply method you cannot do it in regular way:
Person("McKenzie", 1000)
will yield McKenzie got 1000 points in last game

Prototyping in Java instead of extending

Is Javascript-like prototyping anyhow achievable, even using Reflection? Can I wrap my object inside another one, just to extend its functionality with one or two more methods, without wiring all its original nonprivate methods to the wrapper class, or extends is all I get?
If you are looking for extension methods, you could try Xtend. Xtend is language that compiles to java code and eliminates boilerplate code.
The following text is stolen from the Xtend Docs for extensions:
By adding the extension keyword to a field, a local variable or a parameter declaration, its instance methods become extension methods.
Imagine you want to have some layer specific functionality on a class Person. Let us say you are in a servlet-like class and want to persist a Person using some persistence mechanism. Let us assume Person implements a common interface Entity. You could have the following interface
interface EntityPersistence {
public save(Entity e);
public update(Entity e);
public delete(Entity e);
}
And if you have obtained an instance of that type (through a factory or dependency injection or what ever) like this:
class MyServlet {
extension EntityPersistence ep = Factory.get(typeof(EntityPersistence))
...
}
You are able to save, update and delete any entity like this:
val Person person = ...
person.save // calls ep.save(person)
person.name = 'Horst'
person.update // calls ep.update(person)
person.delete // calls ep.delete(person)
I don't think you can do this in Java. You can though in Groovy, using metaclasses
String.metaClass.world = {
return delegate + " world!"
}
println "Hello".world()

Categories