Es mostren els missatges amb l'etiqueta de comentaris scala. Mostrar tots els missatges
Es mostren els missatges amb l'etiqueta de comentaris scala. Mostrar tots els missatges

dimecres, 29 de gener del 2014

Scala code in Android app

I've been meeting Dani at several meetups in Barcelona lately.

We're both interested on scala but he also investigates the options to use it in android apps.

Last Saturday I remebered reading something about scala being used in android apps and tried to restore my notes to share them with Dani. Here's what I could recover:

ALERT: The following is a druid recipee based on maven.

git clone git@github.com:jayway/maven-android-plugin.git 
git clone \git@github.com:jayway/maven-android-plugin-samples.git 
cd maven-android-plugin 
mvn clean install 
cd ../maven-android-plugin-samples/ 
cd scala/ 
sed -i '' 's/2.8.0/2.10.3/' pom.xml
mvn clean install 
adb install -r  target/scala-1.0.0-SNAPSHOT.apk

Note: the previous uses a Mac OSX flavour 'sed' that requires an extra pair of simple quotes.

dissabte, 25 de gener del 2014

DI and testing without mocking in Play!

At the scala developers barcelona meetup we are running monthly challenges. This month's challenge is to implement a REST API. Easy peasy.

At some point, akustik had a question about his approach in Play! and so asked for opinions on the mailing list. Turns out I had been over the same problems few weeks earlier at my (then) current project so offered to help. Since the answer is quite reusable I'm cross-posting here so that you can comment and discuss if my suggestion is actually correct. I worked may way into the solution to make sure I remembered all steps and the PR'd my code into the challenges github: https://github.com/scala-developers-bcn/challenges/pull/29

DISCLAIMER: I'm quite new to Play! and it's very possible there's a better way than what I suggest.




Dependency Injection and testing without Mocking in Play!

Play!'s Main Problem (TM) is the abuse of singleton objects for everything. While it's a great idea to create a single instance of anything and reuse it again and again it's also a problem to make everything object (scala equivalent for classes that contain only static methods). This object-based approach makes it difficult to inject instances at will.

Back to the trigger, here's akustik's question:
I wanted to change [the controller] implementation for testing purposes without modifying the code nor changing to a variable and adding a setter. 
To which I could only reply:
You hit one of the big problems of Play! testing: there's no easy
recommendation for unit testing. The path of objects and Integration
Testing is the default suggestion. Sad.
And finally found few minutes to properly solve the problem.



Dependency Injection

To escape the object singleton mess which forbids you from doing plain old DI you first have to convert you controllers from objects to classes.

(I'm not 100% of what I'll explain now)
But once you did that you have to prepend your routes mappings with an '@' sign. That causes you HTTP requests to request an instance to Play! The responsible to resolve the required instance is a thing** called GlobalSettings.
(back to 100% sure)

Then you have to create your subclass of play.GlobalSettings and then go to application.conf and specify what your Global class is. But you class controllers still use singleton repositories. Let's make the repos injectable. Add a constructor parameter to your controller:


  class MyCtlr(repo:MyRepo) extends Controller

And now you made your controller unavailable because Play can't resolve the incoming requests. Here's where you go back to your Global class and override the method getControllerInstance so that any incoming request lets you decide what Controller to use. And there you have it!

Your Global soon becomes this:


  def flightRepo = new InMemFlightsRepository
  def flightCtlr = new FlightsCtlr(flightRepo)

  override def getControllerInstance[A](controllerClass: Class[A]): A = {
   // extend here when adding more controllers... probably a pattern matching.
    flightCtlr.asInstanceOf[A]
  }


So far so good. We got ourselves so DI wonders.



(trolling mode on)
It's at this point where your Global should be renamed ApplicationContext and you should consider your:

  def flightCtlr = new FlightsCtlr(flightRepo)

a synonim of: (blogspot won't let me use lt and gt)

  bean id=flightCtlr class=controller.FlightsCtlr scope=request
     constructor-arg="flightRepo"

You could have also done:

  val flightCtlr = ...

which would be:

  bean id=... class=... scope=singleton


Scala 1 - XML fuck you!... I mean 0

(trolling mode off)




Unit Testing (without mocking)

And so we end up on our wonderful test. 
If you've read the Play docs you probably have a test that looks like this:

    "return 200 on flights/" in {
      running(FakeApplication()) {
        val flights = route(FakeRequest(GET, "/flights")).get
         ...

Well, without you knowing it uses your Global class. The final trick to easily inject your Mock classes is to tell your Fake Application to use a different Global:
      running(FakeApplication(  withGlobal= Some(MockingGlobal() ) )) {

And that's it!
Well, no!
Oh God this is horrible!
** Remember when I said "a thing** called GlobalSettings" , well by thing I mean some bytecode that may be class or trait and I was being vague on purpose because there's both a class and a trait called
GlobalSettings and you'll need to use both to achieve DI and testing. To distinguish which GlobalSettings you are using pay close attention at the package.

  • To override Global for you app extend play.GlobalSettings
  • To inject a MockGlobal into FakeApplication when testing mixing play.api.GlobalSettigns
Putting it all together

So, to make your testing work you have to provide a MockingGlobal of yours which must mix-in play.api.GlobalSettings. I chose reusing my original Global class and just override a faked repository.

Again, while the running environment requires you to provide a subclass of play.GlobalSettings, FakeApplications expects an Option[play.api.GlobalSettings] (which is the trait). (Mother of Mercy this is wrong!)

I just go and extend and mixin to keep all my DI in a single place:

  class MyGlobal extends play.GlobalSettings
                   with play.api.GlobalSettings { ...

and finally:

  val globalForTest = new Global {
    override def flightRepo = new InMemFlightsRepository {
      override def loadAll(): List[Flight] = 

          List(Flight("ON_TIME","BOS", "CHG", "19B"))
    }
  }



Conclusion

Now, after this terrible mess lets puts this in context (no pun intended) and compare this with the 'easy' setup of a Spring-MVC app with testing and everything.
It's not much simpler but it's 100% scala so it must be cooler.

divendres, 20 de setembre del 2013

Parallel collection manipulation in scala

Scala collections API comes packed with a very cool feature which is parallelizing any processing. See this example:

I first create a list (I could use a range or s/thing else too):

scala> List(1,2,3,4,5,6,7,8,9)
res0: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

... and then build the skeleton of my processing. What I want to to multiply each value by 1000 and then divide each value by 500:

scala> res0.map{ 
    i => i*1000
  }.map{
    i => i/500
  } 
res1: List[Int] = List(2, 4, 6, 8, 10, 12, 14, 16, 18)

Nothing fancy so far.

Entering par

In scala every collection can be automagically wrapped into a counterpart that implements processing with a thread pool. I actually have no clue what the implementation is. Damn! I'll have to look it up. Anyway, insert 'par.' on your code and...

scala> res0.par.map{ 
    i => i*1000
  }.par.map{
    i => i/500
  }
res2: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(2, 4, 6, 8, 10, 12, 14, 16, 18)


... the list becomes a ParVector and keeps all items sorted in the original position.
Let's try and see it in action: (added random sleep to 'help' context switching)

scala> import java.util.concurrent.TimeUnitimport java.util.concurrent.TimeUnit

scala> import java.util.Random
import java.util.Random

scala> new Random

res6: java.util.Random = java.util.Random@b9d964d

scala> res0.par.map { 
    i => TimeUnit.MILLISECONDS.sleep(res6.nextInt(1000));
    println(i);
    i*1000
  }.par.map{
    i => TimeUnit.MILLISECONDS.sleep(res6.nextInt(1000));
    println(i); 
    i/500
  } 
3
7
4
5
8
2
1
9
6
7000
3000
5000
4000
1000
6000
8000
9000
2000
res13: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(2, 4, 6, 8, 10, 12, 14, 16, 18)

scala> 

Ta dah! Execution is run in parallel.

See more information re Parallel Collections on the overviews of the Scala Docs.

PS: For the curious...

If I get rid of the first 'par', the first processing is sequential, and the delays add up.


scala> res0.map { i => TimeUnit.MILLISECONDS.sleep( res6.nextInt(1000)  );println(i) ;i*1000}.par . map { i => TimeUnit.MILLISECONDS.sleep(  res6.nextInt(1000)  ); println(i); i/500 } 
1
2
3
4
5
6
7
8
9
5000
2000
1000
6000
3000
4000
9000
7000
8000
res17: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(2, 4, 6, 8, 10, 12, 14, 16, 18)

dijous, 1 d’agost del 2013

SBT and ScalaTest and a strange exception

After few weeks developing in Play! at some point today I started getting an Exception out of nowhere.

[info] 
Exception in thread "Thread-109" java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2577)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at sbt.React.react(ForkTests.scala:98)
at sbt.ForkTests$$anonfun$apply$2$Acceptor$2$.run(ForkTests.scala:66)
at java.lang.Thread.run(Thread.java:722)
[info] Passed: : Total 23, Failed 0, Errors 0, Passed 23, Skipped 0

Strangely enough it would be thrown on every test execution but all tests pass (see last line). 

Turns out it's a known (and already fixed) issue in sbt 0.12.2 so that was only a matter of updating:

   # sed -e 's/0.12.2/0.12.3/g' project/build.properties

dissabte, 18 de maig del 2013

Word Wrap #katayuno

I finally got the chance to attend a Softonic's Katayuno.

I love the Coding Dojo's in general, but those organised at Softonic are special because of their office decoration (out of the average) and because they're breakfast.

Once I got at Softonic I must say the ambient, even with an empty office, felt different from many other  companies I had visited before. The place is clean, ample and colorful you also have to consider the fact that's we were at story 9 which is over the average building height in Barcelona so the view was also quite stunning. Yes, you can see the sea from the dinner. And yes, there's a dinner.



Back to work

We got to work and after fiunchinho's introduction to TDD and red-green-refactor warmed-up on a first 30 minute pomodoro. The problem at hand was the KataWordWrap which fiunchinho selected specially for it's simplicity. It's not that he thinks we are stupid (which we are) it's that eh wanted us to complete the kata for once. SPOILER some of the pairs did complete the kata so fiunchinho just got a badge unlocked!

I paired twice in Java and after the break I paired once in scala. I'm still not very fluent in scala but I'm happy to report that we completed the kata in scala in little over a pomodoro (and I think we got further than previous pomodoros too!). Here's the final code:

This last session I paired with dvillacampa that is completely new to scala. I must say he very patiently listened to all my funoby comments about the language.

dimarts, 8 de maig del 2012

Simple Build Tool

Today I finally jumped into using sbt.

I found how to get it and how to setup my machine at it's GitHub documentation (https://github.com/harrah/xsbt/wiki/Getting-Started-Setup), and now trying to make it work with my current code (https://bitbucket.org/ignasi35/scala-eclipse).

The main reason why I chose to test sbt is the continous testing:

  • you can have sbt continually running (actually waiting for you to change something) and it will notice when something changed and compile and run it's tests. Actually, that's just a case of the actual feature: continous so you are not limited to continous testing.
So far I'm struggling to make it work with my existing FunSpecs.