News for hackers. Stuff that matters.
Re:Why Swift Guard Should Be Avoided by moonshinefe on Saturday January 02, 2016 @06:29AM (#10825881)
Has anyone seen production code with <=10 lines of code per function before? I've honestly never seen it, and I think at that point the code becomes harder to read because you're tracing through function definitions to decipher what a single function should do.

I usually notice functions get hard to read when they hit 80 lines or so long (generalization, of course), and try to keep mine under say 50 unless it's one of a few core functions in an application.

Interested in hearing others' experiences.

Re:Why Swift Guard Should Be Avoided by krylon on Saturday January 02, 2016 @06:57AM (#10825933)
> Has anyone seen production code with <=10 lines of code per function before?

I have seen code where a function was shorter than 10 lines. ;-) In that same code base, I have seen a function that was ~750 lines. And for that particular function, it actually made sense. It involved a lot of local state, and breaking it up would have involved passing lots of parameters to the new, shorter functions. (The average function in that code base was around 50-60 lines, I guess.)

Using a fixed number, like "10 lines" seems arbitrary to me. Sometimes it makes sense, sometimes it does not. It also ignores other factors, such as comments. Or readability. Sometimes, I 100+-line function can be marvelously clear, other times, a 5-liner can be so dense it makes my eyes bleed.

I have grown wary of "Always do this"/"Never do that"-advice.

"Try to keep your functions short. If they grow long, look if it makes sense to break them up into multiple shorter functions" is sound advice. But to do so without questioning or thinking is problematic.

Re:Why Swift Guard Should Be Avoided by SideburnsOfDoom on Saturday January 02, 2016 @07:49AM (#10826043)
> I have seen a function that was ~750 lines. And for that particular function, it actually made sense. It involved a lot of local state, and breaking it up would have involved passing lots of parameters to the new, shorter functions

If I was refactoring it, and 750 lines is a massive red flag that it is in need of refactoring; then the local state indicates that it becomes not a function or a bunch of functions, but a class with state and private methods. Is that hard to spot?

Re:Why Swift Guard Should Be Avoided by moonshinefe on Saturday January 02, 2016 @07:53AM (#10826051)
I actually missed that one part of his response when I agreed in reply. 750 lines is definitely a red flag for refactoring.
Re:Why Swift Guard Should Be Avoided by krylon on Saturday January 02, 2016 @11:10AM (#10826567)
Well, I agree that 750-ish lines is a bit extreme, but that function was a Win32-message handler. It basically consisted of a huge switch statement that figured out what the message was, did a little parameter mangling and then called a function that did the actual work.

So while that function was very, very long, it was relatively simple to understand and did not contain a lot of logic. Also, the fact that it was a huge switch would have made breaking it up slightly non-trivial.

Re:Why Swift Guard Should Be Avoided by SideburnsOfDoom on Saturday January 02, 2016 @11:28AM (#10826633)
Yes, the "big switch" is the canonical example of something that's hard(er) to break down and easy(er) to read as 1 function.

Though I would still try things like :

- making each case in the switch as small as possible, preferably a 1-liner.

- making a separate object that does the "parameter mangling".

- grouping all the bits of state into an object to hold the "message loop state".

- Or most radically but best: these "map", "lookup", "strategy" style patterns that reduce it to a table of (message id, handler fn) pairs http://stackoverflow.com/a/126453

Re:Why Swift Guard Should Be Avoided by krylon on Saturday January 02, 2016 @12:01PM (#10826749)
It was years ago that I worked at that company. Unfortunately, things like refactoring weren't very big there, and the other developers - who were, I should emphasize, really nice guys! - were not exactly open to change.

When I was hired there, that application had been in development for ~15 years, and a lot of what I did was maintenance. So making coming in as the new guy, then starting to change things, I had to tread rather carefully.

FWIW, I got each of the three developers to individually admit to me that if we had the time and the money, we would basically throw the old code out and rewrite it from scratch, using the lessons they had learnt since. But time and money being what they were, that was not likely to happen. (I was really proud I got them to admit that, though - one of the other developers was very defensive of his work, and getting him to admit that was quite an achievement; I actually gained some valuable people skills in doing so.)

I was glad, though, that the code was relatively readable and organized in a sane manner. There was some cruft that had accumulated over the years, but overall it was surprisingly sane. That was one of the first times I had to read somebody else's code, and it was good code for that purpose - sparsely commented, yet very clear.

Also, keep in mind that this was C. Different languages offer different ways of decomposing / structuring code.

Re:Why Swift Guard Should Be Avoided by moonshinefe on Saturday January 02, 2016 @07:36AM (#10826013)
Agreed.
Re:Why Swift Guard Should Be Avoided by jernfrost on Saturday January 02, 2016 @06:57AM (#10825932)
My impression is that it is somewhat influence by the programming language. Code I've written have often needed so many variables to do its job that it is very hard to split out small functions. But when you can use closures and higher order function easily, I find it easier to keep the size of functions down.

But I prefer Linux take on function size:

> The maximum length of a function is inversely proportional to the complexity and indentation level of that function. So, if you have a conceptually simple function that is just one long (but simple) case-statement, where you have to do lots of small things for a lot of different cases, it's OK to have a longer function.

Re:Why Swift Guard Should Be Avoided by rimantas on Saturday January 02, 2016 @07:04AM (#10825937)
You might want to see this: https://www.youtube.com/watch?v=npOGOmkxuio Not really about production code, but still, some food for thought. Also this: https://www.youtube.com/watch?v=8bZh5LMaSmE
Re:Why Swift Guard Should Be Avoided by SwellJoe on Saturday January 02, 2016 @09:02AM (#10826202)
Those are really excellent. I don't work in Ruby, but her explanations of OO design and refactoring are among the clearest, and most concise, I've ever seen. I'm gonna be watching her talks for the next couple hours, I suspect.
Re:Why Swift Guard Should Be Avoided by moonshinefe on Saturday January 02, 2016 @07:24AM (#10825982)
She seems like a great speaker, will bookmark for later. TY.
Re:Why Swift Guard Should Be Avoided by mercer on Saturday January 02, 2016 @07:52AM (#10826048)
Her book "Practical Object-Oriented Design in Ruby"[1] is also quite good

[1]: http://www.poodr.com/

Re:Why Swift Guard Should Be Avoided by jakobegger on Saturday January 02, 2016 @06:51AM (#10825924)
Maybe people just don't handle errors? Most of my functions are less than 10 lines, but then you add the error handling code, and it becomes 30 lines.

Also, it strongly depends on the code you are writing. Things like reading/writing data often end up as pretty long functions, while glue code between model and view is usually just a couple of lines.

Re:Why Swift Guard Should Be Avoided by SuddsMcDuff on Saturday January 02, 2016 @06:52AM (#10825926)
My general rule of thumb is that a function should be small enough to be entirely visible on screen without having to scroll. It's dependent on screen resolution & font size of course, but I find that having to scroll down adds some cognitive overhead to understanding the whole of a function.

Following this line of thought I've become a lot more precious about vertical whitespace & I've adopted BSD style curly braces.

Re:Why Swift Guard Should Be Avoided by moonshinefe on Saturday January 02, 2016 @07:29AM (#10825997)
Fair enough. I always found horizontal scrolling more difficult than vertical though.

But, for instance, the Python PEP8 spec saying 80 characters max, I think is kind of ridiculous these days. Who is programming on their phone, tablet, or 90s computer that can't handle 120 characters these days?

Edit: I just mention 120 as PyCharm's PEP8 linter 'erroneously' checks that max rather than 80

Re:Why Swift Guard Should Be Avoided by SuddsMcDuff on Saturday January 02, 2016 @08:21AM (#10826107)
Agreed horizontal scrolling is equally disturbing. We do live in an age of wide-screen monitors though so I find vertical whitespace more precious. I would go as far as saying that 160 horizontal chars is a more sensible guide these days.
Re:Why Swift Guard Should Be Avoided by whiddershins on Saturday January 02, 2016 @07:53AM (#10826050)
In my personal experience, the small function thing can drive a maintainer bananas.

When trying to understand code I haven't written, I have had the experience that trying to trace logic and debug through a bunch of little functions is more cognitive overhead than just seeing everything that happens within one larger function.

I get the idea that small functions are supposed to be wonderful, and clear, if everything is named really well and everything works as the name implies.

But for me the downside is it ends up feeling like detective work. I have to jump around and remind myself exactly how each little function works just to figure out what exactly is happening.

My dream IDE would let me see "expand" every function call ... like with little dropdown arrows .. so I could see it as if it were inline, and could trace execution linearly in one solid block.

Re:Why Swift Guard Should Be Avoided by eric_bullington on Saturday January 02, 2016 @07:36AM (#10826011)
> Has anyone seen production code with <=10 lines of code per function before?

It depends on the language. In Node.js code, it's not uncommon to not only see production code that follows this rule, but also puts no more than 1 or 2 functions in each file. Once you get used to it, and as long as you're quick with your editor/IDE's open shortcuts, I've found it a pretty nice way to organize code.

I personally find C code hard to follow sometimes, not because I don't understand C (I have more experience with C than I do JavaScript, if you count years), but because C tends to feature multiple functions per file, each with hundreds of lines of code per function. At least for me, that's hard to follow, and I hate having to move hundreds of lines up and down a file, even using Vim shortcuts.

Re:Why Swift Guard Should Be Avoided by hawkice on Saturday January 02, 2016 @07:34AM (#10826008)
I used to stick religiously to <=15, in C#. This was detrimental to understanding only twice, and a fairly small issue even then. Not a ridiculous standard for interns who don't have an excellent refactor-sense yet, so I didn't begrudge it back then.
Re:Why Swift Guard Should Be Avoided by Dylan16807 on Saturday January 02, 2016 @07:41AM (#10826021)
But in sticking to that standard, what was the effort balance between improving understanding vs. busywork to meet the guideline?

Edit: Huh? Why a downvote?

For a rule made with the goal of improving understanding, it's great that the rule is not actively detrimental to understanding.

But we still need to know how often it actually succeeds vs. having marginal effect.

We also need to know what it costs in terms of labor.

Without those two bits of info we have absolutely no idea if it was a good rule.

Re:Why Swift Guard Should Be Avoided by hawkice on Saturday January 02, 2016 @09:07AM (#10826217)
Extremely low cost -- considering how easy it is to pop in a new private method, no big deal. Seconds, and not that frequently needed.

Extremely low benefit -- I wouldn't even notice, and most actually confusing things are bigger scale, like the confusing DAL "abstraction" that I was dragooned into copying from the wider C# community.

Re:Why Swift Guard Should Be Avoided by lmm on Saturday January 02, 2016 @06:44AM (#10825912)
Yes. Seen and written. Maybe it's easier with a small team, and it's certainly easier with a good language (Scala in my case) but it's absolutely possible.
Re:Why Swift Guard Should Be Avoided by jt2190 on Saturday January 02, 2016 @07:21AM (#10825978)
The discussion is more fairly framed as: Do you use abstraction (hide details) in your code base? Number of lines of code is, perhaps, a symptom of code that doesn't use abstraction well, but isn't proof. We need to see the the code base, understand its design goals, and how it's actually used before we can pass judgement.
Re:Why Swift Guard Should Be Avoided by SideburnsOfDoom on Saturday January 02, 2016 @07:52AM (#10826047)
> Has anyone seen production code with <=10 lines of code per function before?

I've seen code where many functions were like this, and very few were over 30 lines. It was easy to read. And it was tested and generally working well. Naming becomes important, but that's part of the point of extracting functions for readability.

Re:Why Swift Guard Should Be Avoided by Etheryte on Saturday January 02, 2016 @06:40AM (#10825900)
Likewise, agreed. Very weird to see this article score high on HN.
Re:Why Swift Guard Should Be Avoided by merb on Saturday January 02, 2016 @07:06AM (#10825947)
I've written 2 line functions already. It depends. If you write scala or any functional language and you do pattern match it's sometimes more readable if you have something like

    blabla match {
        case 1 => func1
        case 2 => func2
    }

instead of

    blabla match {
        case 1 => 
            println("1")
            1 + 2
        case 2 => biggerFunc
    }
Re:Why Swift Guard Should Be Avoided by voltagex_ on Saturday January 02, 2016 @06:13AM (#10825849)
>What previously was a thirty-line function with several indentation levels and intermediate variables that had to be kept in the head is now ten functions, each having a self-documenting specific name.

My gut feeling is this wouldn't pass the unofficial code reviews at my work - too many functions making the code look messy, instead of cleaner.

Does anyone have any counterpoints?

Re:Why Swift Guard Should Be Avoided by static_noise on Saturday January 02, 2016 @06:31AM (#10825888)
To me the general idea of splitting a complex problem into a series of less complex problems is good. However the example used seems trivial and the solution is worse than the problem:

> 1. It is pretty long, sixteen lines, multiple parts separated by empty lines.

I wouldn't call 16 lines "long".

It contains empty lines for easier reading. Well done, not actually a problem.

But it lacks any comments on why the assertions have to be made.

> 2. It does several things. It gets an item by name, validates parameters, and it implements the logic of vending an item.

These are the things that naturally belong together. Separating validation from logic is not a very good idea. The logic requires the specific assertions in the validation part. They belong together.

> 3. It has several abstraction levels. The high-level vending process is hidden among the finer-level details like Boolean checks, usage of specific constants, math operations, etc.

In the single function implementation it's actually not hidden because it's all in one function. Use some comments to structure your function.

---

In my opinion separating this function into multiple functions would only make sense if these parts are used multiple times AND if they are commented well on why they need to act this way.

Re:Why Swift Guard Should Be Avoided by SideburnsOfDoom on Saturday January 02, 2016 @04:08PM (#10827951)
> However the example used seems trivial and the solution is worse than the problem:

That's more or less the problem when discussing how to work with complex, real world software and giving examples of how to do it: the examples end up being simple enough that the techniques aren't worthwhile in that case. Don't mistake that for the techniques not being worthwhile ever.

I have seen the same when code is presented showing examples of how to use an IoC Container. The response "but this overcomplicates the code" is true, but misses that it doesn't apply to the (far larger) codebase that IoC containers are aimed at.

Re:Why Swift Guard Should Be Avoided by deanclatworthy on Saturday January 02, 2016 @06:21AM (#10825863)
I feel the same. When I'm new to a code base its a pain to keep jumping around functions to see what they actually do. I agree functions should be short but this is a step too far for me.
Re:Why Swift Guard Should Be Avoided by KarlFreeman on Saturday January 02, 2016 @06:20AM (#10825861)
I feel like somewhere between the two would pass. Keep the validation as distinct functions but inline validatedItemNamed, reduceDepositedCoinsBy.
Re:Why Swift Guard Should Be Avoided by static_noise on Saturday January 02, 2016 @06:39AM (#10825897)
My problem with putting the validation in an own function is that this should only be done if the validation itself is generic like "check checksum" but not if it relates to the actual logic like "A must be smaller than B".

At first I wouldn't expect a function "validatedItemNamed" to check the price. While it checks the price it doesn't check the inventory number.

Re:Why Swift Guard Should Be Avoided by jernfrost on Saturday January 02, 2016 @06:51AM (#10825925)
This is just nuts. If you disregard the curly braces each of these guards are just two lines of code. When you place them into a function definition they each become 3 lines of code. Just so you can replace them with single lines in the original code.

That isn't software engineering. That is religious fanaticism.

E.g.

        guard item.count > 0 else {
            throw VendingMachineError.OutOfStock
        }
Is a very low complexity statement. One comparison is made and an enum value is thrown. You are gaining no clarity by placing this inside a separate function.
Re:Why Swift Guard Should Be Avoided by golergka on Saturday January 02, 2016 @07:10AM (#10825956)
This is an oversimplified example. When I imagine how both approaches would look like in actual production code with much more complex requirements, it makes much more sense.
Re:Why Swift Guard Should Be Avoided by DasIch on Saturday January 02, 2016 @07:10AM (#10825954)
Indeed. You should keep the complexity to a reasonable level, lines of code tends to correspond to it so it makes sense to keep the number of lines of code per function low.

The author doesn't understand the relationship, he blindly follows the advice to keep the number of lines low without considering the complexity and that leads to unnecessarily complex code.

Re:Why Swift Guard Should Be Avoided by therockhead on Saturday January 02, 2016 @07:09AM (#10825952)
Agree completely, it comes across that the author of the post has read some useful guidelines and created a strict rule which must not be broken.
Re:Why Swift Guard Should Be Avoided by lassejansen on Saturday January 02, 2016 @06:35AM (#10825893)
Re:Why Swift Guard Should Be Avoided by jakobegger on Saturday January 02, 2016 @06:45AM (#10825916)
A great example of how you can write spaghetti code without using goto: Just split a simple function into a dozen functions with generic names like "validate", and you've made sure no-one ever will comprehend your code.
Re:Why Swift Guard Should Be Avoided by panic on Saturday January 02, 2016 @06:20AM (#10825860)
Lots of short functions are usually worse than a single long function. When you go to figure out what the code is doing, instead of reading through each statement of a single function and understanding it as you go, you keep being interrupted by new functions you have to read and understand. What does "reduceDepositedCoinsBy" do? Yes, I'm sure it subtracts its argument from the deposit amount, but what else does it do? Could it be causing the bug I'm trying to fix? No, it just does the obvious thing, OK, now what does "removeFromInventory" do? And so on…
Re:Why Swift Guard Should Be Avoided by w0utert on Saturday January 02, 2016 @06:34AM (#10825891)
I agree. Obviously 'god functions' and 'god classes' are bad, but splitting up tightly coupled, related logic into piles of <10 line functions seems ludicrous. Not only does it hurt readability (and debugging) like you mentioned, but it also promotes false sharing of functionality. By splitting things up into very small functions many things may start to appear reusable. The moment it turns out one or two instances of the code that calls all these small functions need to have subtly different behavior you'll be hunting down each and every piece of code that calls the function, to be sure that changing it won't break completely unrelated parts of the code.
Re:Why Swift Guard Should Be Avoided by gnufied on Saturday January 02, 2016 @07:48AM (#10826040)
So, leaving aside the fanaticism around number of lines a functions should have which I disagree with, there are some big advantages of splitting a functions in logical units.

1. If you have ever written unit test for 300 line function you know it gets dicey. Such a function will likely require too much setup and will require complex mocks/patches/doubles to be unit tested.

2. As I mentioned before, I don't believe in number of lines thingy but logical unit of separation. If a function, opens a file, reads & parses config data from it, reads URL from the config data , parses http response and writes updated bits to config data - these distinct things can be logically separated and will be easier to unit test perhaps (again production scenario might be more complicated). Also, with modern IDEs and editors jumping back&forth between functions should be a breeze and your IDE/editor should provide an outline of file which can be scanned quickly.

3. If you have written a long function that does too many logical things(not again by number of lines) - next person who makes changes to it, isn't going to break it up - even if breaking up makes sense. For example, lets say in above example original code was written with expectation of certain format of config data but now somehow the function has to support more than one config data. Now the code is so tightly coupled that - it is harder to break out parser of this new format to new function and hence the function will keep growing (and did I mention the unit test setup has to support new config format as well somehow).

3. If however, lets say method computes moving average of a timeseries, it probably makes sense to have it all in one function even if it becomes slightly longer.

TL;DR - Cargo culting must be avoided at all costs, however we don't need to throw the baby with the water. Each problem calls for our own judgement. Separate the functions by logical units, rather than number of lines, use proper editor/IDE.

Re:Why Swift Guard Should Be Avoided by SideburnsOfDoom on Saturday January 02, 2016 @09:58AM (#10826350)
> Each problem calls for our own judgement.

Indeed it does, but if you have never even tried to go full "Uncle Bob" and write really small SRP functions and classes, then your judgement won't be well-informed. You'll be surprised how well it can work if you've never tried it. It works for readability, maintainability and testability.

Statements like the grandparent's "Lots of short functions are usually worse than a single long function" IMHO mostly show a lack of relevant experience.

Re:Why Swift Guard Should Be Avoided by gnufied on Saturday January 02, 2016 @12:57PM (#10826995)
Let me come out and say - I think OP is wrong. When people write 500 line long functions the only way they are going to test it is, run with real input and see if it breaks.

Such testing is not only insufficient, but any regression that is added as a result of a change will go unnoticed too, until a real user hits that bug. You will notice how most people who are supporting long functions - don't even talk about how the heck they are going to test it.

Re:Why Swift Guard Should Be Avoided by Dylan16807 on Saturday January 02, 2016 @08:04AM (#10826077)
>Cargo culting must be avoided at all costs, however we don't need to throw the baby with the water.

But at the same time, just because you can transform someone's point into an ultra-generic form that's true, doesn't mean their original point has any validity. When someone gives you bathwater, don't spend too long looking for babies that aren't actually in it.

Re:Why Swift Guard Should Be Avoided by gnufied on Saturday January 02, 2016 @12:52PM (#10826956)
You have gone wayy too meta for me to understand what you are saying. OP seems to make a claim that more functions hinder readability which is not true if you are using proper editor or IDEs, on other hand smaller functions enable unit testing and extensability which are pretty worthy goals if you are working on a project with multiple people.
Re:Why Swift Guard Should Be Avoided by Dylan16807 on Saturday January 02, 2016 @02:08PM (#10827397)
Its good to keep functions from becoming huge.

But when the article says that a function with 10 lines of code is too long and needs to be split up into a bunch of 3 line functions, that is a very extreme viewpoint. It's okay to flat-out reject such a viewpoint. It's not throwing the baby out with the bathwater.

Let's say I tell you that you need to cap your car's speed at 15mph to save gas. Don't go around telling people that "well, if you control your driving you can save gas, let's not throw the baby out with the bathwater". Just tell people I'm being dumb and to ignore me.

If the only thing true about a statement is such an extreme generalization that the generalization bears little resemblance to the original statement, just go ahead and reject the statement.

(Note: It's okay to agree with the article's view, that functions should be extremely short. This is only advice for disagreeing. I'm sorry for making my analogy intentionally ridiculous.)

Re:Why Swift Guard Should Be Avoided by alexjarvis on Saturday January 02, 2016 @06:25AM (#10825874)
Yes it's more cognitive overhead but it's a more functional than imperative style which usually has many advantages. If the functions are named well (naming being the hardest problem) then it should be easy to read without knowing exactly what the implementation of the function does.
Re:Why Swift Guard Should Be Avoided by Dylan16807 on Saturday January 02, 2016 @07:37AM (#10826015)
I fail to see how reduceDepositedCoinsBy is in any way more functional.
Re:Why Swift Guard Should Be Avoided by rimantas on Saturday January 02, 2016 @06:19AM (#10825859)
That says nothing about the guard itself, only about code organization. Ifs in some of his refactored functions can be as well guards. I think this is much better: http://radex.io/swift/guard/
Re:Why Swift Guard Should Be Avoided by cellularmitosis on Friday January 08, 2016 @03:20PM (#10867899)
Exactly. Here's a version of his refactored code which re-replaces the if statements with guard statements: https://gist.github.com/cellularmitosis/9a175facd5fe260403f1
Re:Why Swift Guard Should Be Avoided by alexjarvis on Saturday January 02, 2016 @06:18AM (#10825857)
I agree that you can split validation parts into separate functions but this is conflating two concerns, for example the rewriting of the guard statement from

  guard item.count > 0 else {
    throw VendingMachineError.OutOfStock
  }
to

  if count == 0 {
    throw VendingMachineError.OutOfStock
  }
only proves that you can refactor the code to not use guard whereas the article starts by talking about small functions, where you could in fact still use guard in this case.
Re:Why Swift Guard Should Be Avoided by rimantas on Saturday January 02, 2016 @06:21AM (#10825865)
Yes. And if all your code is composed of three-lines methods, then ok. Otherwise guard is extremely usefull, because unlike 'if' it leaves your constant/variable accessible outside the guard scope.
Re:Why Swift Guard Should Be Avoided by mhd on Saturday January 02, 2016 @07:43AM (#10826023)
If an article starts with basically "Because Uncle Bob said so", cum grano salis doesn't even cover my mindset when reading the rest of it.

Function size has been a pretty peculiar fetish. Even when viewed on the mythological 80x24 remote terminal, the initial function doesn't seem to be that hard to understand, and spreading it out between some function with lackluster naming doesn't really improve it all that much ("Computer science has two hard problems: cache invalidation, naming things and off by one errors").

Literate programming or the rather esoteric "refinements" at least had the advantage of being able to use proper sentences to describe the functional component and with the former you even had the option of being able to look at the code in both forms.

Having said that: As I'm not a Swift programmer (ba-doom-tish), is this all the language has that approaches Design By Contract?

Re:Why Swift Guard Should Be Avoided by SideburnsOfDoom on Saturday January 02, 2016 @07:47AM (#10826032)
> If an article starts with basically "Because Uncle Bob said so", cum grano salis doesn't even cover my mindset

Uncle Bob is a recognised expert in the area. So no, his opinions on SRP should not just be dismissed out of hand.

Re:Why Swift Guard Should Be Avoided by therockhead on Saturday January 02, 2016 @07:13AM (#10825963)
Re:Why Swift Guard Should Be Avoided by lassejansen on Saturday January 02, 2016 @06:27AM (#10825878)
I don't think it's useful to extract every guard statement into a separate function. Consider importing a json file where each field could potentially contain invalid or missing data. Sure, you could create functions like parseTitle, parseSubtitle, parseAuthorName etc. but these functions will probably only be called from one place and I don't think they improve readability.

On the other hand, I do think that larger functions should be broken up into smaller parts where it makes sense, e.g. a separate function for parsing each object in the json example.

Re:Why Swift Guard Should Be Avoided by SuddsMcDuff on Saturday January 02, 2016 @06:22AM (#10825867)
All too often, in every stack, the language is blamed for design deficiencies which lie with the programmer.
Re:Why Swift Guard Should Be Avoided by andrewchambers on Saturday January 02, 2016 @08:26AM (#10826120)
It seems foolish to take function length as a standard of good code. The example refactor looks horrible to me.

How about the function can be read top to bottom, doesn't mess with global state (unless it explicitly is documented as doing so), and has clear inputs and outputs. Who cares if it is 5,10 or 100 lines if it does that.

Re:Why Swift Guard Should Be Avoided by Dylan16807 on Saturday January 02, 2016 @07:29AM (#10825996)
So the example of a function that's too long, because functions should be 10 or fewer lines, is a function that has exactly 10 lines with code on them.
Re:Why Swift Guard Should Be Avoided by gelasio on Saturday January 02, 2016 @12:55PM (#10826977)
Guard makes things less readable because it "hides" variable declarations. If you break it out onto it's own line I'm sure it would make things look downright ugly.

"Don't put multiple statements on a single line unless you have something to hide" - https://www.kernel.org/doc/Documentation/CodingStyle

(If you disagree or if you think I said something wrong and my comment deserves to be hidden, I'd love to know why!)

Re:Why Swift Guard Should Be Avoided by realo on Saturday January 02, 2016 @07:35AM (#10826010)
This article seems to confuse clarity brought by folding code with versatility brought function reuse.