Thursday, October 15, 2015

Why would you change the way you write your code?

When I first time adopted the way I write my code it was the way I learned so it was natural for me to write it that way. I sometimes came across the code that uses, for example query string inside C# like "SELECT SomeRow FROM SomeTable WHERE Something = Something" and that had perfect sense for me. But other times I came to something like "@ammount" and seeing it written in the same SqlCommand method/class, I tought to my self "Why are they using this when you can achieve the SAME thing with the way, I write it?" I wanted to know "Why?". What is the difference of using this from the other way and what is the reason to it?

Whenever I had a need to write an SQL query like "INSERT INTO someTable VALUES()" inside of C# I had to always take a really good care of what amount of "''' I do and how many spaces I have, debug with pointer to check how is my string being written and why I keep getting that error when I know that my query inside SQL Menagement Studio works. This is one of the reasons your code can be written differently. Main goal that we want to acheive here is to have a good readability.

Lets say you have inside your C# code written this:

string myQuery = "INSERT INTO myTable VALUES('"+ someVar +"','"+ someVar1+"', "'+someVar2+"')"

As you can see you can easily loose the track of how many "''" you wrote. Sure on this example it is not that hard, but imagine you have a query that checks if something exists (IF EXISTS) then you have UPDATE of some data then if that something does not exists and you then have to do a whole another set of values and you have 6 variables to fill...it gets really...really...easy to loose it. I mean really.

I know I was thinking when I used this way of typing like "well it works?! why does it metter?" but when you do this too offten you want something to read it more "easier". Better said, lighter way to read it.

One of the way we can do that is by writting the same query in a bit different way.


 string myQuery = string.Format("INSERT INTO myTable VALUES('{0}','{1}','{2}')",
                                            someVar, 
                                            someVar1,
                                            someVar2);

How does this look? Does your brain realease liquid of joy trough your eyes? I know mine did! Yet there is more. Sure this is a really good read of your code comparing to previous example. But what if you would have this query repeated everytime you need to check an IF ELSE statement? It would become a bit over-burdening that you would have to change, either, query or position of variables for each of those queries inside IF ELSE statments. I had 26 of them but I bet you can get higher then that. But then we get to a problem of a good maintaince of our code.

So how do we make our code more easier to maintain? In this case since we are using SQL queries, we will use that @funkyThing you probably saw but don't know what is it for. These things are called stored procedures. You should read how do you create one and check it out on your own, but for now you should know that your stored procedure can recieve some types of parameters. And you create these inside your SQL Management Studio database server.

Let's say you have stored procedure simple as this one:

GO
CREATE PROCEDURE mySQLProcedure
    @someVar int, 
    @someVar1 int,
    @someVar2 int
AS 

    SET NOCOUNT ON;
    INSERT INTO myTable VALUES(@someVar, @someVar1, @someVar2)

GO

As you can already probably see, you can always give to this stored procedure different parameters withouth changing your query at every possible place. So now back inside of your C# code you would write something like this:

var cmd = new Command("mySqlProcedure", CommandType.StoredProcedure);
                cmd.CommandParameters.Add(new CommandParameter("@someVar"));
                cmd.CommandParameters.Add(new CommandParameter("@someVar1"));
                cmd.CommandParameters.Add(new CommandParameter("@someVar2"));

if ( mySomethingString.Equals("ble"))
{
                 cmd.CommandParameters[1].Value =  1;
                 cmd.CommandParameters[2].Value = 2;
                 cmd.CommandParameters[3].Value = 3;
}

if ( mySomethingString.Equals("bleble))
{
                 cmd.CommandParameters[1].Value = 3;
                 cmd.CommandParameters[2].Value = 4;
                 cmd.CommandParameters[3].Value = 5;
}
. . .

This might look like "what the hell is this ?!?!" but when you think about it and actually see what is going on, you would see that now if you would at any point need to change values its much less time consuming, and more readable then you would otherwise need.

There is always a way you can optimize your code to gain this two things. Readability and Maintance. But if you still wonder "okey but why?!" as I did, good readability and maintance leads to a less error prone code. The less errors your application have the better it will work. Ofcourse, for your applications to be even less with errors there is something called Test Driven Development. And your readability and maitance will just help you with it.

I will not cover Test Driven Development here because there is a bit longer story and in most cases it will involve removing some dependancies in your code but for now, I hope this post helps you in seeing that what you change with your code is not always unnecessary as you would originaly think, but instead help you maintain the code of your applications with more ease.

Have fun and stay stronk!