Javascript – Duplication of code (backend and javascript – knockout)

code-qualityjavascript

We have a new developer on our team. He seems to be a smart guy (he just came in so I cannot really judge). He started with implementing some small enhancements on the project (MVC3 web application using Javascript with jQuery and Knockout).

Let's say we have two values:

A - quite complex calculation    
C - constant    
B = A + C

On the screen there is value B and user can change it (normal texbox). When B changes, A changes as well because C is constant. So there is linear dependency between A and B.

Now, all the calculations are done in the back-end, but we need to recalculate A as user changes B (in Javascript, I would use knockout). I thought about storing old A and B and when B changes by 10 then we know that new A will be old A + 10. He says this is dirty, because it's duplication of code (we make use of the fact that they are dependent and according to him that should be only in one place in our app). I understand it's not ideal, but making AJAX request after every key press seems a bit too much.

It's a really small thing and I would not post if we haven't had long discussion about it.

How do you deal with such problems? Also I can imagine that using knockout implies lots of calculations on the client side, which very often leads to duplication of the same calculations from the back-end. Does anyone have links to some articles/thoughts on this topic?

Best Answer

I think real-time, client-side, more responsive interface features sometimes end up being an exception to the DRY rule in cases just like the one you've described. The need for responsiveness merits client-side code, but often one finds themselves calculating these values on the backend before passing them to the front-end; the values are then dynamically recalculated when the user adjusts the interface somehow.

One thing I can say for certain: this is not worth a roundtrip to the server, unless it's ok that your values on the front-end only update only second or more. Any less than that and you may have not only issues with responses returning out of order, but a certain jarring refresh behavior even if the former isn't a problem.

I've always thought that - at some point - this would be the main reason for using Javascript on both the front and backend but I dunno if anyone's ever taken a stab at a common code transport or something like that.

If anything, I would question whether or not it's necessary to have these calculations in your backend model/server-side code at all - perhaps you need to ensure the linear contraints between the variables are met for consistency reasons, ones of security, etc, but - if not, and if you don't explicitly call these calculations from somewhere in your backend - then I would suggest you consider taking them out of there.