$ReadOnlyArray
instead of Array
JS-0487It is recommended to use $ReadOnlyArray
instead of an Array or the array shorthand notation. $ReadOnlyArray
is an immutable array collection type and the superclass of array and tuple types in Flow.
General reasons for using immutable data structures:
Calculator
with two properties a
, and b
along with two methods, i.e., add()
returns addition of a
and b
and setInputs(a,b)
set the values of a
and b
. The class constructor does not require to pass the two numbers as arguments, and then we have to call the setInputs
first before calling the add
otherwise, it would throw an error as inputs are empty. Here setInputs()
and add()
are coupled together with temporal coupling and have to be invoked in this exact order to avoid runtime errors.Set
or some other complex data structures. If we change the key or value of the underlining object, it may cause an error or create difficulty resolving the derived data's values. So this is avoided using immutable objects. They always have failure atomicity. There are possibilities that some data inside the object
/array
while changing or adding later can lead to some error (runtime mostly), leading to a broken state. So immutability prevents this as the data can't be mutated or changed.Note : Initialization of a variable with an empty array is considered valid (e.g., const values: Array<string> = [];
). This behavior resembles the behavior of Flow's unsealed objects, as it is assumed that an empty array is intended to be mutated.
type X = Array<string> // sometimes empty arrays are preffered over null example some library methods might need Array type alone
type X = string[]
const values: Array<Array<string>> = [];
let values: Array<Array<string>>;
type X = $ReadOnlyArray<string> // sometimes empty arrays are preffered over null example some library methods might need Array type alone
const values: Array<$ReadOnlyArray<string>> = [];
const values: $ReadOnlyArray<string>[] = [];
const values: Array<$ReadOnlyArray<string>> = new Array();
const values: Array<$ReadOnlyArray<string>> = Array();