Thursday, 5 June 2014

Do I really need a Hidden field?

As more and more SPA (Single Page Application) comes into life, maintaining state in the client side is critical for user experience.

Traditionally we use the following methods to maintain state in the client side.

  • Cookies
  • Hidden fields
  • Query string
  • JavaScript objects
  • Local storage
  • Session storage
The last two lean towards the "new" HTML 5 standard. Each has its pros and cons and I am sure a simple search will yield good dozen articles.

I was working on a legacy web application and used a hidden field to maintain state in the client side. During a code review, a fellow developer asked the question "Do we really need a hidden field?".

Hidden fields

Declaring a hidden field is ever so simple (e.g. <input type="hidden" .../>). Now consider the scenario where the hidden field is defined in a form (e.g. <form> tag). (how we are talking...!).

When the page posts back to the server, all the input elements including hidden fields are sent to the server. So the real question is whether there is a real value by sending this hidden field you used for client-side state management? If your site is getting millions of hits every hour, you would like to keep the traffic between client and the server to a minimum.

Set a "class"

My fellow developer suggested to store the state in a "class". Let me explain... Rather than setting a hidden field, add a class to the relevant container (e.g. div) and use JQuery $.hasClass function to check whether the class is set.

Initially this pattern did not register in my brain as I thought it was "odd" to store state as a "class" in the markup. But then again it was not totally insane. However there is the question whether you are bleeding "logic" all-over-the-place.

Use modern patterns

I totally understand that none of the above methods are elegant. But remember, few years ago data-binding in JavaScript was unheard of. Even the use of XHR/Ajax was not widespread.

The most elegant solution might be to use MVVM-type JavaScript library such as KnockoutJs.

It is not an easy task to convince a business to migrate core systems to latest libraries or packages. However as developers (for our sanity) we should attempt to structure code that is modular and easier to maintain!