DEV Community

Discussion on: What is bad code?

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

There's a lot of great answers in the comments already, but for what it's worth, here's what I've observed:

I agree there's a lot of relativity to it. What is "good code" or "bad code" depends on your language, your paradigm(s) (object-oriented, procedural, functional, etc.), your project, your standards, and so on and so forth.

However, I think there are some common traits of bad code, including...

  • Lack of clarity. If someone who has a reasonable grasp on the language cannot discern what it does, there's a problem.

  • Lack of readability. Different languages are capable of different levels of readability (e.g. in general, COBOL source is not going to be as readable as Python, for example), so we have to compare apples to apples, but when style convention and consistent formatting are ignored, the code is going to be an eyesore.

  • Poor naming. x, foo, and xztoab tell us nothing about what the variable or function does. Use self-commenting code principles.

  • Lack of appropriate intent commenting. Without going into the entire debate about commenting, many programmers agree that if the programmer's intent for a block of code is unclear from the code itself, that's what a comment is for. (Comment WHY, never WHAT.)

  • Lack of proper structure. Regardless of what paradigm(s) you follow, there are structures that the code should be organized into. When this organization is lacking or misapplied, we get spaghetti code. (Also, see below.)

  • Lack of clear responsibility. I think the single-responsibility principle can be applied to most structures, regardless of paradigm. A function for writing to a file shouldn't also be the home of the network-checking code. An object for storing high scores shouldn't also contain sound volume settings.

  • Magic numbers. What is that 976 doing in the super important math calculation? We have no idea! Important (and otherwise seemingly arbitrary) numbers should generally be named, usually by assignment to a variable or constant.

Long story short: code should be well-structured and well-formatted (as appropriate to the language/paradigm), (therefore) readable, (therefore) maintainable.

We could, of course, go pretty deep into the principles of clean coding, DRY, SOLID, and the like, but the exact rules will depend on your language and paradigm. (And even then, they're not a magic bullet.)

Ironically, I think most programmers can agree on what very bad code is. We mainly start having difficulty agreeing when it comes to what good code is, and that (again) depends largely on the nature of your language and paradigm.