I created a class that’s called UserSessionModel; in it I’m storing some data about the user and in particular I’m storing several json strings that are the results of queries and serializations.
I have several methods and properties in UserSessionModel that overall look like this:
public string SomeUserDataInJson1 { get; set; }
public string SomeUserDataInJson2 { get; set; }
.... 3 more properties like this
public int UserID { get; set; }
private void GetSomeUserDataInJson1
{
ObjectData1 TheObjectData1 = new ObjectData1();
UserQueries TheUserQueries = new UserQueries();
JavascriptSerializer TheSerializer = new JavascriptSerializer();
TheObjectData1 = TheUserQueries.GetData1(TheUserID);
this.SomeUserData1InJson = TheSerializer.Serialize(TheObjectData1);
}
This code is repeated 5 times, with the only change being the ObjectData, the name of the query and the property SomeUserData that’s getting set.
Is there a way to make this “better” with an interface or some other c# tools?
Thanks.
Ok, lets assume the following regarding to your example: You’re having data for processing with queries defined differently per user (userId).
Our data container class… very simple here, contains only a string.
Next step, lets have a look at the query… could be using that interface (could use events, for the response but lets keep it simple here).
You could have a relation to the user by adding the userId to the IQuery interface but I would prefer to have another interface to solve that:
This way you can alter your user to query resolving in a seperate place.
You’ll have a serializer/converter, too. Ok, lets make an Interface here for serialization of (processed) data.
Now, lets have a look at implementations, first of all the serializer… doesn’t do anything magical here and you should fill in the things you need for serialization of objects (JSON, …)
Now let us go to our Queries. I assume you’re not very familiar with design patterns and you’re meaning something like a Command Pattern instead (for processing jobs, see my link in the comments for more info about design pattern). 3 implementations follows as samples:
If we want to resolve which querys belongs to a user we need our IUserQueryProvider implementation. It is nothing more than a dictionary in this case (but could be easyly switched to other implementations).
Last but not least… the glue for everything. I added another Interface here for our “generator engine”.
To make it more flexible I made the interface/implementation following a design principle introduced by Ralf Westphal called Event Based Components (EBC). Google is your friend if you are interested in this topic.
And now lets put it all together and let us fly:
You should see something like:
As your homework… try to add your own query implementation and data to process. How would you add recursion here? 😉