Categories
blog kotlin productivity

Force yourself to use Kotlin standard library!

Java world vs Kotlin world

One of the main stumbling blocks I encountered when I tried to use Kotlin is how can start writing Kotlin code using Kotlin idioms, instead of just writing Java code with Kotlin syntax. To explain what I mean let’s imagine we want to filter a list of links, and extract only links that contain “.com” domain. That can be done in java with this:
https://gist.github.com/abdurahmanadilovic/2b97a1391e32f746bd60f45d8a95cfa5
This example repeats itself in Java code all the time, but with Kotlin now, there is no need to write code like this ever again.

Filter

In Kotlin there is a generic extension function that can do this for us, it is called, filter. To rewrite this example in Kotlin, it would look something similar to this:
https://gist.github.com/abdurahmanadilovic/b180f506d9851486cba288cfdffea5e7
How beautiful is that? And Kotlin has lots of these extension functions that will simplify our life when doing common operations on collections in our code.

Map and forEach

What if you need to transform a list of type String, into a list of TextViews, and append all those text views on a root view, how would you do it in Java?
https://gist.github.com/abdurahmanadilovic/f61eed70684d16df3560150e7941a1f6
Now, compare that to this Kotlin code that does the same thing:
https://gist.github.com/abdurahmanadilovic/e2e1ecd0ee2c69f8c96ea0ae2915c1c2
Here .map was used for transforming a list of Strings into a new list of TextViews, and you can access each String with it keyword. Then forEach was used to iterate over the text view list and append each to the root view. But we can simplify this even more.

Chaining

One of the main benefits of using built-in collection extension functions is chaining. We can now combine map with forEach:
https://gist.github.com/abdurahmanadilovic/53cc609074f78dc207dd2866ada5e5ae
But why stop there, lets chain from the beginning:
https://gist.github.com/abdurahmanadilovic/4c0a2fea3ed076a522f7cf8ae67dbfde
Now that is much simpler and easier to understand than the Java equivalent.

GroupBy and Any

GroupBy can be used to create hash maps, with the return value from the lambda as a key, and the object itself as the value.
Any is also interesting, if you apply it to the list you must supply a lambda that returns a boolean which then checks if that lambda returns true for any items in the list.

Think standard library

Every time you write a Kotlin code, ask yourself is this Java style of coding, or is there a better way to do this in Kotlin? And most probably there is, every time you do some operation on lists, think how can this be done with Kotlin standard library. For a list of all things related to collections explore this link. You can find documentation for map, forEach, filter and lots of other functions that can be applied to collections.

Conclusion

Mastering Kotlin will take some time, but the important thing is to always be on the lookout for ways to write code that utilizes Kotlin language features to the maximum.

Categories
kotlin

What the hell are Kotlin class constructors?

A Kotlin world

In a Kotlin world, there are primary and secondary constructors, let’s start with a Kotlin primary constructor, the recommended constructor to use:
https://gist.github.com/abdurahmanadilovic/727d25ac09290856b7764fa7d6419d00
That is it, constructor keyword is omitted and the declaration goes after the class name. Class properties are declared as arguments in the constructor definition, and since they are public by default you can access properties by instance.property syntax.
The main constructor cannot contain code, all initialization is done inside init blocks, and there can be multiple init blocks:
https://gist.github.com/abdurahmanadilovic/6dcb13d96f723f871a4acbcb01622345
Alongside the primary constructor, we have secondary constructors, and there can be multiple secondary constructors with different arguments just like in Java. Secondary constructors begin with a word constructor:
https://gist.github.com/abdurahmanadilovic/82f15c844bf5641b7a5163f24fdf672a
One thing to note is that before the second constructor is invoked, a primary constructor must be called with this keyword, that will force the execution the primary constructor and all init blocks to execute and all member initializations to be done, and then the secondary constructor will execute.
If you have multiple constructors you can delegate/call from one constructor to the next with this keyword, then pass the appropriate arguments.
https://gist.github.com/abdurahmanadilovic/d4a7ee4d15bd95038d60a2916783b830
So when to use the primary constructor, a secondary or an init block?

Usages

The primary constructor is the one you will use most of the time, and it has a nice short syntax, 90% of the time it is enough when declaring a new class.
Secondary constructors can be useful when a Kotlin code gets called from Java, an example of that would be when extending an Android View with a Kotlin class. In Kotlin you can declare default arguments, while in java you can’t, that is why secondary constructors are useful, you can create multiple constructors that require different parameters, a nice addition if you are calling Kotlin code from Java.
Init block can be used for, as its name suggests, default initializations that are required to run when an object gets created, because the primary constructor does not contain any expressions init blocks will serve as an extension to the primary constructor.

Order of execution

If you are like me, I was confused when I first saw init blocks, secondary constructors, primary constructor. What does execute first?
The first thing that gets executed is the primary constructor, then in order of placement either member initialization or init blocks, then secondary constructor:
https://gist.github.com/abdurahmanadilovic/b6daae960d8c14fbda3bdad8ef174e2e

Conclusion

As seen in the examples above, Kotlin offers multiple ways of doing things, from a simple primary constructor to multiple constructors that offer better interoperability with Java. Also, the init blocks that can provide a clear way of specifying what is important and what has to be run once an object is created.
If you find the article interesting comment below or share on social media, thanks.

Categories
blog design kotlin OOP

Kotlin extension functions

 A world without extension functions

Imagine a scenario, you are coding a java android app, and you are using java.util.Calendar class for data and time management. You realize that you need to convert a calendar instance into a pretty format like “4 minutes ago…” but you are out of luck since Calendar object has no method that returns pretty format like that. The most common solution to this problem involves creating a util function that does that. Something like this:
https://gist.github.com/abdurahmanadilovic/978c8b8d1eefb3f510f910b50103672a
So what is the main problem with this solution? It goes against OOP principles. Accessing CalendarUtils class directly all over the project tightly couples your code to this utils class, and that is not a good thing.  It is impossible to switch later on to a different implementation of this class since its imported directly.
Another issue is testing, how can you test a class that directly imports a utils class? Tests written for this class will also test the utils class, and when you change that utils class, tests may break even if you did not touch your original class.

Object-oriented programming to save the day

A better way to solve this problem would be to use a wrapper around calendar object. Something like this:
https://gist.github.com/abdurahmanadilovic/7a59361ab767a8e4c9e6c941f7eb5eb7
Now, this is a much better implementation. We can create an interface around this class, provide multiple implementations, use dependency injection to provide this functionality to our app, a much better object-oriented solution.
What are downsides to this object-oriented implementation? It requires more code then the first solution, and it does almost the same thing. A whole class is created just to wrap a calendar object and provide one method on top of it.

A world with extension functions

For simple use cases, it would be nice to have some way of declaring functions that can be attached to some objects, and that function would have access to all properties of that object. So the effect would be similar to creating a wrapper class around that object, and we would not import that extension function all our code base, we would just call it upon the receiver object. It is still not a perfect solution but much better than creating utils classes.
Kotlin extension functions to the rescue! How would an extension function look like for the problem above?
https://gist.github.com/abdurahmanadilovic/99077936c3f308ef4d94c5f90cc79576
The extension function is the second function in the snippet above, Calendar.minutesAgoFrom, and you can immediately recognize that in the name of the extension function we specify on which class we want to attach the method. In this case, it is the Calendar class. So every time we create a Calendar instance in our code minutesAgoFrom will be available on that Calendar instance. The second thing to notice is the use of this keyword inside the extension function. This is the main power of extension functions, it provides an access to all internals of the Calendar object, hence the use of this.timeInMillis.
Extension functions are a middle ground between a fully object-oriented solution and procedural coding with static utils classes.
To really appreciate the power of extension functions let’s look at the code below, taken from the Kotlin extension documentation.
https://gist.github.com/abdurahmanadilovic/e6210ea5706f1d64c36bb605214ea50d
How powerful is that? We just created an extension function that applies to all possible list types. Now every list in your app has a swap function that can swap elements no matter the list type.

Conclusion

This just scratches the beginning of what extension functions look like, in part 2 we will see some popular collections of extension functions and how they actually work behind the scenes.

Categories
android architecture blog design kotlin

Android architecture components with Kotlin

Introduction

After Google announced android architecture components, it was, for the first time, a Google-approved android architecture guidelines. Before this, the whole community would try to come up with best ways to structure android apps. First, everyone tried to follow MVC pattern that Google sort of provided with Android. But MVC for android is very confusing, you have a controller who is a view also (Activity, Fragment). Then MVP came along. model view presenter architecture, which clearly separates responsibilities of views and presenters (controllers). The main idea was to define interfaces (responsibilities) for each view and its presenter, making the app much easier to refactor down the road, given the fact that you know exactly what are responsibilities of each screen. One downside for MVP is the total amount of interfaces you have to create and maintain.
When reactive java came along, it turned everything upside down. MVP did not fit quite well with rxJava, since data is reactive, you do not have to specify what happens when data changes, you just map it to the view and the view became reactive to its data. With reactive programming, you react to changes in the app, whether its user input or network fetching and the view is this dummy representation of that data. It turned out, that reactive programming is perfect for Android, since events are something that is very natural to mobile phones, it became much easier to write and maintain complex UIs with rxJava. So what are downsides to rxJava? Spaghetti code, if you can not recognize when to use rxJava, it is very easy to write spaghetti code.
So what exactly does architecture components bring to the table?

Architecture components overview

Before we look into what architecture components offer, what problems do they solve, let’s look at common issues Android developers face.

  • Configuration change (device rotation),
  • Synchronized UI with data
  • Fetching data from database
  • … (lots more)

Let’s start with the configuration change, what would be a proper way to solve this problem? In my opinion, I want no memory leaks :D, then I would like the data to survive the change, I don’t want to fetch data again just because a user rotated the screen. So we need some kind of lifecycle aware component which survives the configuration change, knows when it can update the activity, but also knows when to destroy itself when it is not needed anymore. This is exactly what ViewModel class is. With few lines of code, you can have a UI that reacts to data changes and also display the latest data when UI gets recreated.
What about UI synchronization? That is where LiveData comes in. Once you create a LiveData instance, you can subscribe to it, and receive updates every time you update that LiveData instance.
What about the database? There are plenty of ORM libraries out there, do we need another one? Well, what if you want an ORM which returns a LiveData, which you can subscribe to it, so when you insert new data into the database, you get updates immediately? That is where Room comes in.
Those are the building blocks of Android architecture components, but the question remains, what about Android architecture? These components serve a specific purpose, how to structure the whole app now?
Well, just follow MVVM architecture, the View reacts to ViewModel, which exposes Models for Views to use and update their representation. Instead of wiring the Views to Models manually, Data-Binding library can be used to that automatically. So what we described above is just a Google recommended/provided implementation of the required components for MVVM architecture.

Github repository

I made a Github repository for a sample project that uses Kotlin and android architecture components, check it out to see how everything fits together in one app. Here are the main specifications of the project in that repository:

  • ViewModel for reactive data binding
  • Room as ORM library
  • Paging Library as a reactive data source for adapters
  • Dagger 2 as dependency injection framework
  • Repository pattern for data fetching
  • Retrofit as a REST client

Categories
blog productivity psychology

Don't trust yourself, trust your daily routine!

The power of environment

Most of our daily decisions are automatic, and most people do not even realize that. The brain is a very efficient machine, everything becomes a habit after a while, meaning that who you are today is mostly habits and a small part of it is your active thinking. If you do not believe me, go back through your day and try to find at least three events where you stopped, thought about what are you doing, or you questioned your decision, then did that thing.
So why do we ignore our habits when we want to change and reach our maximum potential?
Do you check your phone every 5 minutes while you work? Do you check your emails every 10 minutes while you work? If you do something without thinking about it, that is a habit you built over some time, and if you stack multiple bad habits on a daily basis it may be the biggest cause of your low productivity and stress. You know you have to improve your work, but you simply can’t, you end up on the same level you were a month ago, or you descend few levels.
If you do not feel any progress in quality of your work from month to month, it is time for you to seriously reconsider changing your current work environment.

Environment by design

As with anything in life, you can passively receive things, and wait for someone to shape you, your life, or you can be proactive, a habit worth acquiring, and shape your environment so you can shape yourself the way you want to be.
I used to catch myself sometimes spending few hours on browsing facebook and youtube without realizing it and I don’t know how I got to that point at all! I do not remember the point where I decided to open facebook or youtube, so how did I end up wasting the last few hours on pointless entertainment?
I realized I need to proactively block my access to those sites, so I edited my hosts file and redirected facebook and youtube to 127.0.0.1. So every time I want to open facebook or youtube, I have to open hosts file, remove the redirect command, close the file, restart all browsers and access facebook and youtube. And that process cannot be automatic, I need to do that intentionally, and that was enough for me to prevent that habit of opening facebook and youtube without even thinking about it.
The next thing I did was to leave my phone in the other room, so I don’t even see the notifications when they pop up, I am free to focus on my work.
I did leave facebook or youtube available on my old laptop, so when I want to watch youtube or open facebook, I would take the laptop and access those sites, but that would be on my own terms when I am satisfied with the work I did, and I want to take a longer break.

Prevention beats cure

You can not trust yourself, your brain is on autopilot most of the time, don’t count on your brain ignoring phone notifications, don’t count on not opening youtube or facebook, you are driven by habits, facebook and youtube specifically exploit that by creating the dopamine loop that forces you to go back to those sites and engage with them frequently.

How we spend our days is, of course, how we spend our lives.

The quote above is from Annie Dillard, and there is a great article on brain pickings about her book The writing life, a great piece of worldly wisdom.
In summary, place systems that produce environments that nudge you towards high focus and productivity, and you will be more consistent with your work quality, otherwise, you are just responding to outside stimuli.
 

  • Environment has a stronger impact on your productivity than you think
  • The only way to make sure you are focused is to eliminate the possibility of a distraction (leave your phone in the other room, block sites)
  • Purposely create environments for your self that nudge you towards productivity (turn of wifi on your phone, leave a book on your living room desk, sell your TV)
  • How I constrain my internet usage
  • If you feel like you need to relax, don’t open youtube, take a walk or go talk to someone
  • Avoid instant gratification to get used to low dopamine input and to increase your ability to focus, deep work
  • Be aware of your decisions when you perform your work, question everything to produce quality work
Categories
blog psychology

Quit drinking coffee by quitting your job!

How to stop your coffee drinking habit

It is a well-known fact that once you repeat something enough times it becomes a habit. You may think you can not live without some lifelong habits you built, but if you manage to eliminate the habit trigger, you can actually remove that habit from your life without much effort. The quest then becomes to find the trigger, once found the process of overcoming that habit can begin.

Identify habit triggers

So how can you stop that coffee drinking habit that you know is a burden and unhealthy? One way is to find all the triggers that nudge you to think about drinking coffee. Let’s start with your job, most probably the majority of your coffee intake is during your work hours. So how many triggers can you identify at your current office that lead to drinking coffee? I think you can count at least 5 common scenarios, for example coming to the office in the morning and going straight to the coffee machine, or returning from a lunch break and seeing your coffee mug empty. So if there are so many different triggers, can you really stop drinking coffee at the office?

Willpower and behavioral change

When we think about behavioral change, what is the first thing that comes to our mind? Willpower, “yes I will resist the urge of drinking coffee next time I have it.” But how many times did that end up working? For me, it was never!
Using willpower to stop a habit is not impossible but it is very close to impossible. One problem with willpower is you have a fixed amount of it, one day you will have enough willpower to resist your temptation, another day you may not, and on that day will fall back to your old ways and realize your habits are simply stronger than you, and what is the point of fighting something that is stronger than you?

Environment and behavioral change

So if willpower does not work, what will work? There must be something that can be done about quitting habits! Let me drop a quote here:

There’s just one way to radically change your behavior: radically change your environment.
—Dr. B.J. Fogg, Director of Stanford Persuasive Lab

The idea is simple, with all the triggers at your current environment, trying to fight it with willpower will not work, it is far easier to change your environment and be careful not to create bad habits in the first place! If you are familiar with mental models, particularly the inversion mental model, you can immediately understand why would this work. Instead of fighting the habit directly, try to reverse the problem, don’t fight the habit, try to eliminate the cause of the habit, the habit trigger, once you remove the trigger, quitting a habit is an easy task.

New environment, new you

Now lets present a solution for our coffee drinking problem: instead of fighting it directly at your current office, quit your current job, get another job, which means moving to a new environment, resists drinking coffee at the new environment on your first day, and just like that, your urge to drink coffee went away! By each passing day, it becomes easier and easier to resist it! If you can hold off drinking coffee at your new job for about two months, congrats, you successfully removed the excessive drinking habit you thought you can not live without!
Actually, don’t quit your job! Wait until you get a better offer, switch jobs, then try this and let me know if it worked.
Actually, if you have health consequences from all that caffeine, then yes, quit your job, get another one and try this!
Keep on coding healthier!