Lurker News
Recently I joined a relatively small company (50-100 employees) as a medium level software developer. For a while I was very excited about this opportunity.

After few days/weeks of getting to know the whole codebase I finally moved to a specific project I was suppose to work on and I found out the code is a complete mess. Often I find parts of code that unintentionally affects other parts of code. Some parts are just copied and left there doing nothing. Even names of classes/variables are sometimes useless and project structure is unintuitive and seemingly without rules. It's spaghetti and relatively big spaghetti (tens of thousands of LOC).
I started "repairing" the project but there're no tests to check whether my adjustments are correct.

I'm so frustrated and depressed by it. The job basically turned into something I hate - I'm just rewriting the code! The person in charge of this project was working on it alone and from the outside it all looks fine and it's working. So this makes the higher people think that it's all just fine. I really don't know what to do. Should I just go and basically say that this person did a bad job? I don't feel very comfortably doing that because (a) I'm a relatively new hire, (b) the person in charge is working there for about two years and (c) I'm much younger than she/he is both professionally and biologically.
I've already made some comments about rewriting it and the response was basically "ok".

Comments (333) 173 threads

Earlier comments
caymanjim4 replies#
Don't fix things just for the sake of fixing them. Let new features, bugs, or necessary performance improvements drive your changes. Keep your changes small and focused. You need to ensure that you're delivering business value with each change, rather than embarking on an overwhelming, open-ended task.

This is critical if you want the business to support your effort. It demonstrates pragmatism. It will shrink the scope of your changes and make the problem less daunting. You can prove to your boss and your coworkers that it's possible to fix the problem without slowing down new development efforts.
Be careful how you express your dissatisfaction with the code. Many of the people who wrote it are likely still there. Approach every change from a positive angle, so you don't alienate your peers. Get them to help you make the changes, and help them to learn how to become better developers. Don't assume they don't know better; they may have inherited a mess too, and they may have been under pressure to deliver quickly at any cost--or maybe they just don't know any better, but want to improve.
Read these books:
_Working Effectively with Legacy Code_ by Michael Feathers
_Refactoring: Improving the Design of Existing Code_ by Martin Fowler
_Clean Code_ by Uncle Bob
These are invaluable resources. There are many others, but these three are particularly germane to your situation.

marcus_holmes#
I would agree. Your job is to implement the new features and leave the code in a better state than when you found it.

As a professional programmer, your job is not to produce beautiful code. Your job is to make money.
There is a commercial decision for the organisation to make about paying back the tech debt in this code base. That's not your decision to make. Likewise, it's not your decision to create more tech debt if you can avoid it (sometimes you can't because deadlines are more important than tech debt).
As the parent said, your best course is to implement the new features, and refactor where it makes sense to do that to support the new features. But without any test suite, you risk breaking the existing features by doing anything more than the absolute minimum of refactoring. That's bad.
Good luck. And welcome to the profession hehe

arendtio#
I don't agree with the first part. I have worked enough time on the management side to understand that management is always driven by business value (it's their job). So your point 'Let new [...] drive your changes' is valid to some extent. But business value doesn't always mean that you need new features to justify working on a project. Sometimes it is possible to justify working on something just by explaining technical debt and how much time it will cost in the future (e.g. slow you down).

Working in an unstable environment can drive you crazy as a developer and lower your productivity enormously. So if you don't talk about the issues in the code base with the management, they might wonder why you have lower output then others and classify you as a slow programmer.
Instead, I think you should bring the facts to the table (slow down factor (number of bugs, time to trace them down), risks (likelihood of production issues)), in terms of how much time it costs to work within the current code base and let the management decide on how to proceed (make sure to bring a recommendation). If they are willing to let you spend time on improving the quality, try to modularize it so that if the rewrite will be stopped at any time, the time you spend refactoring it helps you in the future. While doing so, show respect to the programmer that worked with that code base in the past (even if she/he create that mess). You don't know under which conditions she/he had to work, how she/he learned to programme or what her/his life looks like outside the job.
The management basically has these options:
1. just minor changes to the code base: no rewrite, no hidden quality enhancements (might be a valid option if an alternative software is being developed already). 2. hidden improvement: no rewrite, but you are allowed to spend some extra time to improve the parts you are working on. 3. restructuring of the code base and systematically writing tests for different modules (recommendation). 4. complete rewrite: unlikely to happen unless it is cheaper than 2 and 3.
If the management decides to continue with option one or two, do the best you can under the circumstances be pragmatic as caymanjim wrote. Make sure to include option four so that the management sees the full spectrum of options at hand.

ebiester#
I came to recommend Feathers' book. Those strategies will save your bacon when you go to solve these problems. I put it in the "must read" list for all mid-level engineers.

To be fair, I put all three of those in my must read category.

rboyd2 replies#
Bookmark this page so that 15 years down the line in your career you can reflect on it. You will have delivered a working software product against all odds, under impossible budget and time demands. Finally they let you hire some help and instead of getting busy helping writing tests and refactoring he starts thinking about the best way to throw you under the bus to your superiors.
t12098#
This should be the top comment. At my company it is amazing how clueless young graduates play politics from day one, while doing no real work other than going from conference to conference and self-promoting on Twitter.
xtrapolate#
> "Finally they let you hire some help and instead of getting busy helping writing tests and refactoring he starts thinking about the best way to throw you under the bus to your superiors."

Here's what actually happens.
By that point in a project's lifecycle, that's not what they usually ask of the new hires. People are usually tasked with fixing bugs/maintenance, and implementing new business logic. Both of which are extremely challenging and stressful when working on a project that comes with no tests, or documentation.
Your actual task as the new hire is to start generating more value for the company, but that's so much more challenging when you have no way of validating your solutions, no infrastructure to rely on, and no metrics or documentation to consult. At that point, being the new hire, you're taking a lot of heat for not getting things done on time - mostly through no fault of your own. At that point, "wanting to throw you under the bus to your superiors" is a very natural response - it's a defense mechanism, you're (rightfully) frustrated. You're between a rock and a hard place. At that point you're no longer doing software engineering, it turns to politics/coverups/fire-extinguishing on a daily basis. Can you not relate to that?

haney4 replies#
Start writing tests, change no production code. You need to understand how it works (by reverse engineering its behavior with tests you’ll learn this) and you need to verify your changes don’t accidentally change existing behavior unless the existing behavior is verifiably wrong, and hey, you may find instances of this too, but don’t start making changes until you have a suite of tests that can spot behavior changes. There are times when things that appear to be bugs are actually weird features that the business needs to function. Sometimes cruft is actually a bug fix.

Start with high level integration tests of the most critical business processes. Then, work your way down to frequently used functions/classes/modules. After the whole thing is covered you can start cleaning/repairing, and I’d suggest doing so incrementally/as you’re adding new other features (make sure all new features come with tests).

askmike1 reply#
I think you are right, though in my experience in these situations is that defining the exact behavior is very hard. In not many cases was the messy code written messy from the start, it's usually an accumulation of changes (to behavior) - which are very hard to figure out.

I've found it's also hard to test code that isn't modular and split up: before you can test anything you need to mock 2 database connections, one external API endpoint and reading/writing from 3 different folder locations. Either that or you split them up yourself and risk breaking something.

haney#
So for a project that lacks tests, I’d suggest higher level integration/smoke tests so that you don’t have to modularize in order to write tests. Don’t mock a database, use a “real” test database with fixtures, if necessary use tools like Selenium and snapshot testing. These tests may be brittle and they may not cover all branches. But you’re looking for things like “can a user register”, “can an order be placed”. For http you can use tools like Charles Proxy to record / replay network traffic from real observations of the existing code running.
yashap#
Definitely this, though I’d say the first thing to address is good observability. Are all errors being logged, with stack traces? If it’s a web service, are errors rates and timings for all endpoints tracked?

Next, the deployment process. Are tests run on all deploys? Are there canary deploys to minimize impact when bad code goes out? Easy rollbacks?
After that, I’d address the dev environment. Can you run it easily locally? Can you easily attach a debugger?
After that, add end-to-end, integration, then unit tests, in that order. Only then, once you understand the code well, and have it nicely instrumented and tested, should you consider significant refactors. By that point, you may even realize that a lot of it is good enough and rarely touched, and doesn’t really need to be refactored.
If any of the above steps are already well covered, skip them. And don’t spend all your time doing this - talk to your manager(s), try to get buy in to spend say 1/3 of your time on the health/quality of the code, 2/3 on features/bug fixes/etc. Justify WHY - in this case it sounds like the code would be hard for anyone but the original author to modify with confidence, to make sure the code scales past this one person without the product becoming full of bugs and instability, it’s necessary to devote significant time each sprint (or whatever) to improving quality. Can frame it as “original author was just trying to ship quickly, and could keep track of all the hacks because they wrote them, but to bring more people onto the project it has to be made safer/easier to modify for non-experts”. Maybe wait until you’ve been there a month or three before you start pushing this.
At the end of the day, the code doesn’t have to be perfect, it just has to be decently easy to modify with reasonable confidence. Tests should catch most errors, monitoring should quickly catch the rest to minimize the impact. Work towards that, over time, without killing yourself trying to sneak in refactors that your manager(s) don’t know about.

akavel#
I once did a major cleanup at the start of my career. The above advice is closest to what proved successful to us, together with the response by JohnBooty https://news.ycombinator.com/item?id=17825093.

In our case, I think we didn't write a lot of tests, because we didn't know they're so useful then. But much later I did a few ports of FOSS software between programming languages, and comprehensive test suites were absolutely godsend in those cases. So, if you can, try to write tests as first thing indeed.
Other than that, we took a kind of "organism fighting a cancer" approach. In a spaghetti codebase, we tried to find some smallest possible islands of the most isolated code (a lot of detectivistic work). Then try to improve the isolation even more — slowly engulfing the "tumor" in a more reasonable API. Once we had a somewhat acceptable API, with mostly well understood semantics, rewrite the internals of the tumor from scratch. Rinse and repeat.
Notably, as mentioned by JohnBooty, we did talk this with management. It made our product release late by ~1yr. The argument was that there was a particular critical bug, which would result in lost consumer data. This one bug was found very close to original release date, and opened our eyes to the horrors in the codebase (actually, a big part written by a subcontractor).
Sorry if the reply is somewhat chaotic, I didn't have much time to write it.
EDIT: Also, I believe the term "technical debt" is reasonably good when talking with management/owners, as it has correct connotation of an investment at early stage, which however has to be repaid later at a cost.

herbst#
This is what i would suggest as well. I did some "rewrites" in my carreer and they only really went well when i worked long enough with the legacy code before. Essentially getting a feeling for what it really does, being that with tests (preferred) or by reading the same lines again and again while introducing new features/bugs.

If you feel the code is messy it is likely you are missing some essential business logic as well when blindly rebuilding it.

lexicality3 replies#
There's a book called "Working Effectively with Legacy Code" by Michael C. Feathers which I heartily recommend.

I got it a while back when working on a similar sounding codebase and it was very useful. It's got chapter headings like "My Application Has No Structure" and "I'm Changing the Same Code All Over the Place".
If your company has a books budget get them to buy it, but I'd personally drop the £35 it costs on amazon given how useful this has been to me over the years.

planxty1 reply#
Yes, so good. Martin Fowler's Refactoring is an excellent companion to Feathers' book.
jschulenklopper#
It will be worthwhile to know that a second edition of that book is expected to come out shortly.
ISL#
This book was written for OP (and many others). It specifically addresses the "there are no tests, what do I do?" concern.
flukus1 reply#
Is there a chapter on what to do if your coworkers don't initialize variables? I just inherited a steaming pile of legacy where they didn't and I'm struggling to understand how they got it to run at all. At least I'm starting to understand why we held off on the spectre patches.
lexicality#
Not explicitly, no, but it does have some techniques for reading code that might help?

Do you mean global variables? I guess it entirely depends on what language and framework you're using, but trying to refactor things to have less global state is generally for the best.

Load more comments