Use the least amount of functions you need too. If you can condense functions together, do it.
Less functions > more functions
Brandon Sanchez
Why do you say that though? Personally I like to make lots of functions because it is easier to parse everything in my brain, but I have a feeling that isn't the right way.
David Gutierrez
Because by doing that, what you are actually doing is making the code more complex, harder to read, and harder to follow. No one likes bouncing around from function to function trying to figure out what's going on when you could have just condensed it to one. Keep it simple, stupid.
The best way to realize you need a new function is if you have behavior you want to replicate in your code.
>avoiding side effects and embracing a functional paradigm is a bad thing >simple functions make your code hard to read Is this the power of Indian software development?
Keep it fucking simple, separate all of your functions, and have a clearly defined pipeline in main.
Jason Walker
t. pajeet.
just write pure functions, and write tests for their domains
Benjamin Ramirez
Do not make tiny functions. That's a horrible programming technique to develop. A general rule of thumb is to only make a function if you are using the same code block more than once or twice in your code.
Mason Sanchez
This is an area where certain programming languages are simply better suited.
Nested functions are the best choice -- that way, it's clear what the overall program is trying to do and you don't clutter up the global function-space with one-use functions. Same goes for lambda/anonymous functions: when available, they're better-used than cluttering things up.
When nesting and lambdas aren't available, your best option is to tend towards writing small/tiny functions separately, as using too many comments or leaving things unexplained can hurt readability. *However*, this has some caveats: be sure that tiny helper functions are nearby and not located in random places; if that's not possible, try to explain what they do and how they work whenever it may be unclear based on the context.
For instance, let's say I'm writing some security feature for a website; this program is "security.py" or whatever. I have to import a function to determine prime numbers, which can call "prime?" or "is-prime". I do that, and I can now determine a number's primality -- however, for someone reading the code later on, they might not realize that I used the Miller-Rabin test, which (while fast) is just a really good heuristic and not a full guarantee of primality. If I make a quick note that "is-prime" is the Miller-Rabin test, all will mostly be clear.
All this said, you should *also* tends towards combining functions upon refactoring your code, if you find some/many functions only being used once.
Christopher Butler
Your code should be self documenting, so use as many functions as possible so that you have to write as few comments as possible. Each function should come with a comment header specifying what it does and the parameters it takes, if any of the parameters is for output, etc.
>make your code consist of properly named function calls >this makes it harder to read! Shoo shoo Pajeet
Easton Reed
I try to have my functions and classes do only one thing (within the limits of reason and practicality). This way the code is easier to unit test and debug. Since you can get the idea of what the problem is depending on where it crashes. It also improves code reusability.
Personally I don't really mind jumping from function to function but I can see why some people might.
Apart from that I believe that this methodology of programming sacrifices resources in order to improve code readability
t.mario spaghettino if you've ever had to maintain legacy code with function called by function you'd understand. and i'm not talking about something like this funcm() { func1() func2() func3() }
but something like this funcm() { func1() }
func1() { func2() }
func2() { func3() } 3 spaghetti function calls just to complete 1 task and some functions are not even reused, they're just there for the sake of who-the-fuck-knows.
Daniel Lopez
>Retarded example that makes no sense in some legacy code, maybe machine generated, who knows >And that's why this is bad Lel
Owen Mitchell
>What is abstraction? >What are separate concerns? >What is ease of testing? pls go back to india.
Aaron Campbell
>unironically defending spaghetti code tell me how i know you've never touched a single project contributed by more than 1 person if you want to test, write your own unit testing script and do whatever you have to before committing, don't push this shit on other people, their logic is different than yours, not everyone thinks the same way as you do.
Benjamin Johnson
Do you even know what spaghetti code is? It is big functions with mutable state and side effects, which cannot be reasoned about in isolation. The smaller your functions, the easier equational reasoning becomes, and the more coverage your tests will have. If the functions have no side effects, you gain composability and reuse. It is also easier to prove their correctness.
Connor Ross
>See in our team projects we constantly get laberinths of function calls that serve no purpose other than to confuse everyone >If you defend good code readability practices you obviously don't work with anyone else! Most of us don't work with Rahesh and his family, Pajeet. You're making no sense.
Isaac Martinez
read my post with the example again, modularity is good as long as you do it right. my second example is literally spaghetti code, it also disrupts your streamlined logic, would you rather read code from top to bottom or having to jump backwards every few lines, it's the equivalent of the abhorrent goto statements.
Lucas Ward
they are not mutually exclusive, what is this post
Jaxon Baker
Nobody here is arguing that if you take a good concept and apply it like a retard in ways that make no sense, that's good.
Cooper Sanchez
As many tiny functions as possible. If your function has more than 2 levels of indentation, make the innermost a new function.
Aiden Turner
Function calls are overhead just put everything in main.
Grayson Turner
Sure mr. tagliatelle. I highly doubt your functions have clear names that self-document. Having a trillion different nano-scale functions, each one taking fuckload of parameters doesn't make your code "easy" to read. A function candidate is, and will always be, if there's something that will be duplicated. Breaking down a function into smaller ones just because makes you a pajeet-tier programmer.
Jack Richardson
FORTH will have a word (or two or three...) with you.
Also, there are cases where you want to offload parts of your code into separate functions, even if they are only used once, namely readability.
For example, initialization of several variables/ data structures /whatever, or finding an initial solution in an optimizing problem.
Charles Ortiz
I had a professor who literally, unironically believed any method in Java should be at most 5-6 lines of code, because "functions should do one thing" and "smaller functions are easy to understand" While it does sound good in theory, after adopting this style for a while I realized it actually made my code harder to understand, because a single, logical piece of code would then be fragmented into tiny pieces scattered around. And these same people claim they "hate spaghetti code". Guess what, she also promoted a retarded bloated class hierarchy for even the simplest cases. I never used that style again after completing that class (it was a compiler class, and boy, writing assignments like that was painful) and ditched Java for good, but that's another story. Unironically, the most sane advice regarding functions is in the Linux kernel coding guidelines. Functions should do one thing, sure, but as long as they are conceptually simple and easy to understand, it's ok to have a longer function (think about a long switch statement). Just follow your common sense. I myself try not to write functions thare longer than necessary, but if the alternative is splitting it into tiny unreadable chunks, I'll keep it long.
Oliver Lee
and dont forget to inline assembly all for loops
Justin Thompson
Imagine reading a book that has a lot of words you don't understand. Would you rather keep switching back and forth between that book and a dictionary to look up the words, or would you prefer to just have an inline explanation at each place?
Blake Fisher
Many small functions is USUALLY ideal. Detailed comments are not only ideal but should be seen as mandatory.
Eli Miller
>Detailed comments are not only ideal but should be seen as mandatory. I strongly disagree, the best code is the one that it's so clear that it doesn't need comments.
Noah Torres
You should have a lot of small functions. In most cases, one function should accomplish one thing by itself, and have a name that explains clearly what it does. You should almost never have to write a comment that explains what a function does. Comments should be used to justify things that are not obvious (which, with proper coding style, should be rare), often some obscure bugfixes etc. Comments tend to get outdated as you modify the code. Also, read Martin's Clean Code instead of listening to Jow Forums fizzbuzzers.
Connor Evans
>Also, read Martin's Clean Code Worst meme ever. Read SICP or TAOCP. Clean Code basically just teaches you common sense (which you shoukd already have) workarounds to overcome the limitations of Java.
Henry Gray
That's a false equivalence. Books do not malfunction if written incorrectly. Programs do.
Brody Torres
A function should do ONE thing and do it well.
Benjamin Gray
>Books do not malfunction if written incorrectly. Programs do. That's why being able to understand them and read them effortlessly is even more important.
Evan Hernandez
This, but you should also avoid writing too big of functions. Anything above 100 lines should be split up into 2 or 3 smaller ones (unless there's no way to logically split it up).
There's also "cognitive complexity" from Sonar that says you should avoid deep nesting and complex conditionals in a single method.
Ryder Thompson
holy shit this thread is completely cringey, I can already tell only like 1 or 2 of the posters here are actually employed
Cameron Johnson
To add to this, I'd say you don't want a comment on your code unless you're doing something that looks strange or complex.
Maybe I'm different from other programmers, but I often find code easier to read than a description. I really hate when I see a function where every line is a call to a one line function. I don't want to read your awful method names to see what's happening. I'm a professional programmer, and I already have a gist of what your function is gonna do and what steps are involved. I'm looking for specific lines of code related to some bug, or trying to refactor your spaghetti mess. 99% of the time I'd rather deal with actual code than your "it reads like a book" bullshit.
Dylan Gutierrez
Agreed, as for nesting, take also Linus' wise words: >The answer to that is that if you need more than 3 levels of indentation, you’re screwed anyway, and should fix your program. Of course here "3" is strictly for C, the actual number may be different with respect to the language, but you get the idea. I'd say that the guideline "functions should do one thing" is valid, but the issue is that most people seem to think that "one thing == few lines of code", when it's not necessarily true. If this one thing is something as simple as computing a pure function (no side effects), but its actual implementation happens to be 40-50 lines of code, IMHO it may not be a good idea to split it, especially if the "sub-functions" that would result have no real use outside that computation and arr only called inside it. It IS a good idea, however, if the same sub-function is used in lots of other functions. In fact, an unpopular code smell is, in my opinion, many small functions that are only called once.
Austin Gutierrez
Then tell us what's wrong instead of saying "hurr durr unemployed".
Luis Parker
[citation needed]
OP, don't listen to him. I can tell you about a very complex project I'm working on. Right now our team is mostly composed by computer engineers or related working on legacy code made by not very clean programmers.
It is an unsustainable mess, where functions are very large with a chain of if-elses which do absolutely everything and have pieces of code just patched on top of it.
It took me an entire week just to figure out how to make this little change. My boss was anxious because I took half of the available time just to patch three lines of code, which is about 10% of the total task.
Now I'm facing the other 90% in the remaining week. But this time is different. The code I'm handling is new, done by our current team. In a pair of hours I completely understood where to touch and what to do. Even if I have to implement some major change, it's going to be a piece of cake which I estimate will take less than tomorrow.
Guess what! New code has a ton of functions with a VERY small length. That way you can focus on the big picture and enter in detail where you need to without having to worry about side-effects.
If you're worried about "too many functions", just group them logically and put them on a different file.
What you need is high cohesion (code is separated in logical groups: file handing is in the file module) and low coupling (code is independent of each other: you don't need the file module to play sound, even if tracks are stored in .mp3 files)
Ethan Miller
>In fact, an unpopular code smell is, in my opinion, many small functions that are only called once. Is this really an unpopular code smell? The first time I saw it I nearly had an aneurysm.
I agree that one responsibility doesn't mean one line of code. If I have a function called "sendEmail" it will call other classes to generate the template, send the email, etc. These are all functions already defined elsewhere. No need to write a function wrapping that function call. That's unreadable nonsense.
Asher Reyes
Neither. Make functions to do one atomic job and that they can be named in a sane way that relates to their function. Look at the parsing functions in the first part of craftinginterpreters.com, that's how it should look. Comments can lie and be outdated. Only use them when its necessary, like when there is some kind of unexpected workaround.
Jacob Martinez
>In fact, an unpopular code smell is, in my opinion, many small functions that are only called once. This.
Mason Kelly
Your team's code was an improvement, but making one line functions is taking it too far. Small, broken up functions are good, but splitting every line of code into a function is a mess and an antipattern.
Ryan Collins
I'm not the other guy you're talking about. Most of your improvements seem to come from a better separation of concerns, not so much about function size: the latter is merely a consequence of the former. I have no doubt that your current code is better than the legacy mess you were left to deal with, but that means that, in your particular case, better separation lead to small functions. That doesn't mean it will always happen. For example, a relatively straightforward LU decomposition function in C will take a little more than 30 lines. Should you split it? The answer, in my opinion, is no: 30 lines, while not super short, is still not an unmaintainable monstrosity, and the intermediate steps used within are not very useful outside this particular algorithm. So in this particular case, splitting doesn't make much sense. What I'm trying to say is that function lenght should end up being the CONSEQUENCE of good design, not necessarily something to design your code around. I said "unpopular" because I rarely see people complaining about it in general, but I personally consider it a smell.
Jace Rivera
Generally, a function should do one thing, and the name of it should make it obvious what it does.
I make separate functions if:
1. It's going to be called from multiple places (aka DRY - Don't Repeat Yourself) 2. It's a big long function that does a bunch of stuff, Eg a big business logic loop that's multiple pages of code.
>t. been coding for longer than some of you kids have been alive.
Mason Walker
The thing is, a function will always get called from at least 2 places: a) The place(s) which requires the functionality b) The place(s) which test the function.
Austin Russell
>write function to do matrix multiplication >program is fucked Thanks Linus.
Hudson Sullivan
While I agree it's dumb to create functions just for the sake of it, when in doubt it's usually better to go for an extra function. Especially in OOP, where you can turn those helper functions private. Writing a function such as "trim" or "isAdjacent" is often a oneliner which makes code more readable.
I'm fine with length 30 functions (as long as they're not an arrowhead ifelse clusterfuck). Also fine with length 1 functions where it makes sense. See What gives me a deathwish is those over9000 functions which do everything chaining code in conditionals and loops. And I'd swear there's some copy-pasting in there too.
Bentley Parker
The ArrayList example you linked is a good guideline, but believe me when I say that quite a handful of "clean code" evangelists would split the if/else branches of remove() because it's a whopping 15 lines, too long! I'm not kidding when I say some would split every function over 5 lines. There must be a limit. Again, common sense. If splitting makes your code clearer and the new functions are used in many places, go for it, otherwise don't. There is only so much that can be said about this issue however, since what is readable and what isn't is quite subjective.
Connor Richardson
Yes. Rules are there to provide guidelines, not blindly enforcing against our benefit. I suppose we can then agree functions are beneficial when they isolate a logical atom and make code more readable from the calling place.
Luis Wright
Gr8 b8, but remember: karma always balances its books.