DEV Community

Discussion on: Immutibilty

Collapse
 
jwp profile image
John Peters • Edited

The example shows poor programming technique.


// This is ambiguous, lazy, and the worst form of mutation.
// Its a terrible way to program in any language!
// Its what was done in "c" 40 years ago
// 93 characters

let d = b * b;
d -= 4 * a * c;
if (d < 0) return [];
d = Math.sqrt(d);

// A better way to program.
// Totally non-ambiguous, non lazy, self commenting. 
// No concern for mutability here.
// 193 characters

let taxmultiplier = taxbase*taxbase;
let exciseTax = 4;
let figuretax = taxmultiplier -(exciseTax*stateTax*countytax);
if(figuretax<0) return [];
let taxRoot = Math.sqrt(taxMultipier);

// even better, we have a tax rule a object which, for safety must be immutable; 
// unless the new taxable rates arrive of which we handle separately somewhere
// 138 characters

let a = {taxbase:.04, taxmultipler:'*2', stateTax:.1, countyTax:.05} 
return a.taxmultiplier -(a.exciseTax*a.stateTax*a.countytax);


// This allows us to pass in an object and return a number based on object content.
// 66 characters

function calcTax(a){
 return a.taxmultiplier -(a.exciseTax*a.stateTax*a.countytax);
}

// implementing a decorator
// 72 chars

function calcFloodTax(a){
 let floodtax = .005;
 let tax = calcTax(a);
 return tax * floodtax;
}

// a decorator with injected floodtax
// Total characters 32

function calcFloodTax(a, floodtax){
  return calcTax(a) * floodtax;
}

If a programmer can type 200 words per minute or 4 lines of code. From a time perspective it's just better to be a better programmer.

My main point is if the programming is done correctly we should be able to mutate any time we want. It's just way easier to set a field to a new value than to do the immutable tricks.

Collapse
 
craigmc08 profile image
Craig McIlwrath

I was struggling to find a small example that could get my point across. Usually confusion due to mutable states arise in larger systems with many pieces, in my experience.

And yes, I agree your example is better code and more readable. But your code uses immutability to improve readability, so how does that support the idea that mutability doesn't decrease readability?

Thread Thread
 
jwp profile image
John Peters • Edited

Good point, the code example was only trying to point out that we don't need to be forced into an immutability model all the time, rather with proper techniques we can mutate at will and not worry about problems down the road.

But thanks for pointing this out. I'm beginning to see that javascript programmers may not follow the techniques listed above, so the "immutability" rules are good. Immutability is a creedo, a warning about what happens when mutating objects by reference where not intended. Always a bad outcome.