Etikettarkiv: Java

Paradigm crisis

Detta inlägg finns även att läsa på HRM Softwares teknikblogg!

Ever since I took the Haskell 101 course I have gradually entered a state best described as a paradigm crisis. Prior to that course I happily hacked away in an object-oriented fashion, and I felt pretty confident in how to tackle problems when I faced them. I knew the most commonly used design patterns and how to look up the ones not that frequently used when needed.

Then came functional programming.

Admittedly I was not immediately convinced when I took my first steps in the Haskell 101 course, and I think the reason for that was that I did not quite see where these new functional tools would fit into my very object-oriented toolbox. Somewhere in that toolbox, along with factories and decorators, I had to find room for map, fold, filter and other functional concepts so I could easily find them.

It turned out that I actually needed a whole new compartment in my toolbox, as object-oriented programming and functional programming indeed are two very different paradigms.

It is true that we in the hybrid world of Java 8 can mix these two paradigms as we see fit, but when we are writing functional Java we leave the object oriented paradigm for a moment and become declarative and immutable, which is really cool. For me as (mainly) a Java programmer, the functional style of doing things are increasingly becoming my first-hand choice. I mean, what’s the point of for-looping a list of elements when all I want to do is to grab some elements that matches a given predicate? The ”old way” of doing this is way to error prone to be worth it. Moreover, when we leave out the ”how” part when working with collections, the language can apply optimizations to the ”how”-part. The declarative style of programming allows you to work on a higher level of abstraction and let the language worry about the specifics of ”how”.

Now, the leading paragraph of my blog post mentioned the word ”crisis”, which intentionally was a strong word to get your attention. 😉 Although the new compartment in my toolbox have complicated my professional life a bit – especially at the time of writing when I am still a newcomer to the functional paradigm – I have noticed that I am starting to think about how to attack problems a bit differently than before. When in the object-oriented world, you would use all kinds of design patterns and language constructs to control mutability of objects in order to get a fair chance to understand and reason about what’s really going on. In the functional world, you would instead work declaratively on immutable data structures, which means that we write code on a higher level of abstraction without the need to worry about mutable data.

And suddenly, the new functional toolbox compartment seems really compelling.

I have to admit that I may be a bit over enthusiastic right now, I usually behave like that when I try out new things that I like. But when listening to Martin Odersky in yet another course I’m enrolled in on functional programming I find it a bit sad that object-orientation turned out like it did in languages like Java. I mean, why is everything mutable by default? That doesn’t make sense. And why did the programming courses I took at the university teach this mutable object-oriented way of programming? As far as I understand, imperative programming where everything is mutable has been a well-known problem for decades.

Time to sum up this blog post with a stupid quote coined by myself over a cup of coffe: functional programming is like sudoku! 🙂

Trash Friend

Detta inlägg finns även att läsa på HRM Softwares teknikblogg!

Last week me and some colleagues took part in a hackathon here in Växjö. This hackathon was one of many events that took place during something called Digitala veckan, an entire week packed with IT-related events around the Linneaus university region. For those of you new to the concept, a hackathon is basically a competition in which programmers hacks away at a problem in a limited amount of time. In this particular hackathon, the challenge was to combine open data sources on the web and produce something useful for making our environment better. While HRM had two teams enlisted in the competition, this blog post is about our contribution. Say hello to Trash Friend.

The rationale for Trash Friend came to us while struggling hard figuring out what to do. We had been provided a list of example open data sources in-line with the overall environmental theme, but the data sources were admittedly not all that great and not always up to date. Moreover, our friends in the other HRM team were hacking away like crazy right from the start with a pretty neat idea, which made at least me feel a bit stressed out. We did come up with a few kick ass ideas right from the start too, but the open data sources were not fitting in nicely in any of those. What to do?

Figuring out what to do

After some headache we finally settled on an idea that were nicely motivated by another colleague of ours during a coffee break. One of the provided open data sources contain information about cars entering one of the recycling stations in Norremark, Växjö, and while brainstorming he said something like:

”They should have a webcam over at that recycling station. The queues can be terrible over there and you never know until you actually get there.”

Now, we did not have access to a webcam or any live data, but we did have access to the data set I just mentioned, which contained statistics over the course of a few months. It included data such as the time of visitors entering the station, the length of the cars (!) and the speed of the cars passing through the sensor. The latter two were not that useful for us, but the time of entry had some potential. Although there were no information about when cars left the recycling station, you could take a wild guess and say that the average time for a visitor staying at the recycling station is, say, fifteen minutes. Not that we actually had any coverage for that estimation, but for a hackathon such as this that estimation was perfectly fine.

With the time of entry and an estimation of how long visitors were hanging out at the recycling station, we could take a particular point in time, for example at three o’clock Friday afternoon, and calculate the expected number of visitors at that time. The algorithm we used to calculate that approximation was to historically look at the visitors to the station at that time on that particular weekday. From all of these occurrences we simply came up with an average to make the approximation somewhat reliable, that is, taking all Friday afternoons at three o’clock into account.

The idea

So, the idea we had was to make recycling easier for citizens and to relieve them from long queues at the recycling station. Such a tool has the potential to be beneficial in several ways:

  • Avoid a high load of visitors; if a citizen has a way to find out that the queue to the recycling station is long s/he can decide to wait before deciding to pay a visit.
  • Reduce the emission level at the station; cars in queue means that there will be more emissions, which leads to our next point.
  • Improve the work environment for employees at the station; less emissions and less visitors at peak hours.

There are probably more points to such a list, but let us settle for those and head over to implementation details.


With the algorithm in place for calculating the number of visitors at the recycling station at a given point in time, we had one more crucial nut to crack – the information had to be super-easy to get a hold of. Would a web site do? For some cases yes, but remembering the URL of that particular site you tend to visit occasionally would not cut it. We wanted something that was just there when you needed it. Perhaps a notification could pop up in your smart phone when things are looking okay at the recycling station? Notifications are nice and all, but how could we possibly know when the citizen wants to recycle their trash? No, we needed something accessible that the citizen could consult when needed. And for this purpose a widget felt just right.

We finally settled on an architecture that involved three central components, described in more detail below.

RESTful web service

As the recycling central station data was encoded in a csv-file, we decided to crunch it and expose it in a format more suitable for our needs (i.e. JSON) via a simple RESTful web service. The technologies we chose for these tasks were Java and Spring Boot. With Spring Boot we had a RESTful web service up and running in no time, which was perfect for the time pressure we had during the hackathon. Aside from the recycling station data, service we build also included weather data. The weather data was fetched from an open weather data API and adjusted to the needs of the widget to inform the citizen about the weather conditions at the station. I mean, it is no fun to recycle your trash when it is raining.

Trash Friend Widget

The widget was developed for Android using Android Studio. This was the first time for me developing a widget, but after a while I got a hang of it and the result came out quite okay for a UI novice like me. As seen in the screenshot below, the widget presents a colored cycle to the far left. This icon indicates the status on the recycling station with one of the three colors red, yellow and green. A red circle tells you that you should wait your visit to the station for a later time, a yellow circle means that you probably will be in queue for a little while and, finally, a green circle means thumbs up, you should stop what you are doing and head over there right away.

The Trash Friend Widget

For a more concrete approximation (if there is such a thing) the text to the far right tells you the approximated number of visitors at the station at the present time. Finally, the weather icon show the weather conditions over at the station at the present moment. The information in the widget is updated every 30 minutes, which in my mind is acceptable as we are not dealing with live data (at least regarding visitor data).

But what if the queues are terrible right now? When should I go? To answer this question, the user simply taps the widget to launch the Trash Friend web application.

Trash Friend web application

The purpose of the Trash Friend web application is to answer questions just like the ones asked in the closing sentences of the previous section. When the widget is tapped, the default browser in your mobile phone fires up with an overview of the expected load of visitors at specific times throughout the current day (see figure below).

The Trash Friend web application

One can easily switch to a weekly overview by tapping the button ”Veckoöversikt” in order to see how the situation at the recycling station is expected to be later on during the week. This web application was developed using the Ionic Framework to make it mobile friendly right from the start.

Summing up

So there you have it. In just a couple of hours we went from frustrated to pretty satisfied with what we had produced. And while we did not win the hackathon (due to stiff competition of course ;)) we pulled through and produced something that, if polished a bit, at least in my mind would be a valuable tool for citizens living near this large recycling station. If all recycling stations in Växjö would start to gather entry data it would be quite easy to improve the design to let citizens select their station to track in their widget. In Android, the way to configure widgets is to flip them over and adjust its settings. Imagine if available stations were available in a list in which you could select the station to track? A tap on the widget would then, naturally, direct the browser to the statistics at that particular station.

That’s all for this time, keep hacking! 🙂 By the way, the code we wrote is MIT licensed and available on GitHub.

Preconditions in Google Guava

Detta inlägg finns även att läsa på HRM Softwares teknikblogg!

While the Guava project from Google comes packed with goodies for Java developers there is one thing in particular that I tend to use over, over and over again. Actually there used to be two of those, but since Java 8 comes with their own implementation of Optional I have shifted over towards that implementation instead. Anyway, the topic of this short text is Preconditions in Google Guava.

You can think of preconditions in Guava (as the word suggests) as a way to express and enforce preconditions that must be true in order for the execution to continue. A natural fit for these would be at the beginning of a method or a constructor, acting as guard statements of sorts that throw exceptions when violated.

To make things a bit more concrete we turn to code. First off we take a look at the ”normal” way to achieve precondition-like functionality without relying on Guava:

public class SomeClass {  
   private final String aString;  
   private final String anotherString;  
   private final int anInteger;  

   public SomeClass(String aString, String anotherString, int anInteger) {  
     if (aString == null) {  
       throw new NullPointerException("aString was null");  
     if (anotherString == null) {  
       throw new NullPointerException("anotherString was null");  
     if (anInteger <= 0) {  
       throw new IllegalArgumentException(  
           String.format("Expected anInteger to be > 0, got %s", anInteger));  
     this.aString = aString;  
     this.anotherString = anotherString;  
     this.anInteger = anInteger;  
   // more code here..  

In the SomeClass constructor we want to a) enforce that the strings passed as arguments are not null and that the integer argument is greater than zero and b) assign the arguments to their respective class member variable. Throughout the 16 lines of code in the constructor body we spend 12 lines of code just enforcing the correctness of the supplied arguments. One word that comes to my mind is verbose.

Another thing to note is that in each of the if-statements we check if the argument has a value that we do not accept. In plain english we can say ”if aString is null, then throw an exception” or ”if anInteger is equal to or lower than zero, throw an exception”.

We now turn to preconditions in Guava. An implementation of the constructor with the same functionality would then look as follows:

import static;
import static;

public class SomeClass {  
   private final String aString;  
   private final String anotherString;  
   private final int anInteger;  

   public SomeClass(String aString, String anotherString, int anInteger) {  
     checkArgument(anInteger > 0, "Expected anInteger to be > 0, got %s", anInteger);  
     this.anInteger = anInteger;  
     this.aString = checkNotNull(aString);  
     this.anotherString = checkNotNull(anotherString);  
   // more code here..  

In this version of the class constructor we make use of two static methods in the Preconditions class, namely checkArgument and checkNotNull. In order to make the code more readable these two methods have been statically imported, as seen above the class definition. Let’s walk through the lines in the constructor one by one.

The first line calls the checkArgument precondition to check that anInteger is greater than zero, otherwise an IllegalArgumentException will be thrown. A second and third argument can be supplied to the method – this is optional as the method is overloaded – that provides the exact same functionality as the String.format method used in the former version of the constructor. The most important thing to note on this line is that we check if the argument has a value that we accept. This is the complete opposite to what we did in the former version of the constructor, where we checked if the argument had a value we did not accept. In plain english we can now say ”anInteger must be greater than 0 or an exception will be thrown”.

The second line in the constructor is just an assignment, nothing more to say about that. The fourth and the fifth lines are however much more interesting. Here we use a precondition on each line to check that the string is not null, otherwise a NullPointerException will be thrown. If the precondition is enforced successfully, the argument supplied to the checkNotNull method is assigned to its member variable. In plain english we can now say ”aString cannot be null or an exception will be thrown”. Again, the way we express this is completely inverted from the former version of the constructor, where we say ”if aString is null, then throw an exception”.

Aside from making the code more compact – we have now effectively reduced the code from 16 lines down to 5 – it is also in my strong opinion that the latter version of our constructor is easier to understand. With preconditions in Guava we have the ability to state how things must be rather than how things must not be in order to proceed with the execution. This might seem like a trivial improvement to code readability, but with each small improvement to readability we add to our code base we also make it more maintainable.

After all, code is a form of communication, and code that communicates well is easier to understand and maintain.

P.S. An alternative to the Preconditions.checkNotNull method is the Objects.requireNonNull method available in Java 7.