Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Following the DRY principle in ASP.NET

Tags:

c#

asp.net

dry

I have just recently got involved in a classic ASP.NET project which contains lots of storing and reading values from the session and query strings. This could look something like the following:

Session["someKey"]=someValue;

And somewhere else in the code the value in the session is read. Clearly this violates the DRY principle since you'll have the literal string key spread out all over the code. One way to avoid this could be to store all keys as constants that could be referenced everywhere there is a need to read and write to the session. But I'm not sure that's the best way to do it. How would you recommend I best handle this so that I don't violate the DRY principle?

like image 217
user1467609 Avatar asked Jun 19 '12 21:06

user1467609


2 Answers

Create a separate public class where you can define your constants, e.g

public class SessionVars
{
   public const string SOME_KEY = "someKey";
   public const string SOME_OTHER_KEY = "someOtherKey";
}

and then anywhere in your code you can access session variables like this:

Session[SessionVars.SOME_KEY]=someValue;

This way you can get IntelliSence and other bells and whistles.

like image 160
Yuriy Galanter Avatar answered Sep 20 '22 16:09

Yuriy Galanter


I think you're reading too much into DRY. I pertains more to things that could be wrapped up in a function. I.e. instead of repeating the same fives lines all over the place wrap those 5 lines in a function and call the function everywhere you need it.

What you have as an example is just setting a value in a dictionary (the session object in this case), and that is the simplest way to store and retrieve objects in it.

like image 25
BlackSpy Avatar answered Sep 22 '22 16:09

BlackSpy