Archive for the ‘Design’ Category

Castle Windsor and Child containers reloaded

Wednesday, June 2nd, 2010

This is a fol­low up to my pre­vi­ous post. I delib­er­ately didn’t dis­cuss the issues that arise when using con­tainer hier­ar­chies to get some feed­back on usage first.

So what’s the problem?

Con­sider triv­ial scenario:

two

We have two com­po­nents, where foo depends on bar. The depen­dency is optional, which means that foo can be con­structed even when bar is not available.

Then we have the fol­low­ing con­tainer hierarchy:

one

We have par­ent con­tainer where foo is reg­is­tered and two child con­tain­ers. In one of them we reg­is­ter bar. Both foo and bar are sin­gle­tons (for sake of sim­plic­ity – the exam­ple would work for any non-transient lifestyle).

Now we do this

var fooA = childA.Resolve<Foo>();

var fooB = childB.Resolve<Foo>();

What should happen?

Build your conventions

Thursday, April 8th, 2010

Con­tin­u­ing the theme of con­ven­tions in code; I talked about val­i­dat­ing the con­ven­tions, but I didn't touch upon one more basic issue. What to base the con­ven­tions on? Short answer is — any­thing you like (as long as it’s black). Long answer is, well — longer.

Strong typed nature of .NET gives us rich set of infor­ma­tion we could use to build con­ven­tions on. Let's go over some of them. I will con­cen­trate mostly on sin­gle sce­nario as an exam­ple — IoC con­tainer reg­is­tra­tion, but the dis­cus­sion can be eas­ily extrap­o­lated to cover any other scenario.

Loca­tion

Assem­blies are the main, most coarse grained build­ing blocks of appli­ca­tion. While they carry quite a bit of infor­ma­tion we could use (name, ver­sion, strong name, cul­ture) it rarely makes sense to use all of that infor­ma­tion. Most com­mon usage is directly point­ing to our assem­bly of inter­est, either by name

GetAssemblyNamed("Acme.Crm.Services");

or in a more strongly typed man­ner for exam­ple via type con­tainer in that assem­bly in cases where we don't mind hav­ing strong ref­er­ence to that assem­bly in your com­po­si­tion root.

GetAssemblyContaining<Acme.Crm.EmailSenderService>();

Most of the time that is enough (at least at this level, in this situation).

Directly point­ing at cer­tain assem­bly is gen­er­ally what we want, and this is the most straight­for­ward and safe way to do that. In some cases (for exam­ple exten­si­bil­ity sce­nar­ios) you may want to leave the door open for con­sum­ing more than one assem­bly, often unknown at the time of com­pi­la­tion. In this case it may make sense to use as much infor­ma­tion as pos­si­ble to fil­ter out unwanted assem­blies as early as pos­si­ble. This obvi­ously depends on the specifics of the sce­nario at hand, for exam­ple who will be author­ing the exten­sions? If only you (mean­ing your team/company), you can use infor­ma­tion in assem­bly name and addi­tion­ally ver­ify the key that the assem­bly is signed with appro­pri­ate key.

GetAssembliesWithNameStartingWith("Acme.Crm.Extensions.")

   .GetAssembliesSingledWithTheSameKeyAs("Acme.Crm.Services");

In case where third party ven­dors will pro­vide exten­sions, you may just require that the assem­bly con­forms to cer­tain nam­ing pat­tern (name con­tains ".Crm.Extensions."). This not only gives you quick way of fil­ter­ing out assem­blies you're not inter­ested in — it also helps you keep your project cleaner. With con­ven­tion like this just a quick glance at direc­tory with your project's assem­blies will be enough infor­ma­tion to tell how many exten­sion assem­blies there are.

This obvi­ously is rarely enough — find­ing right assem­blies is often just the first step and there's a wealth of infor­ma­tion else­where you can use. Mod­ules are sel­dom use­ful as most of the time you have just one per assem­bly, so I'm men­tion­ing them only for com­plete­ness. Within (and between) assem­blies name­spaces are often used to par­ti­tion types. They have two impor­tant char­ac­ter­is­tics that can be use­ful when defin­ing con­ven­tions — their name, and hierarchy.

You rarely use name­spaces on their own. Most often they are one of a few bound­aries you set to nar­row down the set of types you're inter­ested in. For exam­ple you may find your repos­i­to­ries like this:

GetAssemblyContaining<CustomerRepository>()

   .GetTypesInNamespaceOf<CustomerRepository>()

   .SomeOtherConstraints()....

Broadly speak­ing you can find name­spaces using sim­i­lar tech­niques as with assem­blies — strongly typed, as demon­strated in this para­graph or via string.

GetTypesInNamespace("Acme.Crm.Repositories");

While the for­mer is more type safe and refac­tor­ing friendly, the lat­ter is more explicit and reads bet­ter — you get the infor­ma­tion you want directly, with­out hav­ing to go through addi­tional layer of indirection.

It is often valu­able to take advan­tage of name­space hier­ar­chy to use addi­tional layer in the hier­ar­chy to carry addi­tional infor­ma­tion. One such case could be to divide ser­vices in "Acme.Crm.Services" name­space to sub-namespaces based on their lifestyle, such that sin­gle­ton Cache­P­rovider­Ser­vice will live in "Acme.Crm.Services.Global" name­space, and per web request UnitOf­Work­Ser­vice would live in "Acme.Crm.Services.PerRequest".

Type

Types them­selves carry a lot of infor­ma­tion we can use for con­ven­tions: they have mean­ing­ful names (hope­fully), inherit other types, imple­ment inter­faces, have cus­tom attrib­utes, generic con­straints etc. There are two pop­u­lar usages for type names when deal­ing with conventions.

We often put mean­ing­ful suf­fixes, or more broadly speak­ing — name our types in a cer­tain, mean­ing­ful way. For exam­ple type imple­ment­ing IRepository<Customer> would be named Cus­tomer­Repos­i­tory. Or we may require all our ser­vices to have "Ser­vice" suf­fix. While the for­mer helps us keep thins clean and con­sis­tent the lat­ter (by some regarded as cer­tain form of dreaded Hun­gar­ian nota­tion), often serves as safety net layer for val­i­da­tion pur­poses, to help you catch cases where you by mis­take put a type in inap­pro­pri­ate namespace.

The other com­mon usage is using cer­tain pre­fixes to build dec­o­ra­tor chains. You may have the fol­low­ing types: Log­ging­Cus­tomer­Repos­i­tory, Caching­Cus­tomer­Repos­i­tory, Cus­tomer­Repos­i­tory, Log­ging­Pro­duc­tRepos­i­tory, Caching­Pro­duc­tRepos­i­tory, Pro­duc­tRepos­i­tory etc. When putting con­sis­tent, well known pre­fixes on your types you can use that infor­ma­tion to build dec­o­ra­tor chains, so that Logging*foo* will dec­o­rate Caching*foo* which will dec­o­rate actual *foo* type.

In IoC reg­is­tra­tion case base types (or inter­faces) are very com­monly used. Most pop­u­lar case if layer supertype.

RegisterTypesInheriting<IController>();

reg­is­ters all con­trollers in our application.

RegisterClosedVersionsOf(typeof(IRepository<>));

reg­is­ters all generic repos­i­to­ries we might have. It some­times may also be worth­wile to take greater advan­tage of generics.

Hav­ing interfaces:

public interface IHandler<TCommand> where TCommand: ICommand

{

   // ...something

}

 

public interface ICommand

{

   // ...something

}

we might quite eas­ily tie the two together — han­dlers to their respec­tive commands.

Attrib­utes, marker interfaces

In early days of IoC con­tain­ers it was com­mon to see cus­tom Attrib­utes being used for con­fig­ur­ing com­po­nents. In Java (which gained attribute-like abil­i­ties much later after .NET) con­tain­ers tend to pre­fer this approach even now. While this approach is gen­er­ally dis­cour­aged, using domain spe­cific attrib­utes, or mark­ing inter­faces for your com­po­nents may some­times be beneficial.

You may for exam­ple use attrib­utes to mark com­po­nents you want to dec­o­rate, (put [Cache­dAt­tribute] on repos­i­to­ries you want to put cache around). Mark­ing inter­faces can be use­ful for this as well — attrib­utes are pre­ferred solu­tion where you want to asso­ciate some addi­tional data with the com­po­nent (for exam­ple cache duration).

Sim­i­lar infor­ma­tion as out­lined in case of types, can be used to build con­ven­tions around type mem­bers. While it usu­ally makes lit­tle sense in con­text of IoC to do so, it's very use­ful in other cases — like Rob's MVVM frame­work and wiring Can*Foo* with *Foo* property/method pairs.

Wrap­ping up

Any­thing can be used as basis for con­ven­tion. You only have to know what makes sense in given con­text and looks for oppor­tu­ni­ties to improve that. There are a few things to keep in mind when decid­ing upon con­ven­tions. Keep them tight — use more than one con­straint in order to min­i­mize false pos­i­tives. For exam­ple use name­space, base type and name suf­fix to find repos­i­to­ries in your appli­ca­tion. You will pay small addi­tional price of more reflec­tion you do when start­ing, but it will save you lots of time try­ing to fig­ure out why your appli­ca­tion is mis­be­hav­ing later. Make your con­ven­tions well known to the entire team. Put short descrip­tion on a board in your team room, in wiki engine you're using, on in conventions.txt file in your solu­tion. In addi­tion to that make that rules exe­cutable to spot poten­tial mis­takes and dis­con­form­ing code (see my pre­vi­ous post for more detailed dis­cus­sion on the topic). Don't be afraid to refine the con­ven­tions. Once they are decided upon, they don't get writ­ten in stone. If your appli­ca­tion grows and you find them inad­e­quate, adjust them (try­ing not to loosen them up too much).

Validate your conventions

Sunday, March 21st, 2010

I'm a big pro­po­nent of the whole Con­ven­tion over con­fig­u­ra­tion idea. I give up some metic­u­lous con­trol over plumb­ing of my code, and by virtue of adher­ing to con­ven­tions the code just finds its way into the right place. With great power comes great respon­si­bil­ity, as some­one once said. You may give up direct con­trol over the process, but you should still some­how val­i­date your code adheres to the con­ven­tions, to avoid often sub­tle bugs.

So what is it about?

Say you have web, MVC appli­ca­tion, with con­trollers, views and such. You say con­trollers have a layer super­type, com­mon base name­space and com­mon suf­fix in class name. Great, but what hap­pens if you (or the other guy on your team), fail to con­form to these rules? There's no com­piler to raise a warn­ing, since the com­piler has no idea about the rules you, (or some­one else) came up with. What hap­pens is, most likely your IoC con­tainer if you use one, or per­haps rout­ing engine of your appli­ca­tion will fail to prop­erly locate the type, and the appli­ca­tion will blow into your face dur­ing a demo for very impor­tant cus­tomer.
Take another sce­nario. Say you're using AutoMap­per, and you came up with con­ven­tion that enti­ties in name­space Foo.Entities are mapped to DTOs in name­space Foo.Dtos, so that Foo.Entities.Bar gets its map­ping to Foo.Dtos.BarDto reg­is­tered auto­mat­i­cally. Again — it won't pick map­ping to Fizzbuz­zDto when you acci­den­tally put Fizzbuzz entity in Foo.Services. Depend­ing on your test cov­er­age you will either find out sooner or later.

These are usu­ally a hard rules, and both AutoMap­per and most IoC frame­works will be able to fig­ure out some­thing is miss­ing and notify you (with an excep­tion). This is a good thing, since you fail fast, and quickly get to fix your rules. You won’t be that lucky all the time though. Say you’re writ­ing an MVVM frame­work, sim­i­lar to one Rob built, and cre­ate  a con­ven­tion wiring enable state of some con­trols bound to method Exe­cute, with prop­erty CanEx­e­cute on your view model (if you have no idea what the heck I’m talk­ing about, go see Rob’s pre­sen­ta­tion from Mix10). When you fail to con­form to this rule, no excep­tion will occur, world will not end. Merely a  but­ton will be click­able all the time, instead of only when some valid­ity rule is met. This is a bug though, just one harder to spot, which means usu­ally it won’t be you who finds it – your angry users will.

So I have a problem?

So what to do? You can loosen your con­ven­tions. If you had an issue due to name­space mis­match, per­haps don't require name­spaces to match, just type names? Or if you for­got to put a Con­troller suf­fix on your con­troller, just ditch that require­ment and it will work just fine, right?

Yes it will (prob­a­bly), or at least you find your­self break­ing some other require­ment of your con­ven­tion and feel the need to shed it as well. This how­ever does not fix the prob­lem — it merely replaces it with another — you will have rot­ten code.

Prob­lem is not that your con­ven­tion was too rigid (although some­times this will indeed be the case as well), you not adher­ing to the con­ven­tion was the real prob­lem. Con­ven­tions are like com­piler rules — fol­low them or don't con­sider your code 'work­ing'. To get compiler-like behav­ior you need to take this one step fur­ther and along with find­ing code adher­ing to your con­ven­tions, find the code that does not.

Take the AutoMap­per exam­ple again. We have des­ig­nated name­space for our con­ven­tion — Foo.Dtos. For each type in this name­space we require that a match­ing type in Foo.Entities name­space exists. You should check if an unmatched dto type exists and send some noti­fi­ca­tion in case there is. Also since you require DTOs and only DTOs to live in that name­space you should express that require­ment in code — check for types with Dto suf­fix in other name­spaces, and types with­out this suf­fix in Foo.Dtos name­space, and in each case send an appro­pri­ate noti­fi­ca­tion as well.

This is a form of exe­cutable spec­i­fi­ca­tion. When a new guy/gal comes to your team and starts work­ing on the code base you don't have to worry about them break­ing the code because they don't know the con­ven­tions you fol­low. The code will tell them when some­thing is wrong, and what to do to make it right. It will also help you keep your code clean and struc­tured. Improv­ing its read­abil­ity and in the long run, also decreas­ing pos­si­bil­ity of code rot.

What to do?

I still haven't touched upon one impor­tant thing — how and where do you imple­ment the con­ven­tion val­i­da­tion rules. There are three places I would put con­ven­tion validation.

  • The boot­strap­ping code itself. It often makes sense to take advan­tage of the fact you're scan­ning for con­ven­tions to per­form the con­ven­tions boot­strap­ping and do check for misses as well. Espe­cially when the frame­work you're work­ing with does not have any sup­port for con­ven­tions built in and you're doing it all manually.
  • Unit tests. Add tests that call AutoMapper’s ‘Assert­Con­fig­u­ra­tionIs­Valid’ or in case of home­grown frame­work, reflect over your model and look for devi­a­tions from your con­ven­tions. It really is very lit­tle work upfront com­pared to mas­sive return it gives you.
  • NDe­pend. NDepend's CQL rules lend them­selves quite nicely to this task. They work in a sim­i­lar man­ner to unit tests, but they are exter­nal to your code. Espe­cially with very nice Visual Stu­dio inte­gra­tion in ver­sion 3, it has very low fric­tion, and pro­vides imme­di­ate feed­back. In addi­tion they are pretty easy to read, lend­ing them­selves to the task of being exe­cutable documentation.

.NET OSS dependency hell

Thursday, February 25th, 2010

Paul, whom some of you may know as the main­tainer of Horn project, left a com­ment on my blog, that was (or to be more pre­cise – I think it was) a con­tin­u­a­tion of series of his tweets about his dis­sat­is­fac­tion with the state of affairs when it comes to depen­den­cies between var­i­ous OSS projects in .NET space, and within Cas­tle Project in particular.

paul_twitter

I must say I under­stand Paul, and he’s got some valid points there, so let’s see what can be done about it.

Prob­lems

One of the goals of Cas­tle Project from the very begin­ning has been mod­u­lar­ity of its ele­ments. As cas­tle main page says:

Offer­ing a set of tools (work­ing together or inde­pen­dently) and inte­gra­tion with oth­ers open source projects, Cas­tle helps you get more done with less code and in less time.

How do you achieve mod­u­lar­ity. Say you have two projects, Foo and Bar that you want to inte­grate. You could just ref­er­ence one from the other.

eb1c2cc[1]

This how­ever means that when­ever you use Foo, you have to drag Bar with you. For exam­ple, when­ever you want to use Mono­Rail, you’d need to drag ActiveRe­cord with it, along with entire set of its depen­den­cies, and their depen­den­cies, etc.

Instead you employ Depen­dency Inver­sion (do not con­fuse with Depen­dency Injec­tion). You make your com­po­nents depend on abstrac­tions, not the imple­men­ta­tion. This how­ever means, that in .NET assem­bly model, you need to intro­duce third assem­bly to keep the abstrac­tions in.

51067fb6[1]

Now we have 3 assem­blies instead of 2 to inte­grate two projects. Within Cas­tle itself com­mon abstrac­tions are being kept in Castle.Core.dll. But what if we want to take more direct advan­tage of one project in another project still main­tain­ing the decou­pled struc­ture? We need to extract the func­tion­al­ity bridg­ing the two projects to yet another assem­bly. Tick – now we have 4 of them.

607f68d4[1]

In this case the Foo­Bar project would be some­thing like ActiveRe­cord inte­gra­tion facil­ity, which inte­grates ActiveRe­cord with Wind­sor.

When you mix mul­ti­ple projects together you enter another prob­lem – versioning.

Say you want to inte­grate few projects together, some of which are inter­de­pen­dent (via bridg­ing assem­blies, not shown here for brevity)

69f20a13[1]

Now, once a new ver­sion of one of the projects is released, you either have to wait for all the other projects to update their depen­dency to the lat­est ver­sion, do it your­self (pos­si­bly with some help from Horn), or stick to the old ver­sion. The sit­u­a­tion gets even more com­pli­cated when there were some break­ing changes intro­duced, in which case plain recom­pi­la­tion will not do – some actual code would need to be writ­ten to com­pen­sate for that.

These are the main issues with this model, let’s now look at pos­si­ble solutions.

Solu­tions

First thing that comes to mind – if hav­ing some assem­blies means you’ll need even more assem­blies, per­haps you should try to min­i­mize that num­ber? This has already come to our minds. With last wave of releases we per­formed some inte­gra­tion of projects. EmailSender got inte­grated into Core, one less assem­bly. Log­ging adapters for log4net and nlog were merged into core project, which means they still are sep­a­rate assem­blies (as they bridge Cas­tle with 3rd party projects) but they’re now synced with Core and are released with it, which means this is one less ele­ment in your ver­sion­ing matrix for you to worry about. Sim­i­lar thing hap­pened with Log­ging Facil­ity, which now is ver­sioned and released with Wind­sor itself.

For the next major ver­sion, there are sug­ges­tions to take this one step fur­ther. Merge Dynam­icProxy with Dic­tio­naryAdapter and (parts of) Core into a sin­gle assem­bly; Merge Wind­sor and Micro­Ker­nel (and other parts of Core) into an other assem­bly. With that you get from 5 assem­blies to 2.

That reduces Castle’s inter­nal depen­den­cies, but what about other projects that depend on it? After the recent release, we started a log of break­ing changes, along with brief expla­na­tion and sug­gested upgrade paths, to make it eas­ier for appli­ca­tions and frame­works to upgrade. We have yet to see how this plays out.

What else can be done?

This is the actual ques­tion to you? What do you think can be done, for Cas­tle specif­i­cally, but more broadly – for entire .NET OSS ecosys­tems to make prob­lems Paul men­tioned go away, or at least make them eas­ier to sort out?

Thoughts on C# 4.0’ optional parameters

Wednesday, September 2nd, 2009

C# 4.0 is just round the cor­ner and along with it set of nice new addi­tions to the lan­guage, includ­ing optional para­me­ters. There’s been some his­tor­i­cal resis­tance to add this fea­ture to the lan­guage, but here' it is, and I’m glad it’s com­ing, or at least I was.

In few words, optional para­me­ters, have their default value spec­i­fied in the sig­na­ture of the method. You can then skip them when call­ing method, and the method will be called with their default values.

So, what’s the deal?

To sim­plify the cur­rent dis­cus­sion I will refer to the method con­tain­ing default para­me­ters (Foo in this exam­ple) as called method, and to method pro­vid­ing the default value (DateTime.Now get­ter in the exam­ple few para­graphs below) as value provider.

Take a look at the code below. Method Foo has two para­me­ters, but we can call them as if it had none.

defaultParameters_0

Look­ing good so far, right? Let’s take a look at how Main method looks like in Reflector.

defaultArguments_1

As we can see there’s no magic here – sim­ple com­piler trick. Com­piler binds the invo­ca­tion to the method, and them puts the argu­ments for you. The code looks as if you had writ­ten it your­self in ear­lier ver­sion of C#.

Still good, right? So how does exactly the com­piler knows what to put on the call­ing side? Let’s take a look at the com­piled sig­na­ture of the method Foo.

defaultParameters_2

Ha! The val­ues are encoded in Default­Pa­ra­me­ter­ValueAttribute. Do you see the prob­lem here? No? Than let’s try some­thing else. Let’s change the sig­na­ture of the method to take Date­Time instead of int.

defaultParameters_3

Notice we ini­tial­ize the time to default value of DateTime.Now. All good? So let’s com­pile the code, shall we?

defaultParameters_4

Oops.

Turns out we can’t. What seems like a really rea­son­able code is not allowed. Since the default val­ues for argu­ments are being kept in attrib­utes they must be a com­pile time con­stants, which includes prim­i­tive types (numeric types and strings), tokens ( typeof, methodof, which is not exposed in C# though ) and nulls. Pretty dis­ap­point­ing right?  This means no new Foo(), no Foo.Bar is allowed. This dra­mat­i­cally lim­its the range of sce­nar­ios where this fea­ture can be used, as most of the time, you’ll want not null, but some­thing else as your default value, in which case you’ll end up cre­at­ing over­loads anyway.

There are some workarounds, like the one described in this book, but they have their own down­sides, and it’s not always pos­si­ble to use them anyway.

This all makes me think – why did the authors of the lan­guage decided to pro­vide such crip­pled imple­men­ta­tion of the fea­ture? I’m not an expert in this mat­ter, but I found a sim­ple way in which the fea­ture could be imple­mented allow­ing for far greater range of scenarios.

What if…

Let’s re-examine how this fea­ture works.

  • The com­piler puts the default val­ues of the argu­ments in a spe­cial attribute type on the called method signature.
  • On the call­ing side, the com­piler reads the val­ues, and puts these of them that were not pro­vided explicitly.

All the work hap­pens at com­pile time (let’s ignore the dynamic for a moment, we’ll get to that as well) so no addi­tional work at run­time is required. Since the com­piler is very pow­er­ful, why not go one step further.

I think by sim­ply extend­ing this approach the fol­low­ing sce­nar­ios could be enabled.

  • using value returned by sta­tic para­me­ter­less method (this includes sta­tic prop­erty get­ters) as default value.
  • using value returned by instance para­me­ter­less method defined on the same type (or base type of the type) as called method is defined on (this would only be applic­a­ble for instance methods).
  • using default, para­me­ter­less con­struc­tors as default value.
  • or if we wanted to extend it fur­ther: using value return­ing by any vari­ant of the above that does take para­me­ters that are allowed to be put in the attribute (includ­ing both con­stants, and val­ues of other parameters).

Let us exam­ine how this could be (I think) achieved.

The spoon does not exist

What we would need is a way to store infor­ma­tion which method, or con­struc­tor of which type we want to invoke in case no default value is pro­vided. Since tokens are legal in attrib­utes, the exist­ing approach could be extended with some­thing like this:

defaultParameters_5 

We have a way of stor­ing the method. Now, the com­piler could eas­ily retrieve the token and invoke the called method.

  • If value provider is sta­tic there’s no prob­lem – just call it, regard­less of whether called method is an instance or sta­tic method.
  • If value provider is instance method, and called method is instance method as well, invoke the value provider on the instance on which called method is being invoked (hence the require­ment that value provider must be declared on the same type as called method or its base type).
  • If value provider is instance method but called method is sta­tic do not allow (at com­pile time!) this code to com­pile, since there’s no instance to call the value provider on.

When it comes to con­struc­tors it is even sim­pler – since we allow only default con­struc­tor, at com­pile time we would check if the type does indeed have default, acces­si­ble con­struc­tor, and dis­al­low the code to com­pile oth­er­wise. Then when the called method is being invoked, retrieve the type token and call the default con­struc­tor on that type.

What about dynamic code?

I don’t have very inti­mate knowl­edge of dynamic code yet, but I think this could work with dynamic code as well. The com­piler would put all the infor­ma­tion on the call site (new con­cept intro­duced in .NET 4.0) and this would be all we need. In C# 1.0 hav­ing Method­Info of a method you could invoke it. Same hav­ing System.Type it is easy to find and invoke it’s default con­struc­tor using lit­tle bit of reflec­tion. I really see no rea­son why this would not work.

 

What do you think – am I miss­ing part of the pic­ture – is it some­thing ter­ri­bly wrong with my idea that would restrain it from work­ing? Or maybe C# team didn’t really want (as they used to) imple­ment this fea­ture so they pro­vided only the min­i­mal imple­men­ta­tion they needed for other major fea­tures, COM interop specifically.

Tech­no­rati Tags:

Convention based Dependency Injection with Castle MicroKernel/Windsor

Thursday, April 9th, 2009

Quiz

Con­sider the fol­low­ing piece of code (it shows Cas­tle Micro­Ker­nel, but since Wind­sor is built on top of Micro­Ker­nel, it works the same way):

IKernel kernel = new DefaultKernel();
kernel.AddComponent("sms", typeof(IAlarmSender), typeof(SmsSender));
kernel.AddComponent("email", typeof(IAlarmSender), typeof(EmailSender));
 
kernel.AddComponent("generator", typeof(AlarmGenerator));
 
AlarmGenerator gen = (AlarmGenerator) kernel["generator"];

Con­sid­er­ing Alar­m­Gen­er­a­tor has a depen­dency on IAlarm­Sender, which one of two reg­is­tered com­po­nents will it get?

The answer is: the first one.

In this case we reg­is­tered SmsSender first, so it will get injected. If we switched the order of reg­is­tra­tion, EmailSender would get injected. It does not mat­ter if you spec­ify a name when reg­is­ter­ing or not.

I don't know how other con­tain­ers han­dle this prob­lem, but this approach in gen­eral is as good as any (and by any I mean any other than 'throw new IDontKnowWhatToDoException()').

That was easy, wasn't it?

Now, let's get to another one. We have a class:

public class Person
{
 public Person( IClock leftHandClock )
 {
  this.LeftHandClock = leftHandClock;
 }
 
 public IClock LeftHandClock { get; private set; }
 public IClock RightHandClock { get; set; }
}

An inter­face, and two imple­ment­ing types:

public interface IClock{}
public class IsraelClock : IClock{}
public class WorldClock : IClock{}

Then, if we reg­is­ter these like this:

IWindsorContainer container = new WindsorContainer().
    AddComponent<IClock, WorldClock>( "leftHandClock" ).
    AddComponent<IClock, IsraelClock>( "rightHandClock" ).
    AddComponent<Person>();
var joe = container.Resolve<Person>();
 

What watches will our Joe wear on each hand?

The answer is: the first one. Again.

So in this case Joe will have a World­Clock on both wrists (the same instance to be exact since com­po­nents in Micro­Ker­nel are sin­gle­tons by default, but that's besides the point).

Idea

That's not that intu­itive is it? I mean, you could cer­tainly make it work that way, but that would require you to con­fig­ure the con­tainer for it. This how­ever seems like a per­fect place to uti­lize a Con­ven­tion Over Con­fig­u­ra­tion approach.

I got this idea yes­ter­day and decided to try to imple­ment it in Micro­Ker­nel. I also tweeted about it, and Philip Lau­re­ano (author of LinFu, and recently Hiro) and Nate Kohari (author of NIn­ject… and recently NInject2) seem to like that idea.

So here's my ini­tial naive take at it.

Code

Luck­ily, thanks to won­der­ful exten­si­bil­ity of Cas­tle you don't have to mod­ify the con­tainer itself. All you need to do is to extend it, with cus­tom Sub­De­pen­den­cyRe­solver. Here's my ini­tial naive imple­men­ta­tion, which I did in cou­ple of min­utes, as a proof of concept.

public class ConventionBasedResolver : ISubDependencyResolver
{
    private IKernel _kernel;
    private IDictionary<DependencyModel, string> _knownDependencies = new Dictionary<DependencyModel, string>();
 
    public ConventionBasedResolver( IKernel kernel )
    {
        if( kernel == null )
        {
            throw new ArgumentNullException( "kernel" );
        }
        this._kernel = kernel;
    }
 
    public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        string componentName;
        if (!this._knownDependencies.TryGetValue(dependency, out componentName))
        {
            componentName = dependency.DependencyKey;
        }
        return _kernel.Resolve(componentName, dependency.TargetType);
    }
 
    public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        if (this._knownDependencies.ContainsKey(dependency))
            return true;
 
        var handlers = this._kernel.GetHandlers(dependency.TargetType );
 
        //if there's just one, we're not interested.
        if(handlers.Length<2)
            return false;
        foreach( var handler in handlers )
        {
            if( IsMatch( handler.ComponentModel, dependency ) && handler.CurrentState == HandlerState.Valid )
            {
                if( !handler.ComponentModel.Name.Equals( dependency.DependencyKey, StringComparison.Ordinal ) )
                {
                    this._knownDependencies.Add( dependency, handler.ComponentModel.Name );
                }
                return true;
            }
        }
        return false;
    }
 
    private bool IsMatch( ComponentModel model, DependencyModel dependency )
    {
        return dependency.DependencyKey.Equals( model.Name, StringComparison.OrdinalIgnoreCase );
    }
}

Now, we need to add the sub resolver to the container:

container.Kernel.Resolver.AddSubResolver( new ConventionBasedResolver( container.Kernel ) );

And we're done.

Wrap­ping up

We now have basic con­ven­tion based injec­tion of both prop­er­ties as well as con­struc­tor para­me­ters. With a lit­tle bit of work we might extend it a fur­ther to pro­vide plug­gable conventions.

For exam­ple match­ing by name­space (pre­fer close neigh­bors), by name (for ser­vice IFoo, first try to find if Foo is avail­able, then try Default­Foo, then FooImpl) or any other. The pos­si­bil­i­ties are endless.

If you have any ideas on how to extend or best use this approach, leave a comment.

On self-documenting code

Saturday, March 28th, 2009

Take this piece of code:

public int Count(string text)
{
    Console.WriteLine("Counting...");
    // simulate some lengthy operation...
    Thread.Sleep(5000);
    return text.Length;
}

What’s wrong with it?

It’s not very obvi­ous what the magic num­ber 5000 means? Does it mean 5000 years? 5000 min­utes? 5000 the time it takes to run around Main Mar­ket Square in Kraków?

Sure, you can hover over the invo­ca­tion (if you’re in Visual Stu­dio) and see the tooltip

selfdocumentingcode

and see that the num­ber denotes mil­lisec­onds, but then you (as well as the junior pro­gram­mer who will main­tain the code­base) have to remem­ber what a mil­lisec­ond is, and what it means to wait 5000 milliseconds.

The prob­lem is, that mil­lisec­ond is not the most nat­ural unit of time for humans, so I can assure you that the first thing the afore­men­tioned junior pro­gram­mer will do when he inher­its the code will be “refac­tor­ing” it, to this:

public int Count(string text)
{
    Console.WriteLine("Counting...");
    // simulate some lengthy operation...
    Thread.Sleep(5000);// waits 5 seconds
    return text.Length;
}

What this means, is not that junior devel­oper is not very bright – no. Quite the con­trary – he would be doing the right thing, only the wrong way. He would be increas­ing the read­abil­ity of the code by doc­u­ment­ing it. How­ever, he would not have to do that, if the code was self doc­u­ment­ing.

So how do we fix that? For exam­ple, like this:

public int Count(string text)
{
    Console.WriteLine("Counting...");
    // simulate some lengthy operation...
    Thread.Sleep(TimeSpan.FromSeconds(5));
    return text.Length;
}

Unit tests – keep it simple (KISS)!

Friday, February 6th, 2009

I have a ten­dency to over­com­pli­cate things some­times. Unit tests, are one such piece of code, that you want to keep as sim­ple and clean as pos­si­ble, so that other devel­op­ers can eas­ily find out how your class-or-method-under-test is sup­posed to work. There’s a prin­ci­ple for that that says it very strongly – “Keep it sim­ple, stupid.”

Don’t make it flex­i­ble when it does not have to be (just … hard code it). For exam­ple, when I was work­ing on IIn­ter­cep­torS­e­lec­tor sup­port for Cas­tle Dynam­icProxy, I had to test prox­ies with­out tar­get, where return value is set by an interceptor.

My first attempt at it was to cre­ate Return­De­fault­OfT­In­ter­cep­tor class that for any given return type, would instan­ti­ate it with para­me­ter­less con­struc­tor. This solu­tion would pro­vide what I needed, but it was unnec­es­sar­ily com­pli­cated and made the test less read­able. I didn’t need a helper class (that’s what the inter­cep­tor was in this test) that would han­dle just any return type of just any method. For the test I was call­ing one method, with one return type, and that’s all I needed from my helper interceptor.

Once I real­ize that I changed the test to some­thing like this:

[Test]
public void SelectorWorksForInterfacesOfInterfaceProxyWithoutTarget()
{
    var options = new ProxyGenerationOptions
    {
        Selector = new TypeInterceptorSelector<ReturnFiveInterceptor>()
    };
    var proxy = generator.CreateInterfaceProxyWithoutTarget(
    typeof(ISimpleInterface),
        new[] { typeof(ISimpleInterfaceWithProperty) }, 
        options,
        new ReturnFiveInterceptor()) 
    as ISimpleInterfaceWithProperty;
    Assert.IsNotNull(proxy);
    var i = proxy.Age;
    Assert.AreEqual(5, i);
} 

The Return­FiveIn­ter­cep­tor class name clearly sais what the class does. Also the asser­tion in the last line is more obvi­ous now.

So, keep your tests sim­ple and read­able, don’t gen­er­al­ize where you don’t really need to, but know your lim­its, because when you cross the line you’re on the frag­ile tests territory.

Tech­no­rati Tags: , ,

Good comments, bad comments

Monday, December 22nd, 2008

As devel­op­ers from our first years we are taught by our mas­ters: “Com­ment your code you should, my young appren­tice”. I even found this arti­cle, that out­lines 13 rules, on how you should com­ment your code. I only have two rules for that:

  1. Don’t com­ment what your code is doing. If you find it nec­es­sary, it’s a code smell, and you should start think­ing about refac­tor­ing it, so that it’s obvious.
  2. Do com­ment why your code does what it does.

Other than that, merry Christ­mas and happy new year everybody.

Tech­no­rati Tags:

Multilingual .NET applications. Enter .NET localization

Wednesday, December 10th, 2008

Cre­at­ing mul­ti­lin­gual appli­ca­tions is a huge topic. There are whole books devoted to it, and if you’re seri­ous about it, you should def­i­nitely read those, because what you see on sur­face, is only the tip of an iceberg.

If you only want to play with local­iza­tion or need a quick ref­er­ence, hope­fully this post will help.

Fist thing is, .NET is really well thought of if it comes to local­iza­tion, so if you know what you’re doing, it’s pretty pain­less to cre­ate appli­ca­tion that will be easy to trans­late to other lan­guages (local­iza­tion is a LOT big­ger topic than show­ing labels in dif­fer­ent lan­guages, but I’ll leave this topic out.)

Sec­ond thing is, local­iza­tion mech­a­nism in .NET is greatly based on con­ven­tions, and it’s what we’ll focus here.

First obvi­ous rule is, that each string, pic­ture, video… gen­er­ally speak­ing local­iz­able resource must not be hardcoded.

If you don’t hard­code resources where do you keep them? In (sur­prise) Resources file. Gen­er­ally you can use .resx files, or plain .txt, though the lat­ter are use­ful only if you only keep strings.

resourceFile

Visual Stu­dio has pretty good sup­port for edit­ing resources in .resx files, and later I’ll show you another tool that can do it as well.

To access the resources pro­gram­mat­i­cally you need Resource­M­an­ager class. To instan­ti­ate it you need to give it the part to resources within an assem­bly, and the assem­bly itself. If it’s a lit­tle bit unclear, here’s the example:

resourcePath

If the Visual Stu­dio project is named Local­iz­ableApp, and the .resx file we want to use is in folder Prop­er­ties, and the file itself is named Resources.resx, the whole base name for the resources is “LocalizableApp.Properties.Resources”.

That’s where the com­piled .resx file (.resources) will be located within the assem­bly. You can see it, if you open the com­piled assem­bly with Reflector.

resourceLocation

So to instan­ti­ate the Resource­M­an­ager you’d write code sim­i­lar to the following:

var manager = new ResourceManager("LocalizableApp.Properties.Resources", typeof(Program).Assembly);

Each resource is iden­ti­fied by it’s unique name string. For exam­ple in the pic­ture below, we have two resources with names, “greet­ing” and “howAreYou”

resourceEditor

You use these names to get the val­ues of the resources. The resource man­ager does its magic, to pro­vide you with resources best match­ing the Cul­ture­Info you pro­vided. If you don’t pro­vide any Cul­ture, cur­rent thread’s Cur­ren­tU­I­Cul­ture is used. So if you write:

Console.WriteLine("{0} {1}", manager.GetString("greeting"), manager.GetString("howAreYou"));

The Cul­ture­Info object held in Cur­ren­tU­I­Cul­ture prop­erty of cur­rently exe­cut­ing thread will be used. The default value for this prop­erty is the same as lan­guage ver­sion of Win­dows OS the pro­gram is exe­cut­ing on, which is rea­son­able. If your user uses Pol­ish Win­dows she will prob­a­bly want to inter­act with Pol­ish ver­sion of your app as well.

You may not rely on this default though, and either over­ride the Thread’s prop­erty, or spec­ify the cul­ture explic­itly when call­ing meth­ods on Resource­M­an­ager, like so:

culture = CultureInfo.GetCultureInfo("pl-PL");
Console.WriteLine("{0} {1}", manager.GetString("greeting", culture), 
    manager.GetString("howAreYou", culture));

Of course you wouldn’t hard­code the cul­ture the way I did in the exam­ple, because it would defeat the pur­pose of using cul­ture in the first place.

OK, so how to add another language?

You have the .resx file with the default, fall­back resources, right? So now all you need is either send the file to a local­iza­tion com­pany, sit back and enjoy life, wait­ing for them to do the hard job, or do it your­self. To go with the lat­ter option, you may want to use a tool to edit resource files, called Resourcer, by Lutz Roeder (Reflec­tor, people!).

resourceResourcer

You can eas­ily edit any kind of resources in it (not only strings). When you’re done trans­lat­ing your resources, save the file as .resources file, using fol­low­ing pat­tern: {baseResourceName}.{culture}.resources. For exam­ple if you were to trans­late our exam­ple app, to Ger­man lan­guage as spo­ken in Ger­many, you’d save your edited file with the fol­low­ing name: LocalizableApp.Properties.Resources.de-de.resources

It is impor­tant to obey this pat­tern, as by con­ven­tion, this is what Resource­M­an­ager expects. If you fail to obey it, Resource­M­an­ager will not be able to pick your trans­lated resources and will fall back to the default.

Hav­ing trans­lated and prop­erly named .resource file we need to make a satel­lite assem­bly out of it. To do it, you need Assem­bly Linker (al.exe) tool that is part of .NET SDK.

al

There are mul­ti­ple prop­er­ties you can set with al, the min­i­mal ver­sion to get valid satel­lite assem­bly is shown on above screen­shot. One thing that’s impor­tant to note, is the name of result­ing satel­lite assem­bly. Again, by con­ven­tion it has to be {NameOfBaseAssemblyWithoutExtension}.resources.dll, so if our appli­ca­tion assem­bly was named LocalizableApp.exe, satel­lite assem­bly must be called LocalizableApp.resources.dll

Notice that the name of the assem­bly is the same for every cul­ture. So how do we deal with that. Obvi­ously we can’t have two files with the same name in one folder. The way it is han­dled, is through sub­fold­ers. Each satel­lite assem­bly is held in a folder which is named after the cul­ture of the satel­lite assembly.

resourceFolders

For exam­ple if our LocalizableApp.exe is held in a folder, let’s say Debug like on the above screen­shot, the de-de satel­lite assem­bly would be Debug\de-de\LocalizableApp.resources.dll and for instance pl assem­bly would be in Debug\pl\LocalizableApp.resources.dll.

I hope this is all clear by now. The great­est thing is, to add new lan­guage you don’t even need the actual base assem­bly. All you need is its resources and their loca­tion within the assembly.

Tech­no­rati Tags: , ,