The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI.
Sounds like pretty helpful HTTP method to use and implement, especially for the REST API. Unfortunately, not many people decide implement it for
their own API. I think partly we should thank for this our web frameworks and libraries. In past I tried to implement generic OPTIONS
method
handler in many different frameworks (like Play, Unfiltered
or some java frameworks), but unfortunately my experience was very frustrating to say the least (I really don’t want to write this logic manually for every single resource in my API). In most cases you ether required to use reflection
or speculatively try all methods against routing black box in order to find out which HTTP methods are handled and which are not.
akka-http is the first HTTP library in my experience that
provides right set of abstractions for this problem. I was able to implement Options
handler with it in very natural way and in just few lines
of code, so without further ado let me show you how it works.
As a follow-up to the post about Scaldi Play integration I would like to introduce you an integration with the Akka in this post.
Akka integration is pretty recent addition to scaldi and interestingly enough has not much to add to the core library in order to smoothly integration with the Akka. In order to use it you need to add scaldi-akka to the SBT build, so let’s do this first:
libraryDependencies ++= Seq(
"org.scaldi" %% "scaldi-akka" % "0.3.1"
)
This weekend I was continuing my work on the next version of Scaldi. Once again I faced the problem that was bothering me quite some time. In Scaldi you can inject a dependency with something like this:
val server = inject [HttpServer]
In this case inject
method will get HttpServer
class as a type argument and everything works as expected. But what would happen if you forget to specify the type or you just defined the type of the server
but don’t provide it explicitly to the inject
method? Will it even compile or maybe type inference will be able to figure out the type?
val server = inject
val server1: HttpServer = inject
Unfortunately, in both cases it will compile, but the inferred type would be Nothing
. It appears to be a known problem and it will not be fixed. Ideally I would like to see a compilation error in this case, so I started to look for a solution. After some time I actually was able to find the way to prevent Nothing
inference and, by taking this idea even further, found a way to define type constraints in a very generically in the method signature. They will allow you, for example, to describe union types with (T =:= String) Or (T =:= Int)
or even more complex rules like (T <:< Color) And Not[T =:= Color] And Not[(T =:= Yellow.type) Or (T =:= Blue.type)]
.
In this post I would like to make small introduction to Scaldi and show you how easy it is to use it together with Play. Scaldi is dependency injection library for Scala. It’s very lightweight (without any dependencies) and provides nice Scala DSL for binding dependencies and injecting them. It’s more dynamic approach to do dependency injection in comparison to the cake pattern, because not everything is checked at the compile time. This can be seen as an disadvantage, but I personally believe, that there is place for this approach. It can be vary useful in many circumstances and many people can find it more natural (and easy), especially if they are coming from Java background.
There are only 3 most important traits that you need to know, in order to make dependency injection with Scaldi:
bind
and binding
. Module
also extends Injector
trait and implicit Injector
instance always available when you are defining your bindingsinject
function (so it just provides nice syntax for injecting dependencies). It’s important to understand, that it’s the only the purpose of it. So it completely stateless and knows nothing about actual bindings you have defined in the module. In order to actually find and inject dependencies, inject
function always takes an implicit parameter of type Injector
With introduction of string interpolation in Scala 2.10 we finally got a feature, that many modern languages already have. What made me extremely exited though, is the fact, how good this feature was integrated into the language and how customizable it is. In this post I would like to show you some examples of it. I will not concentrate on explaining how exactly it works, but instead I will show you one very cool application of it, which I found recently. It combines string interpolation with regular expressions. What is especially interesting is the way you can use it in the pattern matching expressions.
It is something that I wanted to be able to make for a long time and actually found one way to implement with type Dynamic. That solution was a little bit crazy and looked like something that you normally will never use in real projects. Now I’m happy to show you solution that is actually looks nice (at least for regular expressions). I also want to notice that things I would like to share with you are shamelessly stolen from (were inspired by) this video introduction to Scala 2.10 features by Adriaan Moors and this answer at StackOverflow by sschaef. I want to thank authors for giving me inspiration and educating me :)
Recently I gave introductory tech talk about Scala at my company. The target audience were mostly Java developers. So I tried to give some impression about Scala that, from one hand, tries to explain basics, but from other hand, tries to motivate people to learn Scala further.
Presentation consists of two parts, which I believe are very important for any project and team:
In Scala 2.10 class Dynamic
would be enabled by default, so I think that it’s the right time to look at it in more detail. This class can be used for many different purposes. I think, that an integration with dynamic languages is the most obvious one, but I would like to show you something different. I will demonstrate you how to create parameterizable extractors, that can be parametrized directly within case
expressions.
Class Dynamic
works very similar to Ruby’s method_missing
or Groovy’s methodMissing
/propertyMissing
. So you can call non-existing methods on classes that extend Dynamic
. Such calls would be rewritten by compiler to following method invocations: applyDynamic
, applyDynamicNamed
, selectDynamic
, updateDynamic
. I will describe each of these methods in the next sections.
Scalaz is very interesting Scala library. It can be pretty scary when you first look at it and at examples of it’s usage. I also find, that at the beginning, advantages of this library are not very obvious. So at some point I asked myself: why are people so enthusiastic about it? So I started to learn it, but found that it’s hard to find any resources that are targeting beginners - people who are new to Haskell, Category Theory, or advanced Scala features like Type Classes or Higher Kinds.
In this post I want to summarize all resources I found about scalaz or related to scalaz that are actually approachable by beginners. I started with question at StackOverflow where I received many good answers. I also noticed, that this question was pretty popular, so I decided to write this post where I can summarize the answers and maybe add something more.
I personally believe that even if you don’t completely understand every aspect of scalaz yet (I’m definitely not), it still can help you to write a better code. As far as I can can see, it helps to write more composable, reusable and side-effect free code. But in order to use it, you need to understand some key concepts that it heavily relies on. So let’s start with …
Recently I created home page for my project Scaldi. I wanted to make it for a long time, but from the other hand I don’t want to spend much time finding some hosting and maintaining its infrastructure, making page design, etc. Github page is nice, but still I would like to have somethng more simple and unique as a project’s front page. So my main goals were:
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.
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.
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?
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.
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!
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!
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)
)