DRYer than thou

At work we have a project (launching Monday, w00t!) that has a lot of cool things happening on the browser side. You know kids these days, what with their jQueries and Web 2.0s, they need whiz bang special effects in their websites. In my day, we only had one type of input field in our forms, and we liked it! Don’t know how lucky they are… but I digress.

One problem we ran into was that we needed to do the same calculation on the server side and the client side. Let’s say for the sake of example that we need to calculate Michigan’s 6% sales tax or California’s 7.25% sales tax. The real calculation was only slightly more complex. One thing to note is that the calculation would need to be very responsive because it would be running a lot and affecting user input, so speed is a concern.

I came up with two options. The first is to write the same calculation in PHP for the server side and JavaScript for the client side. I didn’t love this because it isn’t DRY. If we had two calculations in two different files then when someone was updating the code they would likely miss the other one.

The other option I came up with was to put the calculation on the server side only and use AJAX to run it on the client side. This seemed overly complex, which will sound funny when you see what we decided on. We had avoided AJAX on the site because it wasn’t really needed; adding it for this seemed like a bad value/complexity trade off. I was also worried that server lag could cause a bad user experience, as I pointed out above the calculation needed to be fast.

So I was talking it over with my coworker Matt and he made a joke and we both laughed it off. Then we thought about it, and realized there there were fewer downsides to his approach than my two, so I started coding.

Continue reading “DRYer than thou”