Showing posts with label Best Practices. Show all posts
Showing posts with label Best Practices. Show all posts

Thursday, May 7, 2015

Documentation

One day in your coding career (preferably early) you'll reach the point of:  I wrote this weird thing  and for the life of me can't recall what I was attempting to accomplish.  Where'd I go wrong?  What could I have done back then that would've saved me countless hours in the future?  Document your code!

Techniques:


Chances are if you went to college to learn to write software they may have emphasized self-documenting code (aka naming your for loop variable i or x when looping through a list of table rows you could've named the variable rowIndex or something more definitive).  If not, it's a great idea to try to implement self-documenting coding techniques.  Your present and future colleagues will appreciate you more for that one.

Another option is to put in the occasional comment or two.  Generally speaking if I can't rationalize what an obscure block of code is doing (happens quite a bit out in the wild) I throw in at least some documentation on what that block of code is attempting to do.  That way future me and present me can be on the same page quicker than not so future me can determine what action to do next to it more efficiently than if it the coding block wasn't documented.

The last option is putting your pseudo-code into comments near your obscure block(s) of code.  If nothing else future you (or your colleagues) can try to see what present you was attempting to do in the source code.  This form of documentation is one I've been trying to implement in the past six months or so, so far I've used it a few times when the self-documenting code as well as the comments for each block might now give future me (or a colleague) an idea of what present me was attempting to create.

Conclusions


Documenting your code might seem like a bit of a hassle but in the long term it'll save future you (and potentially your colleagues) time to debug/determine what your present code is doing.

Shout outs:


I have to give credit to Peter Hyde and Bobby Russell for blogging along for quite some time now, keep up the great work guys!

Wednesday, September 24, 2014

JavaScript Pollution

Intro

Everyone knows pollution is bad. It turns rain acidic, makes our roads look terrible, fouls our drinking water, and can cause naming conflicts in our JavaScript code. What? Yeah that's right, our JavaScript code. Write your congressperson I tellz ya! It's a huge problem. But don't fret, there are ways you can mitigate this danger to our very way of life, and I'll show you 2 simple things you can do to lower your global-carbon-JavaScript-namespace footprint.

Que?

Polluting the global namespace is a common term for a common practice in JavaScript. When I create a plain old function in JavaScript such as the following:

function someFunc() {
    window.alert('some text!');
}

someFunc();

I've now committed a cardinal sin, right up there with sloth and eating the last Oreo. I've polluted the global namespace! See how the function someFunc is just floating around in the ether, available to be called from anywhere and without a class or namespace prefix necessary? This is what polluting the global namespace is. This might not seem like a big deal to you. I mean, so what? You're the one writing this code and it's not like you're going to conflict with your own function names right? Well JavaScript is a very open language, and many people these days use multiple 3rd party libraries. Now pretend all these 3rd party libraries are also polluting the global namespace. You'd have naming conflicts between the 3rd party libraries and with your own local code, and that would be quite painful to deal with. How can you, the lowly programmer, prevent your own code from polluting the global namespace? For those of you used to C#, the answer should come naturally: namespaces and classes!

Namespace Example

There are many ways to skin a platypus, and there are many ways to create a namespace in JavaScript. I won't cover all of them, I'll just show you my favorite:

var MyNamespace = MyNamespace || {};

MyNamespace.myInt = 3;


It doesn't get much simpler than that. The first line of code creates our "namespace". It's not really a namespace as JavaScript doesn't support namespaces, but we can useMyNamespace quite similarly to how we us namespaces. We can even nest them if we feel like it. The 2nd line of code just adds a variable named myInt to our namespace. If you want to later created a 2nd javascript file and reuse your namespace, all you have to do is copy that first line to the top of your new file. The magic here is that when we declare MyNamespace, we set it to itself, or if it's undefined, we set it to an empty new object. So if you do this in 1 file or 50 files, you'll either create a new "namespace" object or assign the namespace object to itself, so it works quite easily.

Class Example

Classes take a little more work but they're still not too bad. Here's an example of how to define a class, create an instance of it, and then use it:

//set namespace
var MyNamespace = MyNamespace || {};

//create our class in the namespace
MyNamespace.MyClass = function () {
    this.stringProp = "some string";
    this.intProp = 42;
};

//add the method myFunc to our class
MyNamespace.MyClass.prototype.myFunc = function () {
    window.alert(this.stringProp + "::" + this.intProp);
};

//create a method within the namespace (but not in the class) that creates an instance of the class, sets a property of the object, and calls a method of the object
MyNamespace.doThisStuff = function () {
    var myObj = new MyNamespace.MyClass();
    myObj.stringProp = "yep, still a string";
    myObj.myFunc();
};


The first chunk of code you've seen before; it sets up our namespace.
The 2nd chunk of code defines the class. More accurately, it defines the constructor for our class, within which we also define our class properties stringProp and intProp. We set them to default values too.
The 3rd chunk adds the method myFunc to our class. I won't get into the keyword "prototype", but suffice it to say you should use it when setting methods of your classes so that the method will be instance-level instead of static/class-level.
The 4th chunk of code is a namespace-level method that creates an instance of our class via the new keyword, sets a property value on the instance, and then calls a method on the instance.

All you would have to do now is setup an html file to call your code and you're good to go. You can create as many instances of the class MyClass, which is defined in the namespace MyNamespace as you want to. Have at it!

Summary

I hope you can see the great benefits of using classes and namespaces in JavaScript (well, the strange equivalent of them anyways). Polluting the global namespace can be a tricky problem if you run across it, and preventing the problem is quite easy. Plus it makes your code easier to organize, and in my opinion easier to read. Try it out! It's easy I promise, it just takes a little practice.

What's Next?

  • Read further on objects in JavaScript, and how JavaScript doesn't really support namespaces and classes (we just faked it).
  • Do some more reading on other ways people have come up with to emulate namespaces and classes in JavaScript. You might find one that you like better than what I chose!
  • Learn how to nest your namespaces.
  • Learn how to do inheritance. It's kind of tricky for a language that doesn't really support classes.
  • There is another way to create an instance of a class, Object.create. Read about it.

Resources

Introduction to Object-Oriented JavaScript
My Code

Wednesday, September 10, 2014

2 Simple Best Practices for C# Database Coding

Intro

In my many years of .Net coding, more than I'd like to admit sometimes, I've seen a number of mistakes over and over again by people who just don't know any better. I've got 2 in particular that I see when people hit databases with .Net code, and I figured hey, I can call these out so people know not to do it! So here they are.

Best Practice 1

Always, under all circumstances, close your connection to the database. This might sound like common sense, but it's not always as easy as just calling connection.Close(). What happens if your code throws an exception between Open() and Close()? If you don't have the Close() in a try finally and if you're not creating the connection in a using statement, you're leaving that connection open. What happens if you leave those connections hanging? My experience is with SQL Server, and with it you end up eating up all the available connections eventually, which means your queries fail because you can't open any more connections. In the case of a website it means you have to recycle the app pool to free up all those connections, which can be a bit annoying for your users. Let's see some potentially bad code in action first:

using System;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    private void BadSqlConnection()
    {
        var conn = new SqlConnection("some conn string here");
        conn.Open();
        var cmd = new SqlCommand("select * from SomeTable", conn);
        cmd.ExecuteNonQuery();
        conn.Close();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        BadSqlConnection();
    }
}


See the problem? If the SqlCommand cmd throws an exception of any kind, that SqlConnection stays open, eating up one of the connections in our connection pool. Bad! So what can we do to clean it up? My favorite thing is to use a "using" statement. It accomplishes the same thing a try...finally would, but with less code. Here's a sample of some good code:

    private void GoodSqlConnection()
    {
        using (var conn = new SqlConnection("some conn string here"))
        {
            conn.Open();
            var cmd = new SqlCommand("select * from SomeTable", conn);
            cmd.ExecuteNonQuery();
        }
    }


Using the using statement when we create the connection ensures that the connection will be closed and freed before the method ends, regardless of whether or not any exceptions are thrown. It's conceptually the same thing as a try...finally where the Close() call is in the finally. Neato!

Best Practice 2

SQL injection attacks suck! It's a very common way for chodes to attack your data-driven website. Pretend you have a textbox on your website where people can login via userid and password. You've got 2 entries on your page and a button, one for the userid, one for the password, and the button attempts the login. Maybe your login code looks like this:

    private void DoLoginBad()
    {
        using (var conn = new SqlConnection("some conn string here"))
        {
            conn.Open();
            var cmd = new SqlCommand(String.Format("select * from Users where UserId = '{0}' and Password = '{1}'", UserId.Text, Password.Text), conn);
            var reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                //stuff that logs the user in
            }
        }
    }


What's bad about the above code? Think about what will happen if this value is put in the UserId textbox: "peeticus'--". Looks pretty innocuous right? Absolutely, completely, horribly wrong! Think about what this value does to the query which is sent to SQL Server; it now becomes "select * from Users where UserId = 'peeticus'--' and Password = '[blah]'

The key thing there is that our sql statement is terminated after checking the UserId because of the ending of the string value via the apostrophe, then the double-dash "--" which makes the rest of the line a comment. So, with this fairly trivial attempt somebody could log into your system as any user for which they know the userid. Believe it or not there are much worse things they can do with this tactic too, but we'll save that for another day.

How can you thwart the evildoers? Conceptually speaking you need to filter out bad characters such as apostrophes and maybe dashes, or filter in good characters if you want to be even safer. A better idea though would be to use the built-in sql parameters within .Net so that a well-tested library can do the work for you! Here's the same query from above, rewritten to be resistant to SQL Injection:

    private void DoLoginGood()
    {
        using (var conn = new SqlConnection("some conn string here"))
        {
            conn.Open();
            var cmd = new SqlCommand("select * from Users where UserId = @UserId and Password = @Password", conn);
            cmd.Parameters.Add(new SqlParameter("@UserId", UserId.Text));
            cmd.Parameters.Add(new SqlParameter("@Password", Password.Text));
            var reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                //stuff
            }
        }
    }


All you have to do is replace your concatenated values in the query with a couple parameters using @ symbols, and voila! A couple extra lines of code for a lot more peace of mind.