I am currently working on a collection implementation in JavaScript. I need a mutable and an immutable version of that. So what I thought of first was something like:
- Collection
- MutableCollection extends Collection
- ImmutableCollection extends Collection.
My main issue with this is that if I want to implement more specific collections like List or Set, they could still inherit from Collection while their Mutable/Immutable implementations could not inherit from MutableCollection / ImmutableCollection.
So this made me think whether having all three, Collection, MutableCollection and ImmutableCollection would actually bring any significant benefit.
An alternative approach which came to me would be to only have Collection and then have a Collection.prototype.makeImmutable or freeze there. I would then also introduce a Collection.requireMutableInstance( collectionInstance ) which can be used in functions explicitly requiring a mutable collection.
Here are my main concerns about putting everything into just Collection:
- The prototype definition is getting much bigger compared to defineing a MutableCollection prototype as well which would then hold the code of all the operations for alteration. I guess I could solve this by just defining a second file anyhow which would then just extend the basic Collection definition with those additional operations and the makeImmutable operation.
- Documentation of those function signatures that actually care about mutable vs. immutable and not just require the basic collection would look less pretty.
Take:
/**
* @param {MutableCollection} collection
/*
function messAroundWithSomeCollection( collection ) { /* ... */ }
vs.
/**
* @param {Collection} collection A collection not yet made immutable.
/*
function messAroundWithSomeCollection( collection ) { /* ... */ }
What would be the more natural way of doing this in JavaScript? Especially without having interfaces I can check against and considering the flatter chains of inheritance if I would also implement a Set and Map collection, the everything-in-one approach seems more intuitive to me.
...in most cases, code should not really care about whether a given collection is mutable or not.
: while ideally true, the semantics of dealing with immutable vs. mutable objects/collections can vary greatly, so I don't suspect you could get away with that assertion.