What's hot ? (and I mean really ...) - scroll down for more
1).  Code Templating - advanced usage of delegates & generics: my slides & demos are available for download! CodeProject article is also available.

2).  My series "TDD in the eyes of a simpleminded" is in progress(including code!): preface, part1, part2, Q&A 1, Manual Stub .vs. Mock Stub

3).  TDD Workshop: SeeCompass v0.1 and v0.2 are out.
# Wednesday, May 02, 2007

Damn, it was so much fun to play a little with TDD and abstract the lousy API given by Microsoft to register client-side script. I'll write about the process and design changes I've made due to testability reasons. TDD is a great design tool, it's amazing to witness the "before" and "after" of your code, all because of the requirements to test things separately.

Here are a few API samples, taken from the Demo project (you can play with it and see the results):

public partial class _Default : Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      ClientSideExtender script = ClientSideExtender.Create(this);

      script.RegisterMethodCall("alert").WithParameters("hello world!").ToExecuteAt(Target.EndOfPage);

      script.RegisterVariable<string>("myStringVar").SetValue("test").ToExecuteAt(Target.EndOfPage);
      script.RegisterVariable<int>("myIntegerVar").SetValue(5); // Target.BeginningOfPage as default

      script.RegisterScriptBlock("alert('proof of concept - state:' + document.readyState);").ToExecuteAt(Target.PageLoaded);
   }
}

Keep in mind that I'm only supplying a different API (abstraction) of Microsoft's implementation. In order to accomplish that, I'm using Windsor to wire the ClientSideExtender with the new ajaxian ScriptManager(supports UpdatePanel), which will actually be responsible to register the script under the hood. You can look at the web.config (under the <castle> element) for more details.

Source:
Lnbogen.Web.UI.zip (253.56 KB)

.NET | Design | JavaScript | TDD
Posted by Oren Ellenbogen 
02/05/2007 02:05, Israel time UTC+03:00,     Comments [1]  | 
# Saturday, April 28, 2007

Thank God, some may say, that bananas are still way too expensive to replace human developers with apes; Well, at least by Uri Kalish in his Why Software Engineers Should Care About the Price of Bananas. Let's face it, we have too many "chumps" out there, lurking to make a few extra bucks by faking it really well. But every once in a while, the sun is shining in glorious colors and you meet a really talented developer whom you think will be a great addition to your team. You ask her logical questions, she shoot right back with pearly answers; You ask her to design something and bang, she nails it; You ask her to juggle with code a bit and it is all sweet. She has analytic mind and just enough experience. Total Package.

This leaves you with the one thing, the only thing, that really matters - how can you tell whether or not she will use her analytic mind to solve your team's problems instead of introducing more complicated ones while trying?

I came to the conclusion that the only way to know how skilled a developer is, is by letting her solve a very simple problem and shoot more problems to the air while she solves it. Skilled developers will be able to break things into smaller chunks and solve them in a SIMPLE manner. When I say simple, I mean it, it will be so simple taht even a chump will be able to read it. Then they will move on to the next problem and solve it in the same SIMPLE way they did before. Then they'll tell you how to sew the all thing into one wonderful solution. It's actually pretty straightforward, simple things are easier to combine, but only a few folks out there knows how to "break & build" in a graceful, simple manner.

I look way back to my first days with .Net and OOP and I can honestly say that I did it all wrong(although it looked damn right at the time). If you looked at the code, it was elegant, in its own way, it was "sophisticated"(interfaces, events, a few Design Patterns) but it wasn't right. It wasn't SIMPLE. I had too many classes with too many (wrong) responsibilities, some of them contained quite a few God Methods and they were in no way testable. I had a great amount of green words(aka comments) to explain why things "needed" to be complex.

So for the developers among you - read, talk, write, teach and most importantly practice. Continue to improve your skills by breaking tasks into smaller chunks and keep making them green-free. If you spend more lines on documentation, you're on the wrong direction. Invest time in breaking responsibilities to different classes(class should have a very narrow responsibility) and take the time to think about your API. I'm playing quite a lot lately(Fluent Interfaces, Creating a decent API for client side script registration) with method names and the benefit I see in it is huge. readable API requires almost no documentation at all. Adding testable code to the equation and you're definitely on the right track.

For those of you out there that interview people - if you think this is it and you finally found someone - let him\her solve a few problems and focus about how simple is it to read the code, to refactor it, to extend it. How much documentation is required to explain the solution to the rest of your team?


What do you look for when interviewing skilled developers?

Posted by Oren Ellenbogen 
28/04/2007 11:38, Israel time UTC+03:00,     Comments [6]  | 
# Friday, April 27, 2007

Phil Haack gives an excellent example of how to test a registration to event while implementing MVP pattern (via Rhino Mocks). If you did not read it yet, take a pause for 2 minutes and give it a look; It is worth it, I promise.

The only thing that bothers me in the example is that the need to assert the triggering of the event kind of spoiled the code. I think that in those scenarios, it's much better to use some sort of Stub and override the class under test in order to keep the it cleaner. So instead of having this code:

public class Presenter
{
   IView view;
   public Presenter(IView view)
   {
      this.view = view;
      this.view.Load += new EventHandler(view_Load);
   }

   public bool EventLoaded
   {
      get { return this.eventLoaded; }
      set { this.eventLoaded = value; }
   }

   bool eventLoaded;

   void view_Load(object sender, EventArgs e)
   {
      this.eventLoaded = true;
   }
}


I would have created something like this:

public class Presenter
{
   IView view;
   public Presenter(IView view)
   {
      this.view = view;
      this.view.Load += new EventHandler(view_Load);
   }

   protected virtual void view_Load(object sender, EventArgs e)
   {
       // production code here
   }
}


// This will go in the PresenterTests class
public class TestablePresenter : Presenter
{
   public bool WasEventLoaded = false;
   protected override void view_Load(object sender, EventArgs e)
   {
       WasEventLoaded = true;
   }
}


Now we can create an instance of TestablePresenter and Assert the WasEventLoaded field.
My guess is that Phil actually did something like this in his project and merely wanted to show an example, but I still thought it was important enough to demonstrate this separation as I firmly believe we must make sure that our need for tests will not actually hurt the design.

.NET | TDD
Posted by Oren Ellenbogen 
27/04/2007 10:55, Israel time UTC+03:00,     Comments [2]  | 
# Saturday, April 21, 2007

In my last post about Creating a decent API for client side script registration, Eran raised a few great comments about the readability and proper usage of this style of coding. I decided to answer his questions with a post, as my comment started to fill enough paper to clean a Brazilian forest or two (well, in terms of a response).

Introduced by Martin Folwer, Fluent Interfaces ables the programmer to supply an API that can be used to build a genuine use-case in the system or just a complete logical query\request from a service. This coding style is quite different from the traditional 101 lessons in OOP school. The biggest benefit of Fluent Interface, in my opinion, is that you can read the code out load like the customer is talking to you instead of the programmer that wrote it. Sometimes it gets even better, you can read someone's else code like she\he was next to you, explaining what she\he meant do do. My take is that using a method to describe use-case\action\query\request will be (almost)always better, in terms of readability, than using parameter(s) as you'll need the IntelliSense to understand the latter. Here is a simple API, the first one is traditional OOP while the second one applies Fluent Interfaces. Please bare in mind that these samples were written just to set the ground for the difference between these two coding technique:

// take 1 - traditional style
public class ClientSideExtender
{
    public void CallMethod(string methodName, RunAt runScriptAt, bool ignoreExceptions, params object[] parameters);
}


// take 2 - Fluent Interfaces

public class ClientSideExtender
{
   public ScriptCommand CallMethod(string methodName);
}

public class ScriptCommand
{
     public ScriptCommand WithParameters(params object[] parameters);
     public ScriptCommand When(RunAt runScriptAt);
     public ScriptCommand IgnoreExceptions();
}

Assuming that we have a javascript method with this signature "markRow(rowId, shouldDisableOtherRows)", here is how can one use these API to register client-side method call(accordingly):

clientSideExtender.CallMethod("markRow", RunAt.AfterPageLoaded, true, "5", true);

clientSideExtender.CallMethod("markRow").WithParameters("5", true).When(RunAt.AfterPageLoaded).IgnoreExceptions();


Obviously, both API will create the same code eventually: <script ...>markRow("5", true);</script>.
What I really love about Fluent Interfaces is that I don't need the freakin' IntelliSense in order to understand what "true" means as a parameter(the difference is marked in red). It ables me to read it out load - I want to call a client-side method named "markRow", with 2 parameters, execute it after the page is loaded and wrap the entire thing to swallow exceptions (assume that someone else will take care of it). If you want to call a method that doesn't get any parameter, don't call to WithParameters method. You can always change the order of the calls if you see it fit (maybe calling IgnoreException before When).

One of the blames I hear(again and again) about Fluent Interfaces is that it "allows" programmers to abuse the code. "You can change the order of the calls or forget to call one and make a big mess" is a common response to the concept. To be totally honest, I don't eat it as programmers can make a mess of pretty much anything. We've all been there, right? I agree that it requires some different way of thinking about creating & using API, but then again, so does learning a new programming principle, a design pattern or a coding techinque. It took several years until people started to chew TDD and accept the advantages of using it. My guess is that in ~1-2 years, Fluent Interfaces will be much more common in the way we're writing and using code (LINQ rings a bell? well OK, leaving the "sql-like" synthetic sugar aside).


This leads me to my believe about designing Fluent Interface. I say - when appropriate, why not allowing the programmer to choose?
I would create two overloads for CallMethod, as shown above, and let the programmer decide which one she\he would like to use.

I would use Fluent Interface.

.NET | Design
Posted by Oren Ellenbogen 
21/04/2007 11:04, Israel time UTC+03:00,     Comments [6]  | 
# Wednesday, April 18, 2007

I'll start my post with a question:
What's the difference between ScriptManager.RegisterClientScriptBlock and ScriptManager.RegisterStartupScript methods?

Well, the only way to find out is not by looking at the method names but rather to look in MSDN. According to MSDN the former registers your script after the <form> element while the latter is registering your script just before the </form>. Now, let me ask you this - how the word "Startup" can be interpreted as "end of page"?

So OK, the naming is really bad but what's even worse are the arguments of these methods:

public static void RegisterClientScriptBlock(Control\Page control\page, Type type, string key, string script, bool addScriptTags);
public static void RegisterStartupScript(Control\Page control\page, Type type, string key, string script, bool addScriptTags);

Now, most of us write this code 95%(+) of the times:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "some stupid key", "the script here, finally...", true); //like someone is stupid enough to give false - if you have a full script, why not putting it inside myFile.js and add it to the header?

I don't understand the real need behind creating a "unique" key from the type+key given to this method. Why not creating a unique key each and every time? You need to create a simple API for the common (90%) tasks. I almost never actually asked about IsClientScriptBlockRegistered. But enough complaining, time to write a few bits & bytes.

I tried to play with the API a little and here is what I came up with (it's merly the beginning, I'll update on my progress during the week):

PageClientSideExtender clientSide = new PageClientSideExtender(Page);

// A better approach, IMHO, to ScriptManager API
clientSide
  .RegisterScript("alert('run at the beginning of the page');")
  .AddScriptTags()
  .RunAtTheBeginningOfThePage();

clientSide
  .RegisterScript("<script>alert('run at the end of the page');</script>")
  .RunAtTheEndOfThePage();

//let's register something like:
// var width = 300;
clientSide.RegisterLocalVariable<int>("width").SetValue("someValue");

//let's register something like:
// var data = 'width:300;height:500';
clientSide.RegisterLocalVariable<string>("data").SetValueFormatted("width:{0};height:{1}", 300, 500);

// Let's register to the onload of the <body> and trigger a nice alert
clientSide.Body.Load += ClientSideScriptHelper.CreateHandler("alert('run on body onload! cool ah??');");


//Or:

clientSide.Body.Load += delegate { return "alert('another message shown after the page onload event was raised. sweet!');"; };


The Fluent interface gives it a nice "read-the-code-like-a-story" look&feel which makes things really easy to understand. There is no thinking here, the code says it all.

Another rant I have is that all of the API examples I've demonstrated so far are implemented although not fully tested as using Microsoft classes requires a lot of work in order to abstract. The funny thing is that they(Microsoft) have decoupled things in the new Microsoft ASP.NET Ajax library(System.Web.Extension.dll) but they made everything internal!  You have IPage, which is really useful abstraction to the Page class, sitting there as an internal member. I had to come up with some heavy abstraction to make things play nice together.

To sum up, I would really appreciate YOUR feedback about the API and any kind of suggestion or things that you would like to see in future API. I'll release the code later this week with a short demo to get you going.

Posted by Oren Ellenbogen 
18/04/2007 11:08, Israel time UTC+03:00,     Comments [5]  | 
# Friday, April 13, 2007

Agile is really about forming 1-BIG-happy family or in geek terms: one collaborative unit of work.

If you go over most(if not all) of the practices Scrum\Agile\XP have to offer, you’ll find two things in common: how to make your customers ROI as higher as possible as soon as possible and bonding everyone together so they are ALL responsible for the ship to move forward, one step at a time, constantly. Good-will and high IQ is a (really)great start but never enough. At the end of the day, customers understand working functionality described in user stories(“I will be able to move my money between my bank accounts”) rather than functional stories(“The system will supply Web Services in order to integrate with our billing system”) and most importantly – they’ll only pay for the former. But the technologist part in me(I’m made of 70% water, 29% 0 and 1, leaving about 1% for adult context), understands that we programmers really love to solve hard problems in elegant ways. I never saw nor hear a developer jumps up and down saying something like “I made it possible to move money from account A to account B!” or “The user can now get his lost password via email!”. I just love the idea of creating a successful setup so our brilliant guys will be able to transform their IQ into business value. What a noble idea, actually making one’s talent into a fat paycheck (I’m probably the only one finding it romantic am I?). 

In many ways, gather the “right” practices for the team is like getting ready for a lecture in front of a big (important)audience. Forming a good lecture requires a lot of thinking(what do I want to deliver), preparation(how can I do it), ice-breakers\funny stories(keeping them smiling  and cooperative in the process), motivation points(keep their eyes on the ball), examples(proves that it works) and most importantly – letting your audience know what they’ll gain from this lecture(high ROI) and keeping your promise. Don’t be a fool, trying to enforce the process or make a shortcut will be like participating in a lecture where the presenter decide to write a set of articles in his slides causing you to look at the 100–inch-screen-with-1500–words-per-slide, thinking it will deliver all the data you’ll need. It never does.

How can you start making a change(including improve an already great practices)?

  • Read, listen, view, try things, write notes. Play the secret agent role and try to learn your enemy.
  • Let your people know about these practices. Open their eyes into new ideas.
  • Explain how things will work from now on, how it will look in 2 months, 6 months, 1 year, 2 years from now. Inspire them.
  • Answer their questions, make them trust in the system and trust the family.
  • Detect negative workers and detach them from the team. NOW.

A little push to get you going:

Posted by Oren Ellenbogen 
13/04/2007 06:26, Israel time UTC+03:00,     Comments [0]  | 
# Monday, April 09, 2007

Too many times in our lives as developers, we feel that in spite of our talent, skills and knowledge we just can't seem to bootstrap ourselves from the mess we're in. It reminds me many movies (and the great Prison Break television series) where you see a nice, innocent guy put into jail with a bunch of murderers and rapists. After stabbing a guy in order to prevent from being stabbed, our hero gets into more trouble than he started with. This vicious circle goes on and on so by the end of the movie, you are not sure what he could have done different. His skills, talents and knowledge were thrown away, replaced by the need to survive. In many scenarios in life, I feel like that guy.

Avoiding the (really)poor analogy of un-unit-tested\unmanageable\coupled\you-name-it software to jail, I decided to stand up to the challenge(talk about "What not to do") raised by my friend, Uri Kalish, and share with you my vision regarding top mistakes I have experienced in the last few years. If it will able 1-N (see, I just had to be all geeky about it, even after talking for a full paragraph on jail and murderers) of you guys & gals to change 1-Z things in your world, this post will worth any future creepy comments I'll get from real ex-prisoners (what?! there must be some ex-prisoners .Net, Java frustrated coders out there, right?).

  • "Promoting" best coders into solely management positions
    It is the fear of losing someone and the way our community treat one's status causing this behavior. To make things worse, in most of these scenarios, the company (somehow)feels obliged to let him\her* manage 4-5 people so there is no fat chance he'll write code in the coming 2-3 years. I believe that this is the top-1 fatal mistake companies do. They are losing their most talented, most efficient programmers without the right adjustment and natural growth by the rest of the team. The way I see it, this is what a Team Leader should be responsible for:
    • Code for at least 60% of his time. Not 20%, not 30% and most definitely not 50%(this will cause him to fall back into 60%-40% manager). Great war leaders were great warriors, always on the front of their men. If you prefer to be left behind(technology speaking), managing from above, you should not be a Team Lead.
    • Get to know your people - what do they like to do after work hours, what are their hobbies, write down their birth-dates so you could buy them something symbolic. Make them feel like home. Spending 10+ hours in the office is more than most of us spend in our home. Notice how a very cheap gesture may change your team's world - some people like fancy keyboards, some(I'm included) prefer a big LCD screen and others prefer an extra bonus. Let's say that you invest up to 500$ per person, the ROI is still tremendous(try to think your hourly cost and how fast you'll return it). People will have everything they need(=want) in their office. Google is famous of hiring the best just because of taking care of the small details.
    • Manage your team's time - help to set the deadlines per sprint\iteration, but more important - analyze the team's productivity by picking up time estimations and actual time spent, and perform some calculation via various tools to understand the bottlenecks your team experience. Make them see, make them witness of how they can become more productive with the right set of exercises.
    • Be a mentor by leading the team with daily improvements. Change the way they think, blow their mind with new stuff. Direct them to "home reading" that you know they'll enjoy. Make them excited! Be a great developer for them.
    • Shield your team members from political business. Make sure no one is interrupting them meeting the deadline.
    • Meet the deadlines. Don't afraid to speak your mind when things are out of track. Make them see you've got what it takes to lead them back to the right path. Tough love may create great developers with the right amount of genuine caring.

         This will allow the Team Leader to remain an efficient programmer and the team grow into the new situation.         
 

  • Big teams
    Team size should never be more than 4, where preferable(IMHO) is 3. We want our Team leaders to write code, remember? Managing more than 2 people other than yourself will make your TL too busy to code. Even worse, big teams will cause team illness:
    • No matter of how much good-will exists in the team, keeping many people in the loop is simply too much overhead. It will wear off your teammates.
    • This will divide the team into smaller "virtual" teams, each one is built around a user story or a complete feature.
    • Now it's getting hard to know when you're breaking things for others as no one is really into your teammates code or requirements.
    • This leads us to the most unwanted behavior - no one in these virtual teams is an expert on their domain as the team switch context all the time to meet the big team deadlines. Context switch and lack of domain experts will kill you team. From inside out.

         Keep your teams small. Managers should sync the small teams and keep the eye on the ball for them. This is their skill, their talent.

  • Waste valuable time on the wrong tasks - skills .vs. tasks impediment
    This one really gets me. How many times you've been asked to do something you know you shouldn't have assigned for? Giving a c++ hardcore hacker to write HTML is silly(at best). Now, I can relate to the feeling managers have assigning these tasks  just to keep the deadlines but this shows of lack of creativity rather than good leadership. For example, the c++ hacker will cost around ~X5 then a young talented designer (by young I mean 16 years old cool dude that's doing it from age 11). Hire someone, even for a few hours a month and let the them do their magic. From some reason, managers never thought about hiring a graphic designer to write hardcore c++ code, right? It will be amazing to measure the ROI you can show your bosses even after 2-3 iterations just by putting the right players in the right positions. The same goes about database, system administrator, (customer)documentations etc. Stop treating someone's time as equal to someones else time. hardcore multi-threading guru will not enjoy a full day or two of playing with HTML to fit different resolutions. Be creative and make the adjustments! 


I have a lot more rants and tips but I'll leave it for further posts so be good and stay out of software jail.



[*] - I'm sorry but writing him\her all over the place is plain crazy. You know I'm no sexist ;-)

Posted by Oren Ellenbogen 
09/04/2007 01:19, Israel time UTC+03:00,     Comments [4]  | 
# Wednesday, April 04, 2007

One of my favorite C# 3.0 features is Extension Methods. In short, it ables you to extend an existing type with additional behaviors. For example, you can consider to extend the type System.Int32 (aka "int") with a new method named IsEven.

The syntax is quite trivial:

namespace Lnbogen.Extensions
{
    public static class Extentions
    {
        public static bool IsEven(this int i)
        {
            return ((i%2)==0);
        }
    }
}

Notice the "this int" which means "I want to extend the type int".
Now I can write the following code (fully IntelliSense-d and compile time checking):

using Lnbogen.Extensions; //<- this will load the extensions, it won't compile without it!

... void TestIsEven()
{
   int num = 5;
   Console.WriteLine(num.IsEven());
}

What's going on behind the scenes is quite simple, the compiler got a little "smarter" and now knows to look for Extension Methods in the imported namespaces. I don't want to elaborate too much about the syntax and requirements as Anders Hejlsberg makes it all clear in his MSDN video: C# 3.0: Future Directions in Language Innovation.


Let me direct you to the  real  meat:


Extension Methods is going to change the way we enhance "already used" code. Up to now, looking at that need (for backward compatibility), Microsoft suggested to create an interface and an abstract class that implement this interface. This allows us to extend the abstract class simply by providing new virtual members without breaking the code. The problem in this solution is that things were getting out of sync really fast leaving our interfaces shy & dry(=out of date), just to avoid breaking changes. Even worse, due to the fact that multi-inheritance is forbidden, inheriting from the abstract class pretty much slammed the door on most of our design choices. 

Let's face it; Interfaces were programmer's nightmare(before you hack my blog and delete this post, bare with me). On one hand, we're reluctant to implement an interface with 10 members as we prefer to finish our tasks in this century but on the other hand, we want our interface to expose as much API as it can to allow easy usage for its customers(=programmers) and to avoid casting it(the interface) to "specialist" interfaces.

Well, Extension Methods allows us to extend any type. Do you get my drift here?
You can now enhance any interface you've ever exposed thus making old interfaces incredibly strong. You can define a lightweight interface(easy for the implementor of the interface) and extend its abilities without breaking any existing code(enrich the customers of the interface). This is exactly what Microsoft did with LINQ. They have extended IEnumerable<T> with many Query methods such as "Select", "From", "Where", "GroupBy", "Join" (and much more...) to enhance it with a great set of new methods while still keeping the original interface untouched. All we have to do is simply import System.Query namespace.


Brilliant.

.NET | C# 3.0
Posted by Oren Ellenbogen 
04/04/2007 07:01, Israel time UTC+03:00,     Comments [2]  | 
# Sunday, March 04, 2007

 15417-23PY.jpg

We've just received an email describing the agenda for Purim day here at Mercury.
It goes something like:

" Register for Purim disguise competition(M1 building)
(You can be painted for free ; -)

... [ some more text goes here ] ... "

The first thing that came up to my mind was "Oh shit, it won't compile, she forgot to close the second )".

 

Happy holiday everybody!

 

Posted by Oren Ellenbogen 
04/03/2007 01:59, Israel time UTC+02:00,     Comments [1]  | 
# Wednesday, February 21, 2007

Assuming that you're running it from the same directory the .csproj file exists in (using Visual Studio 2005 Command Prompt):

msbuild wapProjectName.csproj /p:Configuration=Release

msbuild wapProjectName.csproj /target:_CopyWebApplication /property:OutDir=c:\SomePath\
  /property:WebProjectOutputDir=c:\SomePath\ /p:Configuration=Release

copy bin\*.* c:\SomePath\bin\

Enjoy.

Posted by Oren Ellenbogen 
21/02/2007 11:26, Israel time UTC+02:00,     Comments [1]  |