by prettyStandard · 3y ago · 0 comments
Let's see if I can write something, that others understand with no context.
//For this example let's ignore the nuances of names.
function (nameUserinput) {
if(isValidName(nameUserinput)) {
return processName(nameUserinput))
} else {
return { first: '', middle: '', last: '' }
}
}
function isValidName () {
return (containsAtLeastOneSpace(nameUserinput) &&
containsLessThanThreeSpaces(nameUserinput) &&
hasThreeOrMoreCharacters(nameUserinput) &&
noSpacesOnEnd(nameUserinput))
}
function processName (nameUserinput) {
const nameObj = { middle: '' };
const nameUserinputArray = nameUserinput.split(' ');
if(nameUserinputArray.length = 2) {
[nameObj.first,
nameObj.last] = nameUserinputArray;
} else if(nameUserinputArray.length = 3) {
[nameObj.first,
nameObj.middle,
nameObj.last] = nameUserinputArray;
}
}
nameObj and nameUserinput and nameUserinputArray are all the same data in different forms. I think it's helpful to start them with the same prefixes, but change the suffix with the type to communicate that.You could imagine taking this a step further, with nameStatemachine. You might chart a person's course through life, do they go to law school, medical school, get married etc.
I've been meaning to write a blog post on this. But this does follow my most important words first rule. You'll see a lot of similarities there, just not on this exact topic.
Ignoring variable name shadowing a static type system helps a lot
Yeah, but only when it adds to the readability. I avoid mentioning Hungarian notation because I don't like it either. I think many criticisms still apply, so I suggest the use case before, where you have the same data passing through multiple types. There may be other good use cases, but I am not sure what those are. This is why my general rule, is "most important words first", I think that technically covers this use case.