When you design immutable classes, do you prefer:
Layer.ColorCorrect ( layer )
or
layer.ColorCorrect ( )
To me #1 seems more intuitive, instead of #2, which looks like it modifies the object that's referenced, since it's an instance method, it might as well change the internals, right?
I would prefer to use an instance method, but choose the name to reflect the fact that it doesn't change the existing instance. For example:
layer.AfterColorCorrection()
or
layer.WithCorrectedColors()
Using static methods becomes tiresome pretty quickly. Also, if you make it clear to your users that the type is immutable, they should get the hang of that pretty quickly. Everyone gets tripped up by String.Replace not actually replacing anything in the target - but they don't keep making the same mistake. With better names as well you should be fine.
I asked a related question about "adding" to an immutable list - the best solution there IMO is to use "Plus" rather than "Add"; again, it doesn't imply that the original value is changed. You may find other answers to that question useful.
My personal preference is to focus on making it visible that the type is immutable. For instance I would call it ImmutableLayer vs. Layer. Or if for some reason Immutable is not a good word to prefix the name with I will add an attribute to the class indicating it's Immutable (attribute is added in both cases).
This has it's ups and downs. The up is it gives a central place to check for immutabliity. Just take a quick peek and the type and you're in business. There is no need to learn new method names or conventions. The downside to the approach is that you can't tell in certain type infererence scenarios that the value is immutable. For instance, this code works just as well for an ImmutableCollection and a normal List
var col = GetTheCollection();
col.Add(42);
However I do not like to change method names to accomidate immutability. The reason being that it is a problem you will have to solve repeatedly. Naming things should be easy, but it's incredibly difficult some times. Think of all of the types you've ever wanted to make immutable. Imagine having to find new names or conventions for every mutating method on those types. It's a non-trivial task and you will spend a lot of time educating users on those new conventions.
My dream scenario though is to find a way to increase the visiblity of immutable types. Because that's the real problem here, not knowing the type is immutable. Currently there is no good way to do this for all scenarios, but I'm hopeful for the next version of the languages / IDE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With