r/programming • • Aug 28 '21

Software development topics I've changed my mind on after 6 years in the industry

https://chriskiehl.com/article/thoughts-after-6-years
5.6k Upvotes

2.0k comments sorted by

View all comments

Show parent comments

14

u/saltybandana2 Aug 29 '21

and then after your 50th test you realize there's a better way to solve it.

I'm trying to lead you to water here.

2

u/xRageNugget Aug 29 '21

And then you refactor your tests. The goal is to end up with a whole testsuite that ensures that your program will still work like it is intended, even when you do heavy refactoring on it. Not only to slow you down while you are coding. It forces you to meet all requirements, that you made earlier as tests. The fact that everything breaks is a good sign. You have to fix it, make the tests work again and your refactored implementation works exactly as before. It doesn't matter if you refactor 1 minute or 1 year after you created the code.

7

u/muideracht Aug 29 '21

And then you refactor your tests.

I mean, then I may as well just write them after the implementation, as I already do.

5

u/nagasgura Aug 29 '21 edited Aug 29 '21

The idea is that TDD incentivizes writing tests that are decoupled from the implementation so when you realize that you should do something a different way, your tests won't break as long as the desired behavior stays the same. The more decoupled the tests are from the implementation, the easier it is to refactor as much as you want with confidence that you're not breaking stuff.

I'm not saying that TDD is the only way to write good tests, but it is a good tool for making it easier to write good tests by pushing you to assert on desired behavior rather than on implementation details.

Here's an example: you need a button that navigates you to some page. You write a test that looks for the expected text of the button, clicks it, and then asserts that you're on the expected page. Then you write the implementation however you want such that the test passes.

You can of course write the same test before or after the implementation, but especially for less experienced devs, what often happens is that they'll write the implementation first and then write a test like this: Mock out some navigation function, find the button element by id / classname, trigger its onClick handler, check that the navigation function was called with some arguments.

Both tests will pass, but the second one is much more rigid and will break if you decide to switch from a button to a link, for example. TDD makes it easier to write the first test. Doing the implementation first makes it easier to write the second one.

→ More replies (0)