DEV Community

Discussion on: We Should All Be Writing WET Code

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

A function (or... "method", if you will) should

Do one thing, and do it well.

Of course, those two simple guidelines are both somewhat subjective. If you set two variables in your function, is it no longer doing "one thing"? (Most certainly not - but you get my point.) And whether the function is doing its thing "well" is always debatable.

But any time you start abstracting the heck outta stuff, you're almost never doing it well. And we often reach for abstraction when we're trying to make a single function do many different things.

So if you have one block of code that's become a true utility function - the sorta thing you write once and use all over the place, then yeah, of course you should centralize that code. But when you start trying to turn that utility into a Swiss Army Knife - the kinda "utility" that will serve every single alert, that meets every single use case, in every single scenario - then you're probably creating an abomination.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

If you set two variables in your function, is it no longer doing "one thing"?

I think that thought is a bit misleading: functions serve as an interface between two levels of abstraction and the "do one thing" rule should apply mostly on the level of the caller, not the internals of the function.

A function (or any other type of subroutine, really) might do lots of things internally that present present as a single atomic action to the outside.

Also, there's one statement that can be generalized a bit:

But any time you start [insert almost any best practice here] the heck outta stuff, you're almost never doing it well.

See? Much more DRY now 😁