Mobile event viewer: basic architecture and retrieving events

This is the first post of a series of tutorials for creating an event viewer for iOS and Android. In this post, we’ll examine the high-level application architecture. The project is located at https://github.com/gergelykoncz/Events.iOS.

The objective of the app is to display events in a view similar to the built-in daily calendar view. Since there are no public APIs for this neither on iOS nor on Android, we’ll roll out our own solutions, but first let’s plan the application.

We’ll work with only one entity (for now), which I decided to call Event. The event class looks like this:

As you can see, it has an identifier, a start and end date, a summary, a description, and a flag indicating if it’s an all day event. Nothing particularly difficult.

Events will come from a web service in JSON format, but it’s an implementation detail. I don’t really care where they come from at this point, but I’ve a firm belief that every class should do one and only one thing (the Single Responsibility Principle), so there should be a class that I can call and it gives me back some events. This is in fact an already named pattern, called Repository. Thus I created a class named EventRepository, which will serve my events whatever way it finds best.

Note: I don’t want to get too enterprisey at this point, but if we’d have more sources for our events, then we could create some more repositories (one for each source, with a common interface/base class), and use a Facade as a coordinator class which would delegate the event retrieval for based on whatever logic we find best.

So let’s review this EventRepository. As I stated before, the events come from a web service, in JSON format. Since it uses the network and this can (and will) introduce so much delay that our app would be very unresponsive if we would want to wait until data is loaded (if it’ll be loaded at all). That’s why I use NSURLConnection in an asynchronous fashion. When someone calls EventRepository to load the dates, it builds an NSURLConnection, set its delegate to itself and fires the request. After this the main thread is free to do whatever meaningful work instead of waiting for the request to complete.

There are two common cases at this point: the request fails, or it succeeds. In both cases we should notify the caller, but first let’s see the cases in detail.

If the request succeeds, we parse the result as JSON, using the NSJSONSerialization class. Since our API returns an array of events, we iterate over each JSON object in the array, and create an instance of Event using a different class, EventMapper. As its name suggests, EventMapper is a mapper. You can find this concept under many names (here is a discussion on the topic, and here’s a recent post of mine regarding mappers), the gist of it is that it is a class that it builds entities based on some input.

After we have our collection of events, we simply notify the caller through a delegate. If anything goes wrong, we use the same delegate as well. There are multiple ways of doing this, we could have used the NSNotificationCenter, but the Cocoa framework uses the Delegation pattern more extensively, and I got very used to it. The concept is exactly the same as with EventRepository and NSURLConnection. EventRepository simply delegates the task of retrieving events to NSURLConnection, and provides a way (in this case, a reference) to NSURLConnection to notify it when it’s done.

EventRepository offers this thing in its loadEventsForDate method. It accepts a date, naturally, and a delegate object which it’ll notify if it has a result (or any error occurs in the process).

Here’s the protocol (EventsDelegate) that is being used:

And we’re almost done! There’s a final piece without our work does nothing: we need a ViewController. And our ViewController has to implement the EventsDelegate so that it can be notified by EventRepository. The example class EventListViewController is for demonstration purposes only. It won’t render our shiny events in the promised daily calendar view format (that is the topic of an upcoming post), rather it uses a mere UITableView. Here is the source:

As you can see, by using the right patterns and careful delegation, we ended up with a short and maintainable view controller. In fact, less than ten lines (blanks included) are responsible for loading events and  reporting errors. Most of the class deals with the UITableView delegates.

I hope that I managed to emphasize how clean your design can become when you use the appropriate patterns and concepts. I think that by creating smaller classes with only truly one goal you can end up with a more maintainable (and thus, cost-effective) codebase. Of course there are some vital functions missing here, like error handling and logging, but I tried to make the examples more concise.

But don’t forget that the point of this is not the admiration of patterns and best practices, but to make an app that works. I’ll follow up this post (and the GitHub project) when I implemented the view I promised.

Advertisements

Tutorial: creating a mobile event viewer

Before I moved to the Czech Republic I did some freelancing. One of my project was an event viewer for iOS and Android. It was like the daily view of the respective system’s calendar with data from web services in its own application. Now the work was done but the customer vanished, so I ended up with these two applications. I thought they would be worth sharing and I intend to create a set of blog posts as a tutorial for them. However, I can’t just push them to GitHub, there are lots of client-specific stuff in it, and tons of anonymization need to be done.

Long story short, I decided to rewrite the whole stuff to avoid any leakage. The iOS version can be found at https://github.com/gergelykoncz/Events.iOS. It’s just a stub yet, but I plan to evolve it with and adding further posts. The first is coming soon.

DTOs and Mappers

Today I’ll post about a practice of which I’m a big fan, namely DTOs (or view models, if you wish) and mappers.

DTO stands for Data Transfer Object, and its sole responsibility is to transfer data between layers. A view model is essentially the same thing, it’s a mostly primitive object to show data to the user and gather information from her/him, tightly coupled to a single view. And a mapper is what does the translation between your entities and your DTOs.

One could question the point of adding yet another layer to an application. It’s true, you can live without another mini-model living in your views and the added complexity of mapping everything back and forth. But allowing entities to reach the user interface layer is not the best idea ever. Let me show an example.

I’ve deliberately created a crappy design here, but crappy design isn’t that uncommon, and using code-generators (e.g. an ORM which is capable to create entities from a database) you won’t even know this happened. So it’s our everyday User and Product entities, except a little twist: Password is stored as plain text (very uncommon, you’d say) and someone, someday for some unknown business reason has added a column to the Product table called LastBuyer, and made a foreign key relationship with the User table. Entity Framework would generate something like this:

It isn’t tragic yet, but under the right circumstances it’s a receipt for disaster. Imagine that you’d like to create a nice REST API for your system to work on mobile devices. Just create a new ASP.NET MVC Web API project and add a service for handling Product entities. If you change nothing (use the default serializer) then you’ll end up publishing some of your unlucky users’ usernames and passwords (and a lot of related information) in this nice format:

As you see, only two things were needed: crappy design and ignorance – both can be found in the wild. Now how can we prevent such situations?

The basic principle is to never, ever send your entities to the end user. One technic to deal with this is to employ DTOs. In our case, we would use a lightweight class called ProductDTO. If we’d really like to follow our business model, we can create something like this:

There’s no chance for the password to slip through this, and we only show what is really needed, and nothing else. Of course the above example of leaking the user’s password is rather serious and grave, and issues like this are hopefully really rare. I did it just to illustrate my point.

Now my beloved part, the mappers. Here’s a fairly simple implementation:

You see it’s super easy, adheres to the Single Responsibility Principle, testable and all that stuff. And even better, for simple cases like this, you can auto-generate all your mappers with e.g. AutoMapper.

And with a simple LINQ query you can create something as elegant as this:

As they are really easy to implement, you could even auto-generate the tedious work of creating mappers there’s really no reason not to employ this pattern. To be more accurate: there’s no reason to present business entities to your end users.