methodology

Is it considered bad practice to have too many functions for one file?


At what point should we consider code to be too cluttered? I'm near completion for making a search widget that reads into a database of files within a server and then displays it, but my code has over 30 functions that could potentially be refactored to be shorter and more compact. As an entry-level programmer still in university, is there a certain standard in the industry, or a methodology that people follow with regards to my question?


Solution

  • I believe a good industry practice is to have functions defined such that they provide a single obvious role. In other words, a function should do one thing and do it well.

    It's common to have functions be as much as ~25 lines of code but if it is more than that...perhaps it can be broken down. This is just a guideline.

    I would argue it's better to have many functions then too few which would commonly result in a monolithic mess.

    Also, having separate functions alone, the next step is organizing them into classes or modules depending on the language you are using.

    You may also want to read about cyclomatic complexity of functions. There are tools that can help analyze cyclomatic complexity but largely what this means is how complex the function is in terms of execution paths. More execution paths means more that needs to be tested, maintained and remembered when you are reading that function. A low cyclomatic complexity score is a good thing.