On Readability
Which of these two statements is more readable?
Assert.AreEqual(5, result);
Assert.That(5, Is.EqualTo(result));
And which one is read faster?
Posted in Emanuele DelBono | 4 commentsDoes C# becaming old?
This year I was at the NDC2010, one of the best conference that I have ever see for the quality of the sessions and for the speakers.
I follow some speeches and discussions about Ruby/IronRuby (Scott Bellware and Shay Friedman) that took me to think about the state of C# and the compiled language in general.
C# is without doubt a wonderful language, as soon as I start to work with it in 2001 I loved its severity and its elegance. I always loved the non virtual methods by default, the sealed keyword and other constructs that protect my code to an improper use.
Then I discovered Ruby (well…I discovered Ruby some years ago but only in the last months I start to work with it seriously).
Ruby is simple, without many constraints and its dynamic nature leave lot of power to the developer since that he can loose control if he’s not quite expert.
Learning Ruby make me change some opinion about C# that compared with it is more “ceremonious” and plaster.
In addition the constructs that I said before (non virtual, sealed …) by another point of view make our classes hard to test (take a look a the Michael Feather session about language testability).
Most people thinks that C# is more safety than Ruby because the compiler, the type system, the intellisense and so on, help us in committing less errors, but, given that we are professional developer, do we really need them? Don’t you think that they limit our productivity?
The new versions of C# go in the direction of dynamic languages, but perhaps its roots can’t give real freedom like other languages. It’s time to take a look around?
Posted in Emanuele DelBono | 2 commentsWindsor Container and NHibernate sessions
When developing MVVM WPF applications that use NHibernate as ORM one of the problems that you encounter is how to manage the sessions and keep the application fully testable.
I like using a Session per “screen” that in the MVVM world is equivalent to use “one Session per ViewModel”.
I also like to separate the presentation logic from the rest so I also create a Model for each ViewModel (even if this is not strictly necessary)
Finally the Model use one or more repository to access the database.
So, the NHibernate session is tied to the life of the Model and all the repositories that belongs the same model should share the same session so I can build transaction between repositories.
In addition to this I would like to inject the interfaces of the dependencies: the ViewModel will get the IModel, and the Model will get the IRepository1, IRepository2.
This picture should clarify the complete schema:
To create this scenario I choose Castle Windsor as a container and with the help of German Shuager, I defined this particular registration method:
public static void RegisterSharedWithFactory<TService>(Function<TService> factory) { _kernel.AddFacility<FactorySupportFacility>() .Register(Component.For<TService>() .UsingFactoryMethod(factory) .LifeStyle.Custom<ResolutionContextLifestyleManager>()); }
This method registers a component using a Factory method to create the instance since we cannot create an instance of the ISession but we must use a SessionFactory. Then sets the the lifestyle to a custom ResolutionContextLifestyleManager to be sure that in the same context the dependencies are created only once.
The implementation of ResolutionContextLifestyleManager is written by German and can be found here.
To understand what it does, consider this test:
[Fact] public void Two_Repo_In_The_Same_Model_Should_Have_Same_Session() { Container.Initialize(); Container.RegisterSharedWithFactory<ISession>(() => SessionHelper.OpenSession()); Container.Register<IRepo1, Repo1>(); Container.Register<IRepo2, Repo2>(); Container.Register<IModel1, Model1>(); IModel1 model1 = Container.Resolve<IModel1>(); Assert.Equal(model1.Repo1.Session, model1.Repo2.Session); // Repo1 and Repo2 shares the same session }
The model uses two repositories that uses the same instance of ISession exactly like in the picture above.
This configuration is very useful to manage the session in the right manner with NHibernate and Castle Windsor container and assure us the testability of all the components.
Posted in Emanuele DelBono | No commentsRemoving “if”
Often, for example when writing a WPF value converter, we end up with a method like this:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { MyEnum myValue = (MyEnum)value; String imageUri; switch(myValue) { case MyEnum.Value1: imageUri = "..."; break; case MyEnum.Value2: imageUri = "..."; break; case MyEnum.Value3: imageUri = "..."; break; } return new Uri(imageUri , UriKind.Relative); }
This use of the switch statement makes me fill sick due to the fact that the above code is hard to maintain and the complexity raise on every new case.
We all know that we can remove the “if” using the polymorphism, but in this case it’s more simple than that, we can use a dictionary to store the couples enumerator value – imageUri:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { IDictionary<MyEnum, string> dictionary = new Dictionary<MyEnum, string>(); dictionary.Add(MyEnum.Value1, "..."); dictionary.Add(MyEnum.Value2, "..."); dictionary.Add(MyEnum.Value3, "..."); MyEnum myValue= (MyEnum) value; return new Uri(dictionary[myValue] , UriKind.Relative); }
Simple and effective.
PS We could move the construction of the dictionary in a Builder and we also have the option to keep the definitions outside our code (in a resource or in a database) so that we can translate them if needed.
Posted in Emanuele DelBono | 2 commentsAnother year @AgileTestingDays
For the second year, CodicePlastico will be active presence at Agile Testing Days.
After the last year session about Continuous Integration and build server configuration, this year the sessions will be two
The title and abstract of my session:
Contextual Domain Models
One of the most well known enterprise pattern is the Domain Model often used in an Onion architecture or Hexagonal architecture: the DM as the center of our application.
I totally agree with that implementation, but, today, I’m not sure that this center should be one and only one.
The doubt is born during a big refactoring of an application that I’m developing with Alessandro. It is a modular application with a front end that the user use to view and manipulate data and a backend that works on that data.
In our case the DM is unique and shared between the frontend and backend.
The problem is that the properties and methods used by the frontend are not always the same of those used by the backend even if they “work” on the same object. They use a different point of view. This take us to have big classes that do two kind of work (SRP violation?)
The classes of an application are an abstraction of the real domain, this mean that a class will have only some of the characteristics of the real object, it will have only the attributes and operations needed by the application context.
So why should I build a single class for the two purpose?
To push us to a single class is the Database. Often on Db we will have a single table for all the Car information, but…
…the Database is only a storage and the DM should be independent from his persistence representation so that the relation 1 Class <==> 1 Table is not always true.
So I can map a single table on different classes without worrying about the persistence.
Doing this way, I mean splitting the domain model in different sub models, take us to a set of smaller specialized classes independent from the others, that means augmented maintainability and cleaner code.
Udi Dahan talks about this concept here: http://www.infoq.com/presentations/Making-Roles-Explicit-Udi-Dahan
Posted in Emanuele DelBono | No commentsMy presentation on Mock Objects (UgiALT.NET Conf)
Here you can find the slides of the presentation that I did last week at the Italian ALT.NET Conference about mock objects: http://www.slideshare.net/emadb/mocking-2998380
(they are in Italian, sorry)
Posted in Emanuele DelBono | No commentsUgiALT.NET V Conference
Last Saturday there was the winter edition of the Italian ALT.NET conference. The 5th edition. It was a great day, with more the 130 participants, 20 sessions about DDD, BDD, TDD, SQL and NO-SQL Database, REST, Dynamic Languages, agility, Refactoring, #Architecture, Mock Objects, HTML5, iPhone, Monotouch, JQuery and many more themes.
One of the aspects that characterize the ALT.NET conference is the high level of the sessions (there was no entry level sessions) and the high level of the attendees. In every session that I followed there were always a discussion on the topic and the speaker leaves the attendees speak and tell their opinion so that everybody can learn from the others. Most discussion has continued in the hall and in the others rooms available for open spaces.
For me, Simone and Claudio it was an hard day dealing with the organization, but most attendees help us when needed, so my thanks goes to all the people that help us yesterday.
Other thanks to the speakers, most of them came from other cities, Hadi and Chris from another country. Thanks for coming.
Finally the donors, this year we collected money from donors that gave us something to cover the costs. It went great. With the donations we cover all the costs and we have more money for the next edition (june? july?).
I’m really happy, in 3 year we built a .NET community that is not tied to the .NET framework but is interested in all the technologies that helps the developer to build better software.
Here are some photos: http://picasaweb.google.com/diegoguidi/Milano23012010
In the next days we will publish the slides and demos from the presentations.
Posted in Emanuele DelBono | No comments
Experiments with MongoDb
During the Xmas holidays I found the time to have a look at MongoDb a Document oriented Database where the schema is based on JSON.
I downloaded the binaries and the C# Driver and I started some experiments.
The setup-time is minimal, the server is a console application that remain ready on a certain port:
D:\mongodb-win32-x86_64-1.2.1\bin>mongod.exe --dbpath ./dataTue Jan 05 19:16:20 Mongo DB : starting : pid = 0 port = 27017 dbpath = ./data master = 0 slave = 0 64-bitTue Jan 05 19:16:20 db version v1.2.1, pdfile version 4.5Tue Jan 05 19:16:20 git version: 45992de574979343f34fdfe96b069d5d1eff0182Tue Jan 05 19:16:20 sys info: windows (6, 0, 6002, 2, 'Service Pack 2') BOOST_LIB_VERSION=1_39Tue Jan 05 19:16:20 waiting for connections on port 27017
Above I simply specified the data folder even if there are a lot of parameters you can set.
The first sample that I write is this:
Mongo mongo = new Mongo();mongo.Connect();Database db = mongo.getDB("MyTestDb");IMongoCollection posts = db.GetCollection("Persons");Document doc = new Document();doc["Name"] = "Emanele";doc["Surname"] = "DelBono";posts.Insert(doc);Document example = new Document();example["Name"] = "Emanuele";ICursor cursor = posts.Find(example);foreach (Document document in cursor.Documents){Console.WriteLine(document.ToString());}
The first block is needed to open the “connection” to the database and to select with collection to work with.
Then I create a new Document and I fill in the key value pairs. The Document class is a dictionary that keep the document data and in JSON format and is converted BSON by the driver when the insert instruction get called.
The third block is a query to the database. I created a new document with a property name and the needed value, the Find method get a cursor from the database with all the matching document (i.e. all the persons whose name is Emanuele).
The power is in the storage and query method. You can create a complex document (with sub-documents, collection and so on) and store like a simple document.
This is a very first basic example on how to setup and run a micro-application on MongoDb, I’m now working on an extension to transform domain model objects in Document hierarchies so I can avoid the manual mapping from a Person class to the Document class.
Maybe in a next post I’ll talk more about that.
Posted in Emanuele DelBono | 6 commentsAvoid DataGrid*
A lot of software houses are migrating their application to the (new) WPF framework to take advantage of all the new stuff (layout models, controls, templates, styles,…)
WPF leave to the developers the freedom to realize appealing user interfaces that support an alternative interaction model not tied to the old windows controls. The benefits for the end user are countless, more productivity, easier interaction, information “find-ability”, and so on…
But what happens most of the times?
As soon as a new developer opens Visual Studio he asks: “Where’s the DataGrid?”
Why?? Is it possible that the only way that a developer knows to show some data on the screen is to put it in a grid?
I developed a bunch of WPF applications and only in one case I used the DataGrid, I always used ListBoxes, ItemControls, StackPanles….using a template to customize their appearance to show the most important information and to give the user the ability to drill down into the details when needed.
So, please, please, with WPF we have the power in our keyboard don’t use datagrids to show your data, think about your user!
The web is full of examples that don’t use the DataGrid (Google and Amazon for example) so don’t be lazy, take time to design a better user interface!
* No datagrid was used to write this post
Posted in Emanuele DelBono | No comments
RSS


