In Scala, how would I give a Singleton a constructor? - scala

My design incorporates a small database abstraction, whereby I implement each database as a Singleton (well, an object), with custom methods on the database for the couple of operations the code calls (it's mainly a log parser, dumping interesting statistics to a database).
I'd like to construct the Singleton database classes if possible, such that at runtime, each is constructed with config values (and those values remain constant for the remainder of the program's runtime). This would allow me to better test the code too (as I can mock the databases using Mockito or some such).
I'm still only learning Scala, but it seems there's no way to attach a constructor to a Singleton, and would appreciate any input on this problem - is there a better way to do what I'm doing? Is there some preferred way of constructing a Singleton?
Cheers in advance for any help.

Just put the constructor code in the body of the object definition:
object Foo {
println("Hello") // This will print hello the first time
// the Foo object is accessed (and only
// that once).
}

Rather than use a singleton (which is hard to test).. Whoever's creating the actors could create a database session factory and pass it to each actor, then it's still shared... and testable.

Not sure if this if this is what you're looking for but as the article explains, use the apply method without extending the base class
case class Foo(name:String)
object Foo { def apply(name:String) = new Foo(name) }
enter link description here

Related

What is the type of scala.concurrent.Future?

I try to understand what's the data type of scala.concurrent.Future?
I found the following types from the scala lang documentation, but still unsure the differences between them, and when to use which one?
trait Future[+T] extends Awaitable[T] //for concurrent programming
object Future extends AnyRef //not sure?
http://www.scala-lang.org/api/2.9.3/scala/concurrent/Future.html
http://www.scala-lang.org/api/2.9.3/scala/concurrent/Future$.html
Sorry, but I got an impression that you need first to get some scala basis, what is trait, what is companion object, and other stuff.
Back to your question.
When you want to execute something concurrently, you can wrap it in Future. Your code has some output type (SomeType, could be Unit - equivalent of void), after wrapping into Future you will get Future[SomeType] - it is extension of trait Future[+T]. Than you need some execution context (thread pool) to execute your Future.
Try to find and read "Programming in Scala" written by Martin Odersky, Lex Spoon and Bill Venners, very good for beginners.
Like a collection (List, Array, etc.), a Future is a type that works on/with another type. A useful comparison is the Option type.
Just as an Option[Int] might be an Int value (and it might not), a Future[Int] might not be an Int value yet. It could be that the Int value is still being calculated, or being extracted from a database table, or being retrieved from a distant network location. Whatever the cause, if it's a slow process there's no reason to wait for it. Turn it into a Future[Int] so that your program can go on with other important tasks.
As for the object Future, that is a singleton object that has a handful of methods for handling/manipulating existing Future elements. Future.sequence() is a useful example.
It is unclear whether you are talking about the trait Future or the singleton object Future. I will answer both.
The trait doesn't have a type. It is a type.
All singleton objects foo have the singleton type foo.type, so the singleton object Future has the singleton type Future.type.
In Scala, object is a singleton class, which means, that there only exists a single instance during the runtime of the application. There are several ways to implement singletons in most languages, but most often, you risk some issues such as thread safety. Scala's object takes care of the implementation of this pattern for you.
A common pattern in Scala is creating an object that has the same name as a class, like the one in your example. This is called a companion object. A common use for these is for essentially defining the equivalents of static methods from Java. You can declare methods that are common for all instances, or methods that handle and manipulate instances of the class. In Java, for example, you would declare them as static in the body of the class itself. The companion object helps you with separation of concern in this case.

In Swift OOP design, how do I arrange a commonly-used class?

I am new to Swift and OOP. For example, I have a class that manages the system-wide configurations.
class system_conf {
init()
getValue1()
getValue2()
...
setValue1()
setValue2()
...
reloadValues()
activateX()
activeteY()
...
}
This class should have only one instance and many other classes will use it. What's the recommended way for this case?
Should I pass around this instance?
Should I consider to use Singleton?
Should I use static functions directly?
Should I create a global instance, so every other class can access it directly?
or?
It seems your class is a configuration class. If you intend to pass it to a bunch of classes, you should wonder if you need to write unit tests for them.
If so, assuming you are either using a singleton or static methods or a global var, take a moment to think about how you would mock this configuration class for each of your tests. It's not easy, is it?
If your class is a kind of mediator, a global var or static methods are fine (or any other alternative you suggested). However, in your case, it would be better to pass your object in any initializer/constructor of each class using it. Then, testing would definitely be easier. Also, passing it via an interface is even better: you can mock it super easily (mock up libraries mostly work with interfaces only).
So there is no unique answer to your question. It is just a matter of compromises and scaling. If your app is small, any of the method you listed above is perfectly fine. However, if you app tends to get bigger, a proxy solution would be better for maintainability and testability.
If you fancy reading, you should glance at this article from Misko Hevery, especially this chapter.

Scala singleton as instance of another class

I have a singleton object, that handles database stuff for my application, but I would like to have a similiar class to be used during testing, so that I can have many smaller test databases that dont interfere with each other. I could just drop the singleton and just create a new instance of the database class at startup, but that would mean I'd have to pass around this instance to everywhere where database actions are needed and I dont want that.
I could make a singleton that would work as an interface to a single instance of the database class. Someting like this:
object DB{
val db = new Database()
def set(a:Int,b:Int) = db.set(a,b)
def get(a:Int) = db.get(a)
}
This just feels sort of stupid and pointless, especially when the database class is fairly big and I'd have to do that to all of the methods. Is there a better way to solve this problem?
Thanks!
The best way to accomplish that would be with a cake pattern, but you would have to indeed extend all the methods in your DB class.
In order to do that I would follow this article: http://www.warski.org/blog/2014/02/using-scala-traits-as-modules-or-the-thin-cake-pattern/
After you have created the cake pattern, you just have to have one trait that implements the "other DB" used for tests only on test source code. And, of course, the trait the implements the "real DB" on the main source code.
Seems to me that your problem involves having multiple, different intances of a class, and being able to access them as a single object. For clarity, note that this things are kind of contradictory.
Hence, you need composition to have a reference to whatever actual instance you want to use. Then either you expose this instance directly (DB.instance.doSomething()) or take the effort of forwarding the API as you mention.
Seems to me you are not comfortable with either of these. If the syntax DB.instance bothers you, you can always put this instance in a package object and use it directly. You can also import DB._ to have direct access to the instance variable.

Are static classes and methods bad? Global variables frowned upon?

I have an application that has database connectivity and although there are obviously objects that correspond to data in my database, I find that all my data processing methods could be static as there is no real need for an instance of the object as my classes simply operate on the data and spit something out, no need to store anything outside the method's scope. If I can make a method or class static should I?
Also I use a utility singleton class for common (single instance) "global data". I want to have a good design, but are these frowned upon?
Let me give you an example of what I'm doing. I load some data from my database using a static method to place it into a global varaiable in my Singleton class (a list of a custom object)
So my singleton class has something like
List<MyCustomObject> SomeList
and my static class has
static void LoadData()
foreach(data in database something or other)
singletonClass.SomeList.Add()
So the code above might load in some records from the database into SomeList, where each item in SomeList is of type MyCustomObject, which contains a single record of information.
Is this good implementation? Is this how you would code it?
Then in my presentation layer I would make calls to another static class of methods to get data from the singleton class in to a format required.
It doesn't feel very OOPey. But I can't really think how to do it another way you do it.
Allow me to direct you toward an excellent article on this topic: Singletons are Pathological Liars.
The problem is that the need to call your LoadData() function isn't self-evident. Compare your situation to that described in the article and I think you'll see some parallels.
Statics and singletons are frowned upon somewhat. But only the same way as starting a sentence with “but” — bad when overused, but sometimes it's what works best.
In your example, why have separate classes, one a singleton and one static? A singleton is in many ways equivalent to a class with only static data and methods. If you already have a singleton, I'd say you should add the methods to load the data to it rather than to a separate class. A class with static methods would be more appropriate if, say, you have utility code common to all of your stored data types.
(Also, I wouldn't worry too much about what's OOPey and what's not. Overengineering in the blind service of OOP principles can be a serious problem, speaking as someone who's had to wade through the Eclipse code base …)
Singletons is one but static is another very big one.
OOP or not, static variables have many drawbacks but little coding convenience.
Can't determine exact allocation time, life span
Can't work well in multi-threaded
Future problem to program expansion
...

Why people define class, trait, object inside another object in Scala?

Ok, I'll explain why I ask this question. I begin to read Lift 2.2 source code these days.
It's good if you happened to read lift source code before.
In Lift, I found that, define inner class and inner trait are very heavily used.
object Menu has 2 inner traits and 4 inner classes. object Loc has 18 inner classes, 5 inner traits, 7 inner objects.
There're tons of codes write like this. I wanna to know why the author write like this.
Is it because it's the author's
personal taste or a powerful use of
language feature?
Is there any trade-off for this kind
of usage?
Before 2.8, you had to choose between packages and objects. The problem with packages is that they cannot contain methods or vals on their own. So you have to put all those inside another object, which can get awkward. Observe:
object Encrypt {
private val magicConstant = 0x12345678
def encryptInt(i: Int) = i ^ magicConstant
class EncryptIterator(ii: Iterator[Int]) extends Iterator[Int] {
def hasNext = ii.hasNext
def next = encryptInt(ii.next)
}
}
Now you can import Encrypt._ and gain access to the method encryptInt as well as the class EncryptIterator. Handy!
In contrast,
package encrypt {
object Encrypt {
private[encrypt] val magicConstant = 0x12345678
def encryptInt(i: Int) = i ^ magicConstant
}
class EncryptIterator(ii: Iterator[Int]) extends Iterator[Int] {
def hasNext = ii.hasNext
def next = Encrypt.encryptInt(ii.next)
}
}
It's not a huge difference, but it makes the user import both encrypt._ and encrypt.Encrypt._ or have to keep writing Encrypt.encryptInt over and over. Why not just use an object instead, as in the first pattern? (There's really no performance penalty, since nested classes aren't actually Java inner classes under the hood; they're just regular classes as far as the JVM knows, but with fancy names that tell you that they're nested.)
In 2.8, you can have your cake and eat it too: call the thing a package object, and the compiler will rewrite the code for you so it actually looks like the second example under the hood (except the object Encrypt is actually called package internally), but behaves like the first example in terms of namespace--the vals and defs are right there without needing an extra import.
Thus, projects that were started pre-2.8 often use objects to enclose lots of stuff as if they were a package. Post-2.8, one of the main motivations has been removed. (But just to be clear, using an object still doesn't hurt; it's more that it's conceptually misleading than that it has a negative impact on performance or whatnot.)
(P.S. Please, please don't try to actually encrypt anything that way except as an example or a joke!)
Putting classes, traits and objects in an object is sometimes required when you want to use abstract type variables, see e.g. http://programming-scala.labs.oreilly.com/ch12.html#_parameterized_types_vs_abstract_types
It can be both. Among other things, an instance of an inner class/trait has access to the variables of its parent. Inner classes have to be created with a parent instance, which is an instance of the outer type.
In other cases, it's probably just a way of grouping closely related things, as in your object example. Note that the trait LocParam is sealed, which means that all subclasses have to be in the same compile unit/file.
sblundy has a decent answer. One thing to add is that only with Scala 2.8 do you have package objects which let you group similar things in a package namespace without making a completely separate object. For that reason I will be updating my Lift Modules proposal to use a package object instead of a simple object.