Thursday, September 11, 2008

Programming the hard way


On several occasions in my short life I have ran across coders that insist on not using the prebuilt classes and functions that come with .net. I can understand not using a 3rd party lib when you write the entire product for the ground up, but if you are using .net you might as well use it to its fullest extent.
Take the following code:

 9    using (FileStream fs = new FileStream(FilePath, FileMode.Open))
10    {
11        using (BinaryReader br = new BinaryReader(fs))
12            rawTiffData = br.ReadBytes((int)fs.Length);
13    }
14    tiffData = Convert.ToBase64String(rawTiffData);
15 
16    string name = tiffPath.Substring(tiffPath.LastIndexOf('\\') + 1,
17        tiffPath.LastIndexOf('.') - tiffPath.LastIndexOf('\\') - 1);

It will open up a tiff file and read in all of the bytes and then convert it to base 64 encoding. Then he gets the name of the file without its extension. Let's do the same thing but using the .Net functions that should be used.

 9    rawTiffData = File.ReadAllBytes(this.FilePath);
10    tiffData = Convert.ToBase64String(rawTiffData);
11    string name = Path.GetFileNameWithoutExtension(this.FilePath);


The second section of code is almost self documenting. You can at a glance see what is going where and why. You also don't have to worry about getting your substring wrong or someone a year down the road coming in and making a small change to the substring call to make it better. Adding a bug that is not trivial to find.

7 comments:

Anonymous said...

Hard way for the win! :)

Erin said...

Proof or stfu

Anonymous said...

Here You go.

James and Crystal said...

gfh, I about gouged my eyes out when i saw that regex for getting a filename without the extension.

trixtur said...

gfh, I about chopped my dick off when I saw that post, God forbid I breed another regex hating bastard. :)

James and Crystal said...

Um... asshatery is fun when playing games like basketball but real men learn to use toys when toys should be used. I have nothing against regex however tools were built into the .Net Framework for a reason to be used. The one trick pony doesn't work here as there are better suited tools in the Path object that get things done without having to reinvent the wheel.

Anonymous said...

Oh I realize that, but I also don't call myself trixtur for no reason. If I'm talking it's probably in jest.