Unit testing, your greatest maintenance tool

Methodology 2 Comments »

Unit Testing, your greatest maintenance tool

Can I have transactions in Life 2.0?

I remember reading a cute cartoon a while back illustrating how nice it would be if real life let you have transactions. I remeber thinking at the time that it was a funny cartoon but didn’t give it much more thought.

Begin Transaction.

This morning I woke up and had a shower just like I do every morning. Afterwards I decided I needed to shave…but my shaver had gone dead. Plugs it in to recharge…oh well, I’ll just shave tomorrow. I am sure Visual Studio won’t mind my stubble for one day.

So I am ready to go with time to spare, what to do? I decide to boot up my old test machine and continue playing with Eclipse and Java; I may even have time to play a game of Risk. What’s this? BOOT DISK ERROR! Crap. Oh well, I’ll reformat the hard drive after work. Boot up my main PC and do some research for this article…yeah I should have been doing that anyways.

Time to go. Out to the car and hop in. Wow it sure rained a lot over night. BRRR BRRR BRRR. You’ve got to be kidding me! My car won’t start.

Rollback. Crap it didn’t work! Sigh. I call a tow truck instead.

Car analogy for unit tests

There are many times I wish real life could be maintained like a software program. In true SlashDot form I am going to try an make my case for Unit Testing with a car analogy (mind you probably a bad one).

To me writing software without writing unit tests is like me working on my car. I know the basics, change the oil, change the tires, and I can probably find my way around, eventually but when it gets down to the details I am scared to touch something because I don’t know what it will break. If I take part A off will I be able to put it back on and not break part B.

Making changes to untested code is much the same. You don’t really know what other parts of the program your changes are going to affect or ultimately break. That is why we end up with lots of redundant code and lots of repetition. Nobody wanted to risk breaking something by changing that method so they just created a new method that did basically the same thing. The end result is an API that is a mess.

A common argument against unit testing is that it takes extra time. This is true but if you stop to think about developing without unit tests for a moment you have to admit that unit tests will save you time in the long run. If you are not using unit tests how do you test your code? You fire up the UI and you input test data and check for the proper output. This process will take you far more time and will not clearly reveal any breaks code changes may have introduced.

With unit testing all this is fixed. You have a suite of tests that you can run and within a couple of minutes know with certainty that things are working as expected.

How do to write a unit test

It can be difficult to get started writing unit tests. Here are a couple of rules to help you get started on the right track.

1. Write the unit test first. What you want to do is write just enough logic (classes and interfaces) to let your code compile. This will force you to look at your code differently. Each piece of code will have a goal and the unit test will check to see if that goal is met or that it is handled properly if the goal is not met.

2. Keep your code loosely coupled. In order to properly, and easily, test your code it needs to be loosely coupled. This means you want to avoid writing methods and classes that depend on other methods and classes. There will be a certain amount of coupling but you want to keep it to a minimum. For example, you’ll obviously want to test your data access layer to ensure it is communicating with your database correctly. However, once you start testing the layer that talks to your data access layer you will want to simulate your data layer instead of actually using it. This is were Dependency Injection comes into play. We will be talking about this in a future post.

[TestFixture]
public class ExampleTests {
	[Test]
	public void GetEmployeesTest() {
		Company comapny = new Company(new FakeDataAccess());
		Assert.IsTrue(company.GetEmployees().Length > 0);
	}
}

public class Company {
	private IDataAccess dataAccess;
	//default data access layer
	public Company() : this(new RealDataAccess()) { }

	//allow dependancy injection of
	//desired data access layer
	public Company(IDataAccess dataAccess) {
		this.dataAccess = dataAccess;
	}

	public Employee [] GetEmployees() {
		return dataAccess.GetEmployees();
	}
}

public class FakeDataAccess : IDataAccess {
	public FakeDataAccess() { }

	public Employee [] GetEmployees() {
		Employee [] employees = new Employee [] {
			new Employee("Bob", "Hudson", "Accounting"),
			new Employee("Jim", "Dunn", "Accounting"),
			new Employee("Mark", "Johnson", "Accounting"),
			new Employee("Bill", "Parson", "Accounting")
		};
		return employees;
	}
}

This test may seem pointless but remember your real Data Access layer is also properly tested and this test is making sure your Company class is interacting with the Data Access Layer properly. This is a fairly obvious example but it illustrates the point I am trying to make.

Hopefully this gives you a taste of Unit Testing and helps get you started.

kick it on DotNetKicks.com

Popularity: 9% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Exception Handling The Right Way

Methodology No Comments »

Exception Handling the right way

If you are just joining us, this is part 2 of a series on programming foundations and good practices.

Part 1 - Object Oriented Programming Is Your Foundation

Exception handling can be an extremely powerful tool for debugging…if it is done right. If you drop the ball on this it can make you want to run home crying to your Mommy. I’d like to point out that I thought it was a bit ironic that I stumbled onto this post from Daily Coder on Exception Handling today. I didn’t copy them. Honest!

When a user encounters an error

It is usually enevitable that your applications will have bugs. It is just a fact of life. No matter how diligent you are you just can’t predict eveything a user might do to break your code and things like unit testing just don’t catch everything.

So when a user encounters a bug in your application what should they expect? Well, idealy they will receive a nice friendly message explaining that something went wrong. No technical mumbo jumbo. The user doesn’t care. They just want it to work. Your error messages should give suggestions on what to do or how to report the bug to the proper people.

I have encountered far too often horrible error pages that are just a dump of the stack trace. Gross! Are you trying to scare your users away? This just makes the problem feel worse to the user. YSOD anyone?

Have an error tracking system in place

It doesn’t matter what you use but you should have some sort of system in place to track errors. This way when the application encounters an exception it can log it to your system and you are notified that there was a problem long before the user even reports it.

These systems are invaluable. You cannot rely on the customer to provide the proper details about the error. It is not their job. It is yours. I get emails and phone calls often from clients saying that such and such is broken or the system is broken. Not exactly helpful.

Because of reports like that I learned early on to log errors with as much detail as possible. I also like to include a user activity log that tracks where and what the user is doing in the system. This provides me with information on what the user was doing leading up to the error and makes diagnosing the problem that much easier. An activity log also lets you see patterns in the way users use your application and can reveal possible problems you didn’t previously anticipate.

Throwing an exception the wrong way

Here is the wrong way to throw an exception.

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

void MethodOne() {
	try {
		MethodTwo();
	}
	catch(Exception ex) {
		throw ex;
	}
}

void MethodTwo() {
	string[] arr = { "one", "two", "three" };
	Response.Write(arr[5]);
}

The output we get is

Index was outside the bounds of the array.

Line 23: }
Line 24: catch(Exception ex) {
Line 25: throw ex;
Line 26: }
Line 27: }

The line that rethrows the exception is marked as the line that is at fault which is not true and doesn’t help us much in figuring out what is causing the problem.

Throwing an exception the right way

Now that we know what not to do, here is the proper way to throw an exception.

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

void MethodOne() {
	try {
		MethodTwo();
	}
	catch {
		throw;
	}
}

void MethodTwo() {
	string[] arr = { "one", "two", "three" };
	Response.Write(arr[5]);
}

Notice that I am not using ‘throw ex’, I am only using ‘throw’. This masks the fact that we intercepted the exception and throws it as though we had not. Now our output is:

Index was outside the bounds of the array.

Line 29: void MethodTwo() {
Line 30: string[] arr = { “one”, “two”, “three” };
Line 31: Response.Write(arr[5]);
Line 32: }
Line 33: }

This is what we wanted. It shows us the correct line that is causing the problem.

Putting it all in perspective

By now I hope you see the importance of proper exception handling and logging. It makes it easier to track down bugs in your programs by giving you details that the user can’t or won’t be able to give you. Also making sure you throw the errors in the right way will give you even more specific details as to where the problem is occuring.

kick it on DotNetKicks.com

Popularity: 15% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Object Oriented Programming Is Your Foundation

Methodology 5 Comments »

Object Oriented Programming is your foundation

This is the first part in a mini series on building a solid foundation of principles and practices that will enable you to write better code.

Object Oriented Programming is going to be the foundation of everything we talk about from here on out. OOP provides huge power and flexibility later on down the line when we discuss techniques to help in the maintainability of our code.

As a side note, you will find that I tote maintainability as a hugely important factor. To me, maintenence is the biggest comsumption of development resources whether it be through bug fixes or adding new features. Anything that can make code easier to maintain long term is, in my book, worth exploring.

I am well aware that OOP has had some strong opposition and criticism including Richard Stallman (see his comments). Perhaps OOP is not for everyone but it has great value to me.

If you feel that OOP is not necessary or is a waste of time then I present to you two options:

  • Stop reading this series and continue to ignore an opportunity that might improve your coding skills
  • Reevaluate your opinon of OOP by reading the Wikipedia page linked above. Then continue this series.

Why Object Oriented Programming?

There are a lot of reasons to use Object Oriented Programming.

  • Code resuse. I try and follow the princliple of Don’t Repeat Yourself (DRY) as much as possible. OOP helps by easily allowing you to create reuseable components
  • Extensibility. When you can easily implement or extend your classes it makes your code more flexible and robust.
  • Maintenence. When your code is modeled after real life objects and concepts and your code is flexible it is easier to maintain. There is nothing worse than trying to make changes to poorly designed code.

The thing I like most about OOP is the ability to mimic the business objects in code as they are in real life. To me this makes the code far more readable and easier to maintain. Let’s look at a simple example (I am using C#).

public class Pet {
	private string name;
	private string species;
	private string favoriteFood;

	public Pet(string name, string species, string favoriteFood) {
		this.name = name;
		this.species = species;
		this.favoriteFood = favoriteFood;
	}

	public string Name {
		get { return name; }
	}

	public string Species {
		get { return species; }
	}

	public string FavoriteFood {
		get { return favoriteFood; }
	}

	public virtual string Speak() {
		return "My name is " + this.name;
	}
}

The above code, being modeled after a real life object, a pet, is easy to understand and should be intuitive as to it’s use. Another great thing about our above class is that we can easily inherit from it to create a similar, yet more specific, class.

public class Cat : Pet {
	public Cat(string name) : base(name, "cat", "mice") {

	}

	public override string Speak() {
		return "meow";
	}
}

See how easy that was? If in the future our program requires all Pets to have new features we just update out Pet class and all classes that inherit from Pet get the new features as well. If you haven’t guessed I like things with low maintenence costs.

That’s about it. I know I didn’t go into a lot of detail explaining all the aspects of OOP. That is just to much for this post. It could easily be a lengthy series of it’s own. I would strongly encourage you to do some reading on OOP if you need to know more.

kick it on DotNetKicks.com

Popularity: 16% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Putting your house in order for success

Methodology 1 Comment »

Putting your house in order for success

I am going to be talking about some of the fundemental things that all developers should know or at least should be working towards. Over the next several posts I will be presenting you with a series of concepts that make up good programming principles.

These principles will provide you with a solid foundation for building high quality software that is easily maintained in the future. Some of these principles are sometimes misunderstood by people who don’t see their value because they have never implemented them or have been misinformed. I know this is true because I was one of those people once. I will be explaining some of these topics like Object Orented Programming, Unit Testing, and Domain Driven Design to name a few. Hopefully this series will give you some insight into these techniques and help you see their benefit and ways that they can improve your software.

That’s enough rambling for now about what I am going to be presenting over the next couple weeks. If you haven’t already be sure to grab the RSS feed so you don’t miss any of these posts. They are going to be good.

I am in no way claiming to be some great all-star programmer. There is still a lot I have t learn but I want to share what I have learn so far with you so maybe it can give you a head start in your learning. If I make any mistakes in the coming posts please share it with me. I am not to proud to admit I am wrong sometimes. Also if you have anything to add to the topic please leave your comments or send me an email. The comments tend to be the most valueable part of my post quite often.

Popularity: 9% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

It is more than a theory. It’s Agile!

Methodology, Personal No Comments »

This is a follow up to my post on getting your clients involved in your projects. I am going to tell a quick story about customer relations gone wrong and respond to a reader comment about the whole idea being nothing more than a nice theory.

When things go very wrong

Last week my wife came to me and asked, “do you remember that article you wrote about customer’s being idiots?”

She proceeded to tell me that she had just heard that her brother had just been laid of because the company is going under.

Now my brother-in-law make kitchen cabinets for a living and he is very good at what he does. In fact, many of the kitchens he installs are worth more than my house!

Now this whole problem stems from one customer that flipped out and threw a tantrum. Now the company was installing the cabinets as the man had requested except there was an issue with the type of wood he wanted and the finish he wanted. This finsih will crack when the wood ages. So the boss went to the client to talk about the issue, explaining carefully why the customer was wrong and provided a solution.

I am not sure the reason for the blow up, maybe the client was one of those guys that can never except that they could be wrong, but a tantrum ensued and the client fired the campany and refused to pay his $40,000 bill for the work that had been completed.

So that was it, the company could afford to start any new projects because it now owed $40K for materials that were already used.

Luckily the customer consulted a designer who also told him he was wrong so he rehired my brother-in-law’s company and handed over a nice big check.

It’s more than a theory. It’s agile.

Even, though the story went bad it did turn out alright in the end. I know this is not always the case. To prove my “theory”, imagine if the client was not shown the kitchen until it was complete. He would have been far more angry to learn that different wood and finish had been used. Even though he reacted poorly initially the problem was able to be resolved early on and the customer was kept happy.

It is the same with software. You know that the client won’t give you all the details correctly, they jut won’t. So it is important to have them involved to keep the project on focus and clear up issues that are bound to arise.

Now this is not my idea to being with. It has been around for a long time and is called Agile Software Development. Agile Software Development refers to a group of software development methodologies that promotes development iterations, open collaboration, and process adaptability throughout the life-cycle of the project.

Now I am not going to convince you of this methodology’s worth. You can decide for yourself. Personally, I have been involved in enterprise level development for almost 4 years now and can tell that since switching to Agile style develoment and following the principles of Domain Driven Design that I have been more productive and produce far been software. Check it out for yourself.

Popularity: 10% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Who ever said “the customer is always right”
is an idiot

Methodology, Personal 3 Comments »

Angry Customer

This type of customer mentality really drives me nuts. I worked at a fast food joint for 4 years while I worked my way through college so I have seen, first hand, the ugly side of this way of thinking. This mind set gives the customer a puffed up sense of their worth. Sure it is their money that pays for salary and keeps you in business but it does not justify childish tantrums and harsh name calling or cursing because their coffee is wrong (even though you made it exactly as they ordered).

Now that I am on the other side I catch myself displaying some of these tendancies from time to time. Mind you, these behaviors only play out in my head, I am a nice guy after all. I wouldn’t ruin someone’s day just because I have to wait an extra 30 seconds while they remake the coffee.

Luckily for me, I have a beautiful wife to keep me inline. She worked in retail for nearly 6 years before deciding to be a stay at home mom after our son was born. She is always quick to point these things out when I start to complain to her about my bad trip to the grocery store.

What does this have to do with software?

Well, nothing. Also EVERYTHING! This thinking does not stop when a client walks into your office for consultation or for a scheduled development meeting. Yes, the client needs to be invlolved regularly through out the course of a project. They are the experts in their business (domain), afterall.

Let me momentarily digress to say that I agree that the customer should always be treated as the the King. They should be listened to and given all the attention necessary to keep them a happy and loyal customer. Their inappropraite actions, however, should not be tolerated.

Back to the point of the article that I am trying to get to. Applying to development, the client should have the final word on features and other design considerations. They are after all going to the the end user and are the ones paying for it in the first place.

You mean do everything they say?

Of course not! Your client doesn’t know anything about software engineering. Huh? What? How do you treat the client as if they are right and intentionally ignore their stupid ideas? Well, you don’t. I mean, you don’t ignore, seemingly, stupid ideas, you address them.

Your client is the expert in their business but you are the expert in your business. You need to find a middle ground to provide what is best to help the client acheive their goals while maintaining good design for your project.

You will first need to explain to the client why you think this is a bad idea. They will likely repeat why they think it is a good idea. Come prepared with a few senarios that highlight why it is a bad idea. You never know maybe you misunderstood and the client can show you why it really is a good idea and you can refactor your code to accomodate this feature in a sound way. Visual aids and narritive dialog go a long way in resolving misconceptions on either side.

This is why I think it is critical that the client be involved in the various stages of a project. They will help you catch mistakes or errors in implementation or they may even think of new or improved features.

Imagine if the first thing the client gets to touch is the finished project. “Why does it do this? I thought we said it has to do that” will leave both parties frustrated with the project even if you did implement it perfectly to specifications. Then you will get to experience those tantrums I am talking about.

Popularity: 16% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

2 tried and true ways to frustrate and discourage your developers

Methodology, Personal 5 Comments »

I have been reading a lot about what makes a developer want to stay or leave their current jobs or clients on some development blogs as of late.

There are two things that stuck out to me, probably because they hit home with me, that can really frustrate and discourage a developer.

1. Poor or incomplete specifications. There is nothing worse for a developer to implement code based on wrong or poor specifications. The results are never what the manager or client wanted. This results in tention on both ends and the developer ends up recoding the task. Everyone loses in this case.

It is very important for the client or project manager to lay out very precise and detailed instructions for the developer before any coding begins. This is even more important if the developer has limited or no access to the client or manager to resolve questions. The poorer the specifications the more questions and guess work the developer must do to complete the project.

Being a the lead developer in my organization I have felt the pain of redoing work and have a strong appreciation for proper planning and documentation.

2. Unreasonable expectations. This can come in many forms, from unreasonable deadlines to being expected to overcome limitations in technology. What ever the expectation both parties end up discouraged and disappointed when things fall apart.

It is essential that the client be made aware from day one what is possible in the realm of technology and timeline. It is also crucial that the person or team that communicates with the clients and relays information to the development team be very knowledgeable in these areas as well. Sales reps love to say whatever will make the sale but this can lead to some messy situations if promises cannot be delivered as stated.

Avoiding disaster

If managers can keep these points in mind, and take them to heart, when organizing projects they will be amazed at the amount of positive outcomes that will result from just a little diligence to make sure both sides stay happy and productive.

kick it on DotNetKicks.com

Popularity: 17% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Friday Roundup for June 13, 2008

Architecture, Methodology, SEO/Marketing No Comments »

Here is what I found interesting this week.

Unit tests are for functionality, not code!
The prevailing philosophy in regards to unit testing is writing your tests before your code. In practice, this happens a lot less than it should. Why should we write our unit tests first?

Turn Google App Engine into your own Personal Content Delivery Network (CDN)
As anybody who has run a growing website or blog knows, response time is going to get worse with the more users you have visiting your site. The users come from all angles, RSS feeds, homepage visits, search engine visits, people sealing your static files that you host, and pretty much anything else that can be served over HTTP. The solution to this problem is to off load your static content on to a Content Delivery Network or CDN. CDN providers cost a lot of money though, so it is nothing for us mere mortals with one server can afford.

But thanks to Google anyone can now run their own CDN for free on Googles servers. Lucky for you and me Google has made the process really painless and you can even have the CDN under you own domain name. In my case static.coderjournal.com.

10 Universal Truths of SEO
Google is great. I use its services on a daily basis and love the traffic it sends to my websites. As smart SEO professionals point out, however, Google isn’t the only search engine around, and may not be the biggest, baddest search engine on the block forever.

Popularity: 12% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Browsers, Methodology, Operating Systems No Comments »

Friday Roundup for May 9, 2008

Here is what I found interesting this week.

IE and Windows XP Service Pack 3
Sadly Microsoft has decided to keep shipping IE6 with SP3 for Windows XP. They missed a great opportunity to boost IE7 adoption.

3 Golden Rules For Working From Home
One of the great things about working from your own home is freedom.
Freedom to start work when you want, wear what you want and work the
hours that you want. Right? Well actually, probably not.

In reality working from home doesn’t work like that –- well not in
my experience anyway. You usually end up working normal business hours
plus a few more to boot (though you may still be in your PJs).

Popularity: 10% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Friday roundup for May2, 2008

ASP.Net, Fun, JavaScript/Ajax, Methodology No Comments »

Here is some highlights from this week.

Hijax
When I was originally writing the DOM Scripting book, its scope was very clear - it was to be an introductory work on JavaScript and the Document Object Model, with an emphasis on best practices. I made a conscious decision not to cover advanced topics like XMLHttpRequest.

But as the writing of the book progressed, Ajax really began to explode. It became clear that I’d have to at least mention the subject, even if I couldn’t cover it in detail. That’s where the book’s final chapter came from.

Jason Calacanis, Please Help Me Become A Pathetic Affiliate Marketer
I’m hoping Jason Calacanis can help me out here. Everyone knows that Jason loves to stir up trouble at Internet conferences and he recently caused quite a stir at Affiliate Summit West a couple months ago when he referred to Zac Johnson’s $300,000 check from Yahoo as pathetic.

Simple Subverison Repository Setup with VisualSVN Server
I have a few projects I am developing for my own company and choosing source control has really not needed much discussion. I use Subversion for everything because it’s free, works really well, has great community support and support a wide-variety of clients on many operating systems.

Why I’m a better software developer than you
What makes one developer better than another? Shouldn’t we all be performing at the same level? Of course not, we’re not sewing buttons on an assembly line. We’re using every bit of our intelligence to create something that we can only begin to understand.

Popularity: 17% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.
WP Theme & Icons by N.Design Studio
Entries RSS Login