News for hackers. Stuff that matters.
Re:Functions Should Be Short And Sweet, But Why? by sdegutis on Wednesday January 22, 2014 @02:27AM (#7101308)
On the flip side, I've seen people take this to the extreme. They often separate lines of code that intrinsically belong together, necessary parts of an algorithm get spread around for no other reason than to try and keep functions small. It leads to code that's really hard to work with and somehow more brittle than when it started.

I'm not saying this happens all the time. But I'm more concerned about it, because I see it more often than the inverse, and it's more damaging to the codebase. At least long spaghetti methods can be refactored into something nice. This kind of mess has to be refactored into a single area first, which is much harder.

Re:Functions Should Be Short And Sweet, But Why? by mironathetin on Wednesday January 22, 2014 @03:24AM (#7101466)
>>On the flip side, I've seen people take this to the extreme.<<

indeed, I have seen functions that contain only one line of code. Even if that is intended for reuse, it makes no sense, because the function call is one line too. Readability goes down the drain this way.

If a reader tries to understand a logic and thinking has to be interrupted by searches and trying to find the right code window, split-ups don't do good things.

Polymorphism, if applied wrong, is a notorious tool to hide the logic from the readers too. If the code decides at runtime, which implementation is used, comments become really important. Especially when this decision is made completely elsewhere in the code. Think strategy pattern, for example.

The underlying problem is IMHO developers blindly following rules. This can be seen a lot. If you ask them 'why' and you get a textbook answer, be careful.

Re:Functions Should Be Short And Sweet, But Why? by yummyfajitas on Wednesday January 22, 2014 @05:23AM (#7101823)
A single line function makes sense because it allows you to alter functionality later without worrying you forgot about some instance of that pattern:

    def logUnexpectedError(t: Throwable) = log.error("Oops: {}", t)
After I get it together and start keeping proper metrics:

    def logUnexpectedError(t: Throwable) = {
      log.error("Oops: {}", t)
      statistics.errorCounterByClass(t.getClass()).inc()
    }
Re:Functions Should Be Short And Sweet, But Why? by ufo on Wednesday January 22, 2014 @07:01AM (#7102084)
but on that opther hand, this means added complexity in all the cases where you dont overload it. Whoever reads the program will always have to keep overloading in mind.
Re:Functions Should Be Short And Sweet, But Why? by pedalpete on Wednesday January 22, 2014 @02:12PM (#7104675)
hence a good naming convention. If the function name is clear, than it shouldn't be a mind drain at all, particularly if it is only a one line function.
Re:Functions Should Be Short And Sweet, But Why? by InclinedPlane on Wednesday January 22, 2014 @05:04AM (#7101761)
There is nothing wrong with a one line function. Nothing whatsoever. There are huge benefits to extracting a single line of code into a function. I'll just link to a stackoverflow answer I made on the subject several years back: http://stackoverflow.com/questions/785145/one-line-functions...

Summary: Performance almost certainly isn't an issue (compilers are smart). Abstraction leads to better design, using a well-named function can improve readability, making it easier to understand, easier to prove correct, and easier to modify. When you keep code inline it increases the inertia of the given design and implementation, extracting even a single line into a function (when warranted) can make it far easier to drastically change implementation. And if you want that single line of code to become several lines, or to switch to calling out to a web service, implement caching, add error checking or what-have-you that's made much easier when it's encapsulated inside a function than when it's sitting inside a block.

Componentization is always good, even when the components are sometimes very small. Like all design choices extracting code into its own function requires judgment based on experience but when done right it can have many benefits, even when it's a single line, even when it's a fraction of a single line.

Blindly following a rule such as avoiding making functions too small is just as big an error as avoiding making functions too large.

Re:Functions Should Be Short And Sweet, But Why? by henrik_w on Wednesday January 22, 2014 @05:12AM (#7101784)
Steve McConnell makes some good points about this in Code Complete too, one of which is "small methods tend to become bigger". Even if it started out as a one-line method, it is not unusual to later find the need to add something else to it. This is from memory (I don't have the book here), so I can't give a more specific reference to it.
Re:Functions Should Be Short And Sweet, But Why? by chongli on Wednesday January 22, 2014 @03:49AM (#7101538)
Depends on the language. In Haskell function calls are extremely lightweight, syntactically speaking, and so it's actually quite common to write one line functions. A one-line function may consist of a composition of a dozen or more other functions and be given a short, one-word name. This makes perfect sense for reuse. Or it can be something as simple as this:

    odds = filter odd
While that might not make sense if you only call odds once, you might end up calling it a dozen times! You may also want to limit the scope of this function definition by using a let or where clause. This can aid readability if it allows you to avoid repetition.
Re:Functions Should Be Short And Sweet, But Why? by NigelTufnel on Wednesday January 22, 2014 @07:23AM (#7102158)
I've tried to learn Haskell for a several times and the composition-heavy/flipping-so-currying-will-work/no-variables style always made the programs difficult for me to understand.

Probably the classic case of Imperative-Guy-Struggling-To-Get-FP.

Re:Functions Should Be Short And Sweet, But Why? by aaronem on Wednesday January 22, 2014 @09:03AM (#7102538)
Speaking as an "imperative guy" who's lately been learning Common Lisp, I tend to suspect the confusion you're encountering is not so much a property of the functional style in general, as of Haskell's style in particular.

While I'm admittedly not best placed to comment on the matter, it seems to me that what Haskell offers is not so much greater power than a Lisp, as greater concision, as well as a language structure which doesn't allow for the sort of "escapes" into imperative behavior that a Lisp programmer can employ.

In fact, now I think about it, I'd say that Lisp and Haskell are in this way roughly analogous to Perl and Java. I'm sure this claim will infuriate partisans of all four languages, so let me hasten to point out that the only sense in which I mean it is that Lisp and Perl allow the programmer considerable stylistic freedom ("TIMTOWTDI"), while Haskell and Java go to great lengths to enforce that style which their respective implementers consider the One True Way.

Both these traits have benefits, of course, or one would've probably outcompeted the other by now; of particular note here, though, is that the One True Way style requires a lot more front-loading on the part of the developer than the TIMTOWTDI style does -- in the latter, you can more or less "fake it 'til you make it", while in the former, trying to "fake it" results in a nasty dressing down from the compiler, and you can't accomplish anything until you've become at least a neophyte, preferably a proper acolyte, of the One True Way.

All of which is a very long-winded way of saying that if what you're interested in is not so much Haskell specifically as the functional style in general, you might be well advised to start with a Common Lisp or a Scheme, where you can study the functional style without needing first to understand any large and rather dry bodies of theory. Granted, you'll probably screw it up a lot right at the start, at least if my own experience is any indication. But Haskell's a big elephant to swallow all at once, and starting in a Lisp or a Scheme will let you nibble around the edges at your own pace, rather than being required to choke down nine-tenths of the entire carcass just to get to Hello World.

Re:Functions Should Be Short And Sweet, But Why? by chongli on Wednesday January 22, 2014 @05:56PM (#7105970)
Pointfree style is a tricky style to get right. There is a bot on the #haskell IRC channel (lambdabot) that has a function which will transform any valid Haskell function definition into pointfree style. The results that come out of this are often totally ridiculous! Here's an example (stolen from the IRC channel, @pl is the bot command to do the transformation):

    @pl transform k z = reverse (foldr (\x y -> y ++ [fst(head(filter (\a -> snd a == k-1) (zip x [0..])))]) [] z)
Transformed into:

    transform = (reverse .) . flip foldr [] . (flip (++) .) . flip flip [] . (((:) . fst . head) .) . (. flip zip [0..]) . filter . (. snd) . (==) . subtract 1
Yeah, neither is readable. This function ought to be broken up into cleaner, more declarative parts. In fact, the whole function can be reduced to this:

    transform k = map (!! k)
Much more readable, wouldn't you agree? Now all you need to know is what map and !! do.
Re:Functions Should Be Short And Sweet, But Why? by amag on Wednesday January 22, 2014 @04:22AM (#7101659)
>> indeed, I have seen functions that contain only one line of code. Even if that is intended for reuse, it makes no sense

IMHO it can make a lot of sense. In many cases you can clearly specify the intention of that one line by putting it in a function with an appropriate name. Just look at the example from the OP:

void HandleNop() { SPIDataPut(SPI0_BASE, HOST_REPLY_POSACK); }

When you want to handle a NOP, you're not interested in how that NOP is handled, you just want it handled...:)

Re:Functions Should Be Short And Sweet, But Why? by pdpi on Wednesday January 22, 2014 @05:41AM (#7101872)
A one-line function is perfectly fine (in fact, it's a good sign!), as long as you're translating domain-specific function calls to implementation-specific one-liners. It means your underlying implementation maps well to the problem.
Re:Functions Should Be Short And Sweet, But Why? by mironathetin on Wednesday January 22, 2014 @05:36AM (#7101858)
I see, you provide many counter examples for a valid one liner. Indeed, these are good points.

Thats the beauty of a forum, if used in a productive way :o).

Re:Functions Should Be Short And Sweet, But Why? by cclogg on Wednesday January 22, 2014 @02:49AM (#7101352)
Yeah I do hate it when trying to follow through code and I'm having to do searches to find where the next method calls out to in a massive chain of tiny methods. But both sides have their point heh.

I wonder if it's a limitation of our IDEs using plain text and files. Maybe the next generation of programming languages will be nodes or visual blocks that chain together or something? Who knows haha.

Re:Functions Should Be Short And Sweet, But Why? by fuzzix on Wednesday January 22, 2014 @03:56AM (#7101557)
> Maybe the next generation of programming languages will be nodes or visual blocks that chain together or something

The problem is, you still need to have control at a "line of code" level of granularity (though not quite a line of assembler mnemonic) if you want to have general purpose programming power. You could probably, with some work, make a graph tool for something like ifttt[0] and do powerful things relatively simply. It's not quite programming though.

I've used state machine UML code generation systems in which you "program" by moving blocks around (something akin to a flow chart). Even when the system's purpose is something extremely limited, e.g. handling a phone's menu transitions, there's still a mind-bending amount of complexity to handle.

I believe ImageJ[1], a freely downloadable image analysis tool, is among the tools with this sort of UML functionality built in if you want to play with it.

[0] https://ifttt.com/

[1] http://rsbweb.nih.gov/ij/

Re:Functions Should Be Short And Sweet, But Why? by nightski on Wednesday January 22, 2014 @05:49AM (#7101896)
If this were true expression based languages would not work. Which simply is not the case. Of course if you live in a world of statement based languages I can see where this would seem the case.
Re:Functions Should Be Short And Sweet, But Why? by fuzzix on Wednesday January 22, 2014 @06:40AM (#7102025)
No matter how powerful and expressive your language is, it still breaks down into lines of code to achieve something.

I'm not trying to claim some complete, graphically represented program will have as many operations (or boxes) as the equivalent C code. It won't, however, require less cognitive overhead than crafting the program in the language of your choice without making most of your choices for you (and in the process becoming much less powerful, not general purpose at all).

edit When a computer is smart enough to derive intent, then a picture will be worth a thousand words. Until then...

Re:Functions Should Be Short And Sweet, But Why? by nightski on Wednesday January 22, 2014 @08:01AM (#7102310)
It is actually getting damn close with modern dependently typed languages (regarding deriving intent). I believe this is what many graphical languages lack, a sophisticated type system guiding the user. Instead they like to emulate statement based languages with cute but not very abstract or reusable boxes.

Also the fact it boils down to code is not true at all. It all comes down to an AST. Text based representation of computer languages is rather archaic when you think about it.

I mean, look at IDEs. So many handle code transformations for the user because of how tedious the work is. Not only that, but in order to perform these translations it is transforming the code into an intermediate form it can work in, performing the specified transformations, and then transforming it back to the textual output. It is crazy.

Re:Functions Should Be Short And Sweet, But Why? by fuzzix on Wednesday January 22, 2014 @09:34AM (#7102679)
> It is actually getting damn close with modern dependently typed languages (regarding deriving intent). I believe this is what many graphical languages lack, a sophisticated type system guiding the user.

Well, you've gone over my head, but given me plenty of reading material. Thanks.

> Instead they like to emulate statement based languages with cute but not very abstract or reusable boxes.

Indeed, though they're rarely cute.

> Text based representation of computer languages is rather archaic when you think about it.

As a workaday sort of guy, it's not really. The code I'm writing at the moment is built on so many abstractions of the underlying storage, the atoms of functionality on the processor and other realities, that I am able to fairly naturally "think in" the language. My run-time makes decisions about sorting, searching, filtering, iterating and so on for me. The typing and context assumptions it makes, the terse nature of it (without golfing) - the attempt to divine my intent without so many words spilled, means I never feel like I'm doing busy work - the boiler-plating, the exception trapping and so on. Someone else's implementation of any given task I need to perform is probably a single command away from being available to me.

I may have twisted my imagination to its will, but we get on well now. I don't find it tedious and don't find I need an IDE or related tools to count the pennies.

Do you have a vision for a "next gen" (not quite Star Trek Next Generation - "Computer, extrapolate" level) programming paradigm? Are we talking an overhaul of computer architecture or will there always be some clever person writing our C for us? Abstractions all the way down...

Also, an AST for some given procedural code, when represented graphically, might look (superficially) like a Jackson Structured Programming diagram, which would have been created by hand... Maybe text is the wrong tool :)

Re:Functions Should Be Short And Sweet, But Why? by fuzzix on Monday February 03, 2014 @11:47AM (#7171672)
Edit window long closed. In case anyone goes looking at ImageJ for state machine UML code generation, don't.

I had confused it with LabView...

Re:Functions Should Be Short And Sweet, But Why? by robin_reala on Wednesday January 22, 2014 @04:37AM (#7101698)
Re:Functions Should Be Short And Sweet, But Why? by Geee on Wednesday January 22, 2014 @03:09AM (#7101406)
Check out NoFlo http://noflojs.org/
Re:Functions Should Be Short And Sweet, But Why? by tunesmith on Wednesday January 22, 2014 @03:05AM (#7101397)
I think some of the perception of how extreme it is has to do with what IDE the coder is using. For instance, in IntelliJ I can have the mouse on a method name and hit a keystroke to go to that method definition, and then another keystroke to go "back" to where I was. That's really helpful for jumping around and following a logical train of thought that goes through several small, one-concept methods - even across files. But, if I were having to deal with an IDE or editor where I was having to string-search and scroll, it'd be maddening and I'd wish for longer, more self-contained (multiple-concept) methods.
Re:Functions Should Be Short And Sweet, But Why? by henrik_w on Wednesday January 22, 2014 @03:35AM (#7101508)
I have the same experience. I coded C++ in Emacs for many years, then switched to Java in IntelliJ IDEA. I definitely write shorter methods now in Java, than I did in C++ (and it's for the better in my opinion). Navigation in general really is so much better in an IDE. More details in "Programmer Productivity: Emacs versus IntelliJ IDEA" http://henrikwarne.com/2012/06/17/programmer-productivity-em...
Re:Functions Should Be Short And Sweet, But Why? by gbog on Wednesday January 22, 2014 @03:23AM (#7101462)
There is another way, we do not need to be either in a big spaghetti blurb or infinite micro onions spread all over the place in multiple files.

With some work and some luck:

- all functions are short enough but all of them do something more than just passing things around.

- there is never any ambiguity on where a function's implementation is to be found. (In Python, I prefer "import x.y.z" then "x.y.z.myfunc()" than using "from x.y.z import myfunc", for this reason)

- like-minded functions are grouped together.

- functions are nice enough (read: testable and tested enough) so that there is rarely a need to check its code to use it.

Re:Functions Should Be Short And Sweet, But Why? by shangxiao on Wednesday January 22, 2014 @02:55AM (#7101371)
Yes code cleanliness would be something like a spectrum where there are instances of extremes on both sides.
Re:Functions Should Be Short And Sweet, But Why? by collyw on Wednesday January 22, 2014 @10:20AM (#7103003)
I am glad to see i am not the only one that finds tons of small methods / functions, with no obvious path through them makes code difficult to read.
Re:Functions Should Be Short And Sweet, But Why? by e12e on Wednesday January 22, 2014 @07:57AM (#7102287)
I think it (at least in part) depends a bit on the language.

When I tried to solve some simple Java exercises with classic Literate Programming (noweb[1]) -- I found that it helped enormously with simple top-down design -- but I ended up with pieces of code that were a lot smaller than the natural java abstractions -- it felt natural to factor out parts of loops etc... mostly this was me overusing the power that comes with literate programming -- but if done reasonably it could also be rather effective.

It allows one to start essentially with pseudo-code -- but that pseudo code often ends up dealing with stuff like arrays, that with (classic, pre-iterator) java implies explicit counter-variables (like "i") to keep track of an array pointer. So you suddenly get a problem reusing blocks of code, for an inner loop that indexes by "j".

At the same time it made for wonderful compact and readable code (where "code" means the Literate Programming document, not the actual java noweb emitted).

[1] http://www.cs.tufts.edu/~nr/noweb/

Re:Functions Should Be Short And Sweet, But Why? by mattmanser on Wednesday January 22, 2014 @04:23AM (#7101660)
Best way I've seen code like this described is Holographic code:

http://www.johndcook.com/blog/2012/01/09/holographic-source-...

It's as much a nightmare to work with as overly coupled code is.

Re:Functions Should Be Short And Sweet, But Why? by agumonkey on Wednesday January 22, 2014 @06:39AM (#7102016)
Funny, I've seen explanations like that for why natural language is full of redundancies. I used to want full DRY/zipped code but I understand the issues better.