Clever code never did no-one nay but no good. Not know-how, not no-way.
Yeah, I’m not sure what I just said either. I do know that “clever” and “slick” are words that I don’t care to hear about code, or a coding solution to a given problem. Code needs to be simple. How simple? As simple as possible [but no simpler, yadda yadda yadda]. “But my code IS simple” you say. I’m done.
…just one more thing. Do all your methods only do one, and only one, thing? Yes, I said all.
Every method (or function) should accomplish only what it’s name says it does. If you have a method “saveThing” it should only save that thing. It should not check for something else, optionally set a flag, make any other call, then save that thing, and return the price of tea. It should only save the thing. This means you will have many very small methods.
At a high level this will lead to something really powerful: Readable code. You see, as your fine granularity builds upwards you are essentially utilizing the ‘composition design pattern’ in a micro-economy.
What are some signs that you may have code that can be refactored into it’s own method?
- Length. If a method is growing beyond 10 lines, take a close look and make sure it’s still doing only one job. As methods grow they want to do more than they should. You can’t convince me that 1,000 line method is as small as it can get.
- Unused parameters or only using one or two variables off an object. Too much data will lead to putting process in the wrong place. If you don’t have the data you can’t do the wrong thing with it. Don’t pass in a few extra objects just in case. If you don’t need them pull them out. Use static analysis to remove unused and dead parameters (and code blocks). If you really only need to do work on a username… just pass in the string, and not the whole user object.
- Comments. If you feel the need to explain a section of code inline, it should be it’s own function with a well suited name. You either use too many comments (rare, and not cool but that’s another topic) or you use one or two in confusing places. That’s the tingly feeling you’re trying to learn that says “put this code in it’s own method”.
This is the path to better code. Code that does what it says it does, nothing more and nothing less. It sounds so simple, but is the essence of a truly powerful system. Keep your code dumb, you’ll thank me for it.
P.S. I know it’s spelled “stupid”. 😉