On Nuget, Git and unignoring packages

Git has a help­ful abil­ity to ignore cer­tain files. When work­ing on .net projects, you nor­mally want to ignore your .suo file, bin and obj fold­ers etc.

If you're using the excel­lent GitEx­ten­sions it will even pro­vide a default, rea­son­able .git­ig­nore file for you.

Prob­lem is, that while you want to ignore cer­tain pat­terns in most of your project, gen­er­ally you want none of those rules to apply to your nuget packages.

Every­thing in pack­ages folder should be com­mit­ted. Always. No exceptions.

To do that, you need to lever­age a child .git­ig­nore file.

Cre­ate a .git­ig­nore file inside your pack­ages folder and add the fol­low­ing line to it:

!*

This tells Git to dis­re­gard any ignore rules of the par­ent file. Now all your pack­ages will be com­mit­ted com­pletely, with­out miss­ing any of their functionality.

On Windsor 3.2 release

Wind­sor 3.2 release is now live on nuget and source­forge.

This release is mostly about bug­fixes and incre­men­tal improve­ments and while some break­ing changes were made, for vast major­ity of users this will be a drop-in update.

The high­lights of the release are in the doc­u­men­ta­tion, so I won't repeat them here.

End of an era

It is the last release to sup­port .NET 3.5 and Silverlight.

Also, I'm think­ing of sun­set­ting (such a nice word) Remot­ing facil­ity, Fac­tory Sup­port facil­ity (the one that allows you to spec­ify fac­tory method via XML, not to be con­fused with Typed Fac­tory facil­ity), Event Wiring facil­ity and Syn­chro­nize facility.

Obvi­ously, Wind­sor being a com­mu­nity dri­ven project, if some­one wants to step in and take over any of these facil­i­ties we'll keep updat­ing them. Oth­er­wise this will likely be their last release.

On Testing: Why write tests?

This post is secod part of my Back to basics: on test­ing series.

Devel­op­ers writ­ing tests

Peo­ple new to soft­ware, or com­ing from orga­ni­za­tions where all test­ing is done by ded­i­cated peo­ple often find the idea of devel­op­ers doing test­ing bizarre.

testing

After all, we're the highly trained, edu­cated pro­fes­sion­als. We get payed to do the hard bits. Click­ing around the UI to see if a label is mis­aligned or an app crashed surely should be del­e­gated to some­body else, out­sourced even.

Truth is, there are var­i­ous kinds of tests, and while there is value in UI tast­ing (auto­mated or not) we'll con­ce­trate at some­thig else first.

You write the tests for your future self

The idea of devel­op­ers writ­ing tests came not from acad­e­mia but from the field. From peo­ple who spent years devel­op­ing suc­cess­ful soft­ware. And as you get out there, and start work­ing with teams of peo­ple, on real life big sys­tems that solve real prob­lems, you realise that some things you belived (or in fact were taught) to be true, are not.

We'll get into the details as we progress with this series, but let's start with the biggest one:

The code is writ­ten, and read, and read, and read and read some more and mod­i­fied, and read, and mod­i­fied again, and read some more again and then few months later read yet again and again

You may notice there's much more read­ing than writ­ing there. That is true for most code — you don't just write and for­get it, like is the case with cod­ing assign­ments at unver­sity. Real-life code is long lived, often expanded and mod­i­fied and com­monly the per­son doing the expand­ing is not the per­son who orig­i­nally wrote the code. In fact the orig­i­nal author may have already moved on to work elsewhere.

  • How do you know what the code does?
  • How do you know where to make the change?
  • How do you know your change didn't break any of the assump­tions that code inter­act­ing with the bit you changed makse about it?
  • How do you know the change you made works the way you wanted it to?
  • How do you know the API you cre­ated (in other words the pub­lic meth­ods) are easy to use and will make sense to the other devel­op­ers using it (that may also be you few weeks from now!).

These are the rea­sons for writ­ing tests. Tests are the most eco­nom­i­cal way of ensur­ing the change you will make two months from now fit in the design con­strants you designed today. Tests are the fastest way for other devel­op­ers (or again, future you) to get a feel of how a piece of code works; what it does, and how you're sup­posed to use it.

Don't just take my word for it

In the next part of the series we'll start look­ing at actual code, writ­ing some tests, and explain­ing the con­cepts around them.

Until then, if you have any ques­tions, or sug­ges­tions as to what to cover in future posts of the series, feel free to leave a comment.

Using Resharper to ease mocking with NSubstitute

The prob­lem

While C# com­piler pro­vides a decent level of generic para­me­ter type infer­ence there's a bunch of sce­nar­ios where it does not work, and you have to spec­ify the generic para­me­ters explicitly.

One such case is when you invoke a generic method inline, and the return type is the generic type parameter.

In other words, the fol­low­ing scenario:

resharper_generic_call

In this case the com­piler won't infer the generic para­me­ter of GenericMethod and you have to spec­ify it explicitly.

As help­ful as Resharper often is, it also doesn't cur­rently pro­vide any help (other than plac­ing the cur­sor at the appro­pri­ate loca­tion) and you have to spec­ify the type para­me­ter yourself.

Oh the typing!

I'm quite sen­si­tive to fric­tion in my devel­op­ment work, and I found this lim­i­ta­tion quite annoy­ing. Espe­cially that the pat­tern is used quite often.

Specif­i­cally the excel­lent NSub­sti­tute mock­ing frame­work is using it for cre­ation of mocks via

Substitute.For<IMyTypeToMock>();

method.

If I wanted to use NSub­sti­tute to pro­vide the argu­ment for my GenericMethod I'd have to do quite a lot of typing:

resharper_step1

type Su or few more char­ac­ters to posi­tion com­ple­tion on the Substitute class.

Press Enter.

resharper_step2

Type . and assum­ing the right over­load of For is selected press Enter again (or press arrow to pick the right over­load before that).

Finally, type enough of the expected type's name for com­ple­tion to select it, and press Enter to fin­ish the statement.

resharper_step3

It may not look like much but if you're writ­ing a lot of tests those things add up. It ends up being just enough repet­i­tive typ­ing to break the flow of thoughts and make you con­cen­trate on the irrel­e­vant mechan­ics (how to cre­ate a mock for IFoo) rather than what your test is sup­posed to be doing (ver­i­fy­ing behav­ior of UsesIFoo method when a non-null arg is passed).

Resharper to the rescue

While there's no easy way to solve the gen­eral prob­lem, we can use Resharper to help us solve it in this spe­cific case with NSub­sti­tute (or any other API, I'm using NSub­sti­tute as an exam­ple here).

For that, we'll write a Smart Tem­plate.

How to: writ­ing a Smart Template

Go to Resharper menu, and pick Tem­plates Explorer…

Make sure you're on the Live Tem­plates tab, and click New Tem­plate.

creating_template_1

For Short­cut select what­ever you want to appear in your code com­ple­tion for the tem­plate, for exam­ple NSub.

Select the tem­plate should be allowed in C# where expres­sion is allowed.

Check Refor­mat and Shorten qual­i­fied ref­er­ences check­boxes and pro­ceed to spec­i­fy­ing the tem­plate itself, as follows:

NSubstitute.Substitute.For<$type$>()

The $type$ is a tem­plate vari­able, and the grid on the right hand side allows us to asso­ciate a macro with it. That's where the magic happens.

Pick Change macro… and select Guess type expected at this point.

After you've done all of that, make sure you save the template.

creating_template_2

Result

Now your tem­plate will be avail­able in the code completion.

resharper_step1a

resharper_step2a

All it takes to get to the end result now is to type ns, Enter, Enter.

The main ben­e­fit though is not the key­strokes you save, but the fact there's almost no fric­tion to the process, so you don't get dis­tracted from think­ing about logic of your test.

On testing

Over the last few years I've been mostly blog­ging about var­i­ous ran­dom top­ics. Most often those were related to Wind­sor, dis­cussing its new and upcom­ing fea­tures, announc­ing releases, and tak­ing in-depth look and its under­pin­ning principles.

Another bucket was one-off posts dis­cussing var­i­ous aspects of soft­ware devel­op­ment, mostly out of larger con­text and not really car­ing if you, dear reader, have the expe­ri­ence and under­stand­ing of the topic or not.

Back to basics

Recently I had an inter­est­ing dis­cus­sion with sev­eral peo­ple on twit­ter about basics. More pre­cisely about basics behind writ­ing tests.

It seems to me, and I'm guilty of that myself, that us, the devel­op­ers, chas­ing the lat­est great thing for­get about the basics. When was the last time you read a blog­post about the impor­tance of test­ing? When was the last time you read about how to write tests, what to look out for, and how to keep the qual­ity of your tests high and the main­te­nance cost low?

Sev­eral years ago I got a lot of value myself by read­ing blogs that taught me what is impor­tant in soft­ware, and I wouldn't be the devel­oper I am today, if it wasn't for those peo­ple, who ded­i­cated their time to share their expe­ri­ence and knowledge.

I may not be sub­scrib­ing to the right blogs any­more, but I noticed those posts are much less fre­quent these days. To help fill the void I decided to con­cen­trate a bit more on the fun­da­men­tals in the future, start­ing with what will hope­fully evolve into a series of blog­posts about tests.

Feed­back

Do you think it's a good idea? Any par­tic­u­lar top­ics you would like me to empha­sise, and areas to explore? Let me know in the com­ments. First post will be com­ing soon(ish).

IoC container solves a problem you might not have but it's a nice problem to have

On frame­works and libraries

A log­ging frame­work helps you log what's hap­pen­ing in your appli­ca­tion. A UI frame­work helps you ren­der and ani­mate UIs to the user. A com­mu­ni­ca­tion library helps con­nect­ing parts of a dis­trib­uted system.

All of these tasks and con­cepts are pretty easy to under­stand. They are quite down to earth, and there­fore, at a high level at least, easy to explain. They pro­duce tan­gi­ble, addi­tive dif­fer­ence in your application.

Also the code of your appli­ca­tion changes in order to use those frame­works and libraries. You add a log­ging frame­work, you write some code against its API and you end up with a file on your disk, or some text in your con­sole. You add a com­mu­ni­ca­tion library, inherit some base classes, imple­ment some inter­faces to des­ig­nate com­mu­ni­ca­tion end­points of your appli­ca­tion and you can see two processes exchang­ing infor­ma­tion. I hope you get the pic­ture and I don't need do go on describ­ing the tan­gi­ble, addi­tive and vis­i­ble results of using a UI framework.

What about IoC container?

So what about inver­sion of con­trol con­tain­ers? There's a lot of con­fu­sion around what they do, and why you should use one at all. Every now and then I meet a devel­oper, who says they read all the def­i­n­i­tions, intro­duc­tions and basic exam­ples, and they still don't get why would they use a con­tainer. Other times I'm hav­ing dis­cus­sions that can be sum­marised as (slightly exag­ger­ated for dra­matic effect):

I got one of the IoC con­tain­ers, put it in my appli­ca­tion, and then all hell broke loose. We got mem­ory leaks, things weren't appear­ing where they should, users were seing other users' data, we had to recy­cle the pool every hour because we were run­ning out of data­base con­nec­tions, and the app got very slow. Ah and also it destroyed main­tain­abil­ity of our code, because we never knew when some­thing is safe to refac­tor, since we never knew where and who would try to get them from the container.

Let's ignore the details for now and con­cen­trate on the wider sentiment.

So? Should I use it or not?

The sen­ti­ment is one of con­fu­sion, scep­ti­cism and frus­tra­tion. Was it a good idea to use the con­tainer? Should we have not used it? Would I use it if I was lead­ing the team?

Truth is, those aren't nec­es­sar­ily the right ques­tions to ask. You can't answer them in a vac­uum. Should I use my phone to twit­ter when I'm on the bus? While the answer might be "sure, why not" if you're a pas­sen­ger, it would be unequiv­o­cally "don't even think about reach­ing for your phone" if you're the driver.

I have seen appli­ca­tions where  intro­duc­ing a con­tainer imme­di­ately, would only worsen things. I also haven't worked with any .NET appli­ca­tion where, if archi­tected the way like to do things, the con­tainer wouldn't be ben­e­fi­cial in the long term.

It all boils down to the fact that con­tainer solves cer­tain prob­lems that arise if and when you build your appli­ca­tions a cer­tain way, and unless you do, you're not going to see the ben­e­fits it brings, sim­ply because the prob­lems con­tainer solves will not be the main prob­lems you'll be fac­ing, or will not appear in your appli­ca­tion at all.

What sort of archi­tec­ture are we talk­ing about?

Con­tainer has cer­tain require­ments in order to work smoothly.  First and fore­most it requires struc­ture and order. At a mechan­i­cal level, con­tainer takes over cer­tain level of con­trol over low level, mun­dane details of your  application's infra­struc­ture. It is how­ever still a tool, and unless the envi­ron­ment where it oper­ates is clean, with well defined lim­ited num­ber of abstrac­tions it will strug­gle, and so will you, try­ing to get it to work.

There's a lot of con­tent in the sen­tence above so let's dig a bit deeper.

The assump­tion con­tain­ers are mak­ing is, that you do have abstrac­tions. Get­ting a lit­tle bit ahead of our­selves, one of the main rea­son for using the con­tainer is to main­tain lose cou­pling in our code. The way we achieve this is by con­struct­ing our types in such a way that they do not depend directly on other con­crete classes. Regard­less if it's a high level type, or low level type, instead of depend­ing on one another directly, con­tainer expects they will depend on abstractions.

Another, related (pre)assumption is you will  build your classes to expose abstrac­tions. And not just in any way, but keep them small and crisp (struc­ture and order, remem­ber). To main­tain loose cou­pling, the abstrac­tions are expected to pro­vide just a sin­gle small task, and most classes will pro­vide just a sin­gle abstraction.

It is not uncom­mon for a con­crete class to pro­vide more than one abstrac­tion (for exam­ple to bridge two parts of the sys­tem) but in that case the con­tainer assumes you will sep­a­rate these two respon­si­bil­i­ties into two abstractions.

Large num­ber of abstrac­tions in your sys­tem will be reusable, that is a sin­gle abstrac­tion will be exposed by more than one type. In cases like that, the con­tainer assumes all the imple­men­ta­tions will obey the con­tract of the abstrac­tion, that is they will all behave in a way that will not be sur­pris­ing to any­one con­sum­ing the abstrac­tion with­out know­ing what con­crete imple­men­ta­tion is behind it.

The point above is espe­cially impor­tant to pro­vide class level exten­si­bil­ity. Cer­tain types in your sys­tem will depend on a col­lec­tion of depen­den­cies, and you should not have to go back and change them, when­ever you add a new type end­ing up in that col­lec­tion. The assump­tion is, the code using the abstrac­tions, as well as the abstrac­tions them­selves are built in such a way, that the type can be extended by swap­ping (or adding new) depen­den­cies it has, with­out the type itself hav­ing to change.

That's a lot of assump­tions, isn't it?

You may say the con­tainer makes quite a num­ber of assump­tions (or require­ments!) about how your appli­ca­tion is struc­tured. You wouldn't be wrong.

How­ever if you look up and read the pre­vi­ous sec­tion again, for­get­ting that we are talk­ing about con­tainer, does this feel like an archi­tec­ture you should be striv­ing for any­way? Does it feel like good, main­tain­able object ori­ented archi­tec­ture? If it does, then that's good, because that's intentional.

A con­tainer doesn't put any arti­fi­cial or arbi­trary cum­ber­some con­straints onto how you should build your appli­ca­tion. It doesn't ask you to com­pro­mise any good prac­tices aim­ing at max­imis­ing testa­bil­ity, main­tain­abil­ity and read­abil­ity of your code and archi­tec­ture. On the con­trary, it encour­ages and rewards you for that.

It's the inversion!

Finally we're at a point where we can talk about some answers. The con­tainer makes a lot of assump­tions about how your code is struc­tured for two reasons.

That makes the con­tainer dif­fer­ent from log­ging frame­work or com­mu­ni­ca­tion frame­work. None of them cares about how your code is struc­tured. As long as you imple­ment cor­rect inter­faces or inherit cor­rect base classes, and are able to call the right API they don't care.

Inver­sion of con­trol con­tain­ers are fun­da­men­tally dif­fer­ent. They do not require your code to imple­ment or inherit any­thing and there's no API to call (out­side of sin­gle place called com­po­si­tion root). Just by look­ing at code of your appli­ca­tion, you can't tell if there is a con­tainer involved or not.

That's the inver­sion of con­trol work­ing. This is what con­fuses so many peo­ple when they first start using con­tain­ers. The dif­fer­ence is so fun­da­men­tal from most other frame­works and libraries that it may be hard to com­pre­hend and make the switch.

Inver­sion of con­trol con­fuses peo­ple and makes it harder to see the value a con­tainer brings because the value is not tan­gi­ble and it is not additive.

Con­trast that with the exam­ples from the first sec­tion. With log­ging frame­work you can point a fin­ger at a piece of code and say "There, here's the log­ging frame­work doing its thing". You can point a fin­ger at your screen, entry in Win­dows event log, or a file on disk and say "There, here's the result of log­ging frame­work doing its thing".

Inver­sion of con­trol con­tainer is just "out there". You can't see the work that it's doing by inspect­ing your code. That ephemer­al­ness and intan­gi­bil­ity is what con­fuses many new users and makes it harder for them to see the value the con­tainer brings to the table.

To make things even slightly more con­fus­ing for new­com­ers, when you're using a con­tainer you don't end up writ­ing code to use the con­tainer (again, expect for a lit­tle bit of code to wire it up). You end up writ­ing less code as a result of using the con­tainer, not more, which again is harder to mea­sure and appre­ci­ate than code you can clearly see as a result of using other kinds of frameworks.

What isn't there…

The sec­ond rea­son why con­tainer makes all of these assump­tions about your code is very sim­ple. Unless your archi­tec­ture fol­lows these rules, you sim­ply will not have the prob­lems that the con­tain­ers are built to solve. And even if you do, they will be far from being your main concern.

Build­ing your appli­ca­tion accord­ing to the assump­tions that the con­tainer is built upon (I hope by now you fig­ured out that they are just SOLID prin­ci­ples of good object ori­ented C# code) your appli­ca­tion will be com­posed of types expos­ing cer­tain characteristics.

Fol­low­ing Sin­gle Respon­si­bil­ity Prin­ci­ple will lead you down the road of hav­ing plenty of small classes.

Open Close Prin­ci­ple will lead you down the way of encap­su­lat­ing the core logic of each type in it, and then del­e­gat­ing all other work to its depen­den­cies, caus­ing most of those small classes to have mul­ti­ple dependencies.

Inter­face Seg­re­ga­tion Prin­ci­ple will cause you to abstract most of those big num­ber of classes by expos­ing an inter­face or an abstract class, fur­ther mul­ti­ply­ing the num­ber of types in your application.

Liskov Sub­sti­tu­tion Prin­ci­ple will force you to clearly shape your abstrac­tions so that they can be used in a uni­form way.

Finally, if you fol­low Depen­dency Inver­sion Prin­ci­ple your types will not only expose abstrac­tions them­selves, but also depend on abstrac­tions rather than con­crete types.

Over­all you will have a big num­ber of small classes work­ing with a num­ber of abstrac­tions. Each of those classes will be con­cen­trated on its own job and largely ambiva­lent (and abstracted from) about who is using it, and details of who it is using.

This leaves you with a prob­lem of putting together a group of those small types (let's call them Com­po­nents) in order to sup­port a full, real life, end to end sce­nario. Not only will you have to put them together, but also, main­tain and man­age them through­out the life­time of your application.

Each com­po­nent will be slightly dif­fer­ent. For some of them you will want to have just a sin­gle instance, that is reused every­where, for oth­ers, you'll want to pro­vide a new instance each time one is needed, or may be reuse instances within the scope of a web request, or any other arbi­trary scope.

Some of them will have decom­mis­sion logic, like Dis­pose method. Some of them will have ambi­ent steps asso­ci­ated with their life­cy­cle, like "sub­scribe me to cer­tain events in event aggre­ga­tor when I'm cre­ated and them unsub­scribe me when I'm about to be destroyed".

Also thanks to the power of abstrac­tions and guar­an­tees put in place by fol­low­ing Liskov Sub­sti­tu­tion Prin­ci­ple you'll want to com­pose some of the com­po­nents using a fur­ther set of design pat­terns. You'll want to cre­ate Dec­o­ra­tors, Chains of Respon­si­bil­ity, Com­pos­ites etc.

Not to men­tion the fact that in addi­tion to depend­ing on abstrac­tions exposed by other com­po­nents (let's call them Ser­vices) your com­po­nents may also have some con­fig­u­ra­tion, or other "prim­i­tive" depen­den­cies (like con­nec­tion strings).

I hope you can see that the com­plex­ity of it all can quickly grow immensely. If you want to main­tain loose cou­pling between your com­po­nents, you will have to write a lot of code to put them together and main­tain all the afore­men­tioned qual­i­ties. The code to do that can quickly grow as well, both in size and complexity.

Con­tainer to save the day

Inver­sion of con­trol con­tain­ers exist to replace that code. I know it took me a while to get here, and I did it in a very round­about way, but there you have it — that's what IoC con­tain­ers do — they help you stay sane, and reduce fric­tion of devel­op­ment when adher­ing to good Object Ori­ented Design prin­ci­ples in lan­guage like C#.

I know it's not a sexy and con­cise def­i­n­i­tion, and some of you will prob­a­bly need to re-read this post for it to "click". Don't worry. It didn't click for me at first either. The value and goal of IoC con­tainer is abstract and intan­gi­ble, and the nomen­cla­ture doesn't help either.

The i-word

Some peo­ple feel that a lot of mis­con­cep­tions and mis­un­der­stand­ing about con­tain­ers comes from their very name — inver­sion of con­trol con­tainer. If you just hear some­one say those words, and leave it to your imag­i­na­tion, you'll most likely see… blank. Noth­ing. It's so abstract, that unless you know what it means, it's pretty much meaningless.

To alle­vi­ate that some peo­ple started refer­ring to con­tain­ers as Depen­dency Injec­tion con­tainer. At first this sounds like a bet­ter option. We pretty much under­stand what depen­dency in con­text of rela­tion between two objects is. Injec­tion is also some­thing that you can have a lot asso­ci­a­tions with, soft­ware related or oth­er­wise. Sounds sim­pler, more down-to-earth, doesn't it?

It does sound like a bet­ter option, but in my expe­ri­ence it ends being a med­i­cine that's worse than the dis­ease. While it doesn't leave you with blank stare, it projects a wrong image of what a con­tainer does. By using the word injec­tion it empha­sises the process of con­struct­ing the graph of depen­den­cies, ignor­ing every­thing else the con­tainer does, espe­cially the fact that it man­ages the whole life­time of the object, not just its con­struc­tion. As a result of that, in my expe­ri­ence, peo­ple who think about con­tain­ers in terms of DI end up mis­us­ing the con­tainer and fac­ing prob­lems that arise from that.

That's why, even though I'm quite aware Inver­sion of Con­trol Con­tainer is a poor name, that doesn't help much in under­stand­ing those tools, at least it doesn't end up caus­ing peo­ple to mis­un­der­stand them.

In clos­ing

So there you have it. I admire your per­sis­tence if you made it that far. I hope this post will help peo­ple under­sand what a con­tainer does, and why putting it in an appli­ca­tion that's not archi­tected for it, may end up caus­ing more prob­lems than benefits.

I hope it made it clearer what hav­ing a con­tainer in a well designed appli­ca­tion brings to the table. In fact I only spoke about the most basic and gen­eral usages sce­nario that every con­tainer sup­ports. Beyond that par­tic­u­lar con­tain­ers have addi­tional, some­times very pow­er­ful fea­tures that will add addi­tional ben­e­fit to your devel­op­ment process.

So even if you feel you don't have a need for a con­tainer right now, hav­ing the prob­lems that the con­tainer is meant to solve is often a sign of a good, object ori­ented archi­tec­ture, and those are good prob­lems to have.

To constructor or to property dependency?

Us, devel­op­ers, are a bit like that comic strip (from always great xkcd):

Crazy Straws

We can end­lessly debate over tabs ver­sus spaces (don't even get me started), whether to use optional semi­colon or not, and other seem­ingly irrel­e­vant top­ics. We can have heated, informed debates with a lot of merit, or (much more often) not very con­struc­tive exchanges of opinions.

I men­tion that to explic­itly point out, while this post might be per­ceived as one of such dis­cus­sions, the goal of it is not to be a flame­war bait, but to share some experience.

So hav­ing said that, let's cut to the chase.

Depen­den­cies, mechan­ics and semantics

Writ­ing soft­ware in an object ori­ented lan­guage, like C#, fol­low­ing estab­lished prac­tices (SOLID etc) we tend to end up with many types, con­cen­trated on doing one thing, and del­e­gat­ing the rest to others.

Let's take an arti­fi­cial exam­ple of a class that is sup­posed to han­dle sce­nario where a user moved and we need to update their address.

public class UserService: IUserService
{
   // some other members

   public void UserMoved(UserMovedCommand command)
   {
      var user = session.Get<User>(command.UserId);

      logger.Info("Updating address for user {0} from {1} to {2}", user.Id, user.Address, command.Address);

      user.UpdateAddress(command.Address);

      bus.Publish(new UserAddressUpdated(user.Id, user.Address));
   }
}

There are four lines of code in this method, and three dif­fer­ent depen­den­cies are in use: ses­sion, log­ger and bus. As an author of this code, you have a few options of sup­ply­ing those depen­den­cies, two of which that we're going to con­cen­trate on (and by far the most pop­u­lar) are con­struc­tor depen­den­cies and prop­erty dependencies.

Tra­di­tional school of thought

Tra­di­tional approach to that prob­lem among C# devel­op­ers goes some­thing like this:

Use con­struc­tor for required depen­den­cies and prop­er­ties for optional dependencies.

This option is by far the most pop­u­lar and I used to fol­low it myself for a long time. Recently how­ever, at first uncon­sciously, I moved away from it.

While in the­ory it's a neat, arbi­trary rule that's easy to fol­low, in prac­tice I found it is based on a flawed premise. The premise is this:

By look­ing at the class' con­struc­tor and prop­er­ties you will be able to eas­ily see the min­i­mal set of required depen­den­cies (those that go into the con­struc­tor) and optional set that can be sup­plied, but the class doesn't require them (those are exposed as properties).

Fol­low­ing the rule we might build our class like that:

public class UserService: IUserService
{
   // some other members

   public UserService(ISession session, IBus bus)
   {
      //the obvious
   }

   public ILogger Logger {get; set;}
}

This assumes that ses­sion and bus are required and log­ger is not (usu­ally it would be ini­tialised to some sort of NullLogger).

In prac­tice I noticed a few things that make use­ful­ness of this rule questionable:

  • It ignores con­struc­tor over­loads. If I have another con­struc­tor that takes just ses­sion does it mean bus is an optional or manda­tory depen­dency? Even with­out over­load­ing, in C# 4 or later, I can default my con­struc­tor para­me­ters to null. Does it make them required or mandatory?
  • It ignores the fact that in real­ity I very rarely, if ever, have really optional depen­den­cies. Notice the first code sam­ple assumes all of its depen­den­cies, includ­ing log­ger, are not null. If it was truly optional, I should prob­a­bly pro­tect myself from Null­Ref­er­ence­Ex­cep­tions, and in the process com­pletely destroy read­abil­ity of the method, allow­ing it to grow in size for no real benefit.
  • It ignores the fact that I will almost never con­struct instances of those classes myself, del­e­gat­ing this task to my IoC con­tainer. Most mature IoC con­tain­ers are able to han­dle con­struc­tor over­loads and defaulted con­struc­tor para­me­ters, as well as mak­ing prop­er­ties required, ren­der­ing the argu­ment about required ver­sus optional moot.

Another, more prac­ti­cal rule, is this:

Use con­struc­tor for not-changing depen­den­cies and prop­er­ties for ones that can change dur­ing object's lifetime.

In other words, ses­sion and bus would end up being pri­vate read­only fields — the C# com­piler would enforce that once we set them (option­ally val­i­dat­ing them first) the fields in the con­struc­tor, we are guar­an­teed to be deal­ing with the same (cor­rect, not null) objects ever after. On the other hand, Log­ger is up in the air, since tech­ni­cally at any point in time some­one can swap it for a dif­fer­ent instance, or set it to null. There­fore, what usu­ally log­i­cally fol­lows from there, is that prop­erty depen­den­cies should be avoided and every­thing should go through the constructor.

I used to be the fol­lower of this rule until quite recently, but then it does have its flaws as well.

  • It leads to some nasty code in sub­classes where the base class has depen­den­cies. One exam­ple I saw recently was a WPF view model base class with depen­dency on dis­patcher. Because of that every sin­gle (and there were many) view model inher­it­ing from it, needed to have a con­struc­tor declared that takes dis­patcher and passes it up to the base con­struc­tor. Now imag­ine what hap­pens when you find you need event aggre­ga­tor in every view model. You will need to alter every sin­gle view model class you have to add that, and that's a refac­tor­ing ReSharper will not aid you with.
  • It trusts the com­piler more than devel­op­ers. Just because a set­ter is pub­lic, doesn't mean the devel­op­ers will write code set­ting it to some ran­dom val­ues all over the place. It is all a mat­ter of con­ven­tions used in your par­tic­u­lar team. On the team I'm cur­rently work­ing with the rule that every­body knows and fol­lows is we do not use prop­er­ties, even set­table ones, to reas­sign depen­den­cies, we're using meth­ods for that. There­fore, based on the assump­tion that devel­op­ers can be trusted, when read­ing the code and see­ing a prop­erty I know it won't be used to change state, so read­abil­ity and imme­di­ate under­stand­ing of the code does not suffer.

In real­ity, I don't actu­ally think the cur­rent one, or few of my last projects had even a require­ment to swap ser­vice depen­den­cies. Gen­er­ally you will direct your depen­dency graphs from more to less volatile objects (that is object will depend on objects with equal or longer lifes­pan). In few cases where that's not the case the depen­den­cies would be pulled from a fac­tory, and used only within the scope of a sin­gle method, there­fore not being avail­able to the out­side world. The only sce­nario where a long-lived depen­dency would be swapped that I can think of, is some sort of failover or circuit-breaker, but then again, that would be likely dealt with inter­nally, inside the component.

So, look­ing back at the code I tend to write, all depen­den­cies tend to be manda­tory, and all of them tend to not change after the object has been created.

What then?

This robs the afore­men­tioned approaches from their adver­tised ben­e­fits. As such I tend to draw the divi­sion along dif­fer­ent lines. It does work for me quite well so far, and in my mind, offers a few ben­e­fits. The rule I fol­low these days can be explained as follows:

Use con­struc­tor for application-level depen­den­cies and prop­er­ties for infra­struc­ture or inte­gra­tion dependencies.

In other words, the depen­den­cies that are part of the essence of what the type is doing go into the con­struc­tor, and depen­den­cies that are part of the "back­ground" go via properties.

Using our exam­ple from before, with this approach the ses­sion would come via con­struc­tor. It is part of the essence of what the class is doing, being used to obtain the very user whose address infor­ma­tion we want to update. Log­ging and pub­lish­ing the infor­ma­tion onto the bus are some­what less essen­tial to the task, being more of an infra­struc­ture con­cerns, there­fore bus and log­ger would be exposed as properties.

  • This approach clearly puts dis­tinc­tion between what's essen­tial, busi­ness logic, and what is book­keep­ing. Prop­er­ties and fields have dif­fer­ent nam­ing con­ven­tions, and (espe­cially with ReSharper's 'Color iden­ti­fiers' option) with my code colour­ing scheme have sig­nif­i­cantly dif­fer­ent colours. This makes is much eas­ier to find what really is impor­tant in code.
  • Given the infra­struc­ture level depen­den­cies tend to be pushed up to base classes (like in the View­Model exam­ple with Dis­patcher and Even­tAg­gre­ga­tor) the inher­i­tors end up being leaner and more readable.

In clos­ing

So there you have it. It may be less pure, but trades purity for read­abil­ity and reduces amount of boil­er­plate code, and that's a trade­off I am happy to make.

Modularity is a feature

Stop me if you know this one. You find a library/framework that does some­thing use­ful to you. You start using it and then realise it doesn’t work the way you want it in cer­tain sce­nario or has a miss­ing feature.

What do you do then?

  • Aban­don the library and look for alter­na­tive that is more “fea­ture rich”?
  • Ask the author to sup­port your scenario/submit a pull request with the feature?

Those two, from my expe­ri­ence, are by far the most com­mon approaches peo­ple take when faced with this situation.

There is another way

Sur­pris­ingly not many peo­ple take the third, most ben­e­fi­cial way, that is swap­ping part of the library for cus­tom one, that is tai­lored for your needs.

Now, to be hon­est this has a pre­req­ui­site, that is, the library you’re using must be designed in a mod­u­lar fash­ion, so that there are swap­pable parts. Most pop­u­lar open source libraries how­ever do a fairly good job at this. What this allows you to do, is to make spe­cific assump­tions and opti­mi­sa­tions for your spe­cific needs, ones that author of a generic library can never make, there­fore hav­ing much more robust and tar­geted solu­tion for your prob­lems. Also being able to sim­ply extend and/or swap parts of the library/framework means you don’t have to wait for a new ver­sion or waste time look­ing for and learn­ing a dif­fer­ent one (only to dis­cover at some later point that it also doesn’t sup­port some sce­nario you’ve got.

I did just that today with RavenDB (or more specif­i­cally Json.NET library it uses inter­nally). The appli­ca­tion I’m work­ing on needs to store object graphs from a third party ven­dor. Objects that weren’t designed with NoSQL stor­age in mind (or any stor­age in mind) and this was caus­ing Json.NET some trou­bles. Not to bore you with the details, I was able to resolve the prob­lem by swap­ping Default­Con­trac­tRe­solver with my own imple­men­ta­tion that catered for quirks of the model we’re using, and in less than 20 lines of code I achieved some­thing remark­able – I was able to store in RavenDB, with no issues, objects that were never meant to be stored in such a way. And all of that with­out authors of RavenDB or Json.NET hav­ing to do anything.

Con­sider the alternatives

This brings us to the main point of this post – mod­u­lar­ity is a fea­ture. It is one of most impor­tant fea­tures of any reusable piece of code. Con­sider the alter­na­tives. If you don’t allow for swap­ping parts of your code from generic one-size-fits-most solu­tion to sce­nario spe­cific vari­ants you’re paint­ing your­self into a cor­ner, in one of two ways.

You are writ­ing a very rigid piece of soft­ware, that unless used exactly in the way you antic­i­pated, will be unfit for the task.

Alter­na­tively as you dis­cover new sce­nar­ios you can try to stretch your default imple­men­ta­tion to sup­port them all, adding more and more con­fig­u­ra­tion flags to the API. In the end you will find that for every new sce­nario you add sup­port for, two new get reported that you don’t sup­port, all while met­rics of your code com­plex­ity go through the roof and main­tain­abil­ity plummets.

giant-swiss-army-knife-thumb-400x316

 

So be smart. Whether you’re cre­at­ing a library or using one, remem­ber about modularity.

lego2

IoC concepts: Dependency

As part of prepar­ing for release of Wind­sor 3.1 I decided to revisit parts of Windsor’s doc­u­men­ta­tion and try to make it more approach­able to some com­pletely new to IoC. This and few pre­vi­ous posts are excerpts from that new doc­u­men­ta­tion. As such I would appre­ci­ate any feed­back, espe­cially around how clearly the con­cepts in ques­tion are explained for some­one who had no prior expo­sure to them.

Depen­dency

We're almost there. To get the full pic­ture we need to talk about depen­den­cies first.

A com­po­nent work­ing to ful­fil its ser­vice is not liv­ing in a vac­uum. Just lie a cof­fee shop depends on ser­vices pro­vided by util­ity com­pa­nies (elec­tric­ity), its sup­pli­ers (to get the beans, milk etc) most com­po­nents will end up del­e­gat­ing non-essential aspects of what they're doing to others.

Now let me repeat one thing just to make sure it's obvi­ous. Com­po­nents depend on ser­vices of other com­po­nents. This allows for nicely decou­pled code where your cof­fee shop is not bur­dened with details of how the milk deliv­ery guy operates.

In addi­tion to depend­ing on other component's ser­vices your com­po­nents will also some­times use things that are not com­po­nents them­selves. Things like con­nec­tion­Strings, names of servers, val­ues of time­outs and other con­fig­u­ra­tion para­me­ters are not ser­vices (as we dis­cussed pre­vi­ously) yet are valid (and com­mon) depen­den­cies of a component.

In C# terms your com­po­nent will declare what depen­den­cies it requires usu­ally via con­struc­tor argu­ments or set­table prop­er­ties. In some more advanced sce­nar­ios depen­den­cies of a com­po­nent may have noth­ing to do with the class you used as imple­men­ta­tion (remem­ber, the con­cept of a com­po­nent is not the same as a class that might be used as its imple­men­ta­tion), for exam­ple when you're apply­ing inter­cep­tors. This is advanced stuff how­ever so you don't have to con­cern your­self with it if you're just start­ing out.

Putting it all together

So now lets put it all together. To effec­tively use a con­tainer we're deal­ing with small com­po­nents, expos­ing small, well defined, abstract ser­vices, depend­ing on ser­vices pro­vided by other com­po­nents, and on some con­fig­u­ra­tion val­ues to ful­fil con­tracts of their services.

You will end up hav­ing many small, decou­pled com­po­nents, which will allow you to rapidly change and evolve your appli­ca­tion lim­it­ing the scope of changes, but the down­side of that is you'll end up hav­ing plenty small classes with mul­ti­ple depen­den­cies that some­one will have to manage.

That is the job of a container.

IoC concepts: Component

As part of prepar­ing for release of Wind­sor 3.1 I decided to revisit parts of Windsor’s doc­u­men­ta­tion and try to make it more approach­able to some com­pletely new to IoC. This and few fol­low­ing posts are excerpts from that new doc­u­men­ta­tion. As such I would appre­ci­ate any feed­back, espe­cially around how clearly the con­cepts in ques­tion are explained for some­one who had no prior expo­sure to them.

Com­po­nent

Com­po­nent is related to ser­vice. Ser­vice is an abstract term and we're deal­ing with con­crete, real world. A cof­fee shop as a con­cept won't make your cof­fee. For that you need an actual cof­fee shop that puts that con­cept in action. In C# terms this usu­ally means a class imple­ment­ing the ser­vice will be involved.

public class Starbucks: ICoffeeShop
{
   public Coffee GetCoffee(CoffeeRequest request)
   {
      // some implementation
   }
}

So far so good. Now the impor­tant thing to remem­ber is that, just as there can be more than one cof­fee shop in town, there can be mul­ti­ple com­po­nents, imple­mented by mul­ti­ple classes in your appli­ca­tion (a Star­bucks, and a CofeeClub for example).

It doesn't end there! If there can be more than one Star­bucks in town, there can also be more than one com­po­nent backed by the same class. If you've used NHiber­nate, in an appli­ca­tion access­ing mul­ti­ple data­bases, you prob­a­bly had two ses­sion fac­to­ries, one for each data­base. They are both imple­mented by the same class, they both expose the same ser­vice, yet they are two sep­a­rate com­po­nents (hav­ing dif­fer­ent con­nec­tion strings, they map dif­fer­ent classes, or poten­tially one is talk­ing to Ora­cle while the other to SQL Server).

It doesn't end there (still)! Who said that your local French cof­fee shop can only sell cof­fee? How about a pas­try or fresh baguette to go with the cof­fee? Just like in real life a cof­fee shop can serve other pur­poses a sin­gle com­po­nent can expose mul­ti­ple services.

One more thing before we move for­ward. While not implic­itly stated so far it's prob­a­bly obvi­ous to you by now that a com­po­nent pro­vides a ser­vice (or a few). As such all the classes in your appli­ca­tion that do not really pro­vide any ser­vices will not end up as com­po­nents in your con­tainer. Domain model classes, DTOs are just a few exam­ples of things you will not put in a container.