DEV Community

loading...

Discussion on: Please refactor your code.

Collapse
dumazy profile image
Fré Dumazy

Be careful though, always go refactor with baby steps. Verify after every small change that the code is still working as it should. Automated tests are incredibly useful for this.
If you try to make multiple changes at once, it's easier to lose sight of what could be affected. Also, the combination of multiple changes will result in an exponential number of issues that can be caused.

One of the best and easiest way to refactor is to rename and move things. Learn the hotkey of your IDE to rename variables, classes, functions and files. It will make the code much more understandable for the next developer (or yourself after a few weeks)

Collapse
harshvats2000 profile image
HARSH VATS Author

Completely agree. Also it's nearly impossible still for me to change things and keep them still working. But that's the real learning I'm talking about, learning of your project's code and how it's working. The more you play the more you learn. :)

Collapse
rvxlab profile image
RVxLab

Be careful though, always go refactor with baby steps.

And for the love of god write tests. Having tests is the safest way to go around this, if your refactor breaks something your tests will catch it.

Collapse
dumazy profile image
Fré Dumazy

Big fan of writing tests and these are a blessing for refactoring, but there are some considerations to make.

  • Not all areas of the code are easy to test. UI is mostly harder to test than business logic, for example, and tends to change relatively fast, which requires updating the tests. In some cases, the effort vs confidence balance will be better with manual testing.
  • writing tests after a feature was made could be misleading (and boring also). The test would be written to validate the current state of things, instead of the requirement. There could always be a bug in the original code that hasn't been spotted, and you end up with a test that falsly says it's working fine.
  • To be able to test code, the code has to be written in a way that made it testable. Mostly this means having it "loosely coupled". Changing this during a refactor might lead you down a rabbit hole.
  • Writing tests is a practice that takes years to master. It's an investment in the long-run, one that might outlive the specific project or only give advantage after the deadline.

As always in IT, it's a trade-off. It's not "write tests" vs "don't write tests". It's about finding the balance between "effort" and "confidence" that's most fitting for the problem at hand.

Collapse
jaronsummers profile image
Jaron Summers

I usually write a terrible hacky mega-function that contains basically the entire application, validate that it works, write tests, and then refactor it to be reasonable, relying on the tests to do most of the work of verifying that it's still behaving.