Ad/iklan :

3gp Mp4 HD
Play/Download
Live 3D App
Search.Pencarian Menu

Add text send email to rh3252705.adda@blogger.com or Click this (Text porn Will delete) | Tambah teks kirim email ke rh3252705.adda@blogger.com atau Klik ini (Teks porno akan dihapus)
Total post.pos : 16329+

[Go Make Things] Code readbility

🎉 Cyber Monday Sale! Today only, you can join the Lean Web Club for just $9/month. Try it free for 30 days, then get 50% off for the next year.

I've been making a ton of updates to the Lean Web Club over the last few weeks.

Last night, I was adding an interactive code sandbox the section on Array.prototype.reduce(), and became aware of just how much my perspectives on code readability have changed over time.

My (former) favorite JavaScript method

There was a time when the Array.prototype.reduce() method was my favorite JS method. I really liked it's versatility.

You could use it like Array.prototype.map(). You could use it like Array.prototype.filter(). You could combine multiple methods into a single process.

Let's imagine you have an array of wizards

let wizards = [  	{  		name: 'Radagast',  		spells: ['Talk to animals', 'Grow plants'],  		tool: 'staff'  	},  	{  		name: 'Merlin',  		spells: ['Dancing teacups', 'Turn into fish'],  		tool: 'wand'  	},  	{  		name: 'Gandalf',  		spells: ['You shall not pass', 'Disappear'],  		tool: 'staff'  	}  ];  

You want to create an array that contains only the names of wizards that use a staff as their tool.

You can do that with Array.prototype.reduce() like this…

let staffUsers = wizards.reduce(function (arr, wizard) {  	if (wizard.tool === 'staff') {  		arr.push(wizard.name);  	}  	return arr;  }, []);  

But… that's kind of weird and confusing and hard to read, right?

It takes a bit of mental processing to figure out what's happening.

Readability is better than being clever

If I were completing that task today, I would use Array.prototype.filter() and Array.prototype.map().

let staffUsers = wizards.filter(function (wizard) {  	return wizard.tool === 'staff';  }).map(function (wizard) {  	return wizard.name;  });  

Yes, it's a second step. Yes, it's marginally slower (but not in a way that a user would ever perceive).

But it's also one line shorter and much easier to read and understand. Each function tells you exactly what it's doing. There's less mental gymnastics to unravel.

At the end of the day, a human has to maintain the code you write.

I'm still not all-in on big libraries, but I do think code that can be read and maintained is more important than hyper-optimizations.

Cheers,
Chris

Want to share this with others or read it later? View it in a browser.

Share :

Facebook Twitter Google+
0 Komentar untuk "[Go Make Things] Code readbility"

Back To Top