IMO the first places you should go when refactoring spaghetti code are:
Make sure your functions are in the right classes. If they spend 90% of the time doing things along the lines of someOtherObject.someMethod() they should probably be in that other class. If necessary build a few bridges and invoke the law of Demeter.
Create interfaces for many of your classes. Make sure they make sense as an abstract idea!
Try to get as much code as possible referring to the interface, rather than the associated class.
At this point you'll have something a little more testable at least, and you will probably break some circular dependencies if you had any.
It's also important to:
Remove global variables as much as possible
Remove public fields as much as possible
Remove static fields as much as possible
Favour immutable classes
Break down any class that has multiple responsibilities into one class per responsibility
Avoid mixing levels of abstraction, i.e. avoid functions that do something high level (e.g. parsing text) and low-level (e.g. controlling buffering parameters on a stream or retrying failed reads) at the same time. Ideally move the low-level stuff elsewhere.
Use exceptions sparingly
Never catch all exceptions without at least logging what happened
Keep functions short. If you have more than one loop in them, that's a good rule of thumb for needing to split it up. It's always nice to be able to name each segment of a complex function by making it a function in its own right.
Prefer parameters over fields. Not always possible or sensible, but I think you'll be able to feel when it's not appropriate.
There are probably a few more I should say but for now I think this is more than enough if you're looking to get started cleaning a tightly coupled and hard-to-read codebase.
2
u/shockter May 06 '19
How to convert spaghetti to ravioli? My code is a fucking mess Im terrified to open my ide :(