Refactoring utility classes with Kotlin : Shared Preferences

If you were developing Android apps in Java until now and haven’t started using Kotlin in production yet, you may have some sort of utility classes for many things like File I/O, Connectivity, Cache, Shared Preferences etc. Today, I am going to write only about Shared Prefs and how we can use Kotlin to refactor our old Java utility classes. This post is intended for anyone including beginners who want to play around Kotlin.

Maybe you have a good solution for shared prefs but I have it copied from here:

It looks ugly. To edit preferences, I have to write same things repetitively. Also, to access and manipulate, there are separate getters and setters for each type. In below steps, we will first try to refactor our Java class and then convert it to Kotlin.

Refactoring Step 1: Higher-order functions

The first step we can do is to identify a repetitive task that has been performing. In our case, every time we put something in preferences, we open an editor, put value and commit that transaction. Instead, we can compose a higher-order function that would accept a function to be performed by the editor. I am not going to discuss how you can use lambda expressions on Android. You can either enable Jack or use retrolambda.

Here, the Performer is a functional interface and edit method takes an anonymous function as an argument:

Refactoring Step 2: Using generics

Even after using lambdas, we have methods for each data type, which is not so good. We can use generics to have conditional checks for the type at run time. Either using instanceOf or using parametrizable class(class<?>), we can avoid writing a separate method for each type:

Finally, we can manipulate preferences with just two methods :getValue()and setValue(). Now code looks less ugly and concise than previous.

However, this if…else still looks bad. Many things like checking for nulls etc. are omitted. There are three to four parameters to pass in every single method. That interface for the higher-order function is unnecessary. We can not refactor those things because of limitations of the language.

Converting to Kotlin

Refactoring Step 3: Using extension functions

In the Java version of our class, we were using all static methods. We can now convert them to powerful extension functions. So, in our case, we will first convert our edit() function as an extension for SharedPreferences:

As we can pass function directly as an argument in Kotlin, we can get rid of that Performer interface. Here I used inline keyword to avoid the cost of higher-order functions. You can read more about it here.

Refactoring Step 4: Using when expressions and reified types

Using when expressions, we can eliminate all those if…else hell and make our setter look like below:

Well, but what about getValue()? In the Java version, we were using parameterizable class (class<T>). In Kotlin, we can do the same thing but with more elegantly using reified type parameters. To put simply, it will allow us to use type passed as a parameter. You can read more about it here.

Look at the following part:

getInt(key, defaultValue as? Int ?: -1)

Here, as? is a safe cast operator and so it returns null if typecast is failed. ?: is an elvis operator. It simply says: ‘take this value if the original value is null’. In our function parameter, defaultValue is the optional parameter. As a result, even if we don’t pass the default value, it will take from the right-hand side of the elvis operator.

Refactoring step 5: operator functions

So, our implementation now looks like below. Notice that I have added methods for accessing default as well as custom preferences and used object declaration to make it work as a singleton.

Wouldn’t it be great if just rename our setter and getter to just set() and get(). Kotlin supports operator overloading and so we can convert function to look like an operator:

Now we can use square brackets for setting and getting values. Just two lines of code for manipulating shared preferences.

It looks neat and elegant. Thanks to Kotlin!

Advertisements

Architecture Components looks great!

The recent talk about architecture component at Google I/O sounds great. With including Kotlin as an official language, a powerful ORM and lifecycle aware architecture components, Google really did a great job this year for Android development. Android framework looks evolved and powerful with all these now. Personally, I am feeling like my life as an Android developer will be far easier and better than previous!

 

A programmer’s view on technology that hijacks people’s minds

It was a great post about how technology is hijacking people psychologically followed by a TED talk from Ex-Google design ethicist Tristan Harris.

We can directly see it by noticing the people surrounding us. How may social networking addicts have you seen in your friends and family circles? How many people open the facebook in your office washrooms to check the stuff behind notifications?

As software developers, to some extent, we are also a part of this hijacking process. Of course not all, but many of us have been. Only for mobile and web developers: just think about all the apps and websites you have been developing. This post in all about my views about the world we are creating.

The technology we created isn’t helping ourselves to do the right things. For example, If you notice a design pattern like pull to refresh, then we are still just pulling the data from servers in order to refresh the data.

1-BNOfmUQ2nTRVPVe0CHx7ew

This is ridiculous, especially in the situation when the network connectivity is good and network costs are affordable. Why do we still need to call web services and pull the data? We should have real time data transfer in order to save time for our users. Stuff like WebSockets and platforms like Firebase and PubNub is really taking off and so we can hope the future to be good. Ideally, every data storage, transfer and manipulation should work in real time.

Second thing, we must need to care about design. We really need to focus on how can we create user interfaces that can provide functionality in the smallest possible interactions. Currently, all design patterns are doing the reverse. They either try to hide the data or to show more and more data.

The future depends on how we can help our users to have a meaningful time spent on technology in all possible ways. When the business rules the technology, it’s all complicated.

Carrot & Stick: that doesn’t work on Programmers!

'A raise might destroy their initiative. The good old carrot and stick bonus keeps them focused.'

Carrot & Stick – by definition “a policy of offering a combination of rewards and punishment to induce behaviour”, perhaps the oldest methodology for motivation in organisations doesn’t work for tech companies. There are many reasons for that, I will discuss them later. Any engineering solution just can’t follow this kind of rigid methodology to motivate their employees. Still, I can see many software companies following it blindly.

It was a great talk – ‘The Puzzle of Motivation‘ by Dan Pink. The quotes from the talk:

There is a mismatch between what science knows and what business does. And what worries me, as we stand here in the rubble of the economic collapse, is that too many organizations are making their decisions, their policies about talent and people, based on assumptions that are outdated, unexamined,and rooted more in folklore than in science. And if we really want to get out of this economic mess, if we really want high performance on those definitional tasks of the 21st century, the solution is not to do more of the wrong things, to entice people with a sweeter carrot, or threaten them with a sharper stick.We need a whole new approach.

There are many reasons for the fact that carrot and stick approach doesn’t work on programmers. First, Good programmers just don’t work for ‘only’ money. They work because they are passionate about developing software, self-motivated and love to do their job. Shiny paychecks don’t always fulfil all the other things they want. Second, Programming is more than a job. Programming is not a mundane routine work. It is all about solving problems, art and craftsmanship, perhaps someone’s hobby or a passion. Programmers need the proper environment to think, brilliant people to surround by and good projects to keep themselves busy. Enticing with carrots does not address these problems. After all, It’s easy to find programmers. It’s hard to find good programmers.

So, to all the employers following it – that 19th-century old absurd approach absolutely doesn’t work on us and you are doing it all wrong!

Dart : Dead or on Bullseye?

bullseye-926864_960_720                                                   [Image source : pixabay.com]

Around late 2013, Google announced 1.0 of its own programming language Dart targeted initially at the web. But since then, it didn’t receive much attention like other modern programming languages. A bunch of enthusiasts started using it and found it interesting. But as it was targeted against the web (and therefore the javascript) initially, it also received much hate. Some people also marked it dead. In late 2014, I picked it up and just did some experiments for a while. It is truly a cool language from a Java background. In this post, I will express some of my opinions about what went wrong with the language, what is still good and why the language still has the potential. It may be more opinioned and it is how I feel about the language.

What went wrong

Targeting the only web

Initially, Dart was targeted ‘only for the web’. This strategy didn’t work fine. The web development community is horribly fragmented. Also, nobody wanted another language in the web community. There are dozens of programming languages that compile to Javascript like CoffeScript, TypeScript, Scala.js, PureScript, Elm, Haxe, etc. Dart has no reason to be chosen over all of these.

Misunderstood Type System

Type systems are always a matter of controversy in programming languages. Many people would agree that dynamic typing makes programmers productive but when it comes to scalability in software, static typing is necessary. Everyone love experimenting at first. Static typing makes experimenting hard. Everyone need scalability at last. Dynamic typing makes it clumsy.

Dart’s type system is cool. It has an optional type system where you can start with loose typing and then specify the types later. The real benefit of it is that you can gradually evolve programs. At first, you can start prototyping without types and then add types later.

However, the type system was initially marketed like a combination of JavaScript and Java. Of course, Dart has Javascript-like syntax and Java-like standard libraries but the goal of optional type system was clearly not that. Many devs thought of the language as some sort of combination of Java and JavaScript. Of course, anyone would not want to put their efforts or money to learn  or use a combination of two another languages. Instead, why not they just learn those languages?

Javascript-like syntax

Dart creators said that as they are targeting for the web, they wanted to keep the syntax familiar to Javascript developers. JavaScript has the syntax similar to languages like C, Java and C#. They are all old languages. Of Course, there are many improvements in Dart like good functional and async support etc. But there are no syntax improvements.

Instead, with that verbose and old syntax, Dart feels boring. There are numerous things still needs to be improved in the language itself. The braces for named parameters and square brackets for optional parameters feels ugly and unreadable. Many modern languages like Swift Kotlin and Go did a good job of removing unreadable and repetitive stuff like ternary expressions and prefix increment decrement operators. There is inconsistency even in type names. Is there a reason for writing String in upper case and int in lowercase even if they all are objects? Why there are numbers and integers both? The underscores for private members suck. Most modern languages give importance to the readability of programs more than writing. Tiny details are important. If everything is put in a language has no solid reason for doing that, that’s a bad thing.

What is still good

Standard Libraries

Dart SDK provides a complete standard library with built-in collections, futures, streams, asynchrony and much more. So, you don’t have to rely on any external modules to do basic (probably most) things. This is also true for any programming language born at Google, take Go for example.

Tooling

Dart plug-in for IntelliJ IDEA community edition works fine. Tools for the formatting and analysing code – dartfmt and dartanalyzer are also available. The Dart Observatory is really a big deal.

Productivity

Starting with Dart is easy.  I like getting started fast and experiment a lot. Fairly, I like the idea of an optional type system. Optional typing helps a lot here. With all the built-in libraries and good tools, it is easy to build a good app without bothering yourself about searching libraries for basic things. Experimenting is always fun without those type-heavy systems and later I can turn those experiments into structured programs, which is really a cool thing about Dart.

Conclusion

Dart is a very productive programming language and has a great potential but a bunch of bad decisions and circumstances turned the language away from being popular. Dart was always designed as a ‘general-purpose’ programming language. Dart creators have already realised these things and Dart now wants to take on all the client-side development including browsers, mobile platforms and embedded devices. As the language has already failed to meet the expectations, there is a good room for improvement. At this moment, Flutter and Dartino are being mature and we just heard a brand new mysterious OS named Fuchsia that will use Dart as a front-end for building apps. Dart developer summit 2016 is nearby in October and we can hope to see what is next. Personally, I am excited about Dart 2.0.