okaryo.log

Creating Immutable Lists in Dart | okaryo.log

Creating Immutable Lists in Dart

    #Dart

This post contains affiliated links.

Introduction

Recently, I have been reading Mino Driven’s book 『良いコード/悪いコードで学ぶ設計入門』.

In the chapter about first-class collections, it was mentioned that it is a good idea to make array-type instance variables immutable when exposing them to the outside.

Although I have been using first-class collections, I realized that I have been exposing them as mutable, and I wondered how to do this in Dart.

How to Create Imuutable Lists

You can use the List.unmodifiable factory to make a list immutable.

class Books {
  final List<Book> _values;
  
  const Books(this._values);
  
  List<Book> get values => List.unmodifiable(_values);
}

final books = Books([Book('title')]);
books.values.add(Book('error'));
// -> Uncaught Error: Unsupported operation: add

There is also a similar class called UnmodifiableListView.

While List.unmodifiable creates a shallow copy of the input list, UnmodifiableListView keeps the original list.

For more on the topic of immutability in Dart, including lists, I recommend reading mono’s article Practical Handling of Immutable in Flutter/Dart(translated title).

Conclusion

I prefer to use immutable programming in my day-to-day development, as it improves code readability.

However, as both Mino Driven and mono point out, care must be taken when high performance is required or resources are limited.

There may not be a silver bullet, but there should always be a better way. I want to keep thinking about how to write better code.


Related Posts
Related Posts
Promotion

This site uses Google Analytics.