|< How to add new features while still supporting old iOS versions||What skills do you need for large projects? >|
Recorded – watch the full episode on YouTube.
Often old code somehow evolves to not work any more, which might be an iOS change or a Swift change or something else. What approaches do you have for making sure old code remains useful and working correctly?
Carola Nitz: I usually try to cover it with tests as much as you can. Sometimes you can’t make unit tests because usually if you want to add unit tests to old code it usually means you need to break it up to make it even work. So before that even just having a simple UI test that makes sure your code does what you expect it to, and then you can break it up and at least have the confidence when you refactored something that it is still working the way you expect.
Paul Hudson: One of my favorite iOS writers, who doesn't get anywhere nearly enough credit, is Jon Reid from Quality Coding. He has a simple mantra that I've totally stolen because it's so good: if you're just changing your code and it isn't tested then that's not refactoring, it’s just rewriting. Refactoring is when you've changed your code so it has the same behavior afterwards as it had beforehand, and the only way of doing that is to make sure you have tests in place. That lets you be sure it was all green before refactoring the code and all green after, so your changes worked successfully. That's what tests do for you – they let you prove it worked correctly.
"Even just having a simple UI test that makes sure your code does what you expect, and then you can break it up and have the confidence when you refactored something that it is still working the way you expect."
So your answer I think has really nailed it in that if you have a big amorphous blob of code that Carola two years ago thought was brilliant – before we make any changes we should pull it apart into smaller parts, then do the simplest possible test to make sure it all works correctly. And then pull it apart, pull it apart, pull it apart; refactor it correctly and then check your tests again. Does the whole thing still work correctly? And if you want you can now add more tests for the individual components to make sure it's better, and this can turn a gnarly old piece of code into a rock solid piece of code for the future.
This transcript was recorded as part of Swiftly Speaking. You can watch the full original episode on YouTube, or subscribe to the audio version on Apple Podcasts.
SPONSORED ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.
Link copied to your pasteboard.