Saturday, May 7, 2011

SharpSvn

Rather than using svn.exe through Process.Start SharpSvn library offers a complete API mapping of the command line tool.

It can be downloaded from the website or fetched via NuGet with: Install-Package SharpSvn.x86 or Install-Package SharpSvn.x64

The API may seem a bit weird at first but that’s because it wraps a C++ library under the hood.

As of April 2011 there is no official documentation of the API, so the best source is still trying to make svn.exe do what you want and then translate that in C#.

So far, the other source of information I currently use is the discussion forums

One other thing don't really like is the footprint of this library, 64Mo for the NuGet package and 21Mo in bin. Its huge!! I hope that future version will be a bit more slim than now.

Overall it's still a lot better than using svn.exe directly.

Thursday, April 7, 2011

Single Responsibility Principle

    Working in god classes with monster methods is no fun.  It usually involves guessing where I should put the new code exactly.  Then it takes a lot of debugging to find out why the change doesn’t work as expected.  After that, it takes more time to make sure we did not break anything else around that change.  This is definitely not fun at all and it shouldn’t be the way we work.  We have control of the code and we should not tolerate a situation like that.  We can fix this!

    The Single Responsibility Principle or SRP state that

    A class should have only one reason to change, only one responsibility.

    This means that when I want to add a new feature I don’t want to care about things I’m not changing.  For example, below in the class diagram we have the ReportingService class responsible to load and process data, then populate and show a report.  This class will be modified every time I need to change my database schema, the report engine behaviour and the layout of the report itself. This mean that it's violating the Single Responsibility Principle, it's doing too much.

    clip_image001

    If we split the class into separated concerns, we will end up with classes that will need to change for only one reason. It's still not perfect but that's a start.

    clip_image002

    So, why is this so important again? 

    Well, first of all reuse.  In the diagram above we see that the DAL concern (Data Access Layer) is now encapsulated into a Repository class.  This means that we can reuse the Repository code to load the same data but not only for creating reports.

    Second, by creating new classes we are forced to think of a name for them.  Good naming of classes and methods will help improve comprehension by people who are not familiar with this part of the code base.  Another side effect is that we expose hidden concepts from inside our original class like the DAL (now the Repository class).

    Third, we are now free to evolve each concern more independently from one another than before.  Also, it will be easier to write unit tests for such smaller and simple classes.  We reduced the overall complexity of the code and we will be more confident that we are not breaking the application everything we make some changes.

    So, should we always break all the large classes into smaller ones until we have only a few methods in each of them?

    Not exactly, we need to be careful not to break the OOP basic notion of encapsulation.  So where should we draw the line, where should we split our classes?  Unfortunately, there is no easy answer, rather we need to understand what the class responsibilities are.

    Responsibility Driven Design

    One technique we could use comes from the 80s as an OO design practices called RDD for Responsibility Driven Design.  The goal was to identify the Object Role Stereotype of classes to better understand their responsibilities.  Let's take a look at those six roles.

    Information Holder: Knows things and provides information. May make calculations from the data that it holds.

    Structurer: Knows the relationships between other objects.

    Controller: Controls and directs the actions of other objects.  Decides what other objects should do.

    Coordinator: Reacts to events and relays the events to other objects.

    Service Provider: Does a service for other objects upon request.

    Interfacer: Objects that provide a means to communicate with other parts of the system, external systems or infrastructure, or end users.

    The second part of this technique is to use CRC Cards which are index card put on a board while designing the systems.

    Class name  
    Responsibilities Collaborators
    - responsibility 1
    - responsibility 1
    - collaborator 1
    - collaborator 2

    CRC stands for Class - Responsibilities - Collaborator.  You put all the responsibilities on the left side and all the collaborators (the classes you talk to) on the right side.  When putting all the cards of a system or sub-system next to each other on a wall you get a really great big picture of what’s going on.

    Back to SRP, our ultimate goal is to take the secondary responsibilities on the left side and transform them into new collaborators on the right.  In the end we should have only one responsibility (the principal one) on the left hand side. So, now in the previous example BetterReportingService is only a Controller for its collaborators. Repository is an Interfacer and ReportEngine is a Service Provider. ReportBuilder acts as an Information Holder and a Structurer so we may consider separating the concerns one more time.

    Dealing with a large code base

    It’s not always easy to look at an aging code base and spot SRP violations. Sometimes we may think a class only have one responsibility when reading the code. The separation opportunities will rarely jump at us.

    Fortunately there is one technique that could help us with that. I'm talking about code metrics. Tools like NDepend and to some extent Visual Studio can use reflection technology to look at the code and calculate metrics to help us see the big picture but with a different set of eyes. It can help us find things we could hardly see ourselves.

    The LCOM (Lack of Cohesion of Methods) is a metric which indicate whether all the methods and fields of a class are strongly connected together.  For that, there should be a connection between all members of the class including fields.

    The diagram below shows that the group composed of methods A and B and field x are connected together but they have no connection to the rest of the methods and field.  The LCOM4 metric gives us a value of 2 for this class because 2 distinct groups exist.

    clip_image003

    Now, a class with a LCOM4 value one 1 will look more like this

    clip_image004

    So, does this mean that the class in diagram 1 have 2 responsibilities and the one in diagram 2 only 1?  Not necessarily.  Some types of classes like pure domain objects may have only properties exposing the attributes of the class without been connected.  We need other indicators to asses that classes may possess multiple responsibilities. 

    The Cyclomatic Complexity metric gives us the number of execution paths in a method.  Code constructs like if, for, foreach, switch and while all generate at least one extra path of execution and contribute to code complexity.  A class with high cyclomatic complexity value means that it is actually doing something more than exposing attributes.

    So, we should look for classes with a high value of Lack of Cohesion of Methods and high Cyclomatic Complexity.  Usually if you know your code base a little bit you should not be really surprised by the top result of that list.  They are the ones you need to change for every new feature, the ones where bugs are found periodically and the ones who does not have unit tests around them.

    I hope now that you understand what the advantages of more little classes are over a few big ones. That in the long run, it is worth our time to think about the OO design of the system to reduce complexity, responsibility coupling and improve the testability of our code.

Sunday, February 20, 2011

SOLID principles at .Net Montreal Community

In a few weeks on Saturday March 12th I’ll be giving a talk on the SOLID principles of Object Oriented Programming.  While collecting information on the subject and preparing my talk I’m figuring out that I’ll be producing quite a lot of materials.  That’s a good thing because I’ll be able to blog about the principles using the same materials for my talk’s slides.  I do know that a lot of people already wrote about this subject but that’s going to be good exercise for me and my writing skills!

del.icio.us Tags: ,,

Monday, December 6, 2010

Balsamiq Mockups

This is something that has been around for a while now.  I first tried it years ago but I had not any real usage for it back then.  Last week, I needed something to capture a UI change I was planning to do in my project.  My first though was just draw on a piece of paper, but I have to e-mail this to someone off site.

What should I do? Scan my drawing, Paint or SketchFlow? No, Balsamiq Mockups!

On the web site there is an introduction video and a web demo you can use to get a feeling of the tool.  The best part is that I was able to create a simple UI including the changes I was planning do to in less than 5 minutes and downloaded the PNG directly from my web browser!

It works really well to create low-fi prototype of fat clients, web apps and even iPhone UI.  Additional controls can be downloaded provided by the community.  Finally Balsamiq Mockups can be embedded in other tools like Confluence, JIRA, FogBugz and XWiki.

If I ever need to do a lot of UI prototyping I think a 79$ for the full version will be really well spend.

Thursday, November 25, 2010

Pex4Fun

Check out this really cool web site. Not only you can write code in your browser you also have IntelliSense. The way it works is you are given a puzzle or a duel to solve (think code breaker C# edition). The goal of the game is to write the same algorithm than the hidden solution. You get hints by running Pex against both the hidden puzzle and your solution.

Pex is a tool that will try to call a function with any kind of input parameters required to use all the code path of the function. It will highlight thing like passing null might cause a NullReferenceException down the line and you should guard against it. So by trying all those combinations against your code and the hidden puzzle will give hints on the difference of implementation. You can then update your code and try again each time getting closer and closer to the solution.

You can even create an account and keep track of all the challenges you solved. A section of the site is structured as a course where you learn about C# and cool features like Code Contracts.

Code Contracts helps us create a more declarative way of expressing pre and post conditions to our code. And because of the declarative way they works, tools can then to provides us with static compile time validation, run time guard code and automated API documentation of the contracts.

Pex4Fun is really a great way to play around those 2 great tools without having to setup libraries on our machine. I can even show some basic C# stuff to my friends, on the web and even from my smart phone (but then it’s not that fun I must admit!)

Tuesday, November 9, 2010

Introduction to LinqPad

It’s really sad that in the late 2010 most people still don’t know about this incredible little tool.  For me it is a bit like what Reflector used to be in the early days of .Net, a great and FREE productivity tool outside of the Visual Studio IDE and Microsoft tooling.


LinqPad was created by Joseph Albahari as a companion tool for his book C# 3.0 in a Nutshell.  You don’t have to buy the book to use the tool (actually I haven’t bought the book either! me bad).
It’s really difficult to do justice to LinqPad in a small blog and I don’t want to write a too long post so I’ll try to expose the most useful features to you today and eventually blog about specific ones in detail in the future.

Code Snippet execution

This is the reason I use LinqPad almost every day.  If I want to test a snippet of code I don’t create a dummy VS project, I simply try it in LinqPad.  You can even write a full program if you want and save it as a code snippet.  I use this to create most of my utility tools like when I need to read and display an xml file or generate one I just use LinqToXml.


LinqPad1

Learning Tool for Linq and other .Net features

Went I first found out about LinqPad it was when .Net 3.5 came out and understanding Linq queries was still hard for me.  The tool has a lot of good Linq code sample built in so I could learn and play with the queries.  What makes this interesting is the Dump extension method of the Object type which is really powerful to display the state of any simple or complex data structure.

LinqPad2

Integrated LinqToSql

Another useful thing to do is connecting to a database and have LinqPad setup a LinqToSql wrapper over the schema so you can query it with code rather than SQL.  I cannot say I’ve used this feature a lot but sometime it can be nice if you want to do some processing of data coming from a database.  A Linq to Entity and OData options are also available.  In the future I guess I’ll be using LinqPad to query source like NetFlix and the other OData feeds too.

LinqPad3

External Library

This is something new for me (and I guess to a lot of people given I haven’t seen much info about it on the net), you can load any dlls in LinqPad to use in your queries.  This is an excellent way to create libraries of useful functions and extension methods.  I’ll be using this feature to query assemblies using Mono.Cecil with some extra functions of my own.  I’ll share with you the result of my experiments in a future series of posts.


Go download LinqPad!  You should definitely give this great tool a try.

Saturday, October 30, 2010

Fun with Mono.Cecil

I’ve always loved playing around with tools like Reflector and NDepend to take a look at the internals of my code base but with an external perspective than inside Visual Studio. 

Reflector was really useful to me to walk dependencies and hierarchies before I started using Resharper.  NDepend is an amazing piece of software that gives me a lot of metrics and other information.  Unfortunately maybe a bit too much, it’s hard to make head and tail a first glance.  I’ve never had the chance to play with the full version and the trial is very well done in the way you can use most of the software but it’s nagging you just one step before you could nail something really useful.

Now in Visual Studio 2010 we have the Dependency Graph which is really neat but difficult to use because of missing key features like a way to control or filter the noise of been force to graph the whole solution.  You always need to start pruning the graph from scratch and zooming on a single namespace and dependency is hard.  Never the less, with a bit of patience I can find a lot of information like dependency circles.  But again, when I find one I’m stuck with only visual information, no way to just extract a list of namespaces, types or methods to help me tackle the culprits.

So, that is where I am now.  I’d like to have something as powerful as Reflector to walk the links, complete as NDepend and Dependency Graph to get all the information I need to learn about, break bad dependencies but also prevent new ones from appearing in my code base.  Wouldn’t be nice to be able to query the code base for metrics, dependencies and general patterns in my code? Tests to help me keep my code clean?

Of course I know that NDepend got this CQL feature.  It’s really amazing but with the trial version of the software I can’t go far.  And to be honest the editor is a bit clumsy and the language a bit limiting.  No, what I need is a better experience, something really interactive to play with my queries until I get them right, something like the experience I get with LinqPad.  Then I can put the result of my efforts into a unit test to be sure I’ll won’t repeat the same mistakes again.

.Net reflection API is all good in theory but to use that I’ll need to be really cleaver because reflection works only by loading a dll in memory before querying it.  And due to the way the CLR works, a dll can’t be unloaded from the AppDomain meaning that you need to close the app every times you want reload a new version.  Too bad for that.  There are ways to go around that limitation but I want to keep it my solution simple.  So an alternative to reflection is Mono.Cecil.  I’ve been hearing a lot of good about this library in the past and I know that a lot of good software use it (like NDepend!) but I never took a look at it myself.

I think it’s time for me to give it a try.  I’ll blog about my experience with it trying to create a thin API on top of it to add metrics and a way to list all the bad dependencies in my code base.