Can the worst possible code ever get cleaned up? Apparently so!
Matt Gallagher has written a thoroughly brilliant piece showing off terrible application architecture and (more importantly) how to refactor it to be sensible. He starts with a scenario that you may already be painfully familiar with: no model separation, meaning that the data required for his app to work must be juggled between views and view controllers.
This in itself is sadly not uncommon, but to really drive his point home Gallagher ported some 20-year-old macOS code to an iOS app, to produce Mines for iOS – a Minesweeper clone that might look good enough to players, but was a festering vortex of appalling code underneath.
How bad? Well, to give you a taste:
Each of the SquareView objects (instances of UIButton) which represent the tiles in the game contains the following properties… This is not a cached representation of state store in another location, this is the only representation of the minefield, spread across the 100 different UIButton subclass instances used to display the minefield.
Now, anyone can write bad code – myself included! – but Gallagher's article is only just getting started, because his whole point is that even something this shocking can be refactored into a more modern, sensible layout. Even better, his GitHub repository provides before and after versions of the code so you can see for yourself what changed and why.
Towards the end the article discusses the whole point of separating your model, and that's where it gets really interesting:
Writing an application without a separated Model is considered the worst application design, not because it immediately leads to disaster but because it indicates that you’ve never tried to clearly isolate what your program does. We don’t write applications because we love constructing views and controllers – these are merely a means to an end. We write applications to present our Model, perform actions on it and view the results.
SPONSORED Stream’s latest iOS Chat SDK release provides a better developer experience with new docs, customizable attachments, and UI components, and under-the-hood performance improvements.
Paul Hudson is the creator of Hacking with Swift, the most comprehensive series of Swift books in the world. He's also the editor of Swift Developer News, the maintainer of the Swift Knowledge Base, and a speaker at Swift events around the world. If you're curious you can learn more here.
Link copied to your pasteboard.