Recommended pattern for sharing common objects across classes in Scala - scala

I'm just looking into Scala and I have a couple of questions regarding the best way to share common attributes like loggers, database handles and configuration across classes without passing them around.
We could make a singleton class which would have the logger, handle and application but this seems wrong to me since and any subclassing the singleton isn't a more specialised case.
I see that Scala has the concept of a trait which I believe is like a mixin. Is it possible - and good practice if it is - to combine a trait with a singleton? If not what is the recommended approach?

The best practice to share common entities throughout the package is by declaring them in the package object file.
Refer here https://alvinalexander.com/scala/scala-package-objects-how-to-name-location-cookbook-recipe

This is a big subject and there is no single correct best approach - your question is quite broad. Here are some areas I would spend some time reading up on if you want to get the bigger picture:-
Mixin traits are a popular way of decorating classes with reusable behaviours - a custom logger being a good example. Assuming you really do need to customise a logging libraries behaviour that is.
For configuration and database connections, mixin traits work as well but some frameworks eg. Play use dependency injection as a way for classes to obtain their dependencies. Note that there are both compile time and runtime DI frameworks.
Another, less common, approach that is arguably more complex is to use aspects (AOP) - https://www.google.co.uk/search?ei=1iN-W6neNePWgAb05orYAQ&q=scala+aop&oq=scala+aop
If you are just starting out then choose some popular libraries - read their docs - and let them guide you as to how best to adopt them, eg.
Logging - https://github.com/lightbend/scala-logging
Config - https://github.com/lightbend/config

Related

What's the scala alternative to runtime-preserved annotations

I just realized I cannot have annotations in scala, that are preserved and analyzed at runtime. I also checked this question, but I didn't quite get it what are the alternatives.
DI - an answer mentions that there is no need for DI framework in scala. While that might be the case on a basic level (although I didn't quite like that example; what's the idiomatic way of handling DI?), Java DI frameworks like spring are pretty advanced and handle many things like scheduled jobs, caching, managed persistence, etc, all through annotations, and sometimes - custom ones.
ORM - I'll admit I haven't tried any native scala ORM, but from what I see in squeryl, it also makes some use of annotations, meaning they are unavoidable?
any serialization tool - how do you idiomatically customize serialization output to JSON/XML/...?
Web service frameworks - how do you define (in code) the mappings, headers, etc. for RESTful or SOAP services?
Scala users need to have a hybrid scala/java (for the annotations) project in order to use these facilities that are coming from Java?
And are the native scala alternatives for meta-data nicer than annotations? I'm not yet fully into the scala mode of thinking, and therefore most of the examples look ugly to me, compared to using annotations, so please try to be extra convincing :)
Actually, Scala does have runtime-retained annotations. The difference is that they are not stored as Java annotations but are instead encoded inside the contents of binary ScalaSignature annotation (which, by itself, is a runtime-retained Java annotation).
So, Scala annotations can be retrieved at runtime, but instead of using Java reflection, one must use Scala reflection:
class Awesome extends StaticAnnotation
#Awesome
class AwesomeClass
import scala.reflect.runtime.universe._
val clazz = classOf[AwesomeClass]
val mirror = runtimeMirror(clazz.getClassLoader)
val symbol = mirror.classSymbol(clazz)
println(symbol.annotations) // prints 'List(Awesome)'
Unfortunately, Scala reflection is still marked as experimental and is actually unstable at this point (SI-6240 or SI-6826 are examples of quite serious issues). Nevertheless, it seems like the most straightforward replacement for Java reflection and annotations in the long term.
As for now, one has to use Java annotations which I think is still a nice solution.
Regarding frameworks and libraries for DI/ORM/WS/serialization - Scala still doesn't seem to be mature in this area, at least not as Java is. There are plenty of ongoing projects targeting these problems, some of them are already really nice, others are still in development. To name a few that come to my mind: Squeryl, Slick, Spray, Pickling.
Also, Scala has some advanced features that often make annotations unneccessary. Typeclasses (implemented with implicit parameters) are probably good example of that.

If you have Traits, do you stop using interfaces, Abstract base classes, and multiple inheritance?

It seems like Traits could completely replace interfaces, abstract base classes, mixins, and multiple inheritance, leaving you with just Traits and concrete inheritance.
Is this the intent?
If you have traits, which of the other code structuring constructs should you use?
(Roles are the Perl name for Traits.)
At least for Perl's Moose, there are no interfaces, so roles clearly subsume those, and generally mixins too. I'd say there still could be a case for abstract base classes. Roles can be considered what objects do, where classes are what they are.
By this line of reasoning, there still might be a valid use for an abstract base class. A URL is one example. There could easily be an abstract base class for a URL. An IO stream might be different, perhaps better as a role, as it defines how things behave rather than what they are.
When using roles, however, I have yet to see any clear need for true multiple inheritance from more than one class.
I have no use for interfaces or abstract classes at this point, but mixins and multiple inheritance are really enabled by traits so the usage of those paradigms is strongly encouraged here. Check the entire collection library to see the very rich classes you can build using these ideas.
Ah, my comments reflect Scala - I didn't realize you tagged this with multiple languages.
When you instanciate a trait; it consumes one classe.
So regardless of expressivity; You may still use legacy construct for preventing classes explosion in your jar (and starting time).
I let others answer about expressivity :)
I'm only talking about Scala here...
Read this.

class inheritance in objective-c falls short in this case. is there any alternatives?

class AGImageVC
class AGVideoVC inherits from AGImageVC
class AGAdvancedImageVC inherits from AGImageVC
class AGAdvancedVideoVC inherits from ????
AGAdvancedVideoVC should have implementation from both AGAdvancedImageVC and AGVideoVC. But that's not possible...
I've also been thinking about category, but same problems would definitely be more obvious.
You need to think of class inheritance as a tree in Obj-C. Each class can have multiple sub-classes, but sub-classes can only have one parent. Objective-C lacks the concept of multiple inheritance as we traditionally understand it. People have found various ways to 'fake' multiple inheritance, which are discussed in the links below (personally, I wouldn't recommend them).
There is a fairly detailed explanation of your options regarding multiple inheritance on this Cocoa mailing list post from a few years back: http://www.cocoabuilder.com/archive/cocoa/131033-multiple-inheritance-and-objective.html
Another discussion on the subject here:
http://www.cocoadev.com/index.pl?MultipleInheritance
That's as close as you can get (using message forwarding) to behavior similar to multiple inheritance. This is not nice design in Objective-C, however. Flat inheritance hierarchies are more common in Objective-C.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtForwarding.html
That means that you have poorly designed architecture for this case. Try to rethink it and use another approach. Maybe you'd better want to use aggregation instead of inheritance. For example in some implementation AGVideo has to control video playback. Maybe it is implemented as the sequence of images. Then the solution would be to aggregate multiple AGImage instances and not inheriting from it.
If you want your class to implement functionality of different nature (e.g. both serialization and graphics rendering) the best choice would be using protocols. In this case each class would have it's own behavior for specified action but still you can manage the set of objects with different behavior but the same interface.

How would one do dependency injection in scala?

I'm still at the beginning in learning scala in addition to java and i didn't get it how is one supposed to do DI there? can or should i use an existing DI library, should it be done manually or is there another way?
Standard Java DI frameworks will usually work with Scala, but you can also use language constructs to achieve the same effect without external dependencies.
A new dependency injection library specifically for Scala is Dick Wall's SubCut.
Whereas the Jonas Bonér article referenced in Dan Story's answer emphasizes compile-time bound instances and static injection (via mix-ins), SubCut is based on runtime initialization of immutable modules, and dynamic injection by querying the bound modules by type, string names, or scala.Symbol names.
You can read more about the comparison with the Cake pattern in the GettingStarted document.
Dependency Injection itself can be done without any tool, framework or container support. You only need to remove news from your code and move them to constructors. The one tedious part that remains is wiring the objects at "the end of the world", where containers help a lot.
Though with Scala's 2.10 macros, you can generate the wiring code at compile-time and have auto-wiring and type-safety.
See the Dependency Injection in Scala Guide
A recent project illustrates a DI based purely on constructor injection: zalando/grafter
What's wrong with constructor injection again?
There are many libraries or approaches for doing dependency injection in Scala. Grafter goes back to the fundamentals of dependency injection by just using constructor injection: no reflection, no xml, no annotations, no inheritance or self-types.
Then, Grafter add to constructor injection just the necessary support to:
instantiate a component-based application from a configuration
fine-tune the wiring (create singletons)
test the application by replacing components
start / stop the application
Grafter is targeting every possible application because it focuses on associating just 3 ideas:
case classes and interfaces for components
Reader instances and shapeless for the configuration
tree rewriting and kiama for everything else!
I haven't done so myself, but most DI frameworks work at the bytecode level (AFAIK), so it should be possible to use them with any JVM language.
Previous posts covered the techniques. I wanted to add a link to Martin Odersky's May 2014 talk on the Scala language objectives. He identifies languages that "require" a DI container to inject dependencies as poorly implemented. I agree with this personally, but it is only an opinion. It does seem to indicate that including a DI dependency in your Scala project is non-idiomatic, but again this is opinion. Practically speaking, even with a language designed to inject dependencies natively, there is a certain amount of consistency gained by using a container. It is worth considering both points of view for your purposes.
https://youtu.be/ecekSCX3B4Q?t=1154
I would suggest you to try distage (disclaimer: I'm the author).
It allows you to do much more than a typical DI does and has many unique traits:
distage supports multiple configurations (e.g. you may run your app
with different sets of component implementations),
distage allows you to correctly share dependencies across your tests
and easily run same tests for different implementations of your
components,
distage supports roles so you may run multiple services within the same process sharing dependencies between them,
distage does not depend on scala-reflect
(but supports all the necessary features of Scala typesystem, like
higher-kinded types).
You may also watch our talk at Functional Scala 2019 where we've discussed and demonstrated some important capabiliteis of distage.
I have shown how I created a very simple functional DI container in scala using 2.10 here.
In addition to the answer of Dan Story, I blogged about a DI variant that also uses language constructs only but is not mentioned in Jonas's post: Value Injection on Traits (linking to web.archive.org now).
This pattern is working very well for me.

How do you go from an abstract project description to actual code?

Maybe its because I've been coding around two semesters now, but the major stumbling block that I'm having at this point is converting the professor's project description and requirements to actual code. Since I'm currently in Algorithms 101, I basically do a bottom-up process, starting with a blank whiteboard and draw out the object and method interactions, then translate that into classes and code.
But now the prof has tossed interfaces and abstract classes into the mix. Intellectually, I can recognize how they work, but am stubbing my toes figuring out how to use these new tools with the current project (simulating a web server).
In my professors own words, mapping the abstract description to Java code is the real trick. So what steps are best used to go from English (or whatever your language is) to computer code? How do you decide where and when to create an interface, or use an abstract class?
So what steps are best used to go from English (or whatever your language is) to computer code?
Experience is what teaches you how to do this. If it's not coming naturally yet (and don't feel bad if it doesn't, because it takes a long time!), there are some questions you can ask yourself:
What are the main concepts of the system? How are they related to each other? If I was describing this to someone else, what words and phrases would I use? These thoughts will help you decide what classes are useful to think about.
What sorts of behaviors do these things have? Are there natural dependencies between them? (For example, a LineItem isn't relevant or meaningful without the context of an Order, nor is an Engine much use without a Car.) How do the behaviors affect the state of the other objects? Do they communicate with each other, and if so, in what way? These thoughts will help you develop the public interfaces of your classes.
That's just the tip of the iceberg, of course. For more about this thought process in general, see Eric Evans's excellent book, Domain-Driven Design.
How do you decide where and when to create an interface, or use an abstract class?
There's no hard and fast prescriptions; again, experience is the best guide here. That said, there's certainly some rules of thumb you can follow:
If several unrelated or significantly different object types all provide the same kind of functionality, use an interface. For example, if the Steerable interface has a Steer(Vector bearing) method, there may be lots of different things that can be steered: Boats, Airplanes, CargoShips, Cars, et cetera. These are completely unrelated things. But they all share the common interface of being able to be steered.
In general, try to favor an interface instead of an abstract base class. This way you can define a single implementation which implements N interfaces. In the case of Java, you can only have one abstract base class, so you're locked into a particular inheritance hierarchy once you say that a class inherits from another one.
Whenever you don't need implementation from a base class, definitely favor an interface over an abstract base class. This would also be handy if you're operating in a language where inheritance doesn't apply. For example, in C#, you can't have a struct inherit from a base class.
In general...
Read a lot of other people's code. Open source projects are great for that. Respect their licenses though.
You'll never get it perfect. It's an iterative process. Don't be discouraged if you don't get it right.
Practice. Practice. Practice.
Research often. Keep tackling more and more challenging projects / designs. Even if there are easy ones around.
There is no magic bullet, or algorithm for good design.
Nowadays I jump in with a design I believe is decent and work from that.
When the time is right I'll implement understanding the result will have to refactored ( rewritten ) sooner rather than later.
Give this project your best shot, keep an eye out for your mistakes and how things should've been done after you get back your results.
Keep doing this, and you'll be fine.
What you should really do is code from the top-down, not from the bottom-up. Write your main function as clearly and concisely as you can using APIs that you have not yet created as if they already existed. Then, you can implement those APIs in similar fashion, until you have functions that are only a few lines long. If you code from the bottom-up, you will likely create a whole lot of stuff that you don't actually need.
In terms of when to create an interface... pretty much everything should be an interface. When you use APIs that don't yet exist, assume that every concrete class is an implementation of some interface, and use a declared type that is indicative of that interface. Your inheritance should be done solely with interfaces. Only create concrete classes at the very bottom when you are providing an implementation. I would suggest avoiding abstract classes and just using delegation, although abstract classes are also reasonable when two different implementations differ only slightly and have several functions that have a common implementation. For example, if your interface allows one to iterate over elements and also provides a sum function, the sum function is a trivial to implement in terms of the iteration function, so that would be a reasonable use of an abstract class. An alternative would be to use the decorator pattern in that case.
You might also find the Google Techtalk "How to Design a Good API and Why it Matters" to be helpful in this regard. You might also be interested in reading some of my own software design observations.
Also, for the coming future, you can keep in pipeline to read the basics on domain driven design to align yourself to the real world scenarios - it gives a solid foundation for requirements mapping to the real classes.