Ask HN: How do you deal with 2000 line functions?
I'm working with an archaic code base and I'm stuck at trying to add new business logic into a 2000 line function that is absolutely crappily written with nothing but if() conditions in it. Given such a scenario, how do I go about adding a new functionality to this mess? Should I tell my manager that the function needs to be refactored and take time to refactor it?
Edit: Removed offensive word
71 comments
[ 4.0 ms ] story [ 150 ms ] threadThe obvious refactoring is to split the function up into smaller pieces, even if you can split it into two 1500 line functions that is a win.
Tell your manager that you want to refactor it. Just don't tell your manager "it's shit".
The "don't say it's shit" was when speaking to the manager... not using it on your thread. Unless I'm the one misunderstanding the statement...
ForAll(x): Shit(x)
It's probably easier to do that than to muck around in the 2000-line version hoping you don't screw something else up.
Making the assumption that anybody is capable of sufficiently testing such functions and subsequently re-writing them will only introduce new bugs and old regressions.
Seems harsh, but I've had to work with a few such monstrosities. Global state galore.
2000 lines of code is a massive amount of behaviour to understand. There's a minuscule chance you can infer all that behaviour from reading the code unfortunately.
It's basically an abstraction over the entire database layer, that has probably over 30 toggles that denote where and how it should fetch data, given a table name and a function call.
And every database call in the entire project is dependent on it.
What you do is that you:
A) Realize that there might be years of hidden bugs, but also fixes to complex problems, speedups, kludges, weird changes to requirements, etc, hiding in the code, so even really creative unit-test might not cover real-world edge-cases.
B) Take as small bit as you can, and just refactor out the smelly code into smaller parts. Often a good name around smelly code helps a long way.
D) Iterate. Until good enough.But not more... Maybe you have more important things to do than rewriting ugly code that works.
There is a big risk that since you probably won't understand everything that goes on, and why - you will break something important.
1) Understand at a very fundamental level what it does (there are probably multiple things).
2) Understand at a very fundamental level what it does (this is really the hard part)
3) Document your hard-earned understanding (tests, ironically, do not work well for this, since there are no fundamental units to test at, and there likely is a metric ton of shared state)
4) Refactor it into something easier to understand and test.
I've had to work with a similar 5,000 line C function at the heart of a DSL parser; literally the core of the entire business. Changes were made very slowly, and with a lot of consideration. Refactoring is still underway 6 years later.
2. Read the function a few times to get a sense of what it's doing.
3. Break the function into blocks of statements that are performing a related task.
4. Factor those out into smaller functions.
5. Recursively repeat 3-5 until you're satisfied with the new functions' line count.
> Should I tell my manager that the function needs to be refactored and take time to refactor it?
It's absolutely worth mentioning. Time estimations are one of the harder tasks of Software Engineering. Being up front with your manager can help better set expectations.
Assertions are comments which can always be trusted and which never get out of date. It baffles me that there's so much reluctance to use them (especially in dynamic languages).
You can probably add some tests around the inputs/outputs, depending on the structure. For example you might have to check the database before/after and other things like that. But it won't be "unit" tests in the conventional sense. More like Integration tests, because something that long should not only be multiple methods, but multiple classes.
I would read the thing a few times and figure out exactly where to add the functionality. Refactor second, if time permits. If the thing is 2k long clearly, refactoring it isn't a priority.
Go to the part that you suspect you need to modify, identify a block of code that together forms something you can give a name, i.e. "initialize_doodad_struct", "validate_widget_params", pull it out put it in a function. Now look at all identifiers that are referenced or declared in your block of code, do a ack or ctrl+f through the 2000-N line function to 100% verify that they're not referenced anywhere. If they aren't you can safely encapsulate them in your new function (if you're working in a static language you probably could just right-mouse-click-extract to do all this).
Then immediately verify that the code still works. Run it, ideally in unit tests but most certainly also in real world(-like) scenarios. Do this for every small step. If your codebase takes 2 hours to compile, instead make a commit. Make a commit for every single 3-10 line extraction you do. (do it anyway, it'll look good and everyone will love you)
And then repeat until either the part you wanted to modify is clear to you, or there's nothing more to extract ;)
By the way, I'm a Ruby programmer mainly, and in Ruby any function over 10 lines is frowned upon. I know that in some programming language communities (looking at you C and C++!) a 200 line function doesn't raise any eyebrows, and they'll sometimes even scold you for extracting a function if it doesn't 'add' anything. I think this is because in C every function pollutes the global namespace, so there's a little more cost associated with it.
That is of course rarely the reason. From what I've experienced it's usually that the developer is uncomfortable with abstraction (at least that was my reason many moons ago).
Citation required.
https://robots.thoughtbot.com/sandi-metz-rules-for-developer...
I can see some view functions being a bit more, but that's boilerplate.
A function should do one thing. It's really, really hard to do one thing in more than a few lines.
I haven't seen any code that could not be refactored to be clearer and shorter. Not being a dick, but five lines is a lot.
e.g. symMerge(), quickSort(), etc.
http://www.amazon.com/Working-Effectively-Legacy-Michael-Fea...
(note: would be happy for you to have left the "offensive" word in - 2,000 lines of code for a single function screams for a refactor, and says that the original dev had no clue how to write good code. if the code makes you want to cuss, well....)
getting a feel for the structure of the function helps me understand it.
Ex:
function someFunction () {
In this case, the developer actually has return statements inside some if blocks. A general point that has stood out from all comments is to first understand how the function achieves what the function is trying to achieve.
Ferinstance:
It's easy to spot that there are really two paths through the method (depending on what thingy1? returns) in this simplified form, but rewriting it will make it clearer even in a 2k line function: This is also useful even when the 'if' clauses aren't identical - even then, there are frequently implied relationships (for instance, if one checks if something is positive and the other checks for zero) that can simplify things.The gist of it: a strong suite of integration and unit tests. Isolate small code paths into logical units and test for equivalency.
[0] http://www.amazon.com/Working-Effectively-Legacy-Michael-Fea...
If you add the new logic this time and also split it into four 500-line methods and maybe a few extra tests, you have done quite a lot and it is likely doable within the time frame of the work you are doing.
But
If there are zero tests and you aren't confident that you can create those tests then I'd bring it up with management. Maybe they'll say that changes in this functionality will be very rare after this small change and that it's very well tested manually and by customers - then that's it. Not all code has to be made concise and elegant, it's better to focus your effort on the code that regularly needs changing. However, in this case I'd ask management to consider not changing it at all, or make sure it will be very well tested manually after your changes).
or read the 'ol refactoring book...