Just wondering about how to avoid Magic Strings in Querystrings? I have a lot of code like
if (string.IsNullOrEmpty(request.Form["projectId"]) ||
!int.TryParse(request.Form["projectId"],out projectId))
return null;
and naturally, I have to hardcode the projectId in the calling pages.
One way is to have a static/const “Dictionary” class that just defines a load of “QueryStringCreateProjectProjectId” identifiers, but then I have to change my JavaScript files to become server-side-generated.
Now, I realize that there is possibly no perfect solution for that because abstraction can only get to a certain extent, and at some point I have to put in strings and hope I never make a typo, but I wonder what solutions are?
Making this CW as this is borderline Poll/Subjective, but I believe that it belongs on SO.
For common request parameters, I created a class which knows all the ‘magic’ names (string constants) to create links to various pages in the site. I set a few properties, and the class emits an
<a>tag with the proper url. None of my links are hard-coded – all internal urls are built using this class.Another class uses the same set of constant string names to read the query string on a request. I create an object with this class when I receive a request, and my pages can then read the necessary values from this object (again, without having to know the magic strings).
Each area of the site which has its own set of ‘magic’ names outside the common set can add parameters to a link (using a method in the same link builder class), and then read them from a query string in the usual way. These should also use constants, to avoid typos.