Hello world!
June 16th, 2011Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!
Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!
I was in the middle of a TDD coaching session a couple of days ago when it hit me - people need a tool that will help them write one assert at a time!
So I started looking for one, and after about 2 exhausting minutes of trying to Google it, I gave up and wrote one myself.
Give it a try at http://www.rauchy.net/oapt.
Following my post on the Special Case pattern, I just wanted to give a few more examples in which the pattern proves to be really helpful. In the previous post, we talked about using the Special Case pattern when returning collections, but you can use it in other places as well.
Suppose we have a cached collection of User objects, and we want to fetch a specific User and save it to the database.
User user = cache.Get(”John”);
if (user != null)
{
user.Save();
}
If we subclass User with a class called MissingUser, and have our cache object return it when it can’t find a user, we can reduce our calling code to:
User user = cache.Get(”John”);
user.Save();
MissingUser.Save() overrides User.Save() and does nothing.
Side note: we could definitely go with checking cache.Contains(”John”), and acting on the result, but I think this is too much detail for this level of abstraction, and may be violating Tell, Don’t Ask.
Suppose we want to display a User’s profile. Our User class has a string called Name and a bitmap called Picture.
User user = profiles.Get(”Mark”);
if (user != null)
{
this.Name = user.Name; // Binding is for the weak.
this.Picture = user.Picture;
}
When a User is not found in the profiles repository, we could make it return an instance of the regular User class, where User.Name = “Not Found”, and Picture is something like
![]()
This way, we can just write:
User user = profiles.Get(”Mark”);
this.Name = user.Name;
this.Picture = user.Picture;
and a profile will always be displayed.
What if we wanted to check if a User exists in a managers repository, and only if it is not found, fetch it from a clerks repository? One might be tempted to write something like:
User user = managers.Get(”Ahmed”);
if (user != null)
{
// Ahmed is a manager.
Display(user);
}
else
{
// Ahmed must be a clerk.
user = clerks.Get(”Ahmed”);
Display(user);
}
In the previous examples, we avoided the conditional (null check) by using Special Case. If you look at the requirement for this example, you’ll see that the conditional is built into it, and there is no way to get around it.
But if we use the same technique we used in the second example, we could create an instance of User, that has a boolean property called Exists, which will be populated according to the result. This way, we could express our condition much better:
User user = managers.Get(”Ahmed”);
if (user.Exists)
{
// Ahmed is a manager.
Display(user);
}
else
{
// Ahmed must be a clerk.
user = clerks.Get(”Ahmed”);
Display(user);
}
No code saved here, but our intention is much clearer this way.
What the hell is a “if (user != null)”? English, people.
Guys, will you knock it off with returning nulls from methods? You should return Special Cases, not nulls! nulls tend to bypass any polymorphic structure, and cause code to be cluttered with null checks. For example:
public IEnumerable<Picture> GetAllPictures()
{
if ( .. there are pictures .. )
{
return pictures;
}
else
{
return null;
}
}
Oh boy, users of this method would have to check for nulls every time before they operate on it: (if they don’t they might get a NullReferenceException, which s-uhhh-cks)
var pictures = GetAllPictures();
if (pictures != null)
{
foreach (var picture in pictures)
{
…
}
}
Isn’t that null check a big distraction from the actual logic? If you use a Special Case for that enumerable and return Enumerable<Picture>.Empty(), the calling code could be reduced to:
var pictures = GetAllPictures();
foreach (var picture in pictures)
{
…
}
Much better, no?
I just hate it when people say “I’m working on unit tests for feature X” on daily scrum meetings.
When you get assigned to implement feature X, unit tests are just another part of that assignment. Just like planning, compiling, banging your head on the keyboard or writing documentation.
Sure, I get it, you want to show that you are very trendy and professional, especially since the project manager has asked everyone to unit test. But if you want to be a real professional, just silently work on unit tests and say “I’m working on feature X”.
And write those unit tests before code. And don’t drink water from a puddle.
I just found out that you can create compound constraints in NUnit (starting in v2.4). This means that you can logically group constraints.
For example, I am currently testing a custom IList<T> implementation, and in a specific test case, I want to make sure a specific entry exists instead of another. Before compound constraints, I would have written these 2 asserts:
Assert.That(this.subject, Has.Member(”rauchy”));
Assert.That(this.subject, Has.No.Member(”Omer”));
My problem with this code is that these two asserts represent a single fact - I want to make sure that rauchy makes it to the list, and not Omer. One might interpert them as two independent facts. With compound constraints, I can just write:
Assert.That(this.subject, Has.Member(”rauchy”) & Has.No.Member(”Omer”));
This way, you cannot think of this as two independent facts. Also, this helps follow the one-assert-per-test rule.
A hallway talk at the Alt.NET Israel Unconference got me thinking about coding standards in general, and naming conventions in particular.
I’ve seen dozens of holy wars regarding the subject of naming conventions - when a project starts, when a new team member comes along, when the team leader is replaced etc.
I used to think that a project should have a single naming convention, and everyone should follow it. Now, I’m not so sure any more. I mean, what is really so important about naming conventions? What makes a project with a unified naming convention better than a project without one?
The first argument for naming conventions is always unity. You want all your data members to look the same.
But, think of it, what is really that important about unity? What business value do you get from it? Does it cut down development time? Does it improve performance?
IMO, if one developer wants his field to be called “_identifier”, another wants “m_identifier” and the other wants “nIdentifier”, just let them! No one ever died from Hungarian notation or a “m_” prefix, I believe.
For those who still believe in Hungarian notation (or any of its siblings), readability seems to be a great argument for naming conventions.
However, Hungarian notation might have been a good argument a decade ago. Today, all IDE’s provide great intellisense, and one could determine the type of a member in a second by hovering on it.
Determining the scope of a variable (method or class) is important, but can also be easily discovered by intellisense.
I’m not trying to say you shouldn’t have a naming convention in your project. I’m just trying to say, don’t let it bother you so much.
Set up a naming convention at the beginning of the project, have your team members agree on it, but don’t hunt down any exception and have it fixed.
Write a unit test or get a cup of coffee instead.
Do you think naming conventions are important? Where would you draw the line?
I’ll be heading out to the first Alt.NET conference in Israel in an hour or so, I’m really excited about the Alt.NET movement forming up in Israel.
I hope to learn some stuff I just never get around to, such as:
I don’t think I’ll be able to share any knowledge, since I’m positive that I will be stunned by the high-level knowledge of the people there.
So I’m off to stare and drool. See you there!
Several months have passed since people starting using C# 3.0 out there. I, however, was busy with linear algebra, discrete math and such at that time.
I did, however, try to keep up and see what’s the fuss about extension methods, but I never got it. I mean, this is anti-encapsulation at it best - break into any type, do whatever you feel like. Total chaos.
So I gave it some time. I didn’t force it into any of my projects until the time was right. Then I finally got it - extension methods are ideal for little pieces of code which you need, but creating a utility class for them feels wrong.
For example, I was implementing a new feature for Regionerate a couple of days ago in which I had to sort a list, split it into distinct values and recursively sort it again.
Its a reflection-based sort and it has quite a bit of logic in it, so it had a class & unit tests just for it. I had to take care of the splitting thingy, but it felt wrong to add it as a method in the sort class, as it operates on lists. It really feels like a method that should run on IList<T>.
Subclassing List<T> for the job feels wrong - c’mon, how would you pitch such a class? “It’s a list that you can split!”. Unpersuasive.
That’s how I got it: If IList<T> was built especially for Regionerate, it would have had a reflection-based Split function, but since its not, I should implement it as an extension method.
Took me 2 minutes and works like a charm.
1: public static IDictionary<object, IList<T>> Slice<T>(
2: this IList<T> list, PropertyInfo propertyInfo)
3: {
4: IDictionary<object, IList<T>> slices =
5: new Dictionary<object, IList<T>>();
6: foreach (T t in list)
7: {
8: // Get the value of propertyInfo.
9: object value = propertyInfo.GetValue(t, null);
10:
11: // Add it to slices.
12: if (slices.Keys.Contains(value))
13: {
14: // slices already has a slice for this value.
15: slices[value].Add(t);
16: }
17: else
18: {
19: // there is no slice for this value
20: // inside slices, create a new slice.
21: IList<T> newSlice = new List<T>();
22: newSlice.Add(t);
23: slices.Add(value, newSlice);
24: }
25: }
26:
27: return slices;
28: }
A fully documented, well-aligned version of this extension method is freely available here.
It’s been a rough day for us tweeters, May 20th had a longer Twitter downtime period. The bright side is that it helped me understand how pathetic we are. See for yourself.