Immutable Models in MVVM

Source: flickr/ Jeff Attaway


The first M stands for Model – an implementation of the application’s domain model that includes a data model along with business and validation logic. Examples of model objects include repositories, business objects, data transfer objects (DTOs), Plain Old CLR Objects (POCOs), and generated entity and proxy objects.

definition source


In object-oriented and functional programming, an immutable object(unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

definition source

Why bother?

Imagine the next simple situation, your application downloads a JSON, deserialises it to an object and then presents the downloaded data. You would expect the downloaded data to be one-to-one to the data on the remote server, however the data can be accidentally or intentionally mutated.

Here is an example of a mutable Model:

public class MyMutableObject
public long Id { get; set; }
public string Title { get; set; }
public List<string> Contents { get; set; }

All the properties has public setters which means that any of those can be changed after the object creation. Even if we make all the setters private, it could be still possible to manipulate data within the List.

Here is an example of immutable Model:

public sealed class MyImmutableObject
public long Id { get; }
public string Title { get; }
public IReadOnlyCollection<string> Contents { get; }

public MyImmutableObject(
long id,
string title,
IReadOnlyCollection<string> contents)
Id = id;

Report Story

Leave Your Comment