3 ms·
After I learnt about refactoring, decades too late, mainly from Refactoring and Clean Code, I spent at least a week refactoring a program of maybe a few hundred
by yesenadam 6y ago
After I learnt about refactoring, decades too late, mainly from Refactoring and Clean Code, I spent at least a week refactoring a program of maybe a few hundred lines. It was amazing how much even such a short program can be improved in every way. It's the same as the difference between a horrible first draft of an article/essay and the 20th draft. Since then, I program in a way that's already "semi-refactored", and far clearer. And refactor/improve as I go. A lot of bugs and potential problems become apparent. The difference in my programs before/after is like night and day. And they're incomparably easier to understand when I return to them a year later. That was after 25 years of leaving it at the first draft stage, so people can change, don't worry! "To write clean code, you must first write dirty code and then clean it." Exactly as for prose writers, noone writes a good first draft. You write something bad then edit it again and again.
Also, I've always known that the more time spent with pen and paper before starting to type, the less time it will take and the better organized and thought-out the program will be.
To be specific about the refactoring/clean code, it's basic stuff like: Use spacing to make maths clearer (e.g. write 2x4 + 7, not 2x4+7). Functions that do one thing, with names that perfectly describe what they do. Variables perfectly named, used for one thing, grouped appropriately in data structures. Move comments into code. (Not "//this bit computes the size" but put it in a function called ComputeSize.) No magic numbers. Basic stuff that somehow I'd never focused on before...
I'm not into "forcing myself" to do anything, that doesn't sound like a good way of thinking about it! But maybe taking one of your messy programs and editing/refining it until it can't be improved further will inspire you like it did me.