The memento design pattern in Kotlin

I started playing with the memento pattern for a use case I was researching when I realized that the Kotlin implementation had a, potentially, show stopper in comparison with the Java one:

I could not use a private property from within the same file

Why was that a show stopper? We’ll see, but first, what is the memento pattern?

Memento pattern

This pattern is a good way to implement a functionality that helps in restoring previous states. One good example is the undo in our text editors. You can write, edit, delete and then, by hitting undo, take each action back.

There are three main ingredients for this pattern:

  1. the originator that holds the current state and creates snapshots of itself,
  2. the memento that, in essence, is the snapshot with perhaps some additional metadata and
  3. the caretaker that orchestrates the backup/restore of the state

So in our example the originator is the editor which knows what the text is, the carets position etc, the memento a copy of those values and the caretaker can be the interface between the user and the editor.

Java implementation

Lets try to have an overly simplified version of the above example in Java:

public final class Editor {
private final List<String> text;
private int caretPosition;
public Editor() {
this.text = new ArrayList<>();
this.caretPosition = 0;
}
public void write(final String sentence) {
text.add(sentence);
caretPosition = calculateCaretPositionInEndOf(text);
}
public void edit(final int index, final String newSentence) {
text.remove(index);
text.add(index, newSentence);
final List<String> subText = text.subList(0, index + 1);
caretPosition = calculateCaretPositionInEndOf(subText);
}
public void delete(final int index) {
final List<String> subText = new ArrayList<>(text.subList(0, index));
text.remove(index);
caretPosition = calculateCaretPositionInEndOf(subText);
}
public void render(final Screen screen) {
final String allText = String.join("", text);
screen.render(allText);
screen.renderCaretAt(caretPosition);
}
public Memento backup() {
return new Memento(text, caretPosition);
}
public void restore(final Memento memento) {
text.clear();
text.addAll(memento.text);
caretPosition = memento.caretPosition;
}
private int calculateCaretPositionInEndOf(final List<String> lines) {
return lines.stream().mapToInt(String::length).sum() + 1;
}
public static final class Memento {
private final List<String> text;
private final int caretPosition;
public Memento(List<String> text, int caretPosition) {
this.text = new ArrayList<>(text);
this.caretPosition = caretPosition;
}
}
}

Here the editor, besides manipulating text, is able to produce snapshots of its state in a way that only itself can access the state’s values. The Memento class might be public, in order to allow the caretaker to handle instances of it, but its fields are private and only the originator can read them.
A great way to copy something while having the smallest possible API surface and maximum privacy.

As a matter of fact, here is the caretaker and its usage:

class UI(
private val screen: Screen
) {
private val editor = Editor()
private val backups = mutableListOf<Memento>()
fun write(text: String) {
backups.add(0, editor.backup())
editor.write(text)
editor.render(screen)
}
fun edit(index: Int, text: String) {
backups.add(0, editor.backup())
editor.edit(index, text)
editor.render(screen)
}
fun delete(index: Int) {
backups.add(0, editor.backup())
editor.delete(index)
editor.render(screen)
}
fun undo() {
val memento = backups.removeAt(0)
editor.restore(memento)
editor.render(screen)
}
}
fun main() {
val screen = StdoutScreen()
val ui = UI(screen)
with(ui) {
write("Hello, there! ")
write("How are you? ")
write("I hope you feel good 🙂")
edit(1, "Kotlin! ")
delete(1)
undo()
undo()
undo()
undo()
undo()
}
}
/* which produces this:
Hello, there! |
Hello, there! How are you? |
Hello, there! How are you? I hope you feel good :)|
Hello, there! Kotlin! |I hope you feel good 🙂
Hello, there! |I hope you feel good 🙂
Hello, there! Kotlin! |I hope you feel good 🙂
Hello, there! How are you? I hope you feel good :)|
Hello, there! How are you? |
Hello, there! |
|
/*

As you can see the UI uses the editor to write, edit, delete but before that it saves a backup with the editor’s state in order to restore it every time the user hits undo!

Kotlin implementation

So lets move originator and memento to Kotlin. Ctrl+Alt+Shift+K and boom.. we have a problem:

Kotlin, in contrast with Java, does not allow accessing private properties when in the same file.

What do we do? Well we can always make the properties public:

class Memento(text: List<String>, caretPosition: Int) {
val text: List<String>
val caretPosition: Int
init {
this.text = ArrayList(text)
this.caretPosition = caretPosition
}
}

but this way we, indirectly, expose the editors state:

Another way to implement the pattern is to have Memento as an interface with no state for the public API and have a private implementation of it for internal usage:

class Editor {
//
fun backup(): Memento {
return ActualMemento(text, caretPosition)
}
fun restore(memento: Memento) {
if (memento !is ActualMemento) return
text.clear()
text.addAll(memento.text)
caretPosition = memento.caretPosition
}
//
interface Memento
private class ActualMemento(text: List<String>, caretPosition: Int) : Memento {
val text: List<String>
val caretPosition: Int
init {
this.text = ArrayList(text)
this.caretPosition = caretPosition
}
}
}

this way we do not expose any state but we do open a bit our API. We now have an interface that can be implemented and given to the restore() function.

Inner classes

Fortunately Kotlin has inner classes. An inner class can access the outer class’s members but, most importantly, can be extended only from within the outer class. This means that this:

class Editor {
//
fun backup(): Memento {
return ActualMemento(text, caretPosition)
}
fun restore(memento: Memento) {
memento as ActualMemento
text.clear()
text.addAll(memento.text)
caretPosition = memento.caretPosition
}
//
open inner class Memento
private inner class ActualMemento(text: List<String>, caretPosition: Int) : Memento() {
val text: List<String>
val caretPosition: Int
init {
this.text = ArrayList(text)
this.caretPosition = caretPosition
}
}
}

checks all our boxes. We keep the originator’s state private and our overall API small!

A use case of using chain of responsibility pattern to scale strategy

Lets say we have a simple application that executes certain actions dictated by an external service.

More particular the external service sends a response that looks like this:

class Response(
val action: String,
val value: String
)

the supported actions are:

interface Action {
val name: String
fun execute(response: Response)
}
class Print : Action {
override val name: String = "print"
override fun execute(response: Response) {
println("printing ${response.value}")
}
}
class Log : Action {
override val name: String = "log"
override fun execute(response: Response) {
println("logging ${response.value}")
}
}
class WriteToFile : Action {
override val name: String = "write_to_file"
override fun execute(response: Response) {
println("writing to file ${response.value}")
}
}

and there is an executor to help as translate the response to an actual action execution:

class ActionExecutor {
private val allActions = mutableMapOf<String, Action>()
fun addAction(action: Action) {
allActions[action.name] = action
}
fun executeByResponse(response: Response) {
val action = allActions[response.action]
action?.execute(response)
}
}

This is an implementation of the Strategy Pattern where every strategy is a certain action allowing us to add as many actions as we want as long as there is a one-to-one relation with what the response sends:

fun main() {
val executor = createActionExecutor()
executor.executeByResponse(Response("print", "leonidas"))
executor.executeByResponse(Response("log", "kotlin"))
executor.executeByResponse(Response("write_to_file", "leonidas loves kotlin"))
}
private fun createActionExecutor(): ActionExecutor {
return ActionExecutor().apply {
addAction(Print())
addAction(Log())
addAction(WriteToFile())
}
}

The problem

One day the external service decides to add a print error action but it does not do it by having a new action value. Instead it decides to have an is error flag which must be taken under consideration when the action value is print!

So the response is now this:

class Response(
val action: String,
val value: String,
val isError: Boolean = false
)

leading us into having an if in the print action’s code

class Print : Action {
override val name: String = "print"
override fun execute(response: Response) {
if (response.isError) {
System.err.println("printing (in error stream) ${response.value}")
return
}
println("printing ${response.value}")
}
}

which defeats the purpose of the strategy pattern and violates the SRP. Each strategy should do one thing and one thing only. By having an if in the strategy we allow it to implement two actions thus having two reasons to change.

Adding a chain

What we need is a way to allow the representation of a single action value from multiple strategies where each one implements a unique action depending on the values of the response.

This is where the Chain of Responsibility Pattern comes in helping as into having multiple actions tied together, passing the response to each other until one of them can execute it.

There are two ways to implement the pattern depending on the size and state of your project.

Using inheritance

If you have a small project with just a few actions and you don’t mind touching many files you can use inheritance and have each action containing the next in the chain:

abstract class BaseAction(
private val nextAction: Action?
) : Action {
override fun execute(response: Response) {
nextAction?.execute(response)
}
}
class Print : Action {
override val name: String = "print"
override fun execute(response: Response) {
println("printing ${response.value}")
}
}
class PrintInErrorStream(
nextAction: Action?
) : BaseAction(nextAction) {
override val name: String = "print"
override fun execute(response: Response) {
if (response.isError) {
System.err.println("printing (in error stream) ${response.value}")
return
}
super.execute(response)
}
}

which can be used as such:

fun main() {
val executor = createActionExecutor()
executor.executeByResponse(Response("print", "leonidas"))
executor.executeByResponse(Response("log", "kotlin"))
executor.executeByResponse(Response("write_to_file", "leonidas loves kotlin"))
executor.executeByResponse(Response("print", "$&#$@#", isError = true))
}
private fun createActionExecutor(): ActionExecutor {
return ActionExecutor().apply {
addAction(PrintInErrorStream(Print())) // first try to print in error and the in simple
addAction(Log())
addAction(WriteToFile())
}
}
Using composition

If we do not wish to change any of the existing actions then composition is the only way.

What we need is a way to wrap an existing action in an object that will (a) hold the next action in the chain and (b) decide which action will be executed, the wrapped or the next one:

class ChainAction(
private val action: Action,
private val canExecute: (Response) -> Boolean
) : Action {
private var nextAction: Action? = null
override val name: String = action.name
override fun execute(response: Response) {
if (canExecute(response)) {
action.execute(response)
return
}
nextAction?.execute(response)
}
fun or(action: ChainAction): ChainAction {
nextAction = action
return this
}
}
fun Action.asChain(canExecute: (Response) -> Boolean): ChainAction =
ChainAction(this, canExecute)
view raw chain_action.kt hosted with ❤ by GitHub

Using ChainAction results in this:

fun main() {
val executor = createActionExecutor()
executor.executeByResponse(Response("print", "leonidas"))
executor.executeByResponse(Response("log", "kotlin"))
executor.executeByResponse(Response("write_to_file", "leonidas loves kotlin"))
executor.executeByResponse(Response("print", "$&#$@#", isError = true))
}
private fun createActionExecutor(): ActionExecutor {
val printInErrorStream = PrintInErrorStream().asChain { response -> response.isError }
val justPrint = Print().asChain { true }
return ActionExecutor().apply {
addAction(printInErrorStream.or(justPrint))
addAction(Log())
addAction(WriteToFile())
}
}

This way we can scale the strategy pattern both vertically, one strategy per action value, and horizontally, one strategy per action value sub cases.

Null object pattern and sealed classes

In a recent code review one of my colleagues was concerned that part of the code I wrote might cause us problems because of the null object pattern I chose to use.

The code was something like this:

class Task(
val description: String,
val assignedTo: AssignedTo
)
sealed class AssignedTo {
object Nobody : AssignedTo()
class User(val name: String) : AssignedTo()
}
fun main() {
val buyMilk = Task("Buy milk", AssignedTo.Nobody)
val writePost = Task("Write post", AssignedTo.User("le0nidas"))
print(buyMilk, writePost)
}
private fun print(vararg tasks: Task) {
tasks.forEach { task ->
val user = when(task.assignedTo) {
AssignedTo.Nobody -> "nobody"
is AssignedTo.User -> task.assignedTo.name
}
println("Task '${task.description}' is assigned to $user")
}
}

and my colleague was referring to the Nobody usage.

That got me thinking. Can this usage of sealed classes be considered as an implementation of the null object pattern? Also, why is the usage of this design pattern a bad thing?

Null object pattern (wikipedia)

So, what is this pattern? This pattern is one way to solve the

we don’t want a method to return a null value and force ourselves to check it before usage

my definition 😛

Ok, it might be better to have an example:

Lets say that we have a service that returns the workout we did in a particular date. Each workout has the duration of the exercise and if we did not workout on the given date the service returns null (we’ll pretend for a moment that Kotlin does not have null safety or those great extensions like map, sum etc):

abstract class Workout(val duration: Duration)
class Walking(duration: Duration) : Workout(duration)
class Swimming(duration: Duration) : Workout(duration)
class Running(duration: Duration) : Workout(duration)
fun workoutService(date: LocalDate): Workout? {
val workouts = mapOf(
LocalDate.of(2020, 4, 25) to Walking(Duration.ofHours(2)),
LocalDate.of(2020, 4, 23) to Swimming(Duration.ofHours(1)),
LocalDate.of(2020, 4, 22) to Running(Duration.ofMinutes(30))
)
return workouts[date]
}
fun main() {
val days = listOf(
LocalDate.of(2020, 4, 22), LocalDate.of(2020, 4, 23), LocalDate.of(2020, 4, 24), LocalDate.of(2020, 4, 25)
)
var sum: Long = 0
for(day in days) {
val workout = workoutService(day)
if (workout == null) {
continue
}
sum = sum + workout.duration.toMillis()
}
println("Total duration: ${Duration.ofMillis(sum)}") // Total duration: PT3H30M
}

By introducing a null object, for those days that we did not workout, we can remove the null checks and have a more readable code:

abstract class Workout(val duration: Duration)
class Walking(duration: Duration) : Workout(duration)
class Swimming(duration: Duration) : Workout(duration)
class Running(duration: Duration) : Workout(duration)
// null object:
object NoWorkout : Workout(Duration.ZERO)
fun workoutService(date: LocalDate): Workout? {
val workouts = mapOf(
LocalDate.of(2020, 4, 25) to Walking(Duration.ofHours(2)),
LocalDate.of(2020, 4, 23) to Swimming(Duration.ofHours(1)),
LocalDate.of(2020, 4, 22) to Running(Duration.ofMinutes(30))
)
return workouts[date] ?: NoWorkout // usage of null object
}
fun main() {
val days = listOf(
LocalDate.of(2020, 4, 22), LocalDate.of(2020, 4, 23), LocalDate.of(2020, 4, 24), LocalDate.of(2020, 4, 25)
)
var sum: Long = 0
for(day in days) {
val workout = workoutService(day)
sum = sum + workout!!.duration.toMillis() // yes, we are that!! sure
}
println("Total duration: ${Duration.ofMillis(sum)}") // Total duration: PT3H30M
}

Why is this a bad design?

From the example we could easily conclude that this pattern is quite helpful. Right?

Well, as everything in our industry: it depends! When we need a way to have some default values so that our calculations won’t crash and burn then it is a good choice. But if we use it in ways that we hide things we might end up in false successes.

For example, lets assume that we have a storage interface and a factory function that returns the proper storage implementation depending on a given value:

interface Storage {
fun save(workout: Workout)
}
class LocalStorage : Storage {
override fun save(workout: Workout) {
// it saves in our database
}
}
class CloudStorage : Storage {
override fun save(workout: Workout) {
// it saves in someone else's database
}
}
object NullStorage : Storage {
override fun save(workout: Workout) {
// it does nothing
}
}
fun getStorage(type: String): Storage {
return when (type) {
"local" -> LocalStorage()
"cloud " -> CloudStorage()
else -> NullStorage
}
}

If something is not configured well we might end up using, through out our entire project, the NullStoragethinking that we have saved everything when in reality we lost our data!

In case you missed it there is a space in the cloud-type so no matter how many times we ask for the “cloud”-storage we will get the null-storage back. Silly example with a silly mistake but imagine what could go wrong in real projects!

So, back to the code that started all this

First thing is first:

Q: Is this usage of sealed classes an implementation of the null object pattern?

A: No. The Nobody object is just a representation of a valid state for the AssignedTo concept and does not provide any default values or hides any method usage.

Q: Can sealed classes be used for implementing the null object pattern?

A: Yes. Sealed classes can help us in having many values for one concept but the fact that we can use full fledged classes, that can also inherit a bunch of things, is quite powerful and can be easily misused. I don’t see anything stopping us from implementing the storage-example using sealed classes so we just need to think things carefully.

And now the twist:

As is, the code does not implement the design pattern but with a small change we can make it not only to implement it but to do it badly too! We’ll just move the name property to the parent and have Nobody provide an empty value:

class Task(
val description: String,
val assignedTo: AssignedTo
)
sealed class AssignedTo(val name: String) {
object Nobody : AssignedTo("")
class User(name: String) : AssignedTo(name)
}
fun main() {
val buyMilk = Task("Buy milk", AssignedTo.Nobody)
val writePost = Task("Write post", AssignedTo.User("le0nidas"))
print(buyMilk, writePost)
// Task 'Buy milk' is assigned to
// Task 'Write post' is assigned to le0nidas
}
private fun print(vararg tasks: Task) {
tasks.forEach { task ->
println("Task '${task.description}' is assigned to ${task.assignedTo.name}")
}
}

Q: Why is this bad? It does not hide anything, it provides a default value and to be honest we just need to pass “nobody”, instead of an empty string, to the super constructor.

A: Well, this time it depends on where we use the pattern and not how. If this code is part of our core layer then we are allowing this layer to decide on presentation issues! It should be the presentation layer that will check what value the assignedTo has and print “nobody”!

Our previous implementation of AssignedTo was forcing us to make the distinction between all of its values so we did not have much of a choice but to let the print function decide.

In conclusion

Think twice before using the null object pattern and, if you are in a team, try to put code reviews as part of your work flow. It is always good to have a fresh pair of eyes look at your code and even better to have a few people to discuss (and argue) about your choices.

Trying to explain something will make you understand it better!