Coder Thoughts on software, technology and programming.

Piotr Mionskowski

  • Simple Config Sections 1.2 released

    25 December 2015 .net

    About a week ago I've released another version of SimpleConfigSections. It's marked 1.2.0 and you can install it through Install-Package SimpleConfigSections.

    What is SimpleConfigSections?

    SimpleConfigSections is a little library that simplifies defining .net configuration sections. As you can see in the mentioned msdn documentation the amount of boilerplate code is substantial. An equivalent example in SimpleConfigSections looks like follows:

    As you can see the SimpleConfigSections version is more concise and a bit easier to write. More examples can be found on project's github page.

  • Android Data Binding Part 2: Observer pattern to the bone

    27 July 2015 android

    In the previous part I've described typical problems we have to face when developing applications on Android. I've also highlighted that some of them may be mitigated when data binding API is utilized properly. It's time to dive into more details of how this promising API works.

    Observer Pattern

    At the root of many of solutions we find in today's APIs is a design pattern. In case of the discussed Android API it is Observer Pattern applied to the bone. In fact this particular pattern is so common and powerful that some languages and runtimes (C# with .NET, Objective-C and Swift on iOS and Mac) provide neat support for it. You may wonder why it is important in the context of Android data binding? The answer is simple yet easy to ignore - memory management. The following diagram depicts dependencies of an observer pattern's elements in the context of Android data binding: Android data binding diagram On the right side we have the observable part producing notifications about changes - an object implementing android.databinding.Observable interface. In the observer pattern events producer can have many events listeners - OnPropertyChangedCallback implementations. Android data binding provides implementations of events listeners taking care of property values changes as well as collection elements changes.

    Note that the Observable object knows nothing about concrete OnPropertyChangedCallback implementations (Dependency Inversion Principle at its best). However, at runtime the Observable object will hold references to many OnPropertyChangedCallbacks instances. If you look further down the diagram you'll see that in order for OnPropertyChangedCallback implementations provided by Android data binding library to update the state of the view component a reference to it is required. This means that although the view model knows nothing about the view components at compile time they will reference them at runtime.

    How Android data binding library aids memory management?

    As stated above in a simple implementation we would have a lightweight and testable view model retain expensive view widgets - thus making it heavy. In the Android context it means that even though an Activity got destroyed we could have other object still retaining its Views, trying to update them and preventing them from being garbage collected. Not so nice, huh?

    If you look closer at how Android data binding is implemented you'll immediately see that its OnPropertyChangedCallback holds only weak references to views. WeakPropertyListener, WeakListListener, WeakMapListener and ViewDataBinding.WeakListener make sure that the Observable object is not retaining views. This means that there's no need for a developer to manually stop data binding in an activity onDestroy or a fragment onDestroyView methods. If you use RxJava you probably know that this extra step is tedious and requires a great deal of attention and boilerplate code. You can find out more about the problem in at least couple of issues on GitHub: 1, 2.

    Because Android data binding library takes extra steps to make sure a view model will not cause views to be retained we can detach a view model's lifecycle from that of an activity or a fragment. We now have an easy way to i.e. do a simple in-memory caching via singleton view models. More importantly, we can cross out at least one place when looking for a memory leak cause.

    This article is cross-posted with my company blog

  • Android Data Binding Part 1: Why it is important

    20 July 2015 android

    Android application code often suffers from being more verbose than it could be. As libraries such as Android Annotations and ButterKnife have shown that's only partially due to tediousness of Java. The recently announced Android Data Binding library can remove at least part of the boilerplate code we need to write. Since I've always liked Presentation Model pattern (MVVM) this is very dear to my heart. However just getting rid of a tedious code is not the main reason I'm so happy to see the new API. Let's recap on common issues developer faces on Android and then I'll show how using mentioned patterns with new offering from Google can mitigate them.

    Problems with classic approach

    I'll explain that step by step using a registration form screen example. We need couple of fields like first name, last name and an email address. To make the example a bit more interesting and to make UX better we'll use floating label pattern. One of the simplest approaches without data binding (for first name only) might look like this:

    Memory leaks

    A seasoned Android developer will immediately spot that we've a potentially leaked activity here. The culprit is of course the anonymous inner class implementing RegisterApi callback (Action2), which in turn uses findViewById. However it's not the mentioned method that retains the activity - in Java every non-static inner class will have implicit reference to the enclosing class instance. While this problem is so common I still haven't found a concise solution in the Android SDK. There are however community driven libraries i.e. Otto and RxJava that can help tackle this problem.

    To much code in Activity

    Many of us, me including, are guilt of stuffing too much into Activity classes. Writing test and maintaining them can become a nightmare over time. The verbosity of Java only makes the matter worse. One way to slim activities down is to use Presenter pattern written either by hand or with the help of Mortar. Another solution is to encapsulate more logic into custom view classes used in layouts and using shared static helper methods with common code that calls Android API. Nevertheless, for a programmer that just starts with Android, it's important that the framework provides guidance and samples that encourage separation of concerns - in my opinion up until now that was rarely the case.

    Maintaining layout files

    Many if not most screens in Android (and other platforms, too) are read-only. That is they are not forms and fields that user can change. Instead they offer neatly presented content with some way of interacting with it (as opposed to changing it directly). When using Android layout files we're forced to use references (auto generated in R class by aapt) that allow setting view's properties. This isn't something necessarily bad especially if you need to heavily interact with a View. Having said that, how often you used findViewById (or @InjectView) just to set the content of TextView or had to refactor activity fields type because of a change in a layout definition?

    Android Data Binding can help you.

    The following code illustrates how registration form might look like with data binding:

    The new RegisterActivity is similar to previous example. We inflate the layout differently to initialize data binding and get an instance of ActivityRegisterBinding class. The class, with the name derived from layout name, is generated by data binding and its main purpose is to provide a glue between a view and an observable view model. When using registerApi.register we only reference form variable thus avoid unnecessarily referencing the activity. The RegisterForm class is a view model for our layout and has all the data that activity_register layout requires.

    The view model has 3 observable attributes marked with @Bindable annotation. We don't strictly need a backing field as the getFirstNameLabelVisibility shows. What we do need is to fire change notification events, which is done via notifyPropertyChanged and notifyChange methods available on BaseObservable. The former method accepts a field id that is assigned by data binding processor in generated class BR (similarily to R class). Deriving from BaseObservable is not a must - to make a model bindable it has to implement android.databinding.Observable. Last but not least a layout file:

    The data binding library, while still in beta, provides a nice toolset to remove the boilerplate code and improve Android code (unit) testability by extracting the logic from activity (or fragment). When used properly it can also save you from leaking resources. In the next post I'll explain in more detail how it happens.

    This article is cross-posted with my company blog

  • Handling different user types in android application

    12 July 2015 android

    In the previous post you can read how to use Session object to maintain current user information through the application lifecycle. Now we'll explore different options of implementing varying behavior depending on user type.

    When an app has only one user type

    I find it neat when an application allows me to use it before I'm forced to create an account or sign in. In such a case there will be a, potentially very long, time where we have no way of identifying the user. At the same time we'll want to provide as much features of an identified user as possible. There will however be cases where application behavior will be different depending on whether the user is logged in or not.

    A simple if will not do any harm, or will it?

    Let's assume that our application allows changing preferences for both anonymous and authenticated users. When saving or reading user dependent application settings we can write a simple if statement to decide which preferences to use.

    Notice how in line 23 we do a check to decide the name of SharedPreferences to use. There's nothing wrong with doing such a check in 1 or 2 places however this type of logic will typically spread over dozens and more places in the various parts of the code base.

    The Null Object pattern to the rescue

    Instead of relying on null checks we can use a simple pattern described in detail by Martin Fowler. Here's how it would look like in our case:

    Now all places where we require an easily substitutable information about the user can be handled with plain old polymorphism.

    The above approach will work whenever we need a default value for the anonymous user - no so much when we need different behavior. It's tempting to embed various actions into UserReference interface implementations (AnonymousUserReference and RegularUserReference) however this will make the mentioned interface depend on UI concepts which I would like to avoid.

    When an app has more than one user type

    Before I show how to avoid putting too much weight onto UserReference interface, let's make our situation a bit more complicated. Let's assume that our app can be used by three types of users: anonymous, regular and premium. A very common approach is to use an enum to handle that i.e.:

    In fact because case supports default the above implementation works well as long as we have a small number of user types and there's little shared behavior.

    A slightly different approach is to hide the decision making and expose method(s) that accept different behaviors. The following code is an example of how we can approach encapsulating differences between user types in by explicitly declaring a behavior:

    Note that the above uses double dispatch but it could easily be replaced with a switch statement. Using separate class to encapsulate differences should make it easier to keep unnecessary logic out of Activity.

    A curious reader might notice that if we would like to change how we handle only one user type we're still forced to override all methods. There's a fairly simple way to improve the above though:

    Now we can implement custom actions as well as indicate a default. As usual whether to go with a simple if statement, a switch or a double dispatch depends on a use case. However it's useful to know the different ways of tackling the same problem.

    This article is cross-posted with my company blog

  • Maintaining current user information in Android

    30 June 2015 android

    Every but trivial android application needs to maintain information about current user - regardless if he has authenticated or not. While this may sound easy there are still at least handful of ways one can do it - in this article I'm going to explore couple of them.

    Keeping state in custom Application class

    This technique boils down to having custom application class like so:

    While the above is both easy to write and understand there are several problems with it. First and foremost if you would like to get some user property you'll need to reference MyApplication i.e.:

    Since data about current user will be used in several places spread through the code each of those places will now be coupled to MyApplication. This on the other hand will jeopardize any attempt to break the code base into modules. Furthermore this approach may encourage sharing other global application state through static variables defined on custom Application class. In short don't do this.

    Keeping global state in User class

    A slightly better idea is to move static variables from Application class into User class itself:

    Now our Application class has one less responsibility and we don't need smelly references spread around the codebase. We may also be able to split the project into modules - as long as we're not too inclined to separating concerns. Problems arise as soon as you start unit testing though. Remember that good unit test should be as isolated as possible. Using global state through static methods on User class forces us to properly setUp() and tearDown() its state in every test. It would be much easier if we could properly inject information about current user through tested component(s) constructor(s).

    I mentioned separation of concerns - does a user class have any reason to know whether a user has signed in? I don't think so.

    Separating concerns with User Session

    I find it helpful to think about objects lifetimes when designing components. In every application that allows users to sign in there will be a time where we don't have a user object to work with. To express that property I usually store the information about current user in a Session object. There is only one user session whenever an application is running. After user signs in the session is updated to represent it. After signing out it's usually a good idea to reset session state. Consider following example:

    Couple of things to note here. First and foremost the Session class is not public it's local to package responsible for maintaining it's state. Typically it's a package dealing with user registration, sign in and keeping remote services auth tokens fresh. Secondly Session public interface only covers methods defined in CurrentUserInfo exposing methods that come handy when getting current user name. The Session object is not limited to one interface. Quite opposite it may implement more interfaces depending on different clients (components requesting various details about current user) needs.

    Since Session embraces Interface Segregation Principle it's much easier to test code that requests information about current user i.e AppBeahvior. A reusable fake can be coded with no effort - it only has to implement very limited set of methods.

    Notice that I've not used static methods nor variables in above example. Instead I've simply marked the class with @Singleton annotation to ensure that there will only be single instance ever created, injected and used. I highly encourage using Dependency Injection frameworks (a.k.a IoC containers) with Dagger (and Dagger 2) taking the lead in Android space.

    In the next article I'm going to show a way to deal with application behavior changing depending on user being logged in or not.

    This article is cross-posted with my company blog