Fork me on GitHub

Hacking Scala

#scala #hacking

April 28, 2013 at 2:13am
0 notes

Conceptual Surface Area of the Project

In this post I want to address (and express my opinion) some of the concerns described in fhil’s comment to my previous post about Scala Complexity vs Book of Magic Spells.

Conceptual Surface Area

First, I want to agree on concerns about language complexity, but I want to look at bigger picture. Scala the language has more concepts in it and from the language perspective it’s more complicated than Java. From my experience, every project bigger than HelloWorld involves heavy usage of libraries (including standard library). In my previous post I tried to take more higher-level view of the language, so I would like to keep this aspect in scope of our discussion. The problem with Java is that many libraries like Spring, Hibernate, EJB, AspectJ, etc. add completely new concepts which are pretty unique to each of them. And believe me, If you are creating real-world Java project (even small) you are expected to learn and understand a lot of new concepts introduced by these libraries (just try to search job sites for Java position and I assure you, most of them, of not all, require you to know a lot of libraries like Spring or Hibernate). I see Scala as product of evolution of other languages that absorbs new concepts in a language level that has proven to be useful or even essential. So Scala libraries can actually express themselves in terms of these concepts. Your real-world project becomes more simple, regular and consequent in terms of conceptual surface area. Just take a look at Unfiltered web framework, and how elegantly it leverages pattern matching, if you want to see an example. As application developer I care much more about project’s conceptual surface area rather than language’s conceptual surface area because language is common knowledge and if you invested some time and learned the Scala language you can jump in any Scala project and be very well prepared for the concepts you will face. It’s often not the case with Java because knowledge of reflection API and Annotations or even Java the language itself would be of little help in understanding new concepts that project or libraries introduce.

Keep reading

2:05am
1 note

Scala Complexity vs Book of Magic Spells

Today was the first day of the wonderful Devoxx conference. I got a lot of positive impressions, but what I want to share with you today is something different. Today I was reminded about recent buzz about Scala complexity. I hear a lot about this recently, but I still fail to understand some aspects of it.

In order to describe my point of view I would like to talk about Java complexity. Let me ask you a question: How complex Spring or Hibernate frameworks are? Some of you may say, that they are pretty simple (especially in comparison to EJB 2). But why is it so? Do you really believe that they are that simple… or may be they are just familiar? I think we can view these frameworks from 2 perspectives: from user perspective and from library developer perspective. I don’t think that you expect all developers in your team to actually be able understand, how Spring/Hibernate is internally implemented. You want them to be able to use these frameworks and understand their purpose, ideology. What does it actually take to understand their internals? Which knowledge about Java can help them to understand these frameworks? Actually users should edit XML files or add annotations in their code and with the help of the Spring/Hibernate magic interesting things will happen. Spring will magically instantiate object and wire them. Hibernate will be able to load/save objects from/to the database. Do you really expect new Java developer, which you want to hire, to understand how exactly this magic works?

Keep reading

2:01am
3 notes

Composing Your Types on Fly

Let me show you class from one of my projects:

class FileTransferHandler extends TransferHandler with Publisher {
    // ...
}

TransferHandler is swing class that generally handles copy/paste and D&D stuff. Publisher is trait that comes from scala-swing. So I generally composing here 2 independent things and making then work together.

As next step I define method, that requires it’s argument to be both - TransferHandler and Publisher. In my codebase I have only one type that extends both of them, and it’s FileTransferHandler. So I can use it to define my method, right?

def register(handler: FileTransferHandler) {
    // ...
}

The problem here is that the body of the register method does not care whether handler is FileTransferHandler or ImageTransferHandler or even StringTransferHandler. It only requires it to be TransferHandler and Publisher. And it’s exactly what Scala allows you to express using with keyword! So now we can write improved version of register method:

def register(handler: TransferHandler with Publisher) {
    // ...
}

So you don’t actually need any concrete class or trait to express such constraint.

Keep reading

1:55am
1 note

Inverting the Flow of Your Code

In previous post I described, how you can make side-effects in very concise way. There is one complementary operation that I also use a lot. This time it helps you to visualize the flow of the code. Let me demonstrate you this code:

case class Item(id: Int, name: String)

def getItem(id: Int): Item = // ...
def prepareForView(item: Item): Map[String, String] = // ...
def renderPage(model: Map[String, String]): String = // ...

def getItemPage(itemId: Int) = 
    renderPage(prepareForView(getItem(itemId)))

You have probably already saw this kind of code a lot. Such method chaining, that I showed in body of the getItemPage method, is pretty common. I personally find it awkward - the code flow is turned inside out. I call the method renderPage at first, even if this is something that would be used only at the end and produces the result value of the whole function. My brain just work in other direction: When I’m writing this code, at first I think, how I can get Item from id and then, how can I get the model for the view … and finally how to produce page. We can do better!

Keep reading

1:15am
2 notes

Side-effecting without braces

Sometimes I find myself in following situation: I have nice one-expression method like this:

def formatUsers(users: List[User]): String = 
    users.map(_.userName).mkString(", ")

Now I want to print the results to the System.out in order to quickly check the result that this function produces.

Common way of solving this problem is to write something like this:

def formatUsers(users: List[User]): String = {
    val result = users map (_.userName) mkString ", " 
    println(result)
    result
}

Too much code for such trivial task. In Scala we can do better than this!

Keep reading

12:46am
2 notes

Essential Scala Collection Functions

Let me ask you a question. How many times you wrote similar code?

case class User(id : Int, userName: String)

val users: List[User] = // ....
val resultUsers: List[User] = // ....

for (i <- 0 until users.size) {
    if (users(i).userName != "test") {
        resultUsers += users(i)
    }
}

May imperative languages like Java, C, C++ have very similar approach for iteration. Some of them have some syntactic sugar (like Java for each loop). There are many problems with this approach. I think the most important annoyance is that it’s hard to tell, what this code actually does. Of course, if you have 10+ years Java experience, you can tell it within a second, but what if the body of the for is more involving and has some state manipulatin? Let me show you another example:

def formatUsers(users: List[User]): String = {
    val result = new StringBuilder 

    for (i <- 0 until users.size) {
        val userName = users(i).userName

        if (userName != "test") {
            result append userName

            if (i < users.size - 1) {
                result append ", "
            }
        }
    }

    return result.toString
}

Was it easy to spot the purpose of this code? I think more important question: how do you read and try to understand this code? In order to understand it you need to iterate in your head - you create simple trace table in order to find out how values of i and result are changing with each iteration. And now the most important question: is this code correct? If you think, that it is correct, then you are wrong! It has an error, and I leave it to you to find it. It’s pretty large amount of code for such a simple task, isn’t it? I even managed to make an error it.

I’m going to show you how this code can be improved, so that intent is more clear and a room for the errors is much smaller. I’m not going to show you complete Scala collection API. Instead I will show you 6 most essential collection functions. These 6 function can bring you pretty far in your day-to-day job and can handle most of your iteration needs. I going to cover following functions: filter, map, flatMap, foldLeft, foreach and mkString.

Also note, that these functions will work on any collection type like List, Set or even Map (in this case they will work on tuple (key, value))

Keep reading