Modularity is a feature

Stop me if you know this one. You find a library/framework that does something useful to you. You start using it and then realise it doesn’t work the way you want it in certain scenario or has a missing feature.

What do you do then?

  • Abandon the library and look for alternative that is more “feature rich”?
  • Ask the author to support your scenario/submit a pull request with the feature?

Those two, from my experience, are by far the most common approaches people take when faced with this situation.

There is another way

Surprisingly not many people take the third, most beneficial way, that is swapping part of the library for custom one, that is tailored for your needs.

Now, to be honest this has a prerequisite, that is, the library you’re using must be designed in a modular fashion, so that there are swappable parts. Most popular open source libraries however do a fairly good job at this. What this allows you to do, is to make specific assumptions and optimisations for your specific needs, ones that author of a generic library can never make, therefore having much more robust and targeted solution for your problems. Also being able to simply extend and/or swap parts of the library/framework means you don’t have to wait for a new version or waste time looking for and learning a different one (only to discover at some later point that it also doesn’t support some scenario you’ve got.

I did just that today with RavenDB (or more specifically Json.NET library it uses internally). The application I’m working on needs to store object graphs from a third party vendor. Objects that weren’t designed with NoSQL storage in mind (or any storage in mind) and this was causing Json.NET some troubles. Not to bore you with the details, I was able to resolve the problem by swapping DefaultContractResolver with my own implementation that catered for quirks of the model we’re using, and in less than 20 lines of code I achieved something remarkable – 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 without authors of RavenDB or Json.NET having to do anything.

Consider the alternatives

This brings us to the main point of this post – modularity is a feature. It is one of most important features of any reusable piece of code. Consider the alternatives. If you don’t allow for swapping parts of your code from generic one-size-fits-most solution to scenario specific variants you’re painting yourself into a corner, in one of two ways.

You are writing a very rigid piece of software, that unless used exactly in the way you anticipated, will be unfit for the task.

Alternatively as you discover new scenarios you can try to stretch your default implementation to support them all, adding more and more configuration flags to the API. In the end you will find that for every new scenario you add support for, two new get reported that you don’t support, all while metrics of your code complexity go through the roof and maintainability plummets.

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

 

So be smart. Whether you’re creating a library or using one, remember about modularity.

lego2

The other blog

I started another blog. The topic range is much different from the usual topics discussed here, so instead of polluting this blog and alienating my audience I decided to start a dedicated blog/posterous about it.

This blog will stay as my programming/design/software development blog and is still going to be maintained. The other one is going to be about things I find on the web. Useful apps, interesting and innovative startups (mostly non-US based, that tend to get less publicity in the mainstream media like Techcrunch, Engadget, or Mashable), and all things related to that. Those who follow me on twitter know I tweet that stuff pretty often. Now I wanted to take it to the next level, not be constrained by 140 characters limit and make it less volatile.

If you feel that’s something that might interest you hop on and subscribe.

address: http://foundontheweb.posterous.com/

To IntelliSense or not to IntelliSense, is that even a question?

UPDATE (tl;dr version):

As it appears people seem not to read the post before commenting. I’m not questioning Intellisense’s value. I’m questioning why .NET developers get panic attack when someone mentions “let’s use X” where there’s no IntelliSense support for X.

As ASP.NET MVC team lately pushes towards third release of their framework including new out of the box view engine, more and more I hear people complaining about the current preview release of it, for one simple reason – it does not have IntelliSense (yet).

This reminds me of similar approach people had for some other view engines like nhaml, NVelocity, BRail both in ASP.NET MVC and Monorail. This can be also extended to not using Boo which is an awesome .NET language that should get everyone excited, but it’s not – because there’s not good tooling story around it Visual Studio (yes, I know about the efforts to bring that to some degree).

So what’s the problem?

I ask you. Ruby community, which seems to be the fastest growing development community at the moment uses what most .NET or Java developers would call “primitive tools”, with hardly even syntax coloring, yet what they seem to be emphasizing the most when they compare Ruby to other platforms is productivity gains.

So is refusal to use something unless it provides IntelliSense just an inner fear in .NET developers? I would envision it to experience children have when they learnt how to ride a bike with additional wheels on each side, and now the additional wheels were taken away.

Isn’t this behavior as irrational?

 

[#Beginning of Shooting Data Section]
Nikon D2Xs
2009/07/03 11:30:57.3
Tiff-RGB (8-bit)
Image Size: Large (4288 x 2848)
Color
Lens: 24-70 mm F/2.8 G
Focal Length: 58 mm
Exposure Mode: Manual
Metering Mode: Multi-Pattern
1/180 s - F/11
Exposure Comp.: 0 EV
Sensitivity: ISO 100
Optimize Image:
White Balance: Color Temp. (4800K)
Focus Mode: AF-S
VR Control: OFF
Long Exposure NR: OFF
High ISO NR: Off
Color Mode: Mode II (Adobe RGB)
Tone Comp.: Normal
Hue Adjustment: 0¡
Saturation: Normal
Sharpening: Medium high
Flash Mode:  
Flash Exposure Comp.:  
Flash Sync Mode:  
Image Authentication: OFF
Image Comment: (C)2008 HALL IMAGE PHOTOGRAPHY      
[#End of Shooting Data Section]

My Visual Studio (with ReSharper) color settings

That’s a post I’ve been meaning to write for quite a long time, yet I never got around to really doing it. Now, here it is – my Visual Studio color theme and it looks like this:

vs_scheme

The theme works with Visual Studio 2010 and requires Resharper 5.1 or newer with “Color Identifiers” option turned on.

Some things to notice.

Instance classes, static classes and interfaces have all very similar but slightly different shade of yellow/green.

Extension methods are slightly lighter than regular methods.

Mutable locals, immutable locals and constants have also similar but slightly different color.

The background is dark, but not completely black.

 

Hope you enjoy it. If you do – you can grab it here.

Build your conventions

Continuing the theme of conventions in code; I talked about validating the conventions, but I didn’t touch upon one more basic issue. What to base the conventions on? Short answer is – anything you like (as long as it’s black). Long answer is, well – longer.

Strong typed nature of .NET gives us rich set of information we could use to build conventions on. Let’s go over some of them. I will concentrate mostly on single scenario as an example – IoC container registration, but the discussion can be easily extrapolated to cover any other scenario.

Location

Assemblies are the main, most coarse grained building blocks of application. While they carry quite a bit of information we could use (name, version, strong name, culture) it rarely makes sense to use all of that information. Most common usage is directly pointing to our assembly of interest, either by name

GetAssemblyNamed("Acme.Crm.Services");

or in a more strongly typed manner for example via type container in that assembly in cases where we don’t mind having strong reference to that assembly in your composition root.

GetAssemblyContaining<Acme.Crm.EmailSenderService>();

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

Directly pointing at certain assembly is generally what we want, and this is the most straightforward and safe way to do that. In some cases (for example extensibility scenarios) you may want to leave the door open for consuming more than one assembly, often unknown at the time of compilation. In this case it may make sense to use as much information as possible to filter out unwanted assemblies as early as possible. This obviously depends on the specifics of the scenario at hand, for example who will be authoring the extensions? If only you (meaning your team/company), you can use information in assembly name and additionally verify the key that the assembly is signed with appropriate key.

GetAssembliesWithNameStartingWith("Acme.Crm.Extensions.")

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

In case where third party vendors will provide extensions, you may just require that the assembly conforms to certain naming pattern (name contains “.Crm.Extensions.”). This not only gives you quick way of filtering out assemblies you’re not interested in – it also helps you keep your project cleaner. With convention like this just a quick glance at directory with your project’s assemblies will be enough information to tell how many extension assemblies there are.

This obviously is rarely enough – finding right assemblies is often just the first step and there’s a wealth of information elsewhere you can use. Modules are seldom useful as most of the time you have just one per assembly, so I’m mentioning them only for completeness. Within (and between) assemblies namespaces are often used to partition types. They have two important characteristics that can be useful when defining conventions – their name, and hierarchy.

You rarely use namespaces on their own. Most often they are one of a few boundaries you set to narrow down the set of types you’re interested in. For example you may find your repositories like this:

GetAssemblyContaining<CustomerRepository>()

   .GetTypesInNamespaceOf<CustomerRepository>()

   .SomeOtherConstraints()....

Broadly speaking you can find namespaces using similar techniques as with assemblies – strongly typed, as demonstrated in this paragraph or via string.

GetTypesInNamespace("Acme.Crm.Repositories");

While the former is more type safe and refactoring friendly, the latter is more explicit and reads better – you get the information you want directly, without having to go through additional layer of indirection.

It is often valuable to take advantage of namespace hierarchy to use additional layer in the hierarchy to carry additional information. One such case could be to divide services in “Acme.Crm.Services” namespace to sub-namespaces based on their lifestyle, such that singleton CacheProviderService will live in “Acme.Crm.Services.Global” namespace, and per web request UnitOfWorkService would live in “Acme.Crm.Services.PerRequest”.

Type

Types themselves carry a lot of information we can use for conventions: they have meaningful names (hopefully), inherit other types, implement interfaces, have custom attributes, generic constraints etc. There are two popular usages for type names when dealing with conventions.

We often put meaningful suffixes, or more broadly speaking – name our types in a certain, meaningful way. For example type implementing IRepository<Customer> would be named CustomerRepository. Or we may require all our services to have “Service” suffix. While the former helps us keep thins clean and consistent the latter (by some regarded as certain form of dreaded Hungarian notation), often serves as safety net layer for validation purposes, to help you catch cases where you by mistake put a type in inappropriate namespace.

The other common usage is using certain prefixes to build decorator chains. You may have the following types: LoggingCustomerRepository, CachingCustomerRepository, CustomerRepository, LoggingProductRepository, CachingProductRepository, ProductRepository etc. When putting consistent, well known prefixes on your types you can use that information to build decorator chains, so that Logging*foo* will decorate Caching*foo* which will decorate actual *foo* type.

In IoC registration case base types (or interfaces) are very commonly used. Most popular case if layer supertype.

RegisterTypesInheriting<IController>();

registers all controllers in our application.

RegisterClosedVersionsOf(typeof(IRepository<>));

registers all generic repositories we might have. It sometimes may also be worthwile to take greater advantage of generics.

Having interfaces:

public interface IHandler<TCommand> where TCommand: ICommand

{

   // ...something

}

 

public interface ICommand

{

   // ...something

}

we might quite easily tie the two together – handlers to their respective commands.

Attributes, marker interfaces

In early days of IoC containers it was common to see custom Attributes being used for configuring components. In Java (which gained attribute-like abilities much later after .NET) containers tend to prefer this approach even now. While this approach is generally discouraged, using domain specific attributes, or marking interfaces for your components may sometimes be beneficial.

You may for example use attributes to mark components you want to decorate, (put [CachedAttribute] on repositories you want to put cache around). Marking interfaces can be useful for this as well – attributes are preferred solution where you want to associate some additional data with the component (for example cache duration).

Similar information as outlined in case of types, can be used to build conventions around type members. While it usually makes little sense in context of IoC to do so, it’s very useful in other cases – like Rob’s MVVM framework and wiring Can*Foo* with *Foo* property/method pairs.

Wrapping up

Anything can be used as basis for convention. You only have to know what makes sense in given context and looks for opportunities to improve that. There are a few things to keep in mind when deciding upon conventions. Keep them tight – use more than one constraint in order to minimize false positives. For example use namespace, base type and name suffix to find repositories in your application. You will pay small additional price of more reflection you do when starting, but it will save you lots of time trying to figure out why your application is misbehaving later. Make your conventions well known to the entire team. Put short description on a board in your team room, in wiki engine you’re using, on in conventions.txt file in your solution. In addition to that make that rules executable to spot potential mistakes and disconforming code (see my previous post for more detailed discussion on the topic). Don’t be afraid to refine the conventions. Once they are decided upon, they don’t get written in stone. If your application grows and you find them inadequate, adjust them (trying not to loosen them up too much).

How to contribute to open source

Once in a while I talk to someone who sais something like this: “I love open source, especially project X – I would love to contribute back, but I don’t know how”. There are different variations. “I am not a programmer”, “I don’t understand the code – it’s so vast”, “I wouldn’t know how to submit these patch-things they ask for” etc.

To help these people I decided to create a small (seriously – 3 posts, excluding this one) series about contributing to open source projects. I hope this will help more people get involved as they realize how much they can help with little effort.

I intend to do the following:

  • How to contribute to open source without writing a single line of code
  • How to contribute code to open source project without knowing its inner workings
  • How to contribute code to open source – reporting bugs and creating patches

This should cover most of the ground to get people started. The topic itself is certainly much broader, and one could write a whole book about it, but why waste time for that, when there’s some great open source waiting for your contribution!

How to contribute to open source without writing a single line of code

Read the introductory post here first.

So, you found an open source project you really like, it saves you a lot of time, takes some friction away from your life, saves you money and you’re full of admiration and gratitude to the people who spend their free time working on it, so that you can stand on their shoulders. You feel like you really should give back to them, or to the (rest of the) community around the project, but you don’t really want or can do the obvious – start fixing bugs or implementing new features, so you don’t. But is it the only way to contribute to the project? Hardly – you can be of great help to the project without writing a single line of code, and dedicating just a tiny fraction of your time to contributing.

Give feedback

The smallest thing you can do to contribute is give feedback. Developers working on every healthy open source project are constantly looking for users feedback. How would you like a feature to work? How do you like the current feature set? What would be the feature you’d like to see the most in vNext? What behavior in this or that corner case would you find more logical? These the kinds of questions that tend to be asked by the developers to the community, and by speaking your mind on these issues you’re helping the developers make the right decisions.

Some project have set up dedicated websites, using uservoice.com where it’s incredibly simple to give feedback – you just click. For more elaborate questions discussion groups, or project blogs are used to ask open questions to the community. Take a moment of your time to write a few sentences to shed some light on your perspective on the matter. This may not seem like much but giving feedback is the most important thing in ensuring that the project progresses in the right direction.

Help others

For commercial software where there’s a big company behind the product, there are usually people hired to build up the body of knowledge about the product. They write documentation, they write articles in magazines, they blog extensively, speak on conferences write books, answer questions on forums etc. Open source projects have usually just a few volunteers writing code, documentation, blogging, answering questions, all at once and on top of that – they do it in their own free (as in speech) time.

What you can do, is to dedicate some of your own time to take some of the non-coding off of their shoulders. Do subscribe to discussion group of your favorite project, or to your favorite Q&A website where people ask for solutions of their problems with the project. If you see someone asking a question that you know the answer for – do answer. This won’t usually require a lot of time, and someone will be very grateful to you. Also this has another aspect – by stating clearly what you know, or think you know you’re learning better the product itself – you’re building up your expertise and gain recognition and respect in the community. This is especially visible on sites like StackOverflow.com where for giving good answers you’re rewarded with points.

Write documentation

If you find some aspect of using the project hard, and the documentation is not very helpful – improve the documentation. Many projects keep their documentation in the form of a wiki, which means that you’re free to edit and improve it. After all – the documentation is the place where everyone is the most likely to look for solutions in the first place. Help keep it up to date. Help it cover the areas you struggled with. If you blogged your problem – you’ve done most of the hard work already. Add parts of your blog post to the documentation, ensuring that they fit with the rest of the documentation and its rules.

It’s not only the code

Open Source projects are not only the coding and documentation – it’s also all the ‘meta’ stuff. If you can help improving the website of the project. Write the copy. Improve the design of the website. Design logo. This all is important stuff, although often there’s no person to take care of that.

Blog, speak on User Group meetings

If you have a blog – do write about the project. Post solutions event to what after the fact may seem as the most trivial problem. If it took you 15 minutes to figure out, it is worth posting about. You’ll be surprised how many people will find your post helpful.

If you like the project – get others involved. Speak on your local user group meeting about it, show what you like about it, how it helped you, why you like it. By advocating good project you’re getting others involved. You’re expanding the community which means more people learn about it, use it and ultimately more people contribute to the project.

Donate money

Open source projects are free to use, but they certainly are not free to develop and maintain. Contributing with your wallet can be very effective way of helping the project progress, yet many people don’t even consider this. Small amounts to cover hosting costs, costs of hardware bandwidth etc may make make a whole world of difference to the maintainers of the project.

Also developing software often requires software which is not free. You want project X to support version Y of Z? Donating money so that the developers can purchase the license of Z can be a great way of contributing. That is especially true on the Microsoft stack, which consists almost entirely of commercial software.

On the larger scale donating can help someone to start working full time on certain aspects of the project to make what would otherwise be impossible, possible. Probably the most famous example of this is IMeta corporation, which donated one of their top developers to work full time for several months on bringing LINQ support to NHibernate.

In case you’re wondering

I did not abandon my tutorial on Dynamic Proxy. However do not expect to hear a lot from me on this blog during the next two to three weeks, since I don’t have an Internet access at home during that period, and I won’t be able to blog too much. Same goes for emails.

The only form of Internet access I have now is using my neighbor’s Wifi, that I can access only in the kitchen using my 10 inch MSI Wind netbook. Not the most ideal set up for blogging as you’ll surely agree.

So as a sneak peak, here’s a short list of topics I’m going to cover when my PC regains the ability to access the Internet

  • Dynamic Proxy and additional interfaces on proxies
  • Dynamic Proxy and mixins (probably split to two posts)
  • NHibernate and IUserType
  • NHibernate and Null Object Pattern
  • How to set up NHibernate testing with SQLite
  • NHibernate and boxing bug (plus a workaround)
  • Async WCF calls without SvcUtil – something about current progress

Ayende on Castle ActiveRecord

I don’t usually do that, but here’s Ayende‘ presentation from last year’s Oredev conference (yes, it says 2007, but it really is from 2008).

It’s fun, very informative if you don’t know Active Record, and of surprisingly good quality (means you can actually hear what Ayende is saying, and see the code). Most of all, this is an awesome presentation.

How many times have you gone to a presentation when presenter said “Give me a domain model that you want to work on” and then went and implemented it!

It’s a must see. Highly recommended. And if you register to viddler, you can download the video in slightly better quality and resolution here.

Keyboard shortcut of the week

My team at work is far from agile, but I’m trying to smuggle some ideas and practices, according to the old Latin proverb gutta cavat lapidem, non vi, sed saepe cadendo.

Recently, as a small way of continuous improvement I suggested each week we print some Visual Studio or ReSharper keyboards shortcut, that we didn’t know or use, and which can help us do some things a little bit faster.

Here’s the first one:

DSC00117

It’s pinned to a cork whiteboard in a location that everyone looks at it few times a day. Hopefully by the end of the week everyone will have it memorized, as we move to another one.

And you? What small things you do to improve your skills (or your team’s)?

Technorati Tags: