November 2008 - Posts

Subcontrollers and caching on ASP.NET MVC
Tue, Nov 25 2008 12:13

I’ve just read two interesting posts by Steve Sanderson which show how to add these features to the current release of ASP.NET MVC. Really interesting, if you ask me…

by luisabreu | 1 comment(s)
Filed under: ,
Book review: Peopleware
Sun, Nov 23 2008 21:03

I’ve been a proud owner of the book Peopleware: Productive Projects and Teams since 2000. However, only recently have I started publishing reviews on books, so to be fair, I had to reread it again (yes, I’ve read the book a couple of times and I find it always entertaining and I always end up getting something which I didn’t quite get in my previous read).

The book is really great! Besides giving data that supports why we need offices (not cubicles, dress codes and other stuff which really doesn’t do anything to improve the quality of development!), you’ll also find several interesting ideas on how you can make teams jell.

What I find most interesting about the ideas on the book is that they’ve been there for some 20 years (or more – the second edition has almost ten years), and I still haven’t found many managers that have read the book (or even have heard about it) or companies that try to apply the principles presented on the book. In fact, when I think about it, it’s really amazing that I’m able to write code everyday and that we ship some apps from time to time…oh well, I digress. Final note: 10/10.

by luisabreu | 1 comment(s)
Filed under:
Contract reference assemblies
Wed, Nov 19 2008 22:29

If you look closely at your bin folder, you’ll see that besides getting your project’s assembly, you’ll also have another assembly with the your_Assembly_name.Contracts.dll name. This assembly is known as the contract reference assembly and it only has the public “interface” of the types defined on your assembly and their respective contracts.

Why do we need this assembly? It is used during the rewriting process to inherit contracts across assemblies. According to the docs, they’re also used for static analyses to discover contracts on methods from other referenced assemblies when you’re performing static validation on a project.

So, this kind of assembly is really important and you should generate them and redistribute them with your assemblies. If you’re using VS, then don’t worry because they will be automatically generated for you. If you’re not using VS or the code contract msbuild task to build your project, then you’ll need to use the command line asmmeta.exe to generate it.

And I guess that this means that the intro series on code contracts is over. It’s time to pick another subject…suggestions?

by luisabreu | with no comments
Filed under: ,
Code contracts: the missing methods
Tue, Nov 18 2008 20:58

In the last posts, I’ve been talking extensively about Code Contracts. If you’re a reader of this blog, you know that I’m hooked on it. I’ve just been reviewing the previous posts and I’ve noticed that I didn’t mention the Assert and Assume methods. Both are used for testing state and  assumptions on a specific point of the program. As you might expect, they follow the same syntax as the other methods that have been presented in the past.

Interestingly, both methods let you use members with less visibility than the method where you’re using them. At runtime, both have the same behavior and will only delegate to the Assert method of the runtime rewriter when you define the CONTRACTS_FULL constant on your code. btw, by default the predefined rewriter will call the Debug.Assert method.

The Assume method is interesting, especially when you think about the static analysis step. All the assumptions that you add (ie, every Assume method call) will be added to the “known facts” list maintained by the static validation tool and will be used by it to check other existing contracts  on that scope. What this means is that you should use Assume for giving the validation tool more info about some facts which you know to be true at runtime, but that won’t be inferred by the static analysis tool.

The best way to test this concepts is to run a small example and start adding Assert and Assume method calls. Unfortunately, I didn’t had the necessary time for building such a sample,so you’ll have to do it yourself….

by luisabreu | with no comments
Filed under: ,
Code Contracts and runtime rewriting
Wed, Nov 12 2008 22:43

Today we’re going to keep looking at Code Contracts. Until now, I’ve been concentrating essentially in presenting its use and mentioning how great it is to have static analysis (ie, have something that goes through your code at compile time and detects several places which might breaking existing contracts). Today it’s time to take a look at the advantages associated with its use at runtime.

You’ll get runtime “support” (lets call it this, ok?) whenever you define the CONTRACTS_FULL constant on your code. The easiest way to achieve this is to go to your VS project property window and check the Perform Runtime Contract Checking checkbox (that is near the top of the window). When you do that, you’ll get some interesting things going on on your build. For starters, your assembly will be rewritten. In practice, this means that:

  • postconditions are moved to the end of the method;
  • method return values are replaced by CodeContracts.Result occurences (more on this on the next paragraphs);
  • pre-state values are replaced with CodeContacts.OldValue occurrences;
  • contracts are enforced in inheritance scenarios (hurray!).

All this work is done automatically by the ccrewrite tool. If you just go ahead and build a project with Code Contracts runtime support enabled, you’ll see that you’ll get assertions at runtime when one of your contracts is not respected. If you want, you can change that behavior. For instance, lets say that I wanted to get an exception instead of getting the Debug.Assert followed by the Environment.FailFast method calls that are used by default…

Since I’m lazy, I’ll just create a new Exception derived class. If this was production code, I’d probably be creating an exception type for each  kind of contract verification (ie, one for preconditions, another for postconditions, etc). Since this is just demo, I’ll probably be able to get away with only one class (ok, I’m really being lazy here! DO check the guidelines before writing your exceptions):

public class DbCException: Exception    {
        public DbCException(String message)
            :base(message)
        {}
}

What we need now is a way to throw these exceptions whenever a contract is broken. According to the docs, we need to add a class which has several static methods (one for each “type” of contract):

namespace Test {
public class CustomRewriter {
        public static void Requires(Boolean condition, String message)
        {
            if (!condition) throw new DbCException(message);
        }

        public static void Ensures(Boolean condition, String message) {
            if (!condition) throw new DbCException(message);
        }

        public static void Assert(Boolean condition, String message) {
            if (!condition) throw new DbCException(message);
        }

        public static void Assume(Boolean condition, String message) {
            if (!condition) throw new DbCException(message);
        }

        public static void Invariant(Boolean condition, String message) {
            if (!condition) throw new DbCException(message);
        }
}
}

And that’s it. Now, you only need to pass the necessary information for the ccrewrite tool to use these classes instead of the default ones. If you’re using VS, just go to the project’s property window and write the name of the assembly that has the previous classes and the complete name of the class that has the static methods.

Suppose that the CustomRewriter class was on an assembly called anotherassembly. In that case, you should put anotherassembly.dll on the Assembly textbox and Test.CustomRewriter on the Class textbox (do notice that I had to add the dll extension for it to work – not sure if this will remain like this on future versions). Oh, and I almost was forgetting to mention that you need to put that custom assembly on the same folder as the assembly that is being rewritten.

Before ending the post, there’s still time for a quick analysis of the rewriting process. To show you what happens, lets reuse the example presented in the post about quantifiers. Lets focus on the OnPeople method. Originally, it looked like this:

public PersonSearcher OnPeople(Person[] people) {
  CodeContract.Requires(CodeContract.ForAll(0, people.Length, pos => people[pos] != null));
  CodeContract.Ensures(_people != null);
  _people = people;
  return this;
}

After the ccrewrite tool ends its work, it will look like this:

public PersonSearcher OnPeople(Person[] people)
{
    __copy+<>c__DisplayClass1 CS$<>8__locals2 = new __copy+<>c__DisplayClass1();
    CS$<>8__locals2.people = people;
    CustomRewriter.Requires(CodeContract.ForAll(0, CS$<>8__locals2.people.Length, new Predicate<int>(CS$<>8__locals2.<OnPeople>b__0)), "CodeContract.ForAll(0, people.Length, pos => people[pos] != null)");
    this._people = people;
    PersonSearcher CS$1$0000 = this;
    PersonSearcher Contract.Result<PersonSearcher>() = CS$1$0000;
    CustomRewriter.Ensures(this._people != null, "_people != null");
    return Contract.Result<PersonSearcher>();
}

If you go back to the previous list on what happens when rewriting happens, things should start to make sense (please don’t concentrate on the lambdas rewritings done by the compiler; they’re not important in this scenario).

CodeContract.Requires is replaced by a call to the “custom” static CustomRewriter.Requires method. Another thing you’ll notice is that the return value is replaced by a Contract.Result local variable (in order to ensure that the postcondition is correctly run, the rewriting process will introduce a field called Contract.Result so that that you can use it in your postconditions – this wasn’t needed in the previous example though). Finally, the Ensures postcondition verification is moved from the top to the bottom of the method. I’ll leave it to you the verification associated with the use of the OldValues method call.

And that’s all for today. We’re getting near the end of this series on Code Contracts. There are still a couple of things  I’d like to mention, so stay tuned if you want to read my ramblings on it.

C# 4.0: named parameters
Mon, Nov 10 2008 21:21

After several failed tries, I finally managed to configure my home PC so that it runs the Server 2008 image (with the first preview of .NET 4.0) and just with a reasonable enough delay. Ok, since I'm finishing writing a book on C# 3.0 (with my good friend Paulo), I thought that I should start by looking at C# 4.0. As has been said, C# 4.0 will be mostly on dynamic programming features. To start my study, I've just picked a random feature: named parameters.

The first thing I've noticed while running some tests on this feature is that C# is becoming closer to VB.NET. If things keep going this way, in a few years the only difference will be in blocks: VB.NET will have the typical begin end blocks and C# will remain with the traditional { } symbols:). Didn't Joel wrote something about that in 2001?

But I digress...so, today is all about named parameters. What can I do with named parameters? Basically, you can pass a value to a parameter by name, instead of using its position. Lets start with a simple example...consider the following class:

class Student    {
        public String FirstName { get; private set; }
        public String LastName { get; private set; }

        public void ChangeName(String firstName, String lastName)
        {
            FirstName = firstName;
            LastName = LastName;
        }
}

Until now, you could only pass values to parameters based on their position:

var std = new Student();
std.ChangeName( "Luis", "Abreu" );

Starting with the next release, you'll also be able to use the name of the parameter to assign its value. Here's an example of how you could write the previous snippet with named parameters:

std.ChangeName(lastName: "Abreu", firstName: "Luis");

Do notice that in both cases you need to pass both values because none has a default value. Yes, with C# 4.0 you'll also be able to set up parameter's default values. Lets change the previous example to show how you could do this:

public void ChangeName(String firstName, String lastName = "Abreu") {
//some code as before
}

Setting default values makes the associated parameters *optional*. This is important because until now this feature wasn't supported in C# (in previous versions, you had to use overload methods for simulating this). What this means is that you could call the previous method and only pass the parameter which doesn't have the default value:

std.ChangeName(firstName: "Luis");

You should also keep in mind that optional parameters must come last (yes, really at the end, after everything else - this includes ref and out parameters too!). One additional observation: you didn't really need to use the parameter name because the mandatory parameter (ie, the one whose value you had to set) was the first one. So, you could simply write:

std.ChangeName("Luis");

What this means is that most of the time, you'll use the named parameter approach for setting the value of some optional parameters. What happens when you write the previous method call? Well, the compiler will pick up the defaults and pass them to that method call. In other words, the compiler will copy the values of the default values you assigned to the parameters and will add them to the method call when those parameters aren't explicitly set. So, when the compiler finds the previous method call, it will replace it with this:

std.ChangeName("Luis", "Abreu"); //Abreu is used as default value for lastName

Notice that you'll be able to use optional and named parameters with constructors and indexes.

Now that we have these new features, it's time to see what happens with overload resolution. What happens when we add another method which receives only one parameter? For instance, suppose the class also has this method:

public void ChangeName(String firstName) {
            FirstName = firstName;
}

Which method will be called when you write std.ChangeName( "Luis" ); ? The new features doc says that

"A signature is applicable if all its parameters are either optional or have exactly one corresponding argument (by name or position) in the call which is convertible to the parameter type.

Betterness rules on conversions are only applied for arguments that are explicitly given – omitted optional arguments are ignored for betterness purposes.

If two signatures are equally good, one that does not omit optional parameters is preferred."

So, the last method should be picked in the previous scenario. That doc has a few more examples which you should look at if you want to have 100% understanding of overload name resolution with named and optional parameters. If you do lots of COM interop, then you'll really love these new features. However, there's still some controversy surrounding its use. In fact, I still remember reading this post on why C# didn't allow for optional parameters. It made sense, though the option of having optional parameter was also valid. I think I'll have to play a little more with it to make my mind. Keep tuned for more on the next version of C#.

by luisabreu | 2 comment(s)
Filed under:
Using quantifiers on Code Contracts
Sun, Nov 9 2008 14:25

Code Contracts also supports are quantifiers (with several limitations, as we’ll see). This means that you can check a predicate against elements in a collection or interval. You can use the ForAll method for running a predicate over several elements maintained on an collection or interval. The Exists method will let you apply a predicate and see if there is at least one item in the  specified collection or interval that validates that predicate.

Consider these two classes:

public class Person {
        public String Name { get; set; }
}
public class PersonSearcher {
        private String _name;
        private IEnumerable<Person> _people;
        public PersonSearcher SearchFor(String name) {
            _name = name;
            return this;
        }
        public PersonSearcher OnPeople(IEnumerable<Person> people) {
            _people = people;
            return this;
        }
        public Person Get() {
            return _people.SingleOrDefault( p => String.CompareOrdinal(p.Name, _name) == 0);
        }
}

There’s a simple Person class and a PersonSearcher class which checks if a specific person in on a collection of Persons. Suppose that one of the things we’d like to make sure is that all the items on the people collection that are passed as a parameter are non null. This is easily done by using the ForAll method:

public PersonSearcher OnPeople(IEnumerable<Person> people) {
    CodeContract.Requires(
                         CodeContract.ForAll(people, p => p != null));
    _people = people;
    return this;
}

And now you do get verification on all the instances of people passed as an argument. For instance, if you try to run this code, you’ll get a Debug.Assert at runtime:~

var people = new[]
                             {
                                 null,
                                 new Person {Name = "Luis"},
                                 new Person {Name = "John"},
                                 new Person {Name = "Charles"}
                             };
new PersonSearcher().SearchFor("Luis").OnPeople(people);

If the method received an array, you could also use the other overload method:

public PersonSearcher OnPeople(Person[] people) {
  CodeContract.Requires(
   CodeContract.ForAll(0, people.Length, pos => people[pos] != null));
CodeContract.Ensures(_people != null);
_people = people;
return this;
}

The Exists method is really similar to the ForAll method, so I won’t be writing any example to show its usage. On the next post, we’ll start looking at runtime behavior. Keep tuned!

Code Contracts and compatibility with existing code
Sat, Nov 8 2008 12:09

Before using Code Contracts, you’ll probably already written several lines of validation code for testing requirements on your methods. I’ll keep using the Person class to illustrate some code that you might have before using the Code Contracts library. So, in the past, you might have something like this:

public class Person {
        private String _firstName;
        private String _lastName;
        public String FirstName {
            get { return _firstName; }
        }
        public String LastName {
            get { return _lastName; }
        }
        public void ChangeName(string firstName, string lastName) {
            if( firstName == null )
                    throw new ArgumentNullException("firstName");
            if( lastName== null )
                    throw new ArgumentNullException("lastName");
            _firstName = firstName;
            _lastName = lastName;
        }
}

Now, the first thing you could do is port your code and replace those if-then-throw statements with calls to CodeContracts.Requires method. That might be quite a bit of work! The good news is that if your code is located at the beginning of the method’s body and is similar to the previous example (ie, it’s in the form of if-then-throw), then you can simply add one line of code to the bottom of those tests and you’ll get all the benefits associated with the direct usage of Code Contracts’s methods. Here’s the changes needed for the previous method:

public void ChangeName(string firstName, string lastName) {
    if( firstName == null )
          throw new ArgumentNullException("firstName");
    if( lastName== null )
          throw new ArgumentNullException("lastName");
    CodeContract.EndContractBlock();
    _firstName = firstName;
    _lastName = lastName;
}

Now, if you try writing the following snippet:

var p = new Person();
p.ChangeName(null, null);

You’ll get a warning at compile time. And that’s it for today. More about this on future posts. Keep tuned.

by luisabreu | with no comments
Filed under: ,
200 000 hits
Sat, Nov 8 2008 11:43

According to ClustrMaps, I’ve had 200 000 visitors on my blog since I’ve started using their product. Not bad since I never expected to hit the 100 000 mark. I would like to say thanks to Everyone who takes the time to visit this place regularly and contribute with comments on my thoughts about development on the .NET platform.

by luisabreu | with no comments
Filed under:
Adding Code Contracts to your interfaces
Fri, Nov 7 2008 20:52

[Update: I’ve changed the code so that the contract class implements the interface explicitly. This is required for getting static analysis. One more thing: the first release of the project has a bug and  even if you implement the interface explicitly, you won’t get static analysis.]

One of the interest things Code Contracts lets you do is define additional contracts on your interfaces. To achieve this, you need to add a “dumb” class which implements that interface and add the required contracts to the body of the methods. To illustrate the necessary work, lets start by creating a new interface called IPerson:

public interface IPerson {
   String FirstName { get; }
   String LastName { get; }
   void ChangeName(String firstName, String lastName);
}

One of the things I’d like to guarantee is that the method ChangeName will only receive valid names. As we’ve seen in a previous post, that is easily achievable by using the CodeContract.Requires method. Since you cannot define a body on C# interface methods, you’ll need to create a new class which implements the interface and has the restrictions you want to apply:

public class PersonContract:IPerson { 
  string IPerson.FirstName {
            get { return CodeContract.Result<String>(); }
  } 
  string IPerson.LastName {
            get { return CodeContract.Result<String>(); }
  } 
  void IPerson.ChangeName(string firstName, string lastName) {
            CodeContract.Requires(firstName != null);
            CodeContract.Requires(lastName != null);
}
}

It’s important to notice that the contract class must implement the interface explicitly. Since I don’t care about the value returned by the methods on that class, I’ll reuse the values returned by CodeContract.Result<T> method (notice that you can return any valid value from the implementation of the interface in the “contract class”). Now, we need to identity the PersonContract class as the one that defines the contract we want to enforce on our interface. This is achieved with the ContractClassAttribute and ContractClassForAttribute attributes. The first is applied to the interface and the second is applied to the class:

[ContractClass(typeof(PersonContract))]
public interface IPerson    {
   //previous code
}

[ContractClassFor(typeof(IPerson))]
public class PersonContract:IPerson    {
   //previous code
}

And now, you can build the “domain” classes and you’ll automatically inherit the contracts “attached” to the interface. For instance, here’s a valid implementation  for the previous interface:

public class Person:IPerson {
       private String _firstName;
       private String _lastName; 
       public String FirstName {
           get { return _firstName; }
       } 
       public String LastName {
           get { return _lastName; }
       } 
       public void ChangeName(string firstName, string lastName)
       {
           _firstName = firstName;
           _lastName = lastName;
       }
}

Notice how we didn’t add any sort of validation to the class…Simply great, right? On the next post, I’ll keep talking about this great library for applying design by contract on your .NET code. Keep tuned!

by luisabreu | with no comments
Filed under: ,
More on Code Contracts: out parameters and field access on preconditions
Thu, Nov 6 2008 21:57

In this post we’ll keep looking at how Code Contracts can really help you improve your code. Today, we’ll see how one can use fields and out parameters in contracts. Lets start with fields. Ok, the title is a little misleading…you can use fields in your contract. But what happens when you need to define a contract on an private field from a public method? Well, lets think about this for a minute…your clients must check for values so that they won’t break the contract. If you’re specifying a contract on a private field, then how will a client validate the contract before invoking the method? That’s why there’s a restriction on the visibility of the members you can use in a contract…

In the previous scenario, you could always wrap your field on a property and use the property from within the precondition. However, there may be some cases where calling the property isn’t really desired (for instance, your property might perform some additional tasks which aren’t really necessary when you’re testing the contract). In those cases, and if you have your field is wrapped by a property which is at least as visible as the place where you specifying the contract, then you can use the ContractPublicPropertyNameAttribute and use the field on your contract. Here’s another really simple example:

public class Person
    {
        public Person(String name)
        {
            Name = name;
        }
        [ContractPublicPropertyName("Name")]
        private String _name;
        public String Name {
             get{ /*suppose you have more code here*/return _name;}
             set{ _name = value;}
       }

        public void ChangeName(String name)
        {
            CodeContract.Requires( _name == null);
            Name = name;
        }
    }

If you compile the previous example, you’ll see that you won’t get any errors or warnings and you’ll be able to use a private field on a contract defined on a public method.

Before ending the post, there’s still time to see how you can use out parameters on your contracts. Honestly, I don’t remember the last time I’ve used an out or ref parameter (without being in a interop scenario). Anyway, if you need it, you can use the CodeContract.ValueAtReturn<T> method for using that parameter on a contract. And that’s all for today. More about this framework tomorrow

by luisabreu | with no comments
Filed under: ,
What’s new in the BCL 4.0
Thu, Nov 6 2008 21:25

I’ve just found an interesting post with some of the new stuff we’ll have on the next version of the BCL. I’m already testing Code Contracts, but it seems like there’s still a long way to go…

by luisabreu | with no comments
Filed under:
Code Contracts: don’t use the overloads that receive a string
Thu, Nov 6 2008 21:18

In my first post about Code Contracts I’ve mentioned that in my machine static analysis wasn’t picking up those evident scenarios where the code was breaking the predefined contracts. Today I’ve got the confirmation on the PEX forum (which, btw, is the place where you should post your questions regarding this framework while we don’t have a discussion place for this framework).

by luisabreu | with no comments
Filed under: ,
More on code contracts: checking return values and old values
Thu, Nov 6 2008 21:01

Today I’ll keep writing about the new Code Contracts framework and we’ll see how we can use the write contracts that validate method return values and “old” values. Lets start with method return values…

As you might expect, you’re able to refer to return values on your postconditions. To show you the kind of thing you’ll be writing, we will start by changing the class we presented yesterday and we’ll add a BirthDate property to it:

class Student{

private DateTime _birthDate;
public DateTime BirthDate {
            get { return _birthDate; }
            set {
                CodeContract.Requires(value> new DateTime(1900, 1, 1));
                _birthDate = value;
            }
  } 
}

Now, we can calculate the age by adding a new method called CalculateAge to this class. This probably is a good way to implement it:

class Student{
  public Int32 CalculateAge()  {
            var currentDate = DateTime.Now;
            var years = currentDate.Year - _birthDate.Year;
            if( currentDate.CompareTo(_birthDate.AddYears(years)) < 0 )
            {
                years--;
            }
            return years;
   }
}

Ok, so one of the things we can do is make sure that we return a valid age. Just to be sure, we can say that the age of a person must always be bigger than 0, so we’ll go ahead and add that condition:

public Int32 CalculateAge()  {
        CodeContract.Ensures( CodeContract.Result<Int32>() > 0 );
        //previous code
}

The CodeContract.Result<T> method is generic and can only be called inside the Ensures method. T should be replaced by the return type of the method.

Besides specifying the contract for the return value, you can also use another special method: CodeContract.OldValue<T>. This method expects a parameter of type T and there are several restrictions which apply to the values that can be passed to it. For instance, the return value (CodeContract.Result<T>) cannot be used on the expression passed to that parameter. You can’t also use out parameters either! The docs contain full list with these rules, so I won’t be putting them here. Instead, I’ll show how you can apply these method in your code.

One of the things you can do is guarantee that you’ll only update the value of the field _birthDate if the new date is different than the existing one. You can also specify this with a contract.Here’s an example (ok, sorry for the lame example, but I’m a little but tired today:)):

public DateTime BirthDate {
   get { return _birthDate; }
   set {
     CodeContract.Requires(value > new DateTime(1900, 1, 1));
     CodeContract.Ensures(
            CodeContract.OldValue(_birthDate) != _birthDate);
      _birthDate = value;
   }
}

Ok, this should be enough for showing you how you can use the OldValue method. So, if you try to write this code:

var st = new Student(2);
st.BirthDate = new DateTime(1976, 6, 27);
//more code here…
st.BirthDate = new DateTime(1976, 6, 27);

You’ll surely get an assert at runtime (on the next posts, we’ll see how easy it is to replace the assert with, say, an exception – which is something I really prefer). And that is it for today, As I said earlier, the examples might not have been the best, but I think that they were enough for illustrating the usage of return methods and old values in your contracts. On the next post, we’ll keep looking at this framework and see how you can use non-public fields and out parameters in your contracts. Keep tuned!

by luisabreu | with no comments
Filed under: ,
C#, LINQ and running several methods over instances of a collection
Thu, Nov 6 2008 14:13

One of the things that I’ve needed to do in the past is filter a sequence of items and then execute a specific method over each of those filtered instances. The Enumerable class introduces several methods, but it doesn’t have any that lets me pass an Action<T> that is invoked over each instance of an IEnumerable<T>. So, what you tipically end up doing is something like this:

var filteredItems = existingItems.Where( item => … );
foreach( var item in filteredItems ){
  item.DoSomething();
}

Yes, there’s nothing wrong with this code, but it starts getting boring when you have to write it 2 or 3 times. Interestingly, the List<T> class already has a method similar to what we need: the ForEach method. Here’s its signature:

public void ForEach(Action<T> action)

So, I could end up converting to a list (by calling the Enumerable.ToList<T> method) and then I could simply call this ForEach method. Here’s how it would look like:

existingItems.Where( item => … )
                     .ToList()
                     .ForEach( item => item.DoSomething() );

Another option would be to add a new extension method  that looks like this:

public static class MyEnumerable{
   public static void ForEach<T>(this IEnumerable<T> items,
                                                                      Action<T> action){
      if( action == null ) throw
  }
}

Then I could simply do something like this:

existingItems.Where( item => … )
                      .ForEach( item => item.DoSomething() );

I’ve tried to understand why Enumerable didn’t add this method. I’ve found some good arguments (for instance, it could be confusion when passing a List – in this case, the List<T>.ForEach method would always be called, but that might not be obvious to all the developers-, maintaining functional purity, etc) , but I still think that having it on the list wouldn’t have been such a bad thing (ok, you’d have side effects, but C# isn’t a functional language, right?).

My friend Paulo reminds me that with a list you have an internal store, so it makes sense to have that method and access the internal array used for saving the members of the list directly. If you think about it, then it probably doesn’t make much sense to add a method like that because you’re extending the IEnumerable<T> and don’t have any info on how the items are stored.

On the other hand, if you think about certain scenarios, then it does make sense to go over a collection of items and call a specific method when an instance is in a specific state (that’s something similar to the example I’ve shown in the beginning of this post).

Btw, if you have a good justification for why this method wasn’t added to the Enumerable class (besides the one I’ve written in the previous paragraphs), go ahead and add it to the comments section. I’d really love to know more :)

by luisabreu | with no comments
Filed under:
Another very smart guy :)
Thu, Nov 6 2008 12:58

Not technical, so move on if you don’t like soccer…just watch how this guy reacts after receiving the yellow card :)

by luisabreu | 2 comment(s)
Filed under:
More on Code Contracts
Wed, Nov 5 2008 21:51

Yesterday I was really excited after finding out that we’ll finally have a library for performing Design By Contract verifications on our code. Ok, the runtime validations could already be simulated by writing some code (I’ve already written several helpers classes in my current applications), but the truth is that the Code Contracts library adds static verification and will enable you to catch several errors during compilation. I believe this is more than enough for you to be interested in this new library, right?

Ok, so lets start with a basic scenario which will let me illustrate the usage of the existing static methods available on the CodeContract class (attention: do notice that this class will be renamed into Contract on the final release): lets suppose we have a simple class called student which looks like this:

public class Student
{
        private String _firstName = "";
        private String _lastName = ""; 
        public Student(Int32 studentId)
        {
            StudentId = studentId;
        } 
        public Int32 StudentId { get; private set; } 
        public String FirstName { get { return _firstName; } } 
        public String LastName { get { return _lastName; } } 
        public void ChangeName(String firstName, String lastName)
        {
            _firstName = firstName;
            _lastName = lastName;
        } 
}

One of the things you’ll want to apply to your methods are preconditions for checking parameter values. For instance, lets assume that only positive integers are valid for student ids. So, if you try to run the following code:

var std = new Student( –1 );

You should get an error at runtime. If you use a precondition, you’ll also get a compile warning (yes, you’ve read it correctly: *compile* warning). Here’s what you need to do to achieve that:

public Student(Int32 studentId) {
   CodeContract.Requires(studentId > 0);
   StudentId = studentId;

Btw, the CodeContract class is defined on the System.Diagnostics.Contracts namespace. Besides simple conditions, you can also, for example, call pure methods. A pure method is annotated with the PureAttribute and when you do that, you’re actually saying that the method doesn’t produce any side effects (using methods might give you false positives too!).

Besides your own methods, you can also access property getters, operators and several methods whose qualified name begins with System.String, System.IO.Path, System.Type and, of course, CodeContract methods. Do notice that whenever you access another member, you’ll have to make sure that that member has at least the same visibility as the method where you’re adding your contracts.

One more note: when you install the code contract bits, your projects will get an additional tab on the property page which you’ll have to configure for having static and runtime analysis. Not setting the checkboxes means that you won’t have either of those validations.

Besides checking  values, you can also give some guarantees regarding the state of your object after your method ends. For instance, in the previous example you can say that when the constructor does its job, you’ll always have a positive ID. Here’s how you can do that:

public Student(Int32 studentId) {
  CodeContract.Requires(studentId > 0 );
  CodeContract.Ensures(StudentId > 0);
  StudentId = studentId;
}

You can also ensure state when you get an exception. You do this by calling EnsuresOnThrow generic method. When you do this, you’re saying that even if you get an exception, the predicate you specify should be met.

You can also use invariants. Invariants define conditions under which an object is in a good state. By adding an invariant, you’re defining a group of predicates that will always be run after all your public method calls. An invariant is defined through a protected method which only contains several Ensures method calls. For instance, if we think that ensuring that the StudentId is always positive is really necessary for guaranteeing the good state of our instances of Student, then we can add a method that looks like this to our class:

[ContractInvariantMethod]
protected void ObjectInvariant() {
    CodeContract.Ensures(StudentId > 0);       
}

And now, whenever someone calls a public method of your class, the previous validation will always be performed. And that’s it for today. Tomorrow we’ll keep talking about code contracts. Keep tuned.

Code contracts are here!
Tue, Nov 4 2008 23:25

Ok, I know I’ve asked for design by contract on C# and that didn’t made it into C# 4.0. However, I’ve just discovered something even better (especially if you’re a VB programmer): we’re getting support for it on the form of a library and some msbuild tasks that are able to perform static and runtime analyses.

There’s an installation package that should work on VS 2008  but it seems like this framework will be migrating to the mscorlib.dll starting from CLR v4.0. YES!!! So, if like me, you’re still on Vista with VS 2008, just go ahead and download the installation package. Then, you can do two things:

  • Read the docs, which are installed on the Microsoft\Contracts folder (inside  your program files folder);
  • Watch the PDC video for a demo of the product

Two things before you start jumping around in pure joy:

  1. you cannot use the current version of commercial software (there’s only an academic license – wtf???)
  2. it seems like there’s a bug and whenever you use one of the overloads of the static methods that receive a string, those validations won’t be picked up during the static analysis (I didn’t found anything on the docs about this, so I’m assuming it’s some sort of bug).

I’ve already written some code, so I’ll probably add a couple of posts on this topic on the next days. Stay tuned…

The new MacBook
Tue, Nov 4 2008 10:38

I’m pissed! I waited several months before buying a notebook. After having bought the Toshiba, Apple releases the new MacBook which is amazing…Unfortunately, I can’t buy another notebook and that makes me feel really bad…oh well, what can I say?

by luisabreu | with no comments
Filed under:
Book review: More Joel on Software….
Mon, Nov 3 2008 19:55

A few days ago I reviewed of Joel on Software. Today I’m reviewing More Joel on Software: Further Thoughts on Diverse and Occasionally Related Matters That Will Prove of Interest to Software Developers, Designers, and ... Luck, Work with Them in Some Capacity. Besides sharing long names, both books end up sharing great essays on software development. Simply put it, it’s another Joel classic!

What I’m saying is that (probably) in the next ten years you’ll be hearing something like this: “you know what? There simply are some books which you must read if you want to be in the software business. You need to read The mythical man-month, Code complete, Peopleware, Joel on Software, More Joel on Software…”. See where I’m getting? Ok, so if you don’t want to buy the books you can still learn a lot by reading the archives on his blog.

Final score 9/10.

by luisabreu | with no comments
Filed under:

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover