DRY has become a mantra throughout the industry. Any time repetitive code shows up, DRY gets applied as a cure all. If you even start to question DRYing up a piece of code, you are viewed as a heretic to the entire industry.
Ok, maybe it’s not that bad, but many times DRY gets applied without much thought. This careless application of DRY leads to brittle code, making even simple changes scary because they could have a huge ripple effect.
I often see this problem in the testing world, particularly around frontend tests that utilize UI automation tools.
The pattern I see is often to abstract chunks of common steps into individual functions that often live in places very disconnected from the test. While this might reduce the number of lines of code in a test and arguably make it more maintainable it has its problems.
Main problem number one is that readability has been diminished. It is now harder to understand exactly what this test is doing because steps have been abstracted away. Tests that can be clearly understood, read and describe functionality and behaviors are immensely important to getting others to quickly understand code. I hate to put a barrier there to making that happen.
Second, i don’t truly believe it ALWAYS improves maintainability. This decision of abstracting carries a risk. When that abstraction needs to change in one place you are faced with a tough choice…
Does this need to change in ALL places? How do you know? How can you get all places it is used and be certain it has to change in all of them? Changing for all usages is RISKY particularly when there are large numbers of uses and you don’t know what they all do.
Do i make a new abstraction? This is safer but now starts to create bloat. It will lead down paths of making future implementations trickier because there are now two things to choose from that are possibly slightly different.
For tests I’m not really convinced that these problems are worth dealing with. Keep it simple and understandable. Repeating yourself for the sake of clarity is okay. I’ll say it again… Repeating yourself for the sake of clarity is okay!
These seem like questions that are equally important and hard to answer regardless of whether you’re using abstractions, although abstractions have a big advantage in that you can find all the sites where they’re used much more easily than you can find all the places where a piece of code is duplicated (or worse yet, duplicated with slight changes).
Yeah, I’ve seen this a ton. And it sucks because it’s always done with good intentions.
That’s why I think that if you need small helpers keep them short and prevent them from going too deep. Nothing is worse than digging through 10 layers of functions just to figure out what’s going on.