7 ms·
Why Swift Guard Should Be Avoided
- jakobegger 11y agoA 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.
- jernfrost 11y agoThis 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.
- therockhead 11y agoAgree 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.
- DasIch 11y agoIndeed. 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.
- golergka 11y agoThis 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.
- voltagex_ 11y ago>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?
- KarlFreeman 11y agoI feel like somewhere between the two would pass. Keep the validation as distinct functions but inline validatedItemNamed, reduceDepositedCoinsBy.
- static_noise 11y agoMy 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.
- deanclatworthy 11y agoI 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.
- static_noise 11y agoTo 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.
- alexjarvis 11y agoI 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.
- rimantas 11y agoYes. 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.
- rimantas 11y agoThat 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/ http://radex.io/swift/guard/
- cellularmitosis 11y agoExactly. Here's a version of his refactored code which re-replaces the if statements with guard statements: https://gist.github.com/cellularmitosis/9a175facd5fe260403f1 https://gist.github.com/cellularmitosis/9a175facd5fe260403f1
- panic 11y agoLots 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…
- alexjarvis 11y agoYes 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.
- Dylan16807 11y agoI fail to see how reduceDepositedCoinsBy is in any way more functional.
- w0utert 11y agoI 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.
- gnufied 11y agoSo, 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.
- SuddsMcDuff 11y agoAll too often, in every stack, the language is blamed for design deficiencies which lie with the programmer.
- lassejansen 11y agoI 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.
- moonshinefe 11y agoHas 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.
- Etheryte 11y agoLikewise, agreed. Very weird to see this article score high on HN.
- lmm 11y agoYes. 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.
- jakobegger 11y agoMaybe 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.
- SuddsMcDuff 11y agoMy 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.
- moonshinefe 11y agoFair 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
- lassejansen 11y agoRelated discussion by John Carmack: http://number-none.com/blow/john_carmack_on_inlined_code.html http://number-none.com/blow/john_carmack_on_inlined_code.htm... https://news.ycombinator.com/item?id=8374345 https://news.ycombinator.com/item?id=8374345 Cached: http://webcache.googleusercontent.com/search?q=cache:LQgMUMTnhn0J:number-none.com/blow/john_carmack_on_inlined_code.html http://webcache.googleusercontent.com/search?q=cache:LQgMUMT...
- therockhead 11y agoAnother take on guard http://ericasadun.com/2016/01/01/another-take-on-guard/ http://ericasadun.com/2016/01/01/another-take-on-guard/
- Dylan16807 11y agoSo 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.
- realo 11y agoThis article seems to confuse clarity brought by folding code with versatility brought function reuse.
- mhd 11y agoIf 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?
- SideburnsOfDoom 11y ago> 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.
- andrewchambers 11y agoIt 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.
- gelasio 11y agoGuard 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 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!)