C# Design Patterns – The Visitor Pattern
What is the visitor pattern?
The visitor design pattern is a way of separating an algorithm from an object structure upon which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. Thus, using the visitor pattern helps conformance with the open/closed principle [Wikipedia].
Our Requirements
One principle that I really like is the Open/Closed principle which says that an object should be open to new functionality but closed to structural changes. The visitor pattern helps facilitate this principle by giving us the means to perform operations against an object without changing the objects structure.
Looking back at a previous pattern we wanted to adjust the registration cost for a dog if they had been picked up by the dog catcher.
Implementing The Visitor
Supposing we have the implementation for the interface below we could use the visitor pattern to perform our tasks without changing the existing classes. Since we won’t be changing the existing implementation we don’t need to worry about breaking existing features. Lets assume that the repository returns 3 infractions for our dog in the code below.
internal interface IDog {
int Id { get; set; }
string Name { get; set; }
string Breed { get; set; }
string Address { get; set; }
DateTime RegisterDate { get; set; }
int RegistrationCost { get; set; }
ICollection<Infraction> Infractions { get; }
void Accept(IVisitor visitor);
}
private IRepository _repo;
public Dog(IRepository repo) {
_repo = repo;
RegistrationCost = 25;
}
public int Id { get; set; }
public string Name { get; set; }
public string Breed { get; set; }
public string Address { get; set; }
public DateTime RegisterDate { get; set; }
public int RegistrationCost { get; set; }
public ICollection<Infraction> Infractions {
get { return _repo.GetInfractions(Id); }
}
public void Accept(IVisitor visitor) {
visitor.Visit(this);
}
}
internal interface IVisitor {
void Visit(IDog dog)
}
internal class Visitor : IVisitor {
public Visitor() { }
public void Visit(IDog dog) {
var cost = dog.RegistrationCost;
var infractions = dog.Infractions.Count;
//increase cost $5 for each infraction
dog.RegistrationCost = cost + (infractions * 5);
}
}
So we have our dog class and we have our visitor setup. All we have left to do is execute it.
static void Main() {
IDog dog = new Dog(Repository.Create<IDog>());
IVisitor visitor = new Visitor();
dog.Accept(visitor);
Console.WriteLine(dog.RegistrationCost); //=> 40
}
}
Conclusion
So just like the Decorator pattern, with the visitor pattern we can modify our class without changing the classes code. This pattern is more flexible because we can create any number of visitor classes to do just about anything without changing any code.
Be sure to grab the RSS feed, sign up for email updates, or follow me on Twitter to stay up to date and not miss any posts.
The C# Design Patterns Series
Part 1 – An Overview
Part 2 – The Decorator Pattern
Part 3 – The Abstract Factory Pattern
Part 4 – The Observer Pattern
Part 5 – The Facade Pattern
Part 6 – The Visitor Pattern
C# Design Patterns – The Facade Pattern
Today I am back with another design pattern. In this post we’ll be exploring the Facade pattern.
What Is The Facade Pattern
The facade pattern is a higher level interface that simplifies and brings together multiple interfaces of a subsystem. What this means is if you want to do something but that requires interacting with multiple subsystems you can create a facade that same only a few methods that handle all the interaction with the subsystem.
Our Application Requirements
In our city dog registration application lets assume there are a few things that need to be done when a new dog is registered. First the new dog and it’s owners must be entered into the system. Next the registration fee must be processed. Finally, we want the system to send the owners the welcome email.
This is a very simple example but this action requires 3 separate systems to do something in order to complete this one task of registering a new dog.
Using The Facade Pattern
For the sake of simplicity and not cluttering this post with too much code, I am not going to provide code for the sub systems, just the facade.
public class RegistrationManager : IRegister { private IAccountingService _accounting; private IMessageService _messaging; private IRepository = _repository;public RegistrationManager(IAccountService accounting, IMessagingService messaging, IRepository repository) { _accounting = accounting; _messaging = messaging; _repository = repository; }public void RegisterDog(IDog dog) { _repository.AddDog(dog); _accounting.ProcessPayment(dog.PaymentOrder); _messaging.SendWelcome(dog.Owners.Find(x => x.PrimaryContact)) } }
As you can see this is a very simple example but it illustrates the concept of the pattern. We have taken 3 tasks, each belonging to a different sub system, and combined them into 1 task in a facade class, in this case the RegistrationManager class.
The RegisterDog method adds the new dog to the repository, sends the payment order to the accounting system, and sends a welcome message to the dogs owners that are flagged as primary contacts.
Summing It Up
I hope this post helps you understand the Facade pattern and I hope you are continuing to learn and have fun with this series.
Be sure to grab the RSS feed or follow me on Twitter to stay up to date and not miss any posts.
The C# Design Patterns Series
Part 1 – An Overview
Part 2 – The Decorator Pattern
Part 3 – The Abstract Factory Pattern
Part 4 – The Observer Pattern
Part 5 – The Facade Pattern
Why You Want To Be A Craftsman Instead Of
A Cowboy
There has been a bit of a code war going on or at least a some what heated debate on code quality and programming principles.
I’m not going to rehash everything but I will sum up the two sides and throw my opinion into the ring. Why does my opinion matter? I’m not so sure that it does but you can be the judge of that. What I do think is different about my opinion than the opinions that I have heard/read so far is that I can’t place myself in either camp. I am not a coding cowboy that just cares that “it works” and I am not a bureaucratic standards Nazi either. I’ll talk a bit more about why I am ducking for cover in no man’s land in this battle of opinions.
The Coding Cowboys Say
Jeff Atwood and Joel Spolsky sure hit a sore spot when they suggested that learning programming principles just wasn’t worth it and just getting it done was more important.
Jeff likened principles and guidelines to the Ferengi and their 285 Rules of Acquisition saying that every situation in programming cannot be governed by a set of rules and there isn’t a one size fits all pattern to solve everything.
Joel refers to the SOLID principles as “extremely bureaucratic programming that came from the mind of somebody that has not written a lot of code.”
The Craftsmen Say
Jeff and Joel’s comments sparked a lot of rebuttals from the ALT.Net community. It is understandable since those comments attack the very foundation of TDD and DDD. I am not going to bore you with a list of everyone that chimed in but I want to highlight a post that I think sums up this position in a clear and nice way.
Justin Etheredge made a great post is response to the criticisms. I have been reading Justin’s blog for a while and I like the way he views software. He likens software development to carpentry and woodworking, both are a learned craft. You don’t get good a carpentry by throwing things together and ignoring building codes. Patterns and principles are like building codes.
My View On The Whole Thing
I was a bit surprised at first to hear Jeff and Joel’s comments because they are some smart guys that have produced some successful software. I highly doubt, regardless of how it came across, they intended to imply that you should ignore all guidelines and just string together your code. Unfortunately, the comments of their posts make it all too clear that this is exactly the way a lot of programmers took it. What’s worse is bad programmers will use this as a defense for their resistance to improving their skills.
Like I said, currently I am somewhere in no man’s land. For too long I had the mindset that would take Jeff and Joel’s comments and use them as an excuse to ignore patterns and principles. From the beginning of my education in software development, no importance was placed on “good design.” My college training only focuses on teaching the syntax and considering that “knowing” the language.
After a few years of living in denial, I had to accept that their was far more for me to learn and I began my journey out of the cowboy coding camp and started striving to develop software in a TDD manner. I still have a lot to learn but facts cannot be ignored. Since making an effort to improve my craft I have seen a significant drop in the amount of bugs found in new software I am producing and the bugs that are found are smaller and much similar to solve. So that is my take on the whole thing and I hope that this at least peaks someone’s interest to dig a little deeper in regard to becoming a craftsmen and taking pride in the code they produce.
C# Design Patterns – Observer Pattern
We’ve covered a couple of design patterns so far in our series. I have been enjoying writing these posts and I hope you have enjoyed reading them or at least got something out of them
In this post we are going to take a look at the Observer pattern.
What Is The Observer Pattern?
The Observer pattern is a way for an object to notify all of it’s dependants when something changes based on a one to many relationship.
The Situation
Continuing to use our city dog registration software senario, one of the project’s requirements is that the dog’s owner’s be notified whenever a dog is processed for an infraction (i.e. picked up by the dog catcher). The Observer pattern is perfectly suited to solve this problem.
Setting Up Our Observer
First before we create our Observer we need to define some classes and interfaces that we will need to use with the Observer.
string Type { get; set; }
int Id { get; set; }
DateTime Date { get; set; }
string Reason { get; set; }
double Fee { get; set; }
}
public class Infraction : IInfraction {
public string Type { get; set; }
int Id { get; set; }
DateTime Date { get; set; }
string Reason { get; set; }
double Fee { get; set; }
}
public interface IOwner {
int Id { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
string EmailAddress { get; set; }
}
public class Owner : IOwner {
public Owner() { }
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
}
The above code defines an infraction and an owner for our Observer to use. Now we can setup our Observer and the notifications when a dog gets an infraction.
int Id { get; set; }
string Name { get; set; }
void AddInfraction(IInfraction infraction);
void AddOwner(IOwner owner);
}
public class Dog : IDog {
private IList<IOwner> _owners;
private IList<IInfraction> _infractions;
public Dog() {
_owners = new List<Owner>();
}
public void AddOwner(IOwner owner) {
_owners.Add(owner);
}
public void AddInfraction(IInfraction infraction) {
_infractions.Add(infraction);
//notify owners of infraction : the Observer
foreach(IOwner owner in _owners) {
string message = “Dear ” + owner.FirstName + “,\n\n” +
“We are writing you to inform you that there has been an incident with your dog, “ +
this.Name + “, and that the city had to get involved.\n\n” +
“Your dog is being held at the city dog pound for the following reason: “ + infraction.Reason + “.” +
“You can pick them up anytime. There will be a fee of $” + infraction.Fee + ” applied.”;
MessageService.SendEmail(owner.EmailAddress, “cityhall@fictionalcity.com”, message);
}
}
public int Id { get; set; }
public string Name { get; set; }
}
You can see the this pattern at work in the AddInfraction method. Everytime this method is called an infraction is added to the dog’s record and all the owners are sent an email detailing the infraction and where to pick up their dog. It’s nice when you can structure your code to handle situations automatically, for you and your clients.
If you enjoyed this post be sure to grab the RSS feed or follow me on Twitter to get notifications of new posts. Also, check out other posts in this series below.
The C# Design Patterns Series
Part 1 – An Overview
Part 2 – The Decorator Pattern
Part 3 – The Abstract Factory Pattern
Part 4 – The Observer Pattern
Developer Productivity – 5 Ways To Kill It
In keeping with the sarcastic tone of my How To Be The Worst Developer Ever post I’m going to explore several ways for managers to systematically destroy productivity among their developers. Unfortunately I am writing some of these from experience, then again, I’m sure we have all experienced some of these at one time or another.
1. Make Them Feel Unvalued By Ignoring Their Advice
Warranted or not, who cares what developers have to say, never mind years or experience and savvy, or blatant evidence that they are right. You’re the manager. You get paid the big bucks to make the big decisions.
2. Keep Them On Their Toes By Changing The Project Requirements
After looking at the prototype they submitted for review, have them implement the dozen “minor” changes that just popped into your head. Hot Shot Trucking Denver . Don’t worry about running those “bright ideas” through a stupidity test, if it goes south you can blame the developers anyway. Be sure to remind them that it is still due next Friday.For maximum effectiveness, be sure to “review” their progress weekly.
3. Keep Them On Their Toes By Changing Deadlines
After dropping number 2 on them, they have the nerve to inform you that your changes don’t make sense and will require major reworking of the entire project. Also, there is no way they can have it ready for Monday. Hmmm. You must quell this little revolution. Inform them that you have scheduled a demonstration with the CEO and are moving the deadline up to Thursday. That should do it. They’ll have to pull an all nighter. They’ll be too tired to question your managerial skills again.
4. Assign Extra Unrelated Work
You get back from a long weekend at a managers conference at the golf club. The project seems to be running smoothly and the developers look a little happy. They must have been slacking off while you were gone. Have someone review the pile of emails in your inbox and respond to the random product surveys vendors send you.Remind them the project is still due Wednesday. Thursday? No. I told you it was due Wednesday. If you can’t keep simple details straight how can I put my confidence in you to get the project completed on time? *alternate execution of number 3*
5. Refuse To Get The Tools They Request
You already provided the team with Visual Studio and something called Subversion, what more do they need? What the heck is Resharper or NHibernate any way? Where do these new ideas keep coming from? Why can’t they just be happy with their adhoc SQL and DataSets? Code completion? Are you kidding me? They want tools that will write the code for them? This is getting out of hand. Perhaps shuffling various team members around will get things back on track.
C# Design Patterns – Abstract Factory Pattern
What Is An Abstract Factory
An abstract factory contains a set of methods that create families of objects. For example you might have a DogFactory class that has various methods for creating different kinds of dogs like CreatePoodle, CreateBeagle, CreateGoldenRetriever, and CreateChocolateLab.
Abstract Class Versus Interface
Before we get too deep into this pattern it is important to note that an abstract class that has only abstract methods is the same as an interface. The benefit of using an abstract class comes when you want to implement functionality in the base class so each derived class doesn’t need to repeat it.
Let’s say you have the following interface.
public interface ICalculatable {
int Add(int num1, int num2);
int Multiply(int num1, int num2);
}
This is a very trivial example but it will be fine for this illustration. If both those methods are going to be the same for each instance of the interface it seems silly to keep repeating the code over and over. It would make more sense to create an abstract class with two non abstract methods so you don’t have to write the code for each instance.
public abstract class Calculatable {
public int Add(int num1, int num2) {
return num1 + num2;
}
public int Multiply(int num1, int num2) {
return num1 * num2;
}
}
Then you could create multiple concreate classes that inherit from the Calculatable abstract class and not have to write any code for the Add and Multiply methods.
Program Requirements
We’ll be continuing on with our fictional city council that has commissioned us to develop an application that lets them manage their yearly dog registrations. Since the application is all about managing dogs and their owners it makes sense to have a DogFactory class that will create the different breeds of dogs that will be stored in the application.
Our application will have a factory that creates different breeds of dogs and each dog breed will inherit from the IDog interface.
The Pattern
First we’ll setup our abstract factory class that will serve as our contract or interface for a concrete factory class.
public abstract class AbstractDogFactory {
public abstract Poodle CreatePoodle();
public abstract Beagle CreateBeagle();
public abstract GoldenRetriever CreateGoldenRetriever();
public abstract ChocolateLab CreateChocolateLab();
}
Then we create a conrete class of our factory contract.
public DogFactory() { }
public overrride Poodle CreatePoodle() {
return new Poodle();
}
public overrride Beagle CreateBeagle() {
return new Beagle();
}
public overrride GoldenRetriever CreateGoldenRetriever() {
return new GoldenRetriever();
}
public overrride ChocolateLab CreateChocolateLab() {
return new ChocolateLab();
}
Now we have our factory in place it is very simple to use. Obviously the above implementation is very basic but it illustrates the point.
AbstractDogFactory dogFactory = new DogFactory();
Poodle mittens = dogFactory.CreatePoodle();
mittens.Name = “Mittens”;
If you enjoyed this post be sure to grab the RSS feed or follow me on Twitter to get notifications of new posts. Also, check out other posts in this series below.
The C# Design Patterns Series
Part 1 – An Overview
Part 2 – The Decorator Pattern
Part 3 – The Abstract Factory Pattern
Part 4 – The Observer Pattern
C# Design Patterns – The Decorator Pattern
In the introductory article to this series we looked at what a design pattern was. It is simply a solution to a recurring problem or situation in code.
Design patterns are something that interests me and I don’t seem to get bored reading or talking about them. I am not sure why that is, my wife can barely endure 5 sentences about the subject, she’s one of those creative types that don’t understand all the fuss about logic and math. Perhaps my interest stems from the fact that I, and many programmers, use design patterns everyday, lots of times not even knowing that it is a design pattern.
Looking back I realize that I used a number of patterns not knowing that they were some documented standard for approaching a situation. Probably the most common of these patterns that I used was the Decorator Pattern. I find that I use this pattern frequently when reworking older code that I have written when I want to guarantee that my new code won’t break any existing functionality. I also use this pattern extensively when I am given charge of someone else’s code for whatever reason.
Sometimes the existing code must be maintained or is very fragile, the Decorator Pattern is great for this type of situation.
Definition
The definition of the Decorator Pattern, according to Wikipedia, is:
“The decorator pattern can be used to make it possible to extend (decorate) the functionality of a class at runtime. This works by adding a new decorator class that wraps
the original class. This wrapping is typically achieved by passing the
original object as a parameter to the constructor of the decorator when
it is created. The decorator implements the new functionality, but for
functionality that is not new, the original (wrapped) class is used.
The decorating class must have the same interface as the original class.”
The Situation
Lets say you are assigned a project that a colleague was working on. Maybe this coworker has fallen ill or has decided to leave the company, for whatever reason, this is now your responsibility. Your manager hands the project off to you and explains the details of the project and the new features that are required.
The application is a dog registration program that your city is currently using to manage all annual dog registrations. The program has been deployed for nearly a year and now the city has decided that they would like to track when a dog gets picked up by the dog catcher. Based on this history, dogs that regularly get into trouble will cost more to register to offset the cost of employing the dog catcher.
Once you take a look at the code you discover that your coworker did not write any unit tests for this application. How will you know if your changes are going to introduce bugs into the existing features? Simple, you don’t. Without unit tests, the only way to determine if something gets broken is to manually fire up the UI and test each feature and all the possible combinations that feature may entail. Not something we want to do. That’s when the Decorator Pattern comes into play. It will allow us to wrap the new functionality around existing objects so that we do not disrupt the other code using the existing objects.
The Existing Code
The existing model looks like this.
int Id { get; set; }
string Name { get; set; }
string Breed { get; set; }
string Address { get; set; }
DateTime RegisterDate { get; set; }
int RegistrationCost { get; }
}
public class Dog : IDog {
public Dog() : this(new DogRepository()) { }
public Dog(IRepository repository) {
_repository = repository;
}
private IRepository _repository;
private int id;
public int Id {
get { return id; }
set { id = value; }
}
private string name;
public string Name {
get { return name; }
set { name = value; }
}
private string breed;
public string Breed {
get { return breed; }
set { breed = value; }
}
private string address;
public string Address {
get { return address; }
set { address = value; }
}
private DateTime registerDate;
public DateTime RegisterDate {
get { return registerDate; }
set { registerDate = value; }
}
public int RegistrationCost {
get { return 25; }
}
}
This may not be the prettiest code but it is what it is. You can chalk that up to your coworker not being as good of a programmer as you or me just being lazy with the example code.
The New Requirements
So as mentioned above, the city now wants to track how often a dog is picked up by the dog catcher to determine if the registration cost for that dog should be higher. These details will be stored in a new database table called Infractions. The corresponding model class will look like this.
public Infraction() { }
private int id;
public int Id {
get { return id; }
set { id = value; }
}
private int dogId;
public int DogId {
get { return dogId; }
set { dogId = value; }
}
private string reason;
public string Reason {
get { return reason; }
set { reason = value; }
}
private DateTime infractionDate;
public DateTime InfractionDate {
get { return infractionDate; }
set { infractionDate = value; }
}
}
The Decorator Code
Now that we know our new requirements and have defined the structure of the new information we can get to work building our decorator. We’ll create an abstract class that implements the IDog interface.
public abstract class DogDecorator : IDog {
private IDog _dog;
public DogDecorator(IDog dog) {
_dog = dog;
}
}
Next we’ll create our decorator from the abstract class that will look up the infractions and calculate the new registration cost.
public InfractingDog(IDog dog) :
this(dog, new DogRepository()) { }
public InfractingDog(IDog dog, IRepository repository) {
base(dog);
_repository = repository;
}
private IRepository _repository;
public int Id {
get { return _dog.Id; }
set { _dog.Id = value; }
}
public string Name {
get { return _dogName; }
set { _dog.Name = value; }
}
public string Breed {
get { return _dog.Breed; }
set { _dog.Breed = value; }
}
public string Address {
get { return _dog.Address; }
set { _dog.Address = value; }
}
public DateTime RegisterDate {
get { return _dog.RegisterDate; }
set { _dog.RegisterDate = value; }
}
public int RegistrationCost {
get {
IList<Infraction> infractions =
_repository.GetInfractionsByDogId(_dog.Id);
//increase registration by $5
//for every infraction
int extraCost = infractions.Count * 5;
return _dog.RegistrationCost + extraCost;
}
}
}
Final Thoughts
What we have done is wrap our original Dog class in a decorator to add new functionality. By doing it this way we don’t have to worry about breaking any old functionality because we didn’t change the original class. I hope this has demonstrated the Decorator Pattern to you in an easy to understand way that resembles a possible real world situation.
If you have any questions or feedback please post them in the comments section.
Be sure to grab the RSS feed or follow me on Twitter so you don’t miss out on this great series.
The C# Design Patterns Series
Part 1 – An Overview
Part 2 – The Decorator Pattern
Part 3 – The Abstract Factory Pattern
Part 4 – The Observer Pattern
C# Design Patterns – An Overview
Over the next number of posts I am going to be exploring the world of design patterns. We’ll look at some of the most commonly used patterns and how they look in C#.
What Is A Design Pattern?
A design pattern is, simply, a solution to a recurring problem in software development. Design patterns outline communication and intreraction between objects in common programming situations.
When talking about design patterns the book “Design Patterns: Elements of Reusable Object-Oriented Software“, by the Gang Of Four, is considered the authority on the subject. Their patterns are considered the foundation of all other patterns that have immerged. They divide patterns into three categories: Creational, Structural, and Behavioral.
What Will This Series Cover?
In this series we will look at the some common patterns we see in real-world programming situations. We will discuss each pattern and look at real-world C# code that implements the pattern.
If all this sounds boring to you, don’t worry we’ll keep it interesting.
Be sure to grab the RSS feed or follow me on Twitter so you don’t miss out on this great series.
The C# Design Patterns Series
Part 1 – An Overview
Part 2 – The Decorator Pattern
Part 3 – The Abstract Factory Pattern
Part 4 – The Observer Pattern
4 Steps To Ensure You’re The Worst
Developer Ever!

Disclaimer: For those with no sense of humor at all; this is an exercise in extreme sarcasm.
There are lots of articles about improving your skills as a developer. Everyone likes to talk about how to strengthen their skills and produce really good software. But, what if you want to be the worst developer ever? Nobody seems to want to share those secrets.
In these tough economic times secure your financial future by milking your employer for as much as you can. They’re not really interested in saving money.
Don’t Write Clean Code
Just think, if you write messy code that is hard to maintain then you are creating job security for yourself. The longer it takes to debug and make changes the more money you will be making.
Writing comments in your code, making the code clear and easy to understand just opens the door for someone to steal your job. If it can’t be understood then nobody else can do you job! You might want to keep a cheatsheet or decrypting key hidden somewhere in case you can’t figure out what you were thinking.
Don’t Write Unit Tests
Here is the excuse many of you have been looking for to justify not writing unit tests. Stop whining about unit tests being too hard to write or taking too much time. I’ve got a better reason.
Writing unit tests makes your code to modular and concise. Refer to the point about not writing clean code above. Besides, unit testing will only save you time in the long run. That is not our goal. We are trying to cash in on overtime pay here!
Don’t Read Development Blogs Or Programming Books!
Who needs to learn new skills? Why on earth would you want to do that? Everyone knows that VB6 is good enough and can do anything we need to do. You don’t want to work for those cheap skates that are trying to improve development performance and cut development costs. Nobody needs to use an ORM, you make more money if it takes you longer to write all that code by hand!
Don’t Waste Time Planning Your Application
Get off my back about planning my application. You don’t need to do that, it will just look like you aren’t getting anything done. The sooner you can get a working prototype up and running the happier your client will be. Don’t worry about the future. Your client won’t need new features or find any bugs.
There You Have It
Now that you are armed with this new liberating information, go out there and be the worst developer that you can be. It’s time to put some mystery back into software development!
By reading this post you agree to the following disclaimer and free Geek Daily from any consequences this information may have on your career.
What I Have Been Up To
I wanted to write a quick post updating you on where things are at in terms of upcoming posts on this blog.I did a guest post for Dev 102 this week and it was received well which is always nice. Since things went so well I have decided to do another guest post which hopefully will be for next week. We are considering making this a weekly or bi-weekly thing.I also finished reading the most recent book I am reviewing for Packt Publishing and will have that review posted next week.Also I have a new series in the works. I plan on writing a number of posts on design patterns. self storage . These posts will outline some of the most common and popular design patterns in use today and explore their purpose and what they can do for your projects.
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.
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.
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.
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. georgia divorce lawyers . 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.
It is more than a theory. It’s Agile!

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.
Who ever said “the customer is always right” is an idiot
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. Carrera de Diseno Web . diamond ring . Treppenlift Infos finden Sie hier . 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.
Running your own server is asking for trouble
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 costsLet’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 administrationAnother 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. brake repair shops . 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.ConclusionThe 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.
2 tried and true ways to frustrate and discourage your developers
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. abingdon md . 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 disasterIf 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.
Friday Roundup for June 13, 2008
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.
Friday Roundup for May 9, 2008
Here is what I found interesting this week.IE and Windows XP Service Pack 3Sadly 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 HomeOne 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 thehours that you want. margarita machine . Right? Well actually, probably not.In reality working from home doesnt work like that – well not inmy experience anyway. You usually end up working normal business hoursplus a few more to boot (though you may still be in your PJs).
Friday roundup for May2, 2008
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.
Top 10 Ways Websites Make Me Suffer
This was guest posted by Jason O’Connor, president of Oak Web Works, LLC www.oakwebworks.com where you can get a free webmaster newsletter and read many other original Web design and marketing articles.I believe some people create and publish websites for the sole purpose of tormenting their visitors. Browsing various websites and navigating the Web can often be like trying to read on an airplane while a kid kicks the back of your seat and the baby next to you alternates between screaming, crying and drooling on you. There are some excellent websites out there to be sure, but there are also a lot of dreadful ones too. The latter are the bane of so many people’s existence, especially those who use the Web regularly.The Net continues to grow in popularity and importance for consumers and businesses alike. Therefore, the quality of sites needs to keep pace. Creating and maintaining high-quality websites is more important now than ever. Higher quality equals more revenue.The following lists the top ten ways that a website misses the boat and contributes to hair loss and nervous breakdowns. Notice the common thread that runs throughout each of these. Namely, a bad website neglects to consider the site visitor’s experience in some fundamental ways.1. AnimationSeven year-olds like watching animated cartoons on Saturday morning, business people, professionals and most other adults don’t. Sites that include showy Flash animations as an ‘Intro’, animated gifs on every page, or flying words are really annoying. They take away from the content and distract the visitor from achieving their goals. Unless your site is an entertainment site, try to avoid maddening motion. However, if your product or service can be better demonstrated using Flash, Quick Time, or other multimedia, which is common, offer your visitors the chance to click a link to view it. But don’t force them.2. Too much scrollingOnce I scroll down a full screen’s worth, my eyes start to blur, I feel slightly lost, my head spins and my interest wanes. Computer monitors really aren’t the best medium for reading. The Net and many sites are so big that it’s important to always provide a clear frame of reference for your visitors at all times while they’re on your site. If a page requires two full screens of scrolling or more, simply split it up into multiple pages.3. Long, text-heavy and blocky paragraphs of unbroken textI really have to be into a topic or desperately need to glean the information to trudge through big chunks of unbroken text online. If I’m just shopping around for a product or service, you’ve lost me if I have to endure this kind of torture. Again, it is harder to read text on the Web than in other mediums such as books. Additionally, Web users are notoriously impatient, so make your content easy to read and non-intimidating. Use titles, sub-titles, small paragraphs, bullets and numbering.4. No obvious ways to contact the companyIf all you supply is an email on your website, your legitimacy may be questioned. Why can’t you answer the phone? Why hide behind an anonymous and cold email address? Make it easy for your existing and potential customers to talk with you.5. Unchanging or out-dated contentIf I start reading content on a site and soon discover that the content was written three years ago, I split. Since there’s so much information out there, my reasoning is there’s got to be comparable information online that’s more current. If you keep your content fresh your site will attract repeat visitors. And repeat visitors are more likely to turn into customers.6. Long page downloadsIt’s amazing that this is still a problem. When I click on to a site and have to sit there waiting for it to appear in my browser, I start sweating, picking my teeth, tapping my toes, rolling my eyes and soon want to throw my computer through my office window. I’m obviously a little impatient, but again, I know there are other sites out there with the same information that will download more quickly, so why wait? I’m gone.7. “Me, me, me!” instead of “You, you, you”Generally speaking, no one cares about you, your company or your thoughts. What they do care about is what you can do for them. So sites that show pictures of the company building or tout their deep philosophy on the way business should be conducted really don’t bode well for keeping the interest of site visitors. On the other hand, sites that speak directly to potential customers about how they can solve their problems, make their lives easier, safer, richer or more comfortable have a much better chance of keeping the eyeballs glued.8. Non-explanatory buttons or linksHere are some examples of buttons that leave me dazed and confused: A wedding site with a button called ‘Blanks’, a boating site with a button named ‘The Lighthouse’, a book site with a button called ‘The Inside Story’, or a Web design site with a button called ‘Tea Time’. They sound like Jeopardy categories. Imagine trying to find your way on a highway where its various signs read ‘Over Here’, ‘Moon Beams’, and ‘Lollypops’. Good luck navigating your way through. It’s the same with navigating websites. Things To Do In New York . Click Jogos . Button and link names need to tell the visitor where the link leads to. Make it as easy as possible for a visitor to know where they’re going before they click. However, there are times when naming a link an ambiguous name may pique the curiosity of a user and get them to click on it. But as a general rule, keep your links and buttons as descriptive as possible.9. Inconsistent navigationImagine sitting down at a restaurant and the waiter comes over to you and hands you five different menus, one for the appetizers, one for the soups and salads, one for the entrees, one for the desserts, and one for the drinks. Annoying. Now imagine if each menu had a different format, layout and method for listing the items. Brutal. I really don’t want to work that hard at picking out my dinner, I’m hungry and I just want a meal. Don’t make your visitors work hard either by expecting them to re-learn your navigation system each time they enter another section of your site. They too are hungry; for useful information and they’re even more impatient.10. Inconsistent look & feelWhen the look & feel completely changes from one page to another in a website, I think I am visiting another site, another company, a partner or subsidiary. I get very confused. This screams poor planning and often results from tacking on new sections later after the original site was built. This can lead to design-drift. It may be tempting to stray from the original design; you may have a better design now. But wait till you do a complete next-generation re-design of the entire site before introducing a new look & feel. If not, lots of visitors will be scratching their heads with one hand and possibly clicking away with the other.Finally, any site that employs a number of these notorious features is particularly painful to experience. When I click to a website that has five different fonts and colors, scrolls down to the core of the Earth, incorporates zinging words and big fat blocks of text, lists no phone number and has content written and dated in 1996, I scream and know deep down inside that pulling my fingernails out wouldn’t be as torturous as having to remain there a minute longer.
The importance of proper error logging
I may be preaching to the choir on this one but I feel that it is important enough to mention incase it turns a light on for some of you or just simply re-enforces an already solid part of your development cycle.What I am talking about is error logging. family psychology . gerry lane . ny divorce attorney . At first glance it may not seem all that important but if you have been in the middle of even a semi-complex development project you know that it can be hard sometimes to track down bugs.I have been working with the Model View Presenter (MVP) pattern for a while now and have grown to appreciate it’s modularization and ease of testing. Despite these great things my code still contains the odd bug, go figure! Now if you are not logging errors and exceptions it can be tough to even now why a bug is happening. but if you are logging every exception, custom ones too, then it makes your life that much easier since you at least know where to start looking.I warned you that this might be a little “well duh”. It is a basic and simple concept with meaningful and significant rewards.
I am suffering from too much GUI
I was thinking about some of my skills sets today and this lead me to a realization.I consider myself to be good with relational databases. I may not be an expert guru, but I have designed and implemented some pretty complex systems, very well IMO.The realization was that I rely to much on GUI interfaces. Yes, they are great and help get things done faster but in the instant the GUI was not available would I be able to function? True, I could always jump onto Google but my productivity would be greatly reduced because I would have to look up a lot of things.I also realized that I tended to be more disciplined when a GUI was available. For example, when working with MSSQL I used plenty of Sotred Procedures and was extremely careful to make sure all contraints and relationships were in place. However, when using MySQL, usually phpMyAdmin, I rarely used an SP or setup relationships. self storage facilities . So why is that? Because for MSSQL there are nice GUI interfaces to let me quickly and easily add all those good things but in phpMyAdmin there is noway to add them except through queries.Conclusion, I am lazy. I am working on this but it is true. hare . car dealers . This is by no means a good excuse to ignore good practices.So here’s to using a little less GUI and brushing up on some advanced SQL techniques in the near future.
Build your own CAB series
Jeremy Miller has been writing a wonderful series on building your CAB/exploring design patterns. tree service seattle . I highly recommend you read the series.Click here for the first article in the series.Click here for a list of articles in the series.
When last we left our hero, D’Artagnan was chasing the evil Lady de Winter across the breadth of France trying to intercept her on her dastardly mission when he found himself beset by disparate responsibilities within the tight confines of a single autonomous view with no room for sword play. D’Artagnan, being a perspicacious young man, quickly sees a way to separate the numerous concerns he’s facing by opening his attack with…
Monitoring code coverage, or “How to descend into madness”
Kyle Baley has given an inside look at how you can become a code coverage Nazi and not even know it. Great read and insightful.
I’ve become a code coverage Nazi.It started innocently enough. We added code coverage statistics a while back but only lately have we broken the build when it dropped below a certain level. We started at 60% and last week, our coverage sat at 67%. local florists . So I upped the threshold to 65% and after some good-natured goading among the team, I raised it to 66%. Y’know, just as a joke. No harm, no foul, eh?
“Beggin’ your pardon, sir. I don’t mean to interrupt your recent bout of insanity but I humbly beg you reconsider your position on our code coverage. You see, I am removing code that is no longer necessary and the thing is, it was fully covered by tests so our numbers are dropping. Please, Coding Hillbilly. I beseech you. Release your iron grip on our code coverage. I can live with ‘about 2/3 covered’. I just want to go home to my family. domain name disputes . Find it in your heart to let me check in my code.”
Top Ten Software Architecture Mistakes – Part 1
Eric Woods has put together a great article (part 1 of a series) on some of the most common design mistakes developers make. Hopefully this will help you avoid making some of these mistakes.
(1) Scoping WoesMany projects end up being doomed to failure before theyve really started, simply because their scope was wrong. The most common problem is the infamous scope creep where the scope of the system steadily increases as more and more people get their say. This is the sort of situation where a simple travel booking system ends up with full expense claim management facilities being built into it, with inevitable repercussions for project costs, timescales and quality. Best Travel Desinations . The converse problem is where scope is artificially limited (perhaps to meet timescales) and so the effectiveness of the system is compromised. Architects need to maintain a particular focus on scope problems that relate to system qualities. Does the system really need to be available 24x7x365? Or would working hours plus Saturday mornings be sufficient? It is really true that no security is needed beyond simple login? Once logged into the system can users really perform any system operation? Catching these mistakes early in the project will help to greatly increase the probability of success.(2) Not Casting Your Net WidelyA related mistake that many of us have made is to focus on just a couple of our system stakeholders classically the acquirer (who is paying for the system) and the end users get all of the attention. However there are often quite a few other interested parties who need to be involved. Consider people like auditors, systems administrators and DBAs, testers, helpdesk staff, the development team and so on. Youll probably need the cooperation of a fair number of these people in order to successfully deploy your system and number of them may not share your enthusiasm for it! Think about searching for stakeholders in groups like acquirers, assessors, communicators (like writers and trainers), developers, maintainers, suppliers, support staff, system administrators, testers and end users. The sooner you can make contact with these groups and understand their interests and concerns, the better.(3) Just Focusing on FunctionsIt goes without saying that a key quality of a system is what it does. People buy or build systems in order to perform useful work and so its crucial that the system does what people need it to do. However, a trap that many new software architects fall into is focusing entirely on a systems functions without considering any of its other properties.Unfortunately, while we do need to get the systems functional processing right, this is rarely enough; unless the system exhibits a whole range of qualities (such as performance, security, maintainability and so on) it is unlikely to be successful.In my experience, an architect needs to focus on the type of functions that a system has to provide and must design a suitable framework that each of the individual features of the system can be slotted into during detailed design. The design of the overall framework has to take into account the kind of functions it will host (be they computationally intensive, data oriented, batch operations, interactive operations and so on) but crucially, it must also be capable of providing the right level of performance, allow the application to be secured, allow for high availability and disaster recovery, support operation and administration and so on.In reality, if the system isnt fast enough or is insecure, if it cant be supported or changed to allow for new requirements, it probably wont be used and may not even make it into production in the first place. Identifying and delivering on these non-functional requirements is a crucial part of the architects role.(4) Box and Line DescriptionsAt some point in the development of the system you will need to write something down to explain your ideas for the architecture of the system in other words, youll need an architectural description.The question is, how do you go about describing something as complex as a modern software intensive system? The approach that weve all tried at some point is the single, all inclusive, boxes and lines Visio diagram that tries to show everything. The diagram probably includes software modules and some interconnections, machines, network links, databases and data flow, some user interaction, perhaps some system monitoring and so on. If youve tried this yourself then you already know that its not a terribly effective approach.There are two reasons why the huge Visio picture doesnt work well as an architectural description: firstly, its trying to show too much information in a single representation, and secondly, no one is really sure quite what each of the different types of symbol that youve drawn mean.The first problem means that the diagram doesnt work well for anyone, as everyone has to hunt through it for the information they are interested in. Infra-structure experts have to discern the machines, network links and infra-structure software from the whole, software developers have to try to work out what the software layering is, testers need to try to untangle dependencies from data flows. Each person is mentally creating their own subset of the diagram in order to understand it. The solution to this problem is to decompose your large diagram into a number of well-defined, non-overlapping views of the system such that each view addresses one aspect of the system structure (such as runtime functional structure, software module structure, data structures or deployment environment). This is a well proven technique and there are a number of standard approaches you can use to guide you in achieving this (see the Further Reading section).The solution to the problem of ambiguity is to make sure that you use a well defined notation for your diagrams and to provide enough supporting text somewhere to make your intentions clear. UML is an obvious starting point, given its tool support and wide use, although quite honestly its not a very good architectural notation (although again see the Further Reading section for some guidance on how to use it effectively). For those situations where UML isnt effective, you will probably design your own notation to represent your ideas. casino live . However, remember to clearly define what your notation means so that people arent guessing different people rarely guess the same way!(5) Forgetting That It Needs to be BuiltIts always very satisfying to create and prototype an elegant, sophisticated design for a new system and its always more interesting if we manage to use some novel new technologies and techniques along the way. However, when we do this, its often worth asking ourselves which stakeholders our new design is really serving the answer may well be ourselves, first and foremost (and possibly the development team).Im not suggesting that we shouldnt innovate or that all systems should use COBOL and VSAM but always bear in mind that your design needs to be built, tested and deployed in order for it to be successful. If the design or the technologies you use are too sophisticated or immature, then you may be jeopardising this.Common things to watch out for related to building the system include designs that the developers or testers dont really understand, technologies that they arent enthusiastic about or dont have the time to learn, and new technologies that dont yet have good tool support or perhaps impose a new and unfamiliar way of working. The presence of any of these factors suggests that you need to tread carefully and make sure that you work with the development and test teams to minimise the risks.Also bear in mind that your system needs to be installed, monitored and controlled in production. Sophisticated architectures can make all of this significantly harder and immature technologies often have weak monitoring and management facilities, even after their development support has been improved. Again, its a case of working with the relevant parties (such as system administrators and perhaps the vendors) to make sure that no one has any nasty surprises late in the day.
Why inheritance sucks
I read the first part of a great article on why inheritance is not the best way to implement things. I like the Jedi references in the explaination. Everyone needs a DarkHippo!
The difference between is-a and has-a relationships is well known and a fundamental part of OOAD, but what is less well known is that almost every is-a relationship would be better off re-articulated as a has-a relationship.
Bad
// bad class Jedi { function drawSabre():Sabre { ... }}class DarkJedi extends Jedi { function crushTownspeople():void { ... plants flowers . }}dj:DarkJedi = new DarkJedi();dj.crushTownspeople();
Good
// good class Jedi { function drawSabre():Sabre { ... dallas dwi lawyer . }}class DarkPowers { function crushTownspeople():void { ... }}class DarkJedi extends Jedi { // DarkJedi has-a DarkPowers public var darkPowers:DarkPowers = new DarkPowers();}dj:DarkJedi = new DarkJedi();dj.darkPowers.crushTownspeople();
Don’t Be a Validation Nazi
Haacked.com has posted another great article. The basic jist is don’t force your users to input the data as you want but manipulate the data to the way you want it giving your users a much nicer experience. It also has a nice Seinfeld Soup Nazi reference.
Be reasonable; are we so afraid of regular expressions that we cant strip extraneous characters from a single input field? Let the users type their telephone numbers in whatever they please. We can use a little quick programming to filter out what we dont need.
User: (filling out form) user+nospam@example.com Validation Nazi: Entering a plus sign is $2.00 extra. User: But the RFC allows for a plus sign. refinance mortgage rate . ars . Soup Nazi: You want plus sign? User: Yes please. Validation Nazi: $3.00! User: What? Validation Nazi: No form submission for you!
Web Standards and Semantics
The Internet has matured alot since it’s inception. It has under gone many changes and today we are seeing some amzing things done with various Internet technologies. One of the key factor in this vast amount of rich and interactive data is Web Standards. auto auction . Web standards have allowed us to transmit and share data in reliable and predictable ways. Semantics is a component of Standards, although not as important as a defined structure for the data, that describes the data it contains. Semantics, in many ways, is about common sense. It makes sense to expect a paragraph tag (<p>) to contain a paragraphic of text. It would also make sense to expect a table to contain a grid or table of data. So why are tables used for layouts?That in and of it’s self is a very interesting question. While the we have made great advances there are still some areas that are a little slow in catching on, for whatever reason. One area is XHTML. While the XHTML specifiaction has been out for years there are still many developers using HTML 4. I was even talking to a fellow developer the other day and a company he is working with still has the bulk of their web work in HTML 3.2, the horror!Perhaps it is the fact that Internet Explorer still doesn’t correctly support the XHTML mime type (XML application) that developers have asked, “Why bother?” Or perhaps some just don’t see the benefit in making the switch. kroger.com . Now to be clear I am not saying we have to go back and convert evry website or application we have ever written but at least any new development should be in XHTML.Why bother? Well, for me anyways, one big reason is Google. The search engine giant is favoring semantic and clean markup in it’s page indexing. So a little extra effort when writing your markup can have big payoffs down the road.So back to the question of why tables for layouts. Well there are many arguments like tabled layouts take longer to load and are less favorable to search engines, which are probably true. Ultimately every developer must choose for themselves. Believe me if I could cram tableless layouts and semantics down everyones throats I would. I am tired of working on projects that someother person has banaided together with horrible markup and then trying to repair the damage (or at least just figure out what is going on). Whether it is that you’re comfotatble with tables or you think that it is easier just bite the bullet, switch to semantic markup and use tables for what they were made for, tabular data. used car . You’ll be glad you did, maybe not today, maybe not tomorrow, maybe not while your cursing my very existence as you piece together your first layout then look at it in IE6, but someday you will thank me!Cheers.
User: (filling out form) user+nospam@example.com Validation Nazi: Entering a plus sign is $2.00 extra. User: But the RFC allows for a plus sign.
RSS ?
