Saturday, October 4, 2008

Project retrospection, my non-called role as acting Agile Coach

Last week I was discussing on the topic - What it takes to guide team of beginners or being agile coach in general, with Mat Hinze. That reminded me my role in previous project.

while people like Jeffrey Palermo are natural coach, personally I find it little difficult to work with beginner level people.

Looking back, here is quick highlight

  • In first week, gave little presentation on what agile is and high level idea of how scrum works.
  • Introduced unit test and integration test for the project. Started working in TDD way
  • Change existing build process (Build = Compile) to include compile plus test execution (Which was later again changed to accommodate things like custom commonasseblyinfo, publishing coverage report and executable specification).
  • Re-organized project structure to facilitate better support for loose coupling.
  • Introduced boundary testing (or Scratch testing) to better integrate with external systems (and these systems where also under active development, using water-fall methodology, giving us hard time every time they give us new version).
  • Introduced Dependency Injection technique to the team.
  • Introduced pair programming (this was the hardest part, for me).
  • Introduced using StructureMap for IoC.
  • Introduced mocking technique to the team. Gave demo-cum-presentation on Rhino Mocks.
  • Introduced MVP to work effectively in  ASP.NET WebForm environment. (Second hardest part on this project, for me)
  • Re-factored existing code to eliminate gigantic code behind files.
  • Introduced CruiseControl.net for build monitoring as well as deploying to staging environment.

Enough!!!!!!!!!!!!!!!!!!!!

What did I got out of this

  • Team realized power of TDD and could see the real value behind it as oppose to doing just test first programming.
  • Pairing helped team, breaking the knowledge silo and promoted collective team ownership.
  • We had better success rate with sprints as we proceed further.

What was still left out:

  • Project owner team, never truly realized power of Agile/Scrum
  • I always had hard time convincing them for shorter sprint as oppose to 1 Month sprint.
  • Sprint velocity was never established properly.
  • Effectiveness of Sprint Retrospective was very low. (it turned out to be mostly time wasting activity)
  • Planning meeting were always mess. Product owner were never ready with new set of requirement which they want in next sprint.
  • Story related pre-requisite work was always done during planning meeting by making calls to 5 different people and then deciding on the fly, what needs to be done for the story in hand.
  • All product owner never bothered to come for planning meeting.
  • During sprint, one representative from product owner team was choose to answer team's question and was rarely available.
  • Cubical structure made it very difficult to communicate with team effectively and has resulted in duplication of effort.
  • Testing team mind-set was fully water-fall oriented. They never bothered automatic tests and continued manual testing focusing on trivial issues which were never called out in story.
  • And the list can go even further, but I think I covered top pain points.

With this kind of project, I am not sure whether I succeeded in doing my best for the team. One thing however is sure enough that while I could make positive changes and affect the overall direction for technical team, I had almost no control/influence on people who were higher in the hierarchy. (By the way, I was originally hired to help them with reliable messaging which never happen in the project).

That spawns nature question, what should I have done differently to help this project better. And more importantly how would you handle this kind of situation where you don't have direct or indirect influence on people who are driving the project. ( And I am looking for answer other than; "Hey, why don't you just update your resume and start surfing dice or monster.com)

Working with high performing team

Not secret anymore, recently I have made one of the most significant move in my career my opting to work with the team HeadspringSystem, the premier agile consulting company based in Austin. It's been my pleasure to work with all BigB's like Jeffrey Palermo, Kevin Hurwitz, Mat Hinze and Jimmy Bogard.

Ever since I stated with new project with this team, I have been learning a lot every day. Be it NHibernate, NAnt, using open source project, spawning new open source project, NBehave, Community Contributed Framework, IoC or applying BDD at work; this team makes every thing so smooth and so juice that you can't live without that it.

Team operate , keeping in mind the sole intention of getting work done and giving product owner what they really like to see in the system (as oppose to doing just what they said initially).  User story flows naturally from left side of the board to Done Done Done column.

If you are wondering how this team attacks individual story, go to my buddy's blog here.

lastly, I here by taking over un-official title of least qualified team member from Matt Hinze. 

Tuesday, July 29, 2008

Burndown chart vs Burndown mentality

It's no surprise that scrum projects are using Burndown chart for tracking sprint progress and overall product release too.

Burndown chart, as name suggest, keeps burning task/stories as and shows what is still left out.
Every day after, stamp up meeting, is good time spot when we re-draw this chart to reflect previous day's work.

Here is the trap which I have seen many team fall in very easily. While we are using daily stand up to come up with burn DOWN chart, what we are really talking about is how much amount of task have been done (i.e. 4 hours or 1 story point etc). Now truly speaking that information is not really helpful to us. In Agile there is no look back. Whatever happened, does happened. No one in the world can go back and change them. What is important is what to do next. What I mean to say, is we need to start talking in terms of what is left in order to finish this story.

Now, does that sounds like weird argument? One might argue that, isn't that the same information. After all we know total size of the story and by telling what has been done, we can easily figure out what is left. (That's simple math I learned, way back in primary school).

Here is my answer,
My experience with past and present scrum project has taught me the above simple math of deducting completed point from original size is failing too often. While working on story we might encounter more or less complexity than originally anticipated. Which means, for then encountered simple story what is left is too less or for then encountered complex story what is left is much more. And somehow human minds are evolved in such a way that they can give more accurate answer for what is left vs how much is done.

Personally, our charts have improved a lot (in terms of reflating actual picture) when we started forcing team thinking in terms of "what is left" pattern over "what is done".

I call this pattern "BURN DOWN MENTALITY" to update burndown chart.

Thought? comments? arguments? I would love to hear.

Develop smartly :)

Xp Team sizing... Even or Odd

Yesterday, we had our sprint retrospective which brought one interesting issue.

We are team of 5 dev, 2 tester and 1 project co-ordinator.

One of the issue we have been facing since very beginning is lack of pair programming which resulted in knowledge silos getting build in the team. With extra effort and quoting past examples I succeeded in showing value in pair programming and we started doing it gradually more and more.

However last sprint's result was surprising to me. We had total 12 user stories in sprint and out of that I did 4 stories alone and then contributed for 3 more stories.

Now with the team of 5 developer, that sounds little ODD to me. So I tried to investigate this in the retrospective session. To my surprise, I heard other developers talking about working in pairs (2 pairs out of 4 developer) and their story comes out to be extra complex than what was originally thought of. So I was the ODD man out from the pair programming this time, for whole sprint.

This gives me interesting question. Should XP team always be Even size to facilitate pair programming? May be YES. (While voting for yes, I am well aware of the fact that even size might give us tie in planning session while estimating story point. My answer to this is use Feast-To-Five technique)

Anybody would like to comment? I love hearing from like minded peoples!!!!!

Develop smartly :)

How to get default value of given type

Found this interesting construct for .net based development.

While we all know default value of each type, at some point we might have generic implementation. So what if we need to make use of default value of give type?

Following method demonstrates, usage of default keyword (code sample in C#)

public T SomeMethod(this T abc)
{
if (whatever)
{
return some valid value;
}
return default(T);
}

This was new to me and in past I had situation where I wanted to return default value for variable type. Now I know exactly, how this can be done!!!!!!

Develop smartly:)

Monday, July 14, 2008

Agile Planning - Planning on wall

Till last week we were facing serious issue with respect to our sprint planning. Team is new to Agile and except me, everybody else is working on agile project for the first time.

Time was killer factor for our planning session. Almost every single time, we are running out of time and it ends up being 1.5 day planning session for 2 week sprint. (Again Business is also responsible for this mess as those user stories were half cooked meal and there wasn't any acceptance criteria)

Last week whole picture changed when we were successful in convincing business, that its important to have user story ready well before planning session. We used their own weapon against them and warned them without well defined user stories, the software is at risk and we will never be able to release it on time :)

That worked magically!

Business spent 2 days, organizing their thought, collected input from other concerned people and finally provided us well defined user stories which has clearly written acceptance criteria.

Wow... we entered greenland for the first time on the project.

Next was our turn and this time business wanted us to estimate them such that they call get idea on when can they release the product.

Looking at our history of planning this would have taken us, probably 4-5 days, if we would have continued to follow our old practice.

But we didn't had that much time. So it was necessity that became mother of new discovery, again.

Earlier when we used to estimate each story, we all where breaking it into task(This was sprint planning, against tasks and not release planning against user stories). And then discuss scope and complexity and come up with magic figure against each task. The whole operation was single threaded as everybody was on same task card and again getting conses for magic figure was taking time too.

So this time, we thought of using multi-threading for planning. And hence one of the wall of our Ping pong house, became playground for this planning. Every body in the team had 4x6 sticky note and a pen in their hand, No body seats in the room and then we have one person read story. (This guy was really proxy for business for us) Then starts Q&A session till we get all answers. Meanwhile everybody in the team uses their sticky and start writting all possible task that they can think of and stick on the wall. Sooner (less than 2 min) we have 10-12 task hanging on wall. They we just look at the cards and eliminate dubplicates. Task keeps on comming till everybody in the team, can't think of anything new.

Then starts next step, re-arrange task into logical order, either vertical or horrizontal.

Next and final step, was to give number to each of them. That starts with top most card, and any one call out number, others either agrees or give different number and then we uses Fist-to-Five to get agreement. Game is everybody vote for the number for given task, by raising either 1-5 figures. Number of figures means, different things as follow
1: Go to hell, I can't get this at all
2: I seriously doubt
3: Well may be good, I am Ok with that
4: Sounds good to me
5: totally agree

3 onwards is fine and you can accept that number for the card. However if even single 1s or 2s means call for further discussion and then second round with new figure based on that discussion.

Well, that's all. The whole thing worked dam good. Room was filled with lot of energy as against two or three sleeping members in the chair. Everybody contributed and we had our planning doen in one and half day without any overtime. We even had two 15 min break and one hour lunch break in between.

Above all, it was team's estimate. We created it together and we owned it. This has bought automatic buy-in from all members. Whole team was happy and everybody in the team had high degree of confidence in the estimation.

The whole magic worked!!!!!!!!!!!!!!!!!!!

I called it 1+1 > 2

Any thoughts, comments, queries, arguments??? I will be glad to hear.

Also how do you go for sprint planning?

Saturday, July 12, 2008

Decorator pattern in Action

This time we are going to solve logging problem.
Requirement is as simple as that:
Login story: System should log all informational as well as failure messages into text file.

That sounds way simple, right? Even without using any existing logging framework.

All it takes is just one static class.
public static class Log
{
public static void Write(string message)
{
//code to write in text file
}
}

And the usage looks like
Log.Write(“something weird happen here”);

So far so good.
The solution works so far and meets our requirement.

Next, lets consider following some OOPs. Here is what I got from Head First OOA & D.
• Make sure your software does what client want it to do
• Apply OOP to make it maintainable.
• Re-factor to improve any duplication.

We have already satisfied first bullet line. So let’s proceed to second one.

One of the OOP says “Depend upon abstraction”. But in our solution, we are tightly binding client with static class. So let’s instead use interface and push all the concrete code behind it.

Our new implementation looks like this:
public interface ILogger
{
void Write(string message);
}

public class TextFileLogger : ILogger
{
private readonly ITextFileWritter _textFileWritter;

public TextFileLogger(ITextFileWritter textFileWritter)
{
_textFileWritter = textFileWritter;
}

public void Write(string message)
{
_textFileWritter.Write(message);
}
}

If we look at closely here, rather than writing code for IO into logger class, I have pushed them into their own class. Why????? Remember Single Responsibility Principle? Class should have only one reason to change, right? So our logger should be responsible for logging not for writing to text file. This also gives me good opportunity to unit test my logger. To achieve this goal, I have used one of my favorite Inversion of Control techniques called Dependency Injection [This might sounds like weird but I am favoring this approach because it gives me, unit testing benefits plus we have textFilewritter, which can be used anywhere else too].

Now, at this stage, our solution looks great. It perfectly meets client need as well as follows OOP from the maintainability point of view.

It’s been well said for software: The only constant in software is Change. So what if we have requirement coming up later: need to feed all these log messages to xyz MQ, so that somebody can take corrective action on them.

With our new code it should be that difficult as all we have to do is CHANGE TextFileLogger class. Add one line there, to make call to some class which will write into MQ.

Remember though, key here is our ability to reach at this file and CHANGE code in it. We may not be lucky to get access to source file every single time (This is the case, almost every single time when code that we wrote, is shipped as part of some framework). And again its always risky to change somebody else’s code. Now you have to test not only your new functionality but existing one too and make sure you haven’t broke any thing (Isn’t that very common, breaking existing code while making change. People working on maintenance project, knows this better than me)

Certainly, our solution is failing at this last litmus. We are in trouble again. Need Help!!!
I heard, one of our old friends, whom we never bother to call so far, can help here. So let’s knock her door. By the way, her name Decorator. Here we are at the door

Me: (Knock knock)
Someone from inside: Who is this?
Me: Hey I was looking for Decorator. Is this a right place where I can find her? I seriously need her help.
Door Opens.
Decorator: I am decorator. I am glad that you came here to help. Many programmers ignore me, either because they don’t know me or my power.
Me: What power you are talking about?
Decorator: Ability to add behavior without touching existing code.
Me: Sounds interesting. I am looking for something like that only. Could you elaborate on this.
Decorator: why not, here is what GoF says about me:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Me: As always, that was big bumper for me ?
Decorator: Don’t worry. Let me simplify it for you. Remember me, when you have requirement to add extra behavior on top of existing one, without changing original code.
Me: I am with you. Go ahead
Decorator: So when it comes to add behavior, all you have to do is implement existing interface, in your case, ILogger, and keep reference to original one in your new class. So the new class looks like this
public class DecoratedMSMQLogger : ILogger
{
private readonly ILogger _logger;
private readonly IMSMQWritter _msmqWritter;

public DecoratedMSMQLogger(IMSMQWritter textFileWritter, ILogger logger)
{
_msmqWritter = textFileWritter;
_logger = logger;
}

public void Write(string message)
{
_msmqWritter.Write(message);

if (_logger != null)
_logger.Write(message);
}
}
Me: Ok, and now all I am doing is passing each calls to that logger, after I am done with mine
Decorator: Exactly. And by doing this, what you just followed is called, OCP.
Me: you solved my problem. Thank you so much and I promise to visit you again and again
Decorator: my pleasure, bye bye
Me: bye

PS: sample code already uploaded in my google repository.

Tuesday, June 17, 2008

Code sample for design pattern available

I have created new google code project for hosting all the code sample which I use through out the series of design pattern.
you can get it from here

you need svn client, for downloading this code sample.

Update on screencast: As I promised earlier, John and I are going to record screencast on each of the pattern, as we post them but so far other personal/work stuff has kept us busy so couldn't record any. Stay tuned at http://feeds.feedburner.com/mahendramavani for these screencast.

Very soon, I will be posting next one in the series

Wednesday, June 11, 2008

How to get latest changeset number from TFS within NAnt

I had hard time getting this up and running so thought of sharing here. Might be useful to someone.

This guy has excellent post on this topic, here

Its very simple and self explanatory, so I don't think I have to give any thing more. Just ignore other target and focus only on Version target

The real gut behind this comes from the C# code, embedded within NAnt task

Here is the unchanged copy of code snippet, in case you don't want to navigate way.

public static void ScriptMain(Project project)
{
project.Log(Level.Info, "Connect to " + project.Properties["tfs.server"]);
TeamFoundationServer tfs = new TeamFoundationServer(project.Properties["tfs.server"]);

// Get a reference to Version Control.
Type type = typeof(VersionControlServer);
VersionControlServer versionControl = (VersionControlServer)tfs.GetService(type);

project.Log(Level.Info, "get changesetId for " + project.Properties["tfs.fullpath"]);
IEnumerable changeSets = versionControl.QueryHistory(project.Properties["tfs.fullpath"], VersionSpec.Latest, 0, RecursionType.Full, null, null, null, 1, true, false);
int latestChangesetId = 0;

// there is only one
foreach(Changeset c in changeSets)
{
latestChangesetId = c.ChangesetId;
}

project.Log(Level.Info, "ChangesetId is " + latestChangesetId.ToString());
project.Properties["project.version.revision"] = latestChangesetId.ToString();
}

Monday, June 9, 2008

Strategy Pattern in Action

Let’s start with describing problem in hand. To be more towards BDD side, let’s define current context.

Here is the requirement cheat that we received from our client.

  • An Eagle is a Bird.
  • A Parrot is a Bird.
  • A Crow is a Bird.
  • A Sparrow is a Bird.
  • All Bird can fly.
  • Eagle and Crow fly the same way i.e. they print “FAST FLY” when the method is invoked.
  • Parrot and Sparrow fly the same way i.e. they print “SLOW FLY” when the method is invoked.
  • All birds eat.
  • Eagle and Parrot Eat the same way i.e. they print “EAT GRASS” when the method is invoked.
  • Crow and sparrow eat the same way i.e. they print “EAT FRUITS” when the method is invoked.

Our goal is to implement this, with in most maintainable fashion or call it best possible solution, which we can think of.

Sounds simple, isn’t it?

All we need is one interface, call it IBird, with fly and eat method. And then Eagle, Parrot, Crow and Sparrow will implement this interface. Base on our current thinking, our class diagram looks something like this:














public interface IBird

{

string Fly();

string Eat();

}

public class Eagle : IBird

{

public string Fly()

{

return "FAST FLY";

}

public string Eat()

{

return "EAT GRASS";

}

}

public class Parrot : IBird

{

public string Fly()

{

return "SLOW FLY";

}

public string Eat()

{

return "EAT GRASS";

}

}

public class Crow : IBird

{

public string Fly()

{

return "FAST FLY";

}

public string Eat()

{

return "EAT FRUITS";

}

}

public class Sparrow : IBird

{

public string Fly()

{

return "SLOW FLY";

}

public string Eat()

{

return "EAT FRUITS";

}

}

Wait a minute!! Are we sure this is best possible thing we can do here? Is this most maintainable/flexible solution that we can possibly have??

Let’s think over this!!!

Aren’t we repeating our self when we implement Fast Fly method in Eagle as well as Crow? Same thing goes for slow fly, eat grass and eat fruit method too. Clearly, we have more than one instance of our algorithms. So it fails on maintainability test (because now we have to remember that every time we change something or fixes some issue, we have to do it at two places)

Let’s run flexibility test now. Our client has come up with following new requirement

A Plane is not a bird.

Plane fly the same way as Eagle and Crow i.e. it print “FAST FLY” when the method is invoked.

Hmmm….. Since we have same behavior as in bird, how about implementing IBird and thereby get the behavior.







public class Plane : IBird

{

public string Fly()

{

return "FLY FAST";

}

public string Eat()

{

throw new System.InvalidOperationException();

}

}

STOP!!!! Does this make sense? C’mon… after all, plane is not a bird. And what does it eat? May be fuel, but our client didn’t specified any requirement related to that. One option could be to leave it as not implemented though.

Grrrrrrrrr!!! You are now violating ISP. Sounds like we are failing on this test too... Shame on us, couldn’t clear even one test.

We need help. F1 please!

Somebody is knocking our door. Let me go and open the door.

Me: Hey, who is there?

Voice from outside: Hey it’s me, Strategy pattern. I heard you screaming for help. I think I can help you. May I come in?

Me: hmmm… sure, why not? So why do you think you can help me with solving my problem?

Strategy Pattern: Well, you see, you are trying to put everything in inheritance base model and that is why you are falling in trap. Rather you can use compositional approach.

Me: ha ha ha… that’s too much jargon, just like Microsoft help. Now can you come to the point and tell me how to solve my problem, instead?

Strategy Pattern: Sure, lets re-consider our approach to this problem here. From the description, it is clear that we are talking about two different set of behavior, Flying and Eating, right?

Me: Ya, I can see that as well.

Strategy Pattern: ok, so lets define two interface called ICanFly and ICanEat, to represent them.

Me: sounds good to me.

Strategy Pattern: Now since we have Fast flyer and Slow flyer, we can implement them in class called FastFlyer and SlowFlyer respectively.

Me: Go on

Strategy Pattern: And then, we have FruitEater and GrassEater , which implement ICanEat. That makes our class diagram look like this:














public interface ICanFly

{

string Fly();

}

public interface ICanEat

{

string Eat();

}

public class FastFlyer : ICanFly

{

public string Fly()

{

return "FAST FLY";

}

}

public class SlowFlyer : ICanFly

{

public string Fly()

{

return "SLOW FLY";

}

}

public class GrassEater : ICanEat

{

public string Eat()

{

return "EAT GRASS";

}

}

public class FruitEater : ICanEat

{

public string Eat()

{

return "EAT FRUITS";

}

}

Me: I am with you. Carry on

Strategy Pattern: Finally, Eagle is fast flyer and eats grass so why not let it implement ICanFly and ICanEat interfaces. In our implementation of Fly, we will delegate this task to FastFlyer and for Eat we will delegate to GrassEater.

Me: Now you are going to tell, we can do same thing for Parrot, Crow and Sparrow too, right?

Strategy Pattern: you are smart! So that gives us new picture like this:














public class Eagle : ICanFly, ICanEat

{

public string Fly()

{

return new FastFlyer().Fly();

}

public string Eat()

{

return new GrassEater().Eat();

}

}

public class Parrot : ICanFly, ICanEat

{

public string Fly()

{

return new SlowFlyer().Fly();

}

public string Eat()

{

return new GrassEater().Eat();

}

}

public class Crow : ICanFly, ICanEat

{

public string Fly()

{

return new FastFlyer().Fly();

}

public string Eat()

{

return new FruitEater().Eat();

}

}

public class Sparrow : ICanFly, ICanEat

{

public string Fly()

{

return new SlowFlyer().Fly();

}

public string Eat()

{

return new FruitEater().Eat();

}

}

Me: Wow, you see that solves my problem, because I am no more repeating my algorithm here. It’s been implemented at just one place

Strategy Pattern: Of course. Do you see any other benefit too?

Me: Hmmm. Let me think………………….

Me: Yes, you see, now I can have plane which implements only ICanFly interface and I am going to delegate actual implementation to FastFlyer again.

Strategy Pattern: right, that gives you







public class Plane : ICanFly

{

public string Fly()

{

return new FastFlyer().Fly();

}

}

Me: And it also passes my second test of flexibility because I could change my design to accommodate new enhancement, very easily.

Strategy Pattern: There you go.

Me: Thank you so much strategy pattern. I am glad that you came here and taught me such an important lesson.

Strategy Pattern: I am glad too, that I could be of some use.

Me: Last thing, I would like to ask though, how do I recognize you in future? Do you have any formal identity?

Strategy Pattern: Oh ya, I am defined as

“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.”

Me: sounds great, and once again thanks for this valuable lesson. I guess we will meet again very soon J

Strategy Pattern: bye bye, and Develop smartly J

-------------------------------------------------X-------------------------------------------------

That was end of my first session on the ongoing series of blog about design pattern. I am planning to upload all my code sample on google code repository. So watch out at http://feeds.feedburner.com/MahendraMavani for more update.

Also, along with my colleague, John Teague, I am going to record screen cast on strategy pattern. This screen cast will briefly cover what I have discussed here and then we will jump to real life usage scenario of strategy pattern in action.

Disclaimer: I am not claiming to be design pattern expert. This is just 2 cent from my side to feel the ocean. I welcome comments, suggest, concern, query and healthy argument on this post. Please feel free to drop your opinion in the comment section.

Wednesday, June 4, 2008

Design Pattern Series - Table of content

As promised in my earlier post about this series kick off here is the table of content.

Entry in this table will directly point to post once it's online, So you can bookmark this blog as index to whole series. Entries are not in any particular order and we might post 3 and 4th before 1 or 2nd. Idea is to make all of them available at the end of this session.

  • Strategy - screencast
  • Observer - screencast
  • Decorator - screencast
  • Singleton - screencast
  • Command - screencast
  • Factory, Factory Method - screencast
  • Abstract Factory - screencast
  • Difference between Factory method and Abstract Factory
  • Template - screencast
  • Difference between Factory and Template
  • Adapter - screencast
  • Facade - screencast
  • Difference between Adapter and Facade
  • Iterator - screencast
  • Composite - screencast
  • Compound - screencast
  • State - screencast
  • Proxy - screencast
  • Difference between Decorator and Proxy
  • Visitor - screencast
  • Builder - screencast
Develop smartly :)

Why do we need to know design pattern?

Probably, we all know definition of design pattern from wiki that its general reusable solution to a commonly occurring problem. And of course we have thousands of web pages over internet, telling about these patterns every now and then. Aha! Don’t forget those dotfactory for GoF.

So the natural question that comes in my mind is, WHY one more? Here is the answer I got from within

While many people know these patterns by definition and by class diagram, what is missing really is what they actually mean when it comes to applying them in practical scenario. Most importantly knowing when to apply and when not to (Nothing is as bad as applying design pattern at wrong place). Besides, what matter more in practical cases are design principles and not just blind application of any pattern (just because you know that pattern). After all ultimate goal behind any design pattern is to encapsulate what is changing.

With that in mind, I am planning to start with series of blog on design pattern, along with my friend John Teague. Our goal is to

  • Uncover design principle buried behind each design pattern
  • Dig bit more into practical application of pattern over just definition and class diagram
  • Going beyond “General reusable solution”
  • Finally, disclosing why everything you hear about these patterns from your friend is almost wrong.
  • Avoiding those silly coupling mistake which gifts you sleepless night just before release.

Here are few important bookmarks, which you might be interested in keeping eye on:

http://www.lostechies.com/blogs/johnteague/

http://mahendramavani.blogspot.com/

Alternatively, you can subscribe to our RSS feed at

http://www.lostechies.com/blogs/johnteague/rss.aspx

http://feeds.feedburner.com/mahendramavani

I will soon post about overall outline of this series of blog. In short, as of now, idea is to cross post on both of above space and each design pattern will followed a screen cast which will demonstrate example discussed in the blog. These screen case will be a very good example of pair programming too.

Watch this space… much more interesting to come

Develop smartly :)

Sunday, June 1, 2008

changed to feedburner for RSS

Here is link to my rss feed

http://feeds.feedburner.com/mahendramavani

I am planning to post series on design pattern in action. Keep tag on this url to learn more.

Code smartly :)

Friday, March 21, 2008

is it a good idea to include source safe binding information in solution and project file?

Microsoft is, as usual, kind enough to give yet another headache to the development team when they gave TFS. I bet its just copy paste from VSS code. (After all both sucks equally)

What I don't like about both of them is the fact that they uses .net solution file and project file to keep track of these binding information.
Now even if I agree that microsoft was kind enough to give those .sln and .csproj file, that doesn't give them luxury of using those file for whatever they think would be OK.
Now when I am working in integrated VS environment, my .sln and .csproj file has many reason to change and I end up, checking then in every single time. And of course, those .vsssc and what not are all your friends. Every single time when you what to check in, this extra noise is always present.

Dam it!!!! Microsoft sucks....

Why can't I have something like subversion. You better keep track of your binding stuffs separately. Give me subversion and I am happy on any day. But never VSS or TFS

I have been fighting on my current project to see if we can change source control. But the real problem is client has standard across all projects to use TFS. (Some people are blind follower of MS)

So best of luck to me again!!!!!!!!
I am hopping to make difference here.

Thursday, March 20, 2008

why would you use scrum?

So far I have seen many reason for why an organization should start doing scrum over waterfall.
They all ultimately nail down to some of these:
  • Frustration
  • Not able to meet deadline
  • Increased stress towards the end of the project.
  • Software with nice to have features but has almost nil business value.
  • Historical failure in the project
3 days back I have started with my new assignment and was very excited for working for one of the big B in the industry. Again from what I learned from job description and then during the interview process,was promising too.

Now since I am insider here, I know some of the ground reality. Here is the few comments that I heard on very first day, as reason for choosing scrum methodology for my current project.
  • This project was in planning phase since last 18 month and we never had something concrete which can be shown to upper management.
  • No one know about project requirements and after searching little bit, we found scrum as the only methodology which allows us to work without requirement.
  • We don't have any process or discipline and scrum is the only possible ad hoc way to do this
After hearing all this, it might sounds frustrating but the silver light here is that: team is really interested in trying this new methodology and they do believe in making things done. People are open for trying new things and learning.

So here is what I am thinking of doing
  • Introduce TDD and BDD(yes they aren't doing it either)
  • Scrum training for team and upper management (session as well as on the job demonstration)
  • Pairing with each member for getting them up to the speed (Playing red-green-refactor game)
  • Re-structuring project solution and refactoring overall architecture.
  • Introducing SRP, DI, IoC to the team.
  • Start using structuremap, NAnt, MSTest, Resharper, RhinoMock
Well, best of luck Mahendra! Hope you can make difference.

finally, Jeffrey is the great guy. I owe all these learning to him, which I am going to implement here. Hey Jeff, its party time for you. Your teaching is paying off here :)

Friday, December 28, 2007

Foreach in C# uses ducktype

This came to me as little surprise. May be for others too.. including my manager with whom I had discussion about this once.

So far I was under the impression that for any class to be used inside foreach, it must implement IEnumrable interface. I remember myself asking this question in interview to many guys and even answered same question in the interview when I was on other side of the interview table.

Today I am going to proove that its not true anymore.... (what??????)

Well, all you need for your class to be used inside foreach is
  • have GetEnumrator method with no input params and return type object which has two method MoveNext (returns bool) and property Current with getter (returns object)
Still not want to believe me? well here is the code snippet
using System;

namespace ForEachDemo
{
public class Program
{
private static void Main(string[] args)
{
// the following complies just fine:

Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};

People peopleList = new People(peopleArray);
Console.WriteLine("This program demostrate usage of foreach without implementing IEnumerable interface.");
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);

Console.WriteLine("Press return key to exit...");
Console.ReadLine();
}
}

public class People
{
private Person[] _people;

public People(Person[] persons)
{
_people = persons;
}

public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
}

public class PeopleEnum
{
private Person[] _people;

// Enumerators are positioned before the first element
// until the first MoveNext() call.
private int position = -1;

public PeopleEnum(Person[] list)
{
_people = list;
}

public bool MoveNext()
{
position++;
return (position < _people.Length);
}

public void Reset()
{
position = -1;
}

public object Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}

public class Person
{
public Person(string fName, string lName)
{
firstName = fName;
lastName = lName;
}

public string firstName;
public string lastName;
}
}

just copy paste this in empty console app and look at the result. You will be more than surprised to see what is happening....

Obvious question you might want to ask here is what the F**k is going on here. The answer to this is foreach in C# (may be even VB.NET, I didn't tried my self) uses ducktype.

Develop smartly:)

NUnit 2.4 is here with support to VS2008 and RowTest

This is really cool. So far NUnit was legging one cool feature of MBUnit - RowTest

Not any more. NUnit 2.4 is here to kick that legging :)

IDE support is included as extension in Test Driven .NET 2.11. you can download from here. Row extension binary is here

Click on one for 2.4.5 and the zip file will have two dlls (NUnitExtension.RowTest.AddIn.dll and NUnitExtension.RowTest.dll )

After you install Test Driven .NET 2.11, navigate to '%ProgramFiles%\TestDriven.NET 2.0\NUnit\2.4' and create subdirectory called addins. Then copy NUnitExtension.RowTest.AddIn.dll inside addins. Its is required that you don't keep any other non dll file in this folder. Click here to know why?

Finally use NUnitExtension.RowTest.dll as your BinRef in the UnitTest or IntegrationTest Project.

Now writing test is very simple. Here is the snippet

using NUnitExtension.RowTest;

namespace Mahendra
{
[TestFixture]
public class RowTestDemoTester
{
[RowTest]
[Row(100,20,120)]
[Row(10,11,21)]
[Row(20,30,51)]
public void Simple_Addition_Test(int a, int b, int sum)
{
Assert.AreEqual(sum, a+b);
}
}
}

What is even cool is, once you install TestDriven.net 2.11, right click on your test project and you will see under Test With submenu -> all your previous installation of NUnit as well. i.e. in my case it is NUnit 2.2 and NUnit 2.4

If you choose to test using NUnit 2.2 (any one prior to NUnit2.4) all the RowTest will be simply ignored without giving any compilation error or failing test.

Develop smartly :)

Thursday, December 27, 2007

T-SQL hacks, getting Nth highest, top N and paging

Its time for T-SQL

Some of the common scenario for data retrieval could be (without using TOP keyword remember oracle doesn't have TOP)
  • Getting Nth highest/lowest value column
  • Getting top Nth highest/lowest value columns
  • For paging purpose, getting X row for page n i.e. getting column 11 to 20)
Here is some of my hecks for obtaining above results. I have used NorthWind orders table for this purpose.

For bullet point 1: Getting Nth highest, here is the t-sql
select * from orders a
where N-1 =
(select count(orderID) from orders b where b.orderid > a.orderid)

trick here is self join. Notice closely here what I am doing.
  1. For each row of inner table (alias b) get count of columns from the same table i.e. self join, who has value higher than current row of outer table.
  2. Use common math like this: for any column, in outer table, to be Nth highest, it must be lower than N-1 columns of inner table.
  3. Select that row. It is your Nth highest row
Apply same logistic and you get N highest/lowest row like this
--TOP N highest
select * from orders a where 10 >
(select count(orderID) from orders b where b.orderid > a.orderid) order by orderid desc

--TOP N lowest
select * from orders a where 10 >
(select count(orderID) from orders b where b.orderid < a.orderid)

The only difference between last two queries are inner query condition. By same methodology mentioned above, first query is looking for number of columns having higher value, second one looks for number of column having lower value.

Well well well....
so what is the practical use of all this crap then? Hmmmm....
May be the answer is bullet point number 3 : For paging purpose, getting X row for page n i.e. getting column 11 to 20)

Now I am applying above logic in two fold to get rows for paging .

My input here would be page size and index of the page (1,2,3 base).
Logic here is to get 11 to 20 row, first get 1 to 20 and then filter out 1 to 10

Here is the query
begin
declare @page_size int, @page_number int

set @page_size = 10
set @page_number = 3

select * from orders a
where @page_size*@page_number >
(select count(orderID) from orders b where b.orderid > a.orderid)
and not exists
(select c.orderid from orders c
where @page_size*(@page_number-1) >
(select count(orderID) from orders d where c.orderid < d.orderid)
and a.orderid = c.orderid
)
order by orderid desc
end

*********************************************************************
Again, I know some of the results above can be obtained easily with sql 2k5 (i haven't spoiled my hand with this yet though) and up,this exercise is to strengthen understanding of how select gets executed. The whole logic is to closely understand execution of query and thereby manipulating it to get desired result. Alternatively it can be helpful as interview question for either side of the table :)

Setting up wireless router

This time nothing my own creation. I was setting up my wireless router for the first time and was concern about security stuffs as wireless is more vulnerable to hacking. I can to this page. Sounds interesting reference to me. May be it can help somebody else too.

Tuesday, July 24, 2007

Beginner's guide to Scrum

Its almost 2 month, since I promise to post more about scrum methodology. Never got chance to write on this till date. None the less, here goes begginers guide

Scrum is yet another s/w methodology which focus more on interaction and colloboration amongs team. Here team doesnt simply mean group of developer/tester and architect but also project manager and business stack holders (or atleast some representatives of them).

Before we can proceed any further here is introduction of few terms
  • User Stories: mini card which describe feature of application, give it a name.
  • Product Backlog: List of all user stories which together implies functionality required by our application, listed in decending order of priority.
  • Sprint: Development Iteration, typically 1-3 weeks time. At the end of which development team comes up with demo of what has been implemented.
  • Sprint Backlog: Document which includes top priority stories out of product catelog which needs to be implemented in next/current sprint.
  • Story Points: Measure used for estimating size of user story.
  • Velocity: Number of story points that can be implemented by given team in single sprint.
  • Focus Factor: Fraction of Idle time, development team is expected to spent on implementation of current sprint backlog items.
  • Burndown chart: Pictorial representation of how many story points have been left, at any point of time during sprint.
With this knowledge lets move forward and state how they fit into day to day work.
At the very begining of project business stack holders, project manger and developers(part of the team if full team is not in place yet) come to user strory writting workshop. Input point for this workshop is user expection from the user and outcome is product backlog. While its true that end user know this part better, its important to involve developer as well since they are the one who comes up with non-funcitonal requirements during this workshop. (i.e. security and performance requirement).

Well if that sounds like requirement gathering phase of Waterfall method, wait a minute. Best part here is, this backlog is not static read only document. It just guides team to the right path. Depending upon visiblity and upcoming ideas during sprint, stack holders can come up with new features, droping certain part and product manger will readjust backlog iteam based on know priority at that point of time.


Once this gourd work is in place development team's work is very straightforward. Decide sprint duration and velocity (Initiate with trail and error method, adjust it until team is comfortable with it).

Now is time for sprint planning meeting.

Attendees for this meeting are stack holders, project manger and development team (by the way development team also includes testing people). Team starts by taking first item of product backlog, clarify what is the scope of this story, estimate it in terms of story points and putting it in current sprint backlog. This process contines till sprint backlog is populated with items whose estimation sums up to agreed velocity for this sprint.) Original story can be further segregated into multiple stories in this planning meeting as well as two or more stories can be combined to one. Nothing is hard and fast here. Flexibility is everywhere:). One important piece of information against each story is "step to demostrate". Together team indetify step to demostrate completion of that story.

With sprint backlog in place, developers task is to grab one story and start implementing till all the stories are done.(Developer can always pick up phone and dial to business owner should there be any doubt during implementation of any story and story can even be changed at this point if that makes sense to business). At the end of sprint, team meets again and performs those agreed upon steps to verify completion of user story. Any finding at this point will be included in product backlog and again starts game of planning next sprint. This game continues till business owners are satisfied with the system or they run out of budget to develop any further.


What are the benefits fo this approch???? Well there are many but someof them I would like to point out are
  • High degree of flexibility and adoptability is clear visible benefits.
  • Making sure that team works on high priority features always.
  • Highly recommend for development project where end user can't envise full set of functionality at the very begining.
  • Continues feedback by user rather than waiting till end which enables early correction.
  • Cost of changing is low and doesn't increase exponetioally with project duration.
  • Continueous collobaration between stack holder/user and developer ensures end product which meets user requiement.