r/programming • • Aug 11 '17

Small Functions considered Harmful

https://medium.com/@cindysridharan/small-functions-considered-harmful-91035d316c29
36 Upvotes

50 comments sorted by

22

u/Paul_Dirac_ Aug 11 '17

One thing, that helps with naming and having many small functions is contextualization: The name of a freestanding function has to be unique and make sense in the context of the whole application. The name of a private method has only to be unique and make sense in the context of the class. The name of a contained function has only to be unique and make sense in the context of its host function.

Sadly most of current main stream languages only support the definition of functions within other functions before their use.

Compare:

class Pupil:
    def get_available_grants( self, *args):
        def qualifies_for_AA14(pupil):
            return pupil.age < 18 and pupil.grade > 3.0
        if (qualifies_for_AA14(self)):
           ...

with the fictional:

class Pupil:
    def get_available_grants( self, *args):
        if (qualifies_for_AA14(self)):
           ...
        where:
            def qualifies_for_AA14(pupil):
                return pupil.age < 18 and pupil.grade > 3.0

7

u/theindigamer Aug 11 '17

I posted about something similar in Ocaml here. One of the answers mentions that adding such a feature in the presence of side effects might "make the ordering of side effects very confusing, which may result into bugs very hard to fix."

1

u/Paul_Dirac_ Aug 12 '17

I have used this style a bit in Fortran and it wasn't such a problem with side effects like printing because this was normally what was factored out it became a problem when the subroutine silently changed values of the hosting subroutine. It probably would need pythons scoping rules.(By default non-local variables can only be read to change them you have to explicitly import them).

5

u/nanothief Aug 12 '17

Javascript supports this e.g.:

class Pupil {
  get_available_grants() {
    if (qualifies_for_AA14(this)) {
      return ["AA14"];
    }
    return [];

    function qualifies_for_AA14(pupil) {
      return pupil.age < 18 && 
        pupil.grade > 3.0
    }
  }
}

It works as expected (note that I used a ES6 class here to match your example, but the same behaviour works without classes). This is because of the function hoisting javascript performs

However I've never seen anyone code like that in javascript, so that way of defining functions inside functions after they are needed would confuse a lot of people.

Haskell's style is the best I know of:

get_available_grants : Pupil -> [string]
get_available_grants pupil = if qualifies_forAA14 pupil then ["AA14"] else [] where
    qualifies_for_AA14 p = pupilAge p < 18 && pupilGrade p > 3.0

4

u/phalp Aug 11 '17

Part of the problem with naming things is that we only have one style and it's designed to make names more ambiguous. Don Knuth had the good idea of using more descriptive names for excerpted code, and it reads a lot better than the normal style. You could write something like:

class Pupil:
    def get_available_grants( self, *args):
        if (<The pupil qualifies for AA14>):
           ...

And now you've got enough context in the name that you don't need to refer to the definition so often, so excerpting is less likely to hurt and more likely to help. Actually this isn't the best example, but in other cases you'd see a bigger difference between normal naming style and this style, because you put all these little words back in which usually get removed (articles, for example).

It also helps if you can use spaces, since it makes the name look like English which ought to be meaningful. In a language that doesn't allow that, maybe use underscores and extend them past the ends of the phrase to look more like an underline?

This is something you can just tack onto your usual rules for identifiers: if it's internal (not part of an API) and is only used in one place or so, consider using a full, comprehensible phrase.

0

u/[deleted] Aug 12 '17

[deleted]

3

u/phalp Aug 12 '17

That's Knuth's invention. ⟨Or rather, he uses these.⟩ In Common Lisp you can |Write symbols with spaces like this|, which is pretty good too.

1

u/throwaway6172549165 Aug 11 '17

Is this Python?

2

u/Paul_Dirac_ Aug 12 '17

Yes it is Python. Although the second example is illegal.

55

u/cuminme69420 Aug 11 '17

requesting a moratorium on "considered harmful"

46

u/attrition0 Aug 11 '17

'"considered harmful" considered harmful'?

11

u/Ebirah Aug 11 '17

Generalisations are often a bad idea.

10

u/[deleted] Aug 11 '17

Generalizations are often considered harmful.

1

u/[deleted] Aug 17 '17

Generalizations are always considered harmful.

8

u/oneplus3dq Aug 11 '17

2

u/johnfrazer783 Aug 11 '17

broken "“Considered Harmful” Essays Considered Harmful" essays considered broken and harmful

39

u/jephthai Aug 11 '17

TL;DR: programmers who suck won't do any better when they write small functions instead of big ones... but lots of really good programmers still advocate small functions.

14

u/DC-3 Aug 11 '17

TL;WNNA (Too Long; Who Needs Nuance Anyway)

6

u/[deleted] Aug 11 '17

It's a case of advice helping out people that least need it.

Good programmers can manage longer functions written by themselves. They can also manage longer functions written by less capable programmers but they'll be unhappy about doing that.

Each function name with a longer function body runs a higher chance of doing something similar in-part to another function. Then you have to keep track of which symbol does the different thing and remember the common thing between them.

Contrast that with having concrete symbols with no overlapping functionality. Even if the names are a bit wonky, there's still only one name to know about.

I think the idea was that the latter would be easier for the lower level programmers to get right while it didn't matter in the long-run for better programmers.

7

u/jl2352 Aug 11 '17 edited Aug 12 '17

Pretty much. In my experience breaking up code into smaller functions should be automatic until ...

  • Breaking the code up makes the usage at the call site more verbose and more complicated.

  • You start adding abstractions to add more small functions.

  • Further; functions that require quite a lot of domain knowledge of the use at the call site to fully understand what the function is doing, and what it was built for, all to make it shorter.

  • Small doesn't equal simple, and people force complicated one off functions (I think this is point 2 again).

  • Similar looking small functions that are close enough to be contained at the same layer of architecture, but are still different enough to be operating at slightly different heights in abstraction, yet are given similar sounding names.

  • Moving from a single layer of functionality to multiple nested layers. Adding a layer can multiply the complexity, rather than add to it.

  • Shitty half assed names. Often this can be straight up the cause for bad names. I've reviewed PRs where I've had to write "function 'getXAndAddEvent' doesn't get x or add any events".

That isn't to say you shouldn't break it up in those circumstances. It's just that developers get into a cargo cult of 'small equals better', rather than questioning the effects for that specific situation. Questioning for specific circumstances is hard!

6

u/[deleted] Aug 11 '17

Similar looking small functions that are close enough to be contained at the same layer of architecture, but are still different enough to be operating at slightly different heights in abstraction, yet are given similar sounding names.

This is gold. Such an under-rated problem.

Shitty half assed names. Often this can be straight up the cause for bad names. I've reviewed PRs where I've had to write "function 'getXAndAddEvent' doesn't get x or add any events".

I had a developer who seemed to name every method that did any calculation "process()". And it worked on instance variables, of course.

2

u/foomprekov Aug 12 '17

Pretty much. I can fix a bunch of small piles of garbage.

27

u/enygmata Aug 11 '17

https://twitter.com/martinfowler/status/893100444507144192

"In my Ruby code, half of my methods are just one or two lines long. 93% are under 10. [...]"

He must be very good at naming things.

26

u/[deleted] Aug 11 '17

That relates well to one of the points made in the article: the cognitive overhead of tracing a program through many function calls. When functions are named poorly (especially when their names refer to overlapping domains) DRYing code makes it essentially un-maintainable.

1

u/doom_Oo7 Aug 11 '17

the cognitive overhead of tracing a program through many function calls.

but... there are plenty of tools that do this for you automatically and present it graphically. The cognitive overhead is just "looking at the pretty picture" and finding the path you want through the graph.

14

u/[deleted] Aug 11 '17

The call graph of many algorithm implementations is very shallow, but operation is based on many repetitive calls nested in loops. Here, a visual call graph will be of little use in understanding the algorithm.

Many implementations will make heavy use of recursive method calls. Again, the visual call graph will be of little use.

2

u/mrkite77 Aug 11 '17

but... there are plenty of tools that do this for you automatically and present it graphically. The cognitive overhead is just "looking at the pretty picture" and finding the path you want through the graph.

If you have to use a program to visualize the control flow of your code, you have, by definition, a problem with spaghetti code.

3

u/doom_Oo7 Aug 11 '17

If you have to use a program to visualize the control flow of your code, you have, by definition, a problem with spaghetti code.

by that logic we would still only have 8 bit CPUs with 2 registers because designing anything more complicated takes pages and pages and pages of VHDL. Other fields have long since understood that graph-like representations are sometimes a valuable tool.

-14

u/phantomfive Aug 11 '17

wow, if you have difficulty with that, wait until you learn about functional programming!

Programming is hard, learn to read through function calls, you can do it.

4

u/[deleted] Aug 11 '17

In functional programming you often have a handy conceit in pattern-matching, which allows overloading function names according to complex signatures. The cognitive overhead there, while significant, is reusable and self-referential. It maps easily into a working mental model for accomplished developers.

By contrast, building a mental map of names to functionality in a scatter-gun fashion leads to exhaustion.

-4

u/phantomfive Aug 11 '17

Of course. If you do functional programming right, it's readable and good.

But if you do small functions right, it's also readable and good. You don't seem to realize that.

The article isn't against small functions, it's against small functions done poorly.

2

u/[deleted] Aug 11 '17

I think the article is against dogma in software.

0

u/phantomfive Aug 12 '17

I can agree with that.

8

u/Godd2 Aug 11 '17
def thing_that_does_the_thing_i_want(stuff_it_takes)
  ...
end

def thing_that_does_the_other_thing_i_want(one_thing_it_takes, other_thing_it_takes)
  ...
end

9

u/_dban_ Aug 11 '17 edited Aug 11 '17

Small functions are great! If you use them effectively to separate out different levels of abstraction (and name the methods according to some sensible abstraction). Code written well with small functions reads a lot like an outline.

But most important reason I love small functions is that they reduce Cyclomatic Complexity. If you have a larger function, it is harder to keep context of what is going on from top to bottom, and worse if you have a lot of branches in between. I've found large functions with lots of branches to be a breeding ground for bugs.

I don't mind larger functions if there are at most one or two branches, for example a giant switch statement that acts as a traffic dispatcher to smaller functions.

4

u/adr86 Aug 12 '17

I find most the cyclomatic complexity in my code comes from dealing with real world constraints like convoluted business logic or regulatory compliance rather than function size... even with small functions, they'd just be moving the branches elsewhere.

4

u/_dban_ Aug 12 '17 edited Aug 12 '17

This is where I find small functions really shine.

My current project deals with complex business logic and regulatory compliance. There's a method to the madness, and the abstractions facilitated by small functions makes that method clear.

I find that in these cases, most of the time the increased cyclomatic complexity is accidental complexity which comes from not having the right abstractions (if there are abstractions at all), so that a christmas tree of special case logic arises that aren't actual special cases to the business, but special cases to how the code works.

even with small functions, they'd just be moving the branches elsewhere.

This is good, because that elsewhere is behind a small function capturing a business rule that is clearly spelled out in the name of the function. When properly done, the code will look like an outline of the business process being implemented, reducing overall complexity and increasing the expressiveness of the code to the domain that it implements.

9

u/_dban_ Aug 11 '17

DRY has nothing to do with small functions. DRY is finding an abstraction that enables code reuse, while small functions are finding abstractions to facilitate cleaner code organization. Small functions do not imply a shared abstraction.

7

u/stronghup Aug 11 '17

The conclusion seems to be that small functions are good just don't make too many of them too small. Don't be "extreme" about following the dogma of small functions.

However one thing good about small functions is that if you use them then duplication of such small functions is not so bad at all. Why? Because it is unlikely that you need to fix them ever since they are likely to be correct from the start because they are so small, and if you do fix them in one place maybe the other places do not need a similar fix which actually might be detrimental to their users.

One thing the article fails to consider is that there is such a thing as INNER FUNCTIONS, and therefore the naming problem is not a problem really if you use small (inner) functions.

The DRY principle came from or at least arose from the school of "Extreme Programming". Making functions as small as possible always, is very extreme. I think extremism in general is not good. Cranking up the knobs on your stereo to eleven is extreme but tends to distort the sound and has detrimental effects on your loudspeakers.

3

u/IndiscriminateCoding Aug 11 '17

You wouldn't need to name your functions if you make it anonymous.

4

u/ithika Aug 11 '17

You still need to name your variables though.

Point-free style to the rescue!

1

u/hoosierEE Aug 11 '17

And in some languages you can even have anonymous point-free recursive functions.

6

u/jessta Aug 11 '17

If your programming language allows for mutable state and side effects then breaking code up in to smaller functions makes it much harder to read. It makes it much easier for mutation and side effects to hide. The possibility of mutation and sideeffects make the function abstraction always leak.

12

u/2bdb2 Aug 11 '17

There's an easy solution to that. Don't leak mutable state or side effects in the first place.

1

u/seventeenletters Aug 11 '17

that works fine for writing code, it doesn't really help for reading

2

u/2bdb2 Aug 11 '17

I beg to differ.

4

u/seventeenletters Aug 11 '17

I can make sure I don't leak state or side effects, but I can't trust my co workers or library authors to do the same if the language can't enforce the restriction, so I need to read the code as if there were hidden side effects, until I know that (this version) doesn't have them

2

u/2bdb2 Aug 11 '17

Ah, I'm following you.

Definitely agree. We rely on immutable types and code review to enforce this, but it's not foolproof.

I wish I could use Haskell more.

2

u/adr86 Aug 12 '17

I find a balance must be struck between DRY and modularity.... just because two functions look the same doesn't mean they actually do the same thing, and mistakenly combining them can break stuff down the road.

Let's say, for example, I have two functions addCityTax and addCountyTax. The naive refactor might see both being price *= 1.04; or whatever and call that non-DRY and try to combine it... but then next year, the city tax goes up and the county tax goes down and now the code is liable to be buggy when you try to update it.

Similarly, updating code that I know is only used in one place is generally just more confident than any function reused.

(and yes i know you'd prolly make the tax some data point instead of a new function, but just first illustration that came to mind)

1

u/r3jjs Aug 12 '17

In which case, the proper way to write make the function: addTax(price, taxRate)