We recommend mobile phone deals

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.

The spyware silver bullet, does it exist?

Personal No Comments »

It is no secret that Windows has security problems and that Windows machines get bombarded with viruses and spyware everyday. The problem is further compounded by users that use Internet Explorer and like to click ‘Run’ on those random popup screens asking to install some software.

Forunately there is antispyware software available to help remove the junk we get on our computers. Well, depending on how you look at it, it is unfortunate that this software is necessary, but is a fact of life with a Windows PC.

I have tried a lot of anti spyware programs in the 15 years I have been using Windows and they all provide varying results. That’s why when I heard that Spyzooka promises 100% spyware removal I was a bit skeptical. After doing a bit of reading they have a pretty strong guarantee. In fact, they are the only software promising 100% removal.

Firstly, they have a 60 day money back guarantee. Pretty standard stuff. The nice thing about their promise is that if Spyzooka doesn’t remove every single piece of spyware on the first scan you can send the scan results (there’s a button on the scan results page) to the Spyzooka team and they analize the data and send you a free update to remove the additional spyware it had missed.

With a promise like that and 60 days money back to give it a try I will be testing this out. I would love to get rid of the other 3 programs I use if Spyzooka can do it all.

Popularity: 9% [?]

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

Zune getting what PSP got wrong

News, Personal 1 Comment »

We all love to hate Sony. In fact, I could make a full time job out of hating Sony and still work overtime. Instead of ranting about some of the reasons I think Techcult did a fine job of it here.

One of the things that really bugs me the most is how Sony crippled the PSP so it could not output to an external screen, like say your TV. So you had these PSP movies that you had to watch on a tiny screen instead of hooking up to your 46 inch flat screen. Thanks Sony. Not a good selling point.

Well, the Zune must have realized what idiots Sony were and decided to do the opposite and include TV out capabilities. You can watch your Zune content on your TV which is nice because seriously who wants to watch movies on a tiny screen especially if you want to show someone else? This may require some extra Zune accessories like a Zune AV cable but that is pretty common.

Another nice feature of the Zune is the ability to stream video and audio to your XBox. Sony could have easily done the same with the Play Station but nope, why would anybody want to do that? It amazes me that Sony is still in business.

On top of it all the Zune has a battery life up to 30 hours. This beats my old iPod by a long shot. Another nice feature of the Zune is the Zune charger. You can plug Zune into a standard powere outlet to charge and not have to plug into your computers USB ports, although that is an option if you want. This bugs me about my iPod I have to plug it into my PC and must have iTunes installed on the computer to charge the device. Not exactly convenient on the road sinceI don’t have a laptop to bring along to charge it.

The Zune seems to take some flack as a second rate player but I like the feature I have described and it easily beats the pants off PSP for any media content. Whether you’ll like if over iPod is matter of preference.

Popularity: 11% [?]

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

Keeping up in your career

Personal 2 Comments »

Information Technology changes rapidly and it can be hard sometimes to keep up with the skills required to maintain your career.

Programming is no exception to the above statement. Lately I have been reading books to upgrade my development skills. Programming is not all about the language you use. It goes way beyond the basic syntax to methodologies, patterns, and best practices.

With our companies latest piece of software we truly jumped into the enterprise market. I figured I better get up to speed on enterprise programming techniques as the software is growing fast and will need to be flexible and very maintainable. Consider it a bit of IT professional development.

My first stop along the career training path was to start reading Foundations of Programming Ebook by Karl Seguin which walks you through everything you need to know about programming for the enterprise and writing maintainable code.

This approach to continuing education applies to most trades, maybe not to the extent as IT. The long and the short of it is you never stop learning and you can’t survive in a career without learning new skills as they are presented. Consider professional development like the Natural Selection of the work force. If your skills are weak or out of date you will get pushed out by younger or more educated workers. It’s survival of the smartest working.

Popularity: 10% [?]

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

Running your own server is asking for trouble

Architecture, Operating Systems, Personal 8 Comments »

As someone who has been on both sides of the hosting fence there are few times that I would recommend a client trying to run and manage their own server. Generally, it sounds like a good idea, especially when you look at the cost of managed hosting. It is important to remember that although it may appear cheap to host your own server, using Linux and other open source technologies, the costs can be deceptive and not always be directly tied to money. Most often if careful and honest assessment is done the managed services turn out to be the cheaper option in the end. What am I talking about? Lets see.

Let me clarify that when I talk about running your own server I am not referring to some guy running a Linux web server on an old PC in his basement. I will be comparing both options for the same level and quality of service.

Up front costs

Let’s compare the up front costs for managed hosting and running your own server.

A typical dedicated server will probably start around $175 per month and gives you a modest server with lots of bandwidth and unless you are running heavily used sites or applications then it will most likely be more than enough. So at $175 per month that will cost you $2100 for the year. That may sound like a lot but really it is not because you get a fully functionally server out of the box with operating system and software per installed based on the package you chose. You also get power redundancy because your server is part of a data center. Also the hosting company still owns the hardware and is responsible for replacement if any hardware fails.

If you were to host your own server and you had the same $2100 budget for the first year. Well it would be impossible to build your server, install power redundancy (modest UPS at a minimum), buy the operating system (if you wanted Windows), and buy any backup and protection software. Also on top of that you are going to need a static IP address (you get that as part of the managed services) which can easily run you $100 per month from your ISP which alone eats up over half your budget.

Server administration

Another important thing to consider is server administration. Who is going to run and maintain your server? Who is going to troubleshoot your server when it goes down at 2 in the morning and you start getting panicked calls from your clients.

Most hosting companies will also administer your server for you as part of your managed hosting package, well, for a bit more money of course. This means that if something goes wrong you just call up technical support and they take care of it. This also means they are on the hook for the protection of your data and making sure the backup routine is in place and functioning.

Let’s consider that compared to you having to maintain your own server. If you are a person that is knowledgeable about computers than chances are you could manage to run your server fairly smoothly. On the other hand consider that if you are busy keeping the server running optimally then who is running your business and generating revenue? You can’t do everything and out sourcing your server administration is one of those things you should let go.

Now even if you paid your hosting company double to include server administration into your package ($350 per month or $4200 per year) this is considerably less then a salary for a fulltime IT person which will run you a minimum of $40,000 per year for someone decent and if you decided to use Linux to save money on your OS costs that salary just took a big jump.

Conclusion

The long and short of this post is to say if you need dedicated hosting then go with a professional company because when you stop to consider all the costs involved whether it be money or just peace of mind running your own server will cost you way more.

Popularity: 27% [?]

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