Taswar Bhatti
The synonyms of software simplicity
design patterns

Learn the Observer Pattern:

I am starting to write a series of blog post which would be named “Learn {tagline}…..”
In these series I would post things about design pattern, programming methodologies, skills etc etc

For today, I will start with my favorite Design Pattern. The Observer Pattern.

I would first state out what the GoF book, states as the intent of this pattern.

Intent

  • Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Applicability of this pattern

  • When a change to one object requires changing others, and you don’t know how many objects need to be changed
  • When an object should be able to notify other objects without making assumptions about who these objects are. (Loosely coupled objects)
  • When an abstraction has two aspects, one dependent on the other.

UML Structure

observerpattern

Sample Code

I am going to write a sample application using WPF to show how to use the pattern. One may say its an overkill but it does show loose coupling.

First our pattern, our class diagram would look like this

classdiagram1

Our Interface ISubject and our Concrete Subject implementation

 

Next the interface for IObserver

 

Now that we got the pattern in place, let start with creating two UserControl in WPF, we will create an English and Turkish Label Control that implements the IObserver interface, as shown in the class diagram below
classdiagram12
English and Turkish Label Control implementation

 

Simple nothing fancy about these 2 controls other than the Turkish one, which has English -> Turkish hard coded translation.

Now lets see how the WPF app looks like and how it hooks it all up.

 

Application Screen shot

observerapp

Conclusion
Our main WPF app hooks the EnglishControl and TurkishControl with the Concrete Subject by using poor man’s Property Injection in the Default Constructor of the App. When a button is clicked on the App it sets the Subject State to a random English word from the list. This in turns calls the Notify on the Subject and it will then notify all its IObservers.

Additionally I would like to mention that we have used the pull method. Where we request to get the state from the subject, we could also use the push method where the subject will sends details information about the change to the observer. The push method makes the observer less reusable, because Subject class makes assumptions about the Observer classes that might not always be true. I suggest one to use the pull method whenever possible.

Once you understand the Observer Pattern concept, it is very easy to implement your own Events, the basic idea of Events is the Observer Pattern. In my next post I will show you how to use Events and Delegates to implement Observer Pattern in C#

You can also download the entire source code.

Hope you enjoy the first series of the Learn topics, will be posting more in the future.

mysql

Here is another post moved over from old blog about mysql installation on FreeBSD.

Installing the mysql ports

 

I will be using mysql50-server from the ports section of FreeBSD 7.0

The above command will build and store the database in /var/db/mysql

One will also need to add to rc.conf file to start mysql

The scripts of where the database to start is stored at /usr/local/etc/rc.d/mysql-server

But before we start it, we will create a my.cnf file and store it in /etc/my.cnf

By default the install provides a list of my.cnf files stored in /usr/local/share/mysql

I will be using the my-large.cnf since I know I will be using large data tables, but choose one that you find fits your needs.

Now lets start the database (assuming you are logged in as root)
Now that the database has started, lets set the root password for mysql

To setup root password for first time, use mysqladmin command at shell prompt as follows:

However if you want to change (or update) a root password, then you need to use following command:

 

Backup of Mysql Database

 

For backup of the database I will be using mysqlblasy.pl

On can download mysqlblasy.pl from http://pol.spurious.biz/projects/scripting/mysqlblasy.php#download

I will be using mysqlblasy verison 0.73

In order for mysqlblasy to run one needs to have the configuration file ready for it

Here is a sample configuration file that I placed in /etc/mysqlblasy.conf

This will allow root user to use mysqldump with password provided above and it will rotate the logs 7 days, compress it and store it at /database/mysql-backup

Lets try to run the command now (I got an error since I have not got some of the Perl modules in)

So lets fix it and install the Archive/Zip perl module

Now when we run

We should have a mysqldump stored in /database/mysql-backup

Lets now add it to the crontab at the end of the file.

This will backup mysql everyday at 11:00 pm

FreeBSD

This is a repost of my old blog wanted to move the post over, since I used to use a lot of FreeBSD in my previous position, and still love the OS wanted to continue posting stuff about it.

In this little tutorial I will teach how to upgrade ports in FreeBSD

  1. Install and use cvsup to sync the ports collection
  2. Create / Copy the supfile and use portsdb to update the database INDEX.db
  3. Use portversion to find which all ports need upgrading
  4. Use portupgrade to upgrade those ports
  5. Use portaudit to find vulnerabilities
  6. Script and add to crontab to auto do things for you

 

1. First lets install cvsup-without-gui

2. Now that cvsup is installed we need to create/copy the supfiles

Now we need to edit the ports-supfile to get only the ports

Edit the lines

Since my ports are installed on /usr/ports therefore I change base to /usr

For host one can change it to the one that is nearest you. Here is a list of cvsup server http://www.freebsd.org/doc/en/books/handbook/cvsup.html#HANDBOOK-MIRRORS-CHAPTER-SGML-CENTRAL-CVSUP

Remember to check if ports-all is listed since you wish to update all the ports

Next use this command to update the ports tree

Now that the port tree is updated, lets update the ports database (the following commands assume you have installed portupgrade form /usr/ports/ports-mgmt/portupgrade)

This creates an INDEX.db btree file on your server

3. Lets try to find out which ports needs upgrading

This will list out which ports need to be upgraded where the < sign means a new port exist.

Might show you something like

4. If we wish to upgrade php5 we would simply type

5. One may also like to install portaudit to check installed packages for known vulnerabilities.

This will list out all the ports that is installed and has vulnerabilities.

e.g

So you might want to upgrade that package.

Now that we have done all of this maybe it would be a good idea to actually script all of this into one script and put it in a cron job maybe even email yourself the result everyday (email left for yourself to script )

6. Here is a quick script that we can use.

Add it to crontab

Working Effectively with Legacy Code

This is part 2 of Extract and Override refactoring technique. You can find part 1 in my previous post.

I am going to show another technique by using Factory Method to break dependency in your code.

*WARNING* *WARNING*

Before I begin I would like to say all these techniques are not the best design but they will help you to break dependency and it might make some people flinch for the method but the intention is to get people to start looking at breaking dependency. Hopefully it will lead them to learn better design and make their code more modular in the process of it.

For anyone who doesn’t know Factory Method, you can read the GoF book or Head First Design Patterns. Which I would suggest you to buy if you don’t already own them.

Let’s say you have to send a letter to someone

Now we see from the above code that it is actually very hard for us to test this Letter class dependency since LetterSendingService is not quite accessible and created in the Construtor of Letter class. So how do we extract and override it then?

Lets give it another shot.

Now with this in place we can create a stub Letter class and override its dependency like this

With this in place we can then override the dependency and test the Letter class with a fake dependency.

The downsides
This method maybe great since its easy to work with but it lacks the interaction.

  • What if you wanted to check or verify some return values from ILetterSendingService?
  • What if SendLetter method returns a boolean value, true if letter was sent and false otherwise
  • What if ILetterSendingService interface has 15 methods in them, do we override all of them but we only care about 1 of them, which is SendLetter

A Mocking Framework like Rhino Mock or Moq would do a much better job at this, although you probably can override all the ILetterSendingService method but that is just too much work by hand writing stub etc.

Hopefully this post gave you some ways to think about breaking dependency in the future I will be writing about modular code and using some kind of IoC container to dependency inject and mocking framework to test your code 🙂

appengine_java

Just a link post today since google started supporting Java for their app engine rather than just Python, this will very likely bring lots of developers on board by having Java for Google App Engine

http://code.google.com/appengine/ Google AppEngine
http://code.google.com/eclipse/ Eclipse Plugin
http://blog.springsource.com/2009/04/07/write-your-google-app-engine-applications-in-groovy/ App Engine in Groovy

Time to start writing some apps in it 🙂

demeter

The Law of Demeter (LoD), or Principle of Least Knowledge, is a design guideline for developing software, particularly object-oriented programs. (wikipedia)

While everyday working on code that was written by lazy coders or junior coders I see a lot of violation of this law. I think every programmer should know the Law of Demeter by heart, as it states.

Any method of an object should call only methods belonging to:
1. Itself
2. Any parameters that were passed in to the method
3. Any objects it created
4. any directly held component objects

Quite simple one may think, in fact it is simple and here is an example of it

Now if only people would follow these principles, but the sad part is this is how I see most people just going about and violating the principle.

So how do we fix this, so that it doesn’t violate the principle.

By having phoneBook return us the withAreaCode, we reduce the number of class we are dependent on, and if anything changes in PhoneNumber this class/method would not be affected, only one place to change.

Next time if you see someone using code that violates the principle (wack them in the head first and then refer them here), remember to use an analogy I used with my co-worker.

  • I told him, I know you and your cell number, but would you think it would be okay for me to go through your contacts and get your girlfriend’s number?
  • Don’t you think that there is something wrong with it that?
  • I should only be able to get her number if I request it from you. (if he is willing to give me that is)
  • Not going through your contact list, what if your contact list changes? (Now he stores it in Outlook but what if he changes it to using pen and paper)
  • Does that mean when I call outlook contact list I am looking at your ex-girlfriend’s number? Since you moved to pen and paper?
  • Why am I dependent on your contact list? I only know you, shouldn’t I be able to just ask you for it and wherever you store it, is not my problem.
  • All you have to do is give me the number or return me nothing and life goes on.

 

Last but not lease always remember to question and review code, find out, why is this part dependent on that part? Why is there a call to something that feels like couple of level’s down, (i.e ObjectA.ObjectB.ObjectC.methodZ ) once you see that you know there is something fishy there, and own it to yourself to refactor and change it.

artofunittesting

Resources

  • Manning – Where one can buy the MEAP early release of the book
  • Amazon – Sometimes cheaper than Manning for print books
  • Art of Unit Testing Wiki Site -The wiki site for the book
  • The book will be in print I think April 2009 as Roy mentioned in his blog if you wish to wait for a hard copy

 

Additional Information

  • Paperback: 225 pages
  • Publisher: Manning Publications (May 1 2009)
  • Language: English
  • ISBN-10: 1933988274
  • ISBN-13: 978-1933988276

 

Audience and Content

The intended audience for this book are people who are beginning/intermediate learning unit testing or in the process of implementing unit testing at their shops. The contents is for developers to start writing better unit test. I wouldn’t say it is a book target at expert unit testers out there, people who may already be using SpecUnit or BDD, since the book doesn’t cover BDD or Spec. But nevertheless it still has valuable information for everyone.

What is it all about?

Part I Getting started

The first two chapters 1 and 2, goes through the basic of what unit testing is, (definitions, intro to nunit) and writing your first unit test using nunit. The author touches a bit on TDD but not going into details of it, since I think TDD is another mind set and the author just didn’t want to overwhelm the reader (if they were beginners). In the book he also uses the example of a Logger which he builds upon to explain the techniques of unit testing.

Part II Core techniques

The second part of the book chapters 3, 4 and 5, details the core techniques of how to use stub, what mocks are and using mocking framework Rhino Mocks to do unit testing. These three chapters I believe are quite important for a beginner to go through, since in chapter 3, the author goes through the techniques of Extract and Override, using Factories and Dependency Injection through constructor/properties. The author also talks about when should one use these techniques, the pros and cons of them.

In Chapter 5 he introduces Rhino Mocks, (also mentions other frameworks, Typemock, NMock2) although he uses the “using record/playback” way of Rhino Mocks (i.e. not using AAA style or the fluent way) of coding the examples, not that there is anything wrong with it, personally I prefer the AAA style and using lamda expressions. If you are looking at technical information or the meat of things, these three chapters are definitely the core of it.

Part III The test code

In part three of the book chapter 6 and 7, the author explains the important of using build automation, and continuous integration. How to separate out test so that they are in different folders/projects for integration and unit (i.e. slow and fast test). Also some techniques of refactoring your code to use base class/template method/generics to reuse code, although warning that base class etc might lead to less readability of the code.

In chapter 7, the author goes into the explaining trustworthy test by using coding standards (naming of test), some basic principle of DRY (don’t repeat yourself), code coverage, testing only one thing, using only one assert statement and finally using attributes to test different input cases of the test, rather than writing test for each case. I think this might be the chapter that some might considered it controversial, since they might see this chapter as in telling readers (laying down the law) of how to create trustworthy unit test. I would only say to that, give it a read and nobody is pointing a gun and saying this is the way to do it, I don’t seem to remember reading a book and following it the exact way of coding or using the exact libraries the book uses. Yes, things that the author list out might be valuable but at the end of the day whatever fits your boat or shop is what matters.

Part IV Design and process

The last two chapters 8 and 9 talks about integrating unit testing and working with legacy code. Chapter 8, was the chapter that had the most importance for me personally, on bring change and unit testing into an organization. Although there was an error on Table 8.1 which had the amount of bug found in production for teams doing test and not doing test, they were in reverse, I guess a typo from the author. The last chapter 9 talks about where should one start introducing test in your code, the hard part or the easy part, where does it pay off and some tools to use for unit testing. The author also uses the 4 quadrants to map out easy/hard test with dependencies, so that one can pick what would be easy and hard to test.

And lastly in Appendix I and II, the author talks about using design for testability and some tools/framework. In Appendix I, the author lays out a table of design guidelines and benefit of using them. What I found lacking was the cons of using the design, I think a column that also included some cons of using these techniques might be a better and be well rounded for readers to choose which design to use.

Conclusion

Last but not least, would I recommend this book to anyone? The answer is definitely “YES”!!! I would give this book a 4.2 out of 5 stars, I only wished the MEAP version didn’t have so many typos but hopefully when the final release comes out it would be all corrected.

DD-WRT

This post is more of a geeky type of post about the awesome DD-WRT firmware. And how I set up two wireless router to talk to each other without wires.

So, yesterday the digiturk web tv set-top box arrived, that my wife purchased for Onur (our son, who is only 1 year old now) to watch “Turkish” television, basically the box runs windows CE and has an internet jack that requires you to plug in to get IPTV from the web.

The problem is that our TV is located on the main floor while our office is downstairs in the basement where all internet connection is located, cable modem with the linux version of linksys wireless WRT54GL to provide wireless to our laptop on the main floor.

Now in order for me to provide internet for this new set-top box I need to either pull an ethernet wire all the way up or use the existing cable coax to the TV and move my modem and linksys upstairs, and I was thinking wouldn’t it be great if I can use my old WRT54G (without linux which I was selling on kijiji, and some guy was trying to offer me $20 bucks for it, glad I didnt take his offer) just plug it up there with the set-top box and have it talk to my linux WRT54GL wirelessly to go to the internet.

So that got me thinking and googling for a solution and I found out about WDS (Wireless Distributed System) and how to set it up.

To get started I flashed my v8 CDFF version of my linksys WRT54G with the dd-wrt as listed here

Once I got that running, I had to flash my WRT54GL with the same dd-wrt, you want to have the same version of firmware running on both.

After that I had to follow this techinque of setting it up for my 54GL router to talk to the 54G router, although that cost me  to go to bed around midnight to get it all working, even though I was proud of achieving it, my wife was like “weren’t it suppose to take only half an hour?”

It always that “geek factor” where you say, just half and hour I will be there and half hour turns to 2 hours later 🙂 But I did go to bed smiling that I got it working, and thinking about what I can do next with it, maybe set up VOIP etc, just need to investigate more into DD-WRT.

Now I just need digiturk to enable my service at their end to let my son watch some Turkish TV, it makes me wonder why would you send a box and not enable the serial number to login to your system, but that’s another story or post for bureaucracy in this world of large co-op, how disfunctional they are.

From all of this my lesson learned is, estimation of hacking/software setup stuff always doesn’t take half an hour 🙂

Working Effectively with Legacy Code

When doing unit testing, one always comes to a point where there this “kind of hard” part to test since the part depends on something you might not have control over or depends on the functionality of the dependency to complete.

In “Working Effectively with Legacy Code” by Michael C. Feathers talks about a dependency breaking technique called “Extract and Override” which is also in Roy Osherove book “Art of Unit Testing“.

The basic technique is quite simple and quite powerful as Roy puts it

Extract & Override is a very powerful technique because it lets you deal directly with replacing the dependency without going down the rabbit hole at all (changing dependencies deep inside the call stack). That makes it very quick and clean to perform, almost to the point where it corrupts your good sense of object oriented aesthetics, leading you to code that might even have less interfaces but more virtual methods.” (Art of Unit Testing, pg.50)

In this post I am going to show a simple example of how to use the extract and override method, lets say for example you have an Order Class and it has a dependency call User as shown below

For us to test out the Add method we have a dependency that calls and checks if the user is valid, this basically makes it pretty hard to test, unless you refactor your code to use an interface IUser, pass it in the constructor and mock the user with a Mocking Framework or hand write the stub but lets say you don’t have access to User or some other reason that there will not be a setter for ValidUser on the user object for some reason (security comes to mind). [Although using an interface IUser would be a better design]

This can be one of the reason where some people quit unit testing since it just makes it hard to test but there is a way to test and it is quite simply. The way to do it is actually by extracting the dependency, since to us we don’t really care about the user and we want to test the Add functionality only to see if things are working properly. Let see how we do it

We introduced a virtual method called CheckValidUser so that we can override it. Now for our stub we can simply override the method so that it always returns what we want it to

And finally for our unit testing we can write something like

There are definitely better ways to design this class by using interface IUser, dependency injection frameworks and mocking frameworks to ease the testing, but those methods would be mentioned later in my blog. Hope you enjoyed the read 🙂

Taswar

WCF Error Handling with log4net

WCF Error Handling with log4net

In this blog post I will be going through how to do error handing with WCF by using attributes to log your errors.

There are multiple ways to do error handling in WCF as listed by Pedram Rezaei Blog.

The default way that WCF allows errors message to display is by setting IncludeExceptionDetailInFaults Property to true in web.config or on the service attribute but this is only recommended when you need to debug you development code not in your shipped/release code.

In Web.config file

In the web.config file of the WCF service the includeExceptionDetailFaults attribute set it to true.  With this action every endpoint associated to WCF service will send managed exception information.

In Attribute

Another way is setting the IncludeExceptionDatailInFaults property to true using the ServiceBehaviorAttribute.

That is fine and dandy but it is definitely not recommended for production server, you don’t want an stack trace to show up when someone is viewing it on the webpage for this service.

The IErrorHandler interface

The basic form of error logging in WCF is to use the IErrorHandler interface, which enables developers to customize the default exception reporting and propagation, and provides for a hook for custom logging.

Another thing to note is we need to implement the IServiceBehavior also since installing our own custom implementation of IErrorHandler requires adding it to the desired dispatcher. Since we need to treat the extensions as custom service behaviors in order for it to work.

Rather than just calling Log4Net I create a class called Logger which decouples log4net so that one can use any logging framework by using a dependency injection framework. (Code not listed)

Back to building our own ErrorHandler, ServiceBehavior with Attribute, the code is listed below

Now one can just add an attribute to the WCF service code to log our error message to log4net or whatever logging framework that you may be using.

There is also another way by using the web.config and adding the error logging to all the services listed by Stever B in his blog, but I find that does not give me the flexibility that I wanted, I may want to log some but not others etc.

Hope you enjoy this post.

UA-4524639-2