I wish some high-level languages tried copy-on-write value semantics for values types, where 'value types' includes strings, arrays, dicts and anything else that's logically a value type.
E.g:
type MyClass {
myCoolListDoNotStreal: List<Coolness>;
constructor(lst: List<Coolness>) {
this.myCoolListDoNotStreal = lst; // copy-on-write
}
letThemHaveCoolness(request: CoolnessRequest) {
if (request.allowed) {
return this.myCoolListDoNotSteal; // copy-on-write
} else {
return fatalErrorAlertMurder();
}
}
}
function knave(myClass: MyClass) {
var lst = myClass.letThemHaveCoolness(); // copy-on-write value semantics, creates an independent value but with no copying cost
if (window.myLocal) { // rare condition
lst.push(UNCOOL); // doesn't affect myClass, only lst. (But does incur copy cost on first modification)
} else {
// enumerate and have fun with lst here, still with no copying cost.
}
} // lst goes out of scope and thus future modifications to myClass's member variable incur no copying cost either.
func coolnessProcessor(lst: &List<Coolness>) { // Reference semantics can also be explicitly requested
// (and so MyClass can make use of coolnessProcessor to process its member variable.)
lst.push(TOO_COOL); // no copying cost due to reference semantics
}
// Oh and the above applies only for value types (which can include user-defined value types).
// The rest of the types are "identity" (aka object/reference) types (like MyClass above),
// which are passed by reference as in java/what-have-you.
// (Possibly with some way to easily distinguish the two kind of types at a glance)
Now, I realize the implementation of this would have to incur some unfavorable costs and complexities, but the result will just make more sense than the current "everything is a reference".
For example, if one were to write the above MyClass in javascript/java/etc, he'd have to copy the list in both constructor and getter in order to avoid users of the class accidentally modifying it.
Of course, some languages like C# and java provide other solutions like read only maps, but I feel these are just workarounds to the pitfalls of reference semantics.
It's worth a try, 'sall I'm saying.