Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object is Immutable?

Tags:

immutable.js

Immutable object can be an instance of:

  • Immutable.List
  • Immutable.Map
  • Immutable.OrderedMap
  • Immutable.Set
  • Immutable.OrderedSet
  • Immutable.Stack
like image 929
Gajus Avatar asked Aug 09 '15 18:08

Gajus


People also ask

How do you check if something is immutable in Python?

There are no general tests for immutability. An object is immutable only if none of its methods can mutate the underlying data. the answer says: 1) Keys must not be mutable, unless you have a user-defined class that is hashable but also mutable.

How do you know if a class is immutable?

It's properly constructed ( this reference doesn't leak from constructor) Object state cannot be modified (so class should not have setters and mutator methods) Don't store external (passed to constructor) references to mutable objects (e.g. create defensive copy of passed collection argument)

Is an object immutable?

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications.

Is object immutable in Java?

Immutable class in java means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. We can create our own immutable class as well.


2 Answers

There is an open ticket to improve the API which is on the roadmap for 4.0. Until this is implemented, I suggest you use Immutable.Iterable.isIterable() (docs).

Using instanceof is not reliable (e. g. returns false when different modules use different copies of Immutable.js)

like image 143
mbh Avatar answered Oct 07 '22 23:10

mbh


I have learned that using instanceof to determine wether object is Immutable is unsafe:

Module A:

var Immutable = require('immutable');
module.exports = Immutable.Map({foo: "bar});

Module B:

var Immutable = require('immutable');
var moduleA = require('moduleA');
moduleA instanceof Immutable.Map // will return false

Immutable.js API defines the following methods to check if object is an instance of Immutable:

  • Map.isMap()
  • List.isList()
  • Stack.isStack()
  • OrderedMap.isOrderedMap()
  • Set.isSet()
  • OrderedSet.isOrderedSet()

and

  • Iterable.isIterable()

The latter checks if:

True if an Iterable, or any of its subclasses.

List, Stack, Map, OrderedMap, Set and OrderedSet are all subclasses of Iterable.

like image 45
Gajus Avatar answered Oct 07 '22 22:10

Gajus