DEV Community

Discussion on: How do you write your code?

Collapse
 
craser profile image
Chris Raser

Bob's answer is spot-on: It depends. But, in general, I follow the basics of TDD.

The first thing I do is hard-code the result I want to see, and then build a test to make sure that it works. So, for example, if I'm building a process that will use JS/AJAX to display today's weather for my location on a web page, I start by hard-coding the HTML on the page, and building a test that checks to make sure that the HTML is there.

From there, I write the JavaScript that populates the weather display. Again, still hard-coded. The original test still should pass.

Then, I'll write the AJAX call to retrieve the weather from a third party weather information service. I'll hard-code the location. The original test still must pass, and I'll write new unit tests as needed.

Next, I'll write the code to retrieve the current location, but I'll hard-code the return value. Original test still passes.

Then, I'll update the location code to remove the hard-coded location and have it determine my current location dynamically. As before, I'll write unit tests for this as needed.

At this point, I've built out the code to find my location, pass it to the weather service's API, retrieve the current weather for that location, and display it. All my tests pass, and I have a working solution for the original task.

Next, I start expanding the testing.

I live near Los Angeles, California, USA, but my code should work anywhere in the world. I write a test to make sure that my code still works if I travel to Helsinki, Finland, or Lima, Peru.

I'll look for potential points of failure, and make sure that my code will break gracefully if, for instance, the AJAX calls fail, or if the AJAX call returns the HTML for "500 Server Error" instead of the JSON I'm expecting.

When I'm done, I have a reasonable stack of automated tests, and code that I can be confident works as needed.

I find that coding goes pretty smoothly when I work like this, and I do less re-thinking, because I'm continually starting from code that works (in a loose sense), rather than trying to build separate components and then cobble them together.

If I'm working with existing components, I follow a similar pattern, but I make sure that the first things I soft-code use those components, since I don't want to make incorrect assumptions and have to rethink everything later. I start with the things I cannot change, and build around them.

I hope that's illuminating!