@Enterprise Architect said:
Strings are immutable too, but they make it easy to make a new string from an old one:
String string = "Hello";
string = string + ", world";
What's the equivalent with your class?
a) I guess you are aware that we don't have operator overloading in java. The special handling that Strings and primitives get is not an option to custom classes. Which is sometimes sad, but most of the times a good thing. Developers get what they expect, they don't have to search the code base for some hidden overloading to check it's semantics.
b) Sure, I guess it would be possible to add a copy constructor that would either add or remove a mapping entry, but last time I checked, I was under fire for creating too much code, and now you want additional features? Which is it going to be?
Also, due to syntax restrictions in java, the call syntax would have to be very awkward. Something like this:
Mapper<Integer, Integer> newMapper = originalMapper.addKey(230).addValue(7)
would unneccessarily create two new Instances (which is the way a functional language would do it, but java objects are heavier than their functional equivalents) or give up immutability. Also, it would not give me the option to insert the value at arbitrary positions (the key would be sorted to the correct position) without something like this
originalMapper.addValue(int value, int offset)
The key problem here is that there are no associative arrays in java. In another language I might have written something like this:
Mapper mapper = Mapper.create([10 -> 1, 20 -> 2, 30 -> 3])
etc.
And then the copy factory method would be something like
newMapper = oldMapper.withAdditionalMappings([50 -> 4, 80 -> 5])
But things like that are impossible in java.
I'd say adding and removing values is not an option with this solution without turning it into a real monstrosity. Create a new instance instead.
BTW, how are you going to create new mappings at runtime using the classic if/else solution you seem to favor?
BTW (2) this is awful code
@Enterprise Architect said:
String string = "Hello";
string = string + ", world";
It works, as a "convenience" for developers, but it internally creates lots of StringBuilder calls and it's hell to step through that with a debugger.
Use
newString = oldString.concat(", world")
instead or if you are going to concatenate multiple elements, use a StringBuilder.