About data classes, named parameters & default values

Writing data models in Java is a pain. You have to write getters, setters, toString(), hashCode() and equals() methods, constructors and possibly builders or a copy() method. For complex models this can easily create classes of a few hundred lines. Not only is it tedious to write all of those methods, it’s also error prone. What if you add a new field? You might forget updating your hashCode() or equals() method.

While there’s tools like Lombok or AutoValue that help with that they’re still not ideal. They’re not part of the language and don’t work well with the IDE – even with plugins. In Kotlin you can write all of this in one line:

data class Song(val title: String, val album: String, val artist: String, val year: Int)

This includes all the getters, toString(), hashCode(), equals() and copy() methods, and the constructor. If you change a val to var you also get a setter. This is great, right? But what a about builders? Well you could still write it yourself, but in most cases you won’t need them because of named parameters and default values.

Named Parameters

Builders are useful when you have complex classes that take in a lot of values. Especially when some of them are just boolean or int values – what does true mean here? What is 16? You have to look at the constructor to see what property you’re setting. It’s also error prone: you might put values in the wrong order.

Builders help with that: you can set all your parameters in any order you want and you will always know what exact value you’re setting.

In Kotlin named parameters help with that. First – let’s create a new song in Java:

new Song("Cristina", "Breakfast", "Teleman", 2014);

So what’s the artist, what’s the album and what’s the title again? Let’s look at the Kotlin code with named parameters to find out:

Song(title = "Cristina",
     artist = "Teleman",
     album = "Breakfast",
     year = 2014)

Aha! Much clearer! You might’ve noticed that I swapped the artist and album around. That’s because you can change the order of the parameters – as long as you’re using the named parameters the right parameter gets set.

This works great for Kotlin, but if you’re still using Java in your project you can still create a temporary builder to use from Java. It’ll be a great reward to remove it once you’ve migrated all the necessary code to Kotlin.

Default Values

Named parameters are brilliant, but sometimes you don’t want to write the same set of parameters again and again. Let’s look at the song model above and extend it a bit.

data class Song(val title: String,
                val album: String,
                val artist: String,
                val year: Int,
                val playCount: Int,
                val rating: Int,
                val language: String)

That would be quite a lot of code to write to create a song! Here come default values:

data class Song(val title: String,
                val album: String,
                val artist: String,
                val year: Int,
                val playCount: Int = 0,
                val rating: Int = 0,
                val language: String = "English")

You might’ve noticed val playCount: Int = 0. This means every time you instantiate a song and don’t provide the count it’ll automatically be set to 0. Let’s have a look at the code:

Song(title = "Cristina",
     artist = "Teleman",
     album = "Breakfast",
     year = 2014)

Even though we’ve added a few more parameters you can create a song without any new code. Any parameter that you provide will be set, if not the default value will be used. However when creating it from Java you still have to provide all values. To workaround that you can add the @JvmOverloads annotation to expose overloads for all the required constructors.

Default values not only work in constructors, but also in functions. One area where I found that useful were fixtures in tests. Say you have the song model above. You might want to write some tests for some app logic depending on if the song was rated or not or was released in 2017. Obviously you could just create a new song for every test and set all values, but that can be tedious, especially for more complex models.

In Java code I used to create fixtures which returned a builder, which I could then modify whenever needed. Now in Kotlin I don’t write builders anymore, but I found a nice way to work around that using default values:

fun createSong(title: String = "Cristina",
               album: String = "Breakfast",
               artist: String = "Teleman",
               year: String = 2014,
               playCount: Int = 0,
               rating: Int = 0,
               language: String = "English")
          = Song(title, album, artist, year, playCount, rating, language)

All arguments of this function have default values set. This means that every time I create a fixture I only have to set the values I care about and want to test using named parameters. Here’s an example:

val ratedSong = createSong(rating = 5)

Neat, right? I only care about the rated value in this case – everything else can be the default value as I’m not testing for it.

What else can you do with all of that?

Data classes, named parameters and default values are very powerful and there’s many use cases for them.

Data classes work great for for all your models, including your Api models – they work well with Json parsing libraries like Gson or Moshi.

Named parameters are useful for any complex functions or constructors, but even if they’re not – if it is not clear what you’re assigning use named parameters – it’ll make your code much easier to read, especially when reviewing your code.

Default values have so many great use cases – whenever you want to overload a function you can use default values instead. This is especially powerful when used with extension functions, but onto that another time…

About data classes, named parameters & default values

A problem like Kotlin

Kotlin has been around for a while now. My first dive into it was short – I was just finishing up at Path and had a few hours to do something small, so I decided to play around with Kotlin. A few hours later I gave up. Back in 2014 there were not many people using it, the language was still in alpha and I didn’t know anything about the syntax or the language itself.

I went back to my Java world and kind of ignored Kotlin. I knew people started to use it, but would it really give me much? Would it really work that well? A few months later Dario sent me a small code snippet. In Kotlin – it was an extension function. I started to become interested. I can just add a method to a class without having to extend or modify it. That sounds really cool, right? But still. Was it actually ready? Was JetBrains really behind it – what if they just abandoned it?

Fast forward to September 2016. I joined Deliveroo and we were using Kotlin in some tests. I actually started to write Kotlin code. But again – I didn’t know much about the language and I was basically just writing Java code with the Kotlin syntax. Rarely was I actually using some of its powerful features. But over the months I started to discover them one by one and I started to learn how powerful the language is. It started to be established in the Android community and was actively supported by Google in Android Studio.

However, using Kotlin in test means you can’t make much use of most of its features. So we decided to actually use it in the main app.

We’ve slowly started to use Kotlin. Learning the language as we go and discovering new features as we go. A few weeks later Google announced Kotlin as an officially supported language at Google I/O. I was VERY excited. Suddenly all my doubts were gone.

Kotlin is here to stay

Kotlin has come a long way, but I’m still a beginner. I want to start sharing my learning story – all the language features I’ve discovered and where to apply them. So over the next few weeks/months/years I will share some snippets that show where Kotlin shines. I might discover later, that there’s a better way to do things, or that I’m simply doing things wrong, but it’ll be a great learning journey.

A problem like Kotlin

A problem like L – part 2

I’ve managed to spend a bit more time playing with L since my last blogpost. This time I’ve dived deeper into two areas: Toolbar and Animations.

Action Bar to Toolbar

Toolbar is one of the things that was hardly mentioned at Google I/O. A lot of things were hard with the Action Bar. Especially when you were trying to do animations you were stuck. It wasn’t part of your layout and you couldn’t access it directly.

Toolbar changes this. You can integrate it into your layout and therefore animate it or even change its position. The features of Action Bar and Toolbar are pretty much the same. All the navigation options like tabs have been deprecated in the Action Bar and are also not in Toolbar. Custom views can be added directly in the layout. Toolbar extends ViewGroup, so you can add them just like anywhere else.

Activity Transitions

L had lots of additions in the Animations framework. Activity Transitions are one of them. Before L you either had to use an animation defined via xml or create a lot of boiler plate code to make a nice transition between screens. In L you can now define shared elements that are available on both screens and either won’t be transitioned or have a custom transition. The actual window transition is also much richer and can be customized.

One thing that surprised me is that this seems to move away from using Fragments everywhere. Although the shared element transition also works with views inside Fragments, the transition support wasn’t added to the Fragment transition. This means that if you’re using a single Activity and are only replacing Fragments you’re out of luck. Even the Google I/O app uses Fragments rarely.

Is that all?

I’ve also created a custom view to make FloatingActionButtons easier to use, which is using other new features like ripples, state list animators and elevation. There’s still lots more to look into and I want to dive deeper into some areas, so expect a part 3 🙂

A problem like L – part 2

A problem like L

I’ve spent the weekend playing around with some of the new L APIs. A lot of things got me really excited at Google I/O and I wanted to see how things really work.

Holo to Material

I started off by transforming my existing Holo theme to Material. Turns out this is incredibly easy. My Holo theme was huge – mainly to change the highlight colour on all the controls. The Material theme does all this work for you. All you have to do is define four colours:

<style name="AppTheme" parent="android:Theme.Material.Light">
    <item name="android:colorPrimary">@color/primary</item>
    <item name="android:colorPrimaryDark">@color/primary_dark</item>
    <item name="android:colorAccent">@color/accent</item>
    <item name="android:colorControlHighlight">@color/ripple</item>
</style>

This will automatically colour all the controls in your accent colour, set the status bar, action bar and ripple effect colour. Just these few lines should be enough to have a simple theme.

But what if you’re using a light theme, but have a group of Views with a dark background? Luckily they added an android:theme attribute for Views. This means you can change a theme specifically for a view or view group and its children. Just define a dark and a light theme and use them across views.

ListView to RecyclerView

Listview is a pain. As soon as you need more as the basic functionality you find yourself extending ListView and hacking functionality on top of an already bloated widget. RecyclerView changes that. A lot of functionality was moved out from the widget itself and into separate classes. This makes tailoring it to your use cases a lot easier and hopefully you’ll never have to extend RecyclerView.

The new OnItemTouchListener allows you to intercept touch events without extending RecyclerView, which makes things like swipe to delete easier. If you want your dividers back you can find a DividerItemDecoration class in the samples. A lot of other things have been removed from the RecyclerView, like item click listener and item selection. You’ll have to define those on the item views directly.

RecyclerView is still a work in progress, so a lot of things might change and some functionality might be added back, but so far I think it’s a good evolution of ListView.

What about animations, CardView or Palette?

There’s a lot more great stuff in L, but I didn’t have the time to look into those yet. I will do so in the following weeks and keep posting my experiences.

The real question for me is how easy backwards compatibility will be. Things like RecyclerView are in the support library, but I doubt the Material theme will be available. Supporting old API levels currently seems very difficult as soon as you go beyond a simple application and might even be worse than supporting Gingerbread. I’m hoping for a lot of additions to the support library with the actual release of L (Lollipop?).

A problem like L

A problem like… Android UI

People always talk about Fragmentation being a problem on Android. From a UI perspective I don’t think it’s that much of a problem. Of course – it is easier to build an application for two fixed screen sizes like on the iPhone, but if you define your layouts correctly different screen sizes and devices shouldn’t be a problem. Here are a few tips what to do:

  • Use dp and sp (for fonts) instead of pixels – this will resize your views and texts depending on the screen density
  • Avoid to set fixed dimensions for your view. Yes, sometimes they have to have a fixed size, but a lot of times they can resize depending on the available space. In a lot of cases just the margin between the views is fixed.
  • Use RelativeLayouts. Once you understand them you cannot work without them. Use them wisely – they need at least two layout passes and can be slow!
  • If you can’t use RelativeLayouts use layout_weight to fill up the available space.
  • Use 9-patches and/or drawable resources instead of fixed pngs. Obviously this doesn’t apply for icons.
  • If you don’t want to use standard Android Checkboxes etc – use themes
  • And most importantly: keep trying and testing!

A few more tips: Watch the Google I/O sessions (not just about UI – they are very useful in general!), check out this blog and finally: watch the following video. It’s definitely useful – even if you’ve been working on Android for a while.

A problem like… Android UI

Handling Orientation Changes in Android

Orientation changes are something I wouldn’t consider as being handled very well on Android. The standard behavior is: you change your orientation – the Activity is being recreated, which means you’ll use your changes that happened while the Activity was visible. You changed the visibility of views after a user interaction? It’s gone. You’ve displayed data that’s been retrieved from the server? It’s gone. Luckily there are a few options to fix those problems:

  • Prevent your Activity from being recreated
  • Save simple data in a bundle
  • Retain an object

Each of those methods have their pro and cons and you can also use multiple options.

I don’t want any changes!

If you don’t have any differences between your landscape and portrait mode it’s easy. But beware – if you have different layouts depending on the orientation this won’t work – even if you just use a different dimension or string! Those changes won’t apply on orientation change if you use this method. If that’s not a problem for you all you have to do is add android:configChanges=”orientation” to your activities in your AndroidManifest.xml. If you still want do make some easy changes in code (maybe change the padding or orientation of a view) you can do this using onConfigurationChanged(Configuration).

Using this method your Activities won’t be recreated and all your views and data will still be there after orientation change. But as I mentioned before: if you have different layouts this is not the option for you. Also it is not being recommended by Android.

I just want to save a few Strings!

If everything you want to save during an orientation change are just Parcelable objects such as Strings, Booleans, String arrays, Integers etc you can save those values in a Bundle and read the data when the activity is being recreated. Using this method your Activity will be destroyed and recreated again, which means you can have different layouts for your orientations. Saving and restoring the data works using those two methods:

@Override
protected void onSaveInstanceState(Bundle outState) {
    // save your data
    super.onSaveInstanceState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    // read your previously saved data
}

I want to save complex Objects!

When you want to save other objects you have another option. Also here the Activity is being recreated and you can easily combine it with the second option. Save your simple stuff in your bundle and your complex stuff using this method. You can only save one object but you can create a class containing multiple objects and save this one. This way you can save your visible Dialogs, your current running tasks or pretty much anything else. To save this object all you have to do is this:

@Override
public Object onRetainNonConfigurationInstance() {
    return yourObject;
}

In your onCreate you can then read out the information of your object using:

Object o = getLastNonConfigurationInstance();
if (o != null) {
    if (o instanceof YourClass) {
        yourObject = (YourClass) o;
    }
}

Using the second and third option you have the advantage of changing your Activity based on the orientation but still retain your data, but beware: If you have a service running or callbacks they will still be attached to your old activity and you will have to rebind to them in your new activity! In general: if you have data you receive from a server you should always cache that information to prevent the same data being retrieved multiple times – a user doesn’t like to wait! If you’re caching your data you can also use this data when you change your orientation and you don’t have to care about saving them just for this specific state.

I think this should cover all the options you have – if you know more please add a comment.

Handling Orientation Changes in Android

AI-Class.com – A classroom with 160,000 students

AI Class is a great experiment by two professors at the Stanford University: Sebastian Thrun and Peter Norvig. The course is being held as an actual course at Stanford University plus an online course for about 160,000 enrolled students. People in the advanced track have to do homework and write exams, people in the basic track just have to watch the lectures. Currently I’m in the advanced track, although I might switch to the basic track due to time problems (having a full time job + working on a private application + a University course is a bit too much). At the end of the course you’ll get a certificate, sadly not from Stanford but still. Pretty cool having done a course at Stanford… kind of.

I think it’s a great experience to attend a course entirely online with such a big group of people, although that causes the servers to be down quite a lot when a deadline is coming up. It really shows the potential of the Internet. I hope they’ll offer more like that in the future!

AI-Class.com – A classroom with 160,000 students

Theming and Styling in Android

After being an Android Developer for more than 1.5 years and being the main person at work responsible for UI I’ve learnt a lot about styling and theming. Sadly the Android developers website doesn’t provide a lot of information about it. That’s why I’m dedicating my first blog post to this topic.

Why use themes and styles?

Although at first it might seem like an overhead and complicated to use styles there are many advantages for using them. First of all a lot of Views in your application will have similar styles. A button might always have the same styles – often just the text is different. The same works for most of the other Views. If you’re using styles or themes you can reuse the style for each view. Whenever you update the design of your application you have to make the changes just in one place.

Another advantage of using styles is that it cleans up your layout files. It gives you a nice overview of the whole layout when each view has just the android:id and style value.

If you have different layouts in landscape and portrait mode it makes life a lot easier too. Without using styles you have to recreate the layout files in your layout-land folder. Whenever you change something you have to make the changes in two places. When using styles in most cases you won’t have that problem because the styling and the structure are separated. All you have to do is create a styles file in your values-land folder and overwrite the styles that are different. In most cases that works, especially when using RelativeLayouts. I usually end up with 1 or 2 layout files in my landscape folder – everything else is done with styles.

How to use styles?

I won’t write about how you’re using styles in general – that’s described very well on the Android developer website. I will describe how I am using them and how to take most out of them.

I inherit from other styles using Prefixes and define two base styles:

<style name="TextAppearance" parent="@android:style/TextAppearance">
	<item name="android:typeface">sans</item>
</style>

<style name="View">
	<item name="android:layout_width">wrap_content</item>
	<item name="android:layout_height">wrap_content</item>
</style>

I keep TextAppearances separated because they have no sizes defined. They can be used in other styles by setting android:textAppearance. The only problem I’ve experienced with that is that for Buttons you have to set the textColor separately. For Views I usually create a style for each type (Button, ListView, EditText etc). But sometimes there are views that are very different to the others of their kind. That’s when I create a style for the part of the application it is being used in.

This approach doesn’t work for every type. Especially when it comes to ViewGroups, where the layout parameters are often different. I create a View.Container style and the most common combinations of size and orientation. For most of the containers this is enough if background colors stay the same.

How to use themes?

When it comes to themes there’s really little information to find. I often had to look at the Android source code to find what and how I can theme something. Sadly it’s often not as powerful as I’d wish. Especially when it comes to theming Dialogs. If you want to change more than the background image you have to create a custom view (I’ll write about this in detail another time).

How a theme is created is being described on the Android developer site again. But how do I actually find out WHAT I can style? First of all look at the themes.xml  and styles.xml of the Android source code. If for example you want to change the drawable rof a checkbox search for checkBoxStyle in the themes.xml. Then you can find the style in either themes.xml and styles.xml. In that case it’s in the styles.xml and you can see the values you can change:

<style name="Widget.CompoundButton.CheckBox">
    <item name="android:background">@android:drawable/btn_check_label_background</item>
    <item name="android:button">@android:drawable/btn_check</item>
</style>

Don’t forget that there are other values from the styles you’re inheriting from. To change the checkBox drawable all you have to do is create this style:

<style name="CustomTheme.Widget.CompoundButton.CheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">
	<item name="android:button">@drawable/btn_check</item>
</style>

I keep those in the themes.xml to know which styles are global, but you can also put them in your styles.xml. I also keep the package name and just add my theme name to it. To use the style globally you have to add this line to your main theme:

<item name="android:checkboxStyle">@style/CustomTheme.Widget.CompoundButton.CheckBox</item>

As soon as you know where to search it’s very simple. Of course you could do the same with just styles, especially if you inherit by layout type, but it gives you a nice overview over your global style guidelines.

When not to use styles and themes?

The only time I’m not using these is when I just create a layout and am not exactly sure how it will work. I find it much easier to play around with different attributes in the layout file. After I found the right solution I create a style for it. I never put id’s in my styles because that prevents it from being reused. If I have references to other items I create a style specific for this item (using a generic parent style).

All these tips are what I found is best. Of course there are many other ways how to do it. If you have better options please leave a comment.

Theming and Styling in Android