mvc pattern

MVC stands for Model-View-Controller, a pattern widely used in web application development.
First, lets take a look at the three parts:



For each part of your application you use a different controller. It executes a different set of instructions based on the request, manages the models, and constructs the view.

Typically, after a request is made, following steps are undertaken by the controller:

  • check if the request is valid, else return an error message
  • update data if the request wishes to do so
  • retrieve all data needed in the view
  • construct a view object, and let it render the view


a model is an object which stores data, and most of the time represents an object from the real world which is managed by the application. It is the primary form of communication between your views and your controllers.


the view is responsible for displaying information received from the controller such as models.

Why use this pattern?

This pattern allows a loose coupling between Application Logic and View Logic. This has some numerous advantages:

  • extensibility & maintainability
  • if you have to redesign the application, you would not need to rewrite already working application logic, you only have to replace the view, and vice versa
  • easy for other developers to understand what you were doing

I’ve made an example in php: github

I explain this example in detail here

repository pattern

This pattern is an application of the separation of concerns principle. It basically separates the consumer from the supplier of data.

For the consumer of an RSS feed it is irrelevant if the feed is read out from the storage, or downloaded from the internet. This is where the Repository Pattern jumps into action; it provides a simple API for the consumer, and takes care of resolving the data from the best source available.

A small example (c#):

internal class RssRepository
    public List<RssItem> GetRssItems()
        if (DeviceHelper.HasInternet)
            return RssHelper.DownloadFeedItems();
            return StorageHelper.RetrieveCachedFeedItems();


Keep It Simple, Stupid!
Do not write complex code.

Simplify your code by following principles as DRYseparation of concerns and single responsibility principle. Everyone who takes a look at your code should be able to understand what it does as fast as possible. If one of your methods is very long (30 lines and up), or needs comments to be easy human readable you are probably writing overcomplicated code. Try to further split up your logic, divide it into smaller, easier bits of code.

Some signs your method may be overcomplicated:

  • you cannot name it in a way so you do not need additional comments to explain its functionality
  • it is longer than 30 lines
  • it is split up into various parts which all deal with a different part of the problem (read out file, process its contents, append lines, save it again)
  • you need comments to explain its functionality

Of course, if you need to implement an encryption or a compression algorithm, the code for this specific task may be rather complex. Still, for any other part of your application KISS is applicable.


Don’t Repeat Yourself
Write each line of code only once.

If somewhere in your application you feel like you have written very similar code before, or worse, are copy-pasting code from somewhere else, you are probably doing something wrong. Duplicated code makes it hard for other developers and you to extract the really relevant instructions, and debugging a living hell (as you correct a mistake in copy-pasted code, you will have to do the same thing at all other places where you have used that code).

You can omit duplicated code by abstraction; write your code in a way that it works for all inputs. Use interfaces and common parent classes to execute tasks on similar objects: bad vs good (see method public double CalculateAreas())

If you can’t reduce the problem by implementing interfaces or inheriting from common parents, you can take it a step further and try reflection: Reflection allows you to determine at runtime what properties and what methods you want to call from an object. As this topic is rather complex, and differs a lot from language to language, it is probably best if you look up for yourself how it is implemented in the language of your choice.


separation of concerns

Separation of Concerns is like the Single Responsibility Principle, but in a larger context. You basically split different parts of your application into different parts in your code. If you build a RSS reader you can divide you code into the following sections:

  • download the RSS feed from a URL
  • parse the feed, and extract the relevant data
  • display the feed to the user

This has following advantages:

  • extensibility & maintainability
  • multiple developers can work at the same project at the same time, each one has its own clear defined task
  • you may be able to reuse large parts of your code for other projects, for example the download part in a weather application

This is maybe one of the most important principles there is, and probably every developer uses this to some degree instinctively, even without knowing its fancy name. The better you divide your logic, the easier development is.

single responsibility principle

This principle is quite simple: a class should have one, and only one purpose in your application. Use a Person object only to store data about a person (name, age, address..) but you may not use it to format how the date is displayed. Use a DownloadHelper to download a file but not to process its content.

Why is this desirable?

  • extensibility & maintainability
  • It avoids code duplication
  • It forces the developer to break down his application into smaller, easier manageable parts

As an example, if you as a developer new to a large project have the task to change the formatting of the date, you would not need to know which objects display dates, you only have to find and adapt a class with a name similar to FormatHelper or DateTimeFormater.

digital state

I don’t want to type in my address at each new onlineshop I want to order something from. I don’t want to remember which companies have which kind of information about me. I don’t want to contact ten different services when I’ve changed my home address. I don’t want to keep five different cards in my purse and install multiple apps on my smartphone to use for authentication. I think its time to unify personal data and its authentication (“who sees what”) into one central system.

Now, how can you combine credit cards, identification cards, online logins etc into one system, while keeping the user in control of who, when and how his data is used? Here’s my idea how:

Each participant of this system receives a private key, a public key and access to an administration webpage. There is an api which gives access to the data managed by this system to authorized services.

the administration webpage

A webpage which gives the user control over the api. It visualizes requests to the api (which service called when, and received which information), and all active Authentications. The user is able to create new Authentications, and invalidate existing ones.

On this webpage, the user will manage all his personal data. His data will be split into various parts; one may be the home address, other work infos, payment information… If the user edits his data, he can choose if he wants to notify the services with access to this data.

Other connected services can provide additional personal data (which can also be shared over this api of course): The service called “police” provides access to criminal records, or “health services” provides access to the allergies the users has.

The user can select for each Authentication to which parts of the api he will grant access to.

the api

The api contains all information about a member of this system.

/authenticate: the first request every service has to do as soon as registering a new user. It will have to provide details about the service itself, an url to be called by the api for event callbacks (those are invoked if personal data of the user is changed the service has access to), the users private key, and the users password. It will receive an Authentication Hash for future requests, the public key of the user, information which parts of the api it will have access too, and for how long the Authentication will be valid.

/info: all following request go to this url. The calling service needs a valid Authentication, and specification which data it would like to receive. The response will contain all data requested, if the Authentication permits access to it of course.

/valid: This node is called with a public key, and simply return a boolean if it is still valid or not.

the keys

The two keys are not related to one another, and not resolvable from one another.

They could be supplied in form of a credit card, or an application on your smart phone, it does not really matter. It should be removable from the carrier, so nothing terrifying like tattooed barcodes or implemented chips. If the user chooses to do so, he should be able to leave the public key at home. The private is only needed for the authentication of new services, and should be kept out somewhere inaccessible to others.

If the public or the private key is lost, the user has to contact an authority as soon as possible, which invalidates the old key, and sends a new one. If its the public key, all services with access to user data will receive an event callback over the specified URL. If its the private key, it does not really matter, as this one is only used whilst authenticating new services.

the authentication of a new service

If you need your personal information, for example when registering at a onlineshop, or opening a banking account, you perform following steps:

  • go to the administration webpage
  • create a new Authentication
  • choose the information this new Authentication has access to
  • choose the time span this Authentication is valid
  • confirm the creation

The administration webpage will provide you with a unique password for this newly created Authentication.

You provide the new service with this new password and your private key. Now the service can authenticate itself against the api. It can do this multiple times, each time it does it, it will receive a different Authentication hash. But as soon as the first request with one of those hashes to /info is made, the password will be invalidated, and the used Authentication hash is the only one remaining valid. The new service is now authenticated and has access to the api!

advantages of this approach

You will only have to carry around the public key with you, and all companies, bank or public transportation service, know who you are. All other cards will become obsolete.

The possibilities for the api are limitless; as all data is gathered at one place, you may combine information about a user never possible before. Some examples:

  • Banks can expose asset information to be consumed by the tax administration
  • Users can share their medication & disease records to be consumed by research to find correlations
  • If users change important data like their address, all services will be automatically contacted

dangers of this approach and how to avoid them

As you have only one public key to authenticate yourself, if someone has access to the system and is able to invalidate your card you lose all access to all your services. Therefore, the system must be an independent authority.

If someone unauthorized gets access to the administration webpage, it could end pretty badly for the rightful user. This can be prevented by choosing a save way to authenticate the user, and take all steps necessary to develop a well-tested, high quality implementation without security holes. As the concept is not overly complicated, this should be possible. Also, to authenticate a new service, one does always need the private key.

async await

async-await is a very important concept from C#. It allows you to execute code in another thread than from the calling one; this results in a responsive UI even while  long background tasks are running.

Some examples:

/* ## Example 1 ## */
public async Task<bool> Execute()
    //long running CPU bound operation
    await Task.Run(() => {
    for (int i = 0; i != 10000000; ++i)

    //long running I/O Operation
    using (var client = new HttpClient())
        await client.GetStringAsync(url);
    return true;

//call this method
var response = await Execute();

/* ## Example 2 ## */
//remove the async-await if not needed, and return directly the Task.
public Task<string> Execute2()
    //long running I/O Operation
    using (var client = new HttpClient())
        return client.GetStringAsync(url);

//call this method
var response = await Execute2();

/* ## Example 3 ## */
//add the async keyword to event handlers to use them asynchronusly
public async void OnTapped()
    //long running I/O Operation
    using (var client = new HttpClient())
        await client.GetStringAsync(url);

From my own experiences, the simpler the expressions, the better. If it looks wrong or overcomplicated to you, it probably is. I recommend to take a look at Stephen Cleary’s Blog (specifically at async-await) for extensive information and tutorials about async-await.

inversion of control

A very handy pattern for large projects. Think of it as an enhancement from the dependency injection pattern.

When using dependency injection, the caller of a class provides the implementations of the requirements.
This gets cumbersome with classes which have a lot of requirements, and large code bases where you may not even know where the implementation is, or how it is called.

Inversion Of Control to the rescue: With this pattern, the framework provides the implementations.

As the implementation is a bit more complex, I’ll only explain the concept:

  • Create a helper, which can construct classes with requirements (non-empty contructor with interfaces)
  • Register the implementations you want to use against the helper at a central place in your code
  • Retrieve all classes which have requirements over this helper

An Example in pseudo-php code:

class IoCContainer extends Singleton
    private $registeredInterfaces = array();
    public function register($interface, $implementation)
        $this->registeredInterfaces[$interface] = $implementation;

    public function construct($object)
        $arguments = get_needed_arguments($object);
        //match each argument with an implementation, and construct the object
        return $instance;

now at the start of your application you register the implementations:

IoCContainer::getInstance()->register("IProgress",new ProgressService());
class Workflow
    public function __construct(IProgress $progressService) { }

    public function doStuff() { }

Now, you do not want to write an IoCContainer yourself. Not because it is hard, but because it has been made before, and tested before. For C# I can recommend the SimpleIoC Container from the MVVMLight Package: MVVM Light (you can get it over NuGet). There are similar implementations for most other languages.

dependecy injection

This is one of my favorite patterns out there! Use this if you have a large codebase or multiple consumers of a library.

Use case: You have some code, and multiple Consumers (Webpage, Phone Application & Desktop Application) which want to use the contained Logic (so you do not copy paste the same code three times). Now you want to show progress for a long running operation in the DownloadLargeFileWorkflow. What to do:

  • You create a IProgress interface
  • Each of your Consumers implements this interface
  • You pass the instance which implements this interface to the shared code.

Ready! Now you can use the same code for all three very different consumers.

Now how to implement this?

public interface IProgress
    void ShowProgress();
    void HideProgress();

public class DownloadLargeFileWorkflow
    private IProgress _progress;
    pulic DownloadLargeFileWorkflow(IProgress progress)
        _progress = progress;

    public void Execute()
        //do long running operation

In your consumer specific code you can now construct the DownloadLargeFileWorkflow with your specific implementation of the IProgress interface.