Think Before Coding

To content | To menu | To search

Tuesday, December 17, 2013

Generalized Conway's law

Disclaimer: This article is not just about Conway's lay which I'd call Classical Conway's law, it's already on Wikipedia. You'll find its Generalized form at the en of the post..

BuildStuff 2013 has been really inspiring. Talking with all those people from different CS culture always raise the level of the conversation.

 

Several times came Conway's law into the discussion, as Pieter Hintjens noticed in his blog post yesterday.

 Classical Conway's law

Conway's law is quite simple. It states that:

organizations which design systems ... are constrained to produce designs which are copies of the communication structures of these organizations

 

À partir de l’adresse <http://en.wikipedia.org/wiki/Conway%27s_Law>

 

It's often seen as a joke to mock companies organization, like this famous drawing:

 

 

But it is more than that.

First, it can be a force to drive a change in the system.

 

When two parts are too strongly tied and mangled together, it's a good idea to move teams apart. Communication friction will increase, and eventually, teams will find way to decouple parts so that friction can be reduced.

 

Pieter's example of LSHS vs LSNS is totally an example of this.

 

Second, it is both ways.

A messy system structure reflects a messy team organization.

But we can go far beyond.

 

Generalized Conway's law

System should match the structure of any external concern it interacts with

 

Of course, the Conway's law is included here. There's a match between people building the system and it's structure.

 

But we can here also include design methods like Domain Driven Design which address a different concern the same way:

Align the system structure with the structure of the Domain you're working in/for

 

Using Domain Events and Event Sourcing is a way to make explicit something that is usually implicit in most systems: Time

 

CQRS will reflect the fact that outside the system, getting information and acting on it are two totally different things.

 

Architecture in general is also included: find the match between your system and non functional requirements.

  • Deployment
  • Security
  • Performance
  • Maintainability

At a lower level, it is also known that code clarity reflects the level of the developers understanding.

 

All those external forces will shape the system, and any mismatch in structure will create friction.

And any smell in the system is a sign that something is not understood or working well outside of the system.

 

Generalized Conway's law gives a higher frame of thought to find what's ok and what's wrong in all the dimensions of building systems in interaction with their environment.

Thursday, June 14, 2012

Make it simpler : get rid of Mocking Fx

In the wake of Rinat Technology Demons, I’d add Mocking frameworks to the list.

 

There are several reasons to do that.

 

Stubs

One of the usage of Mocking - or isolation – frameworks is stubbing. A component that access external resources or has complex behavior will be changed for a fake to have simpler predictable results.

 

  • When the component interface is small, the stub declaration code is often more complicated that writing a fake implementation directly.
  • When the interface has many methods, it makes things easier, but here you’ll ignore a code smell. It makes things easy in situation you should not reach !

There are also easy patterns that make the use of mocking irrelevant. A common one is configuration loading.

Lots of developers think: “I need a class to access my configuration. Let’s make a class for this”:

 

    public class Configuration

    {

        public string EndPoint

        {

            get { return ConfigurationManager.AppSettings["EndPoint"]; }

        }

 

        // other properties here//

    }

 

Then they realize they’ll have to isolate from ConfigurationManager, so they add a interface :

 

 

    public interface IConfiguration

    {

        string EndPoint { get; }

    }

 

    public class Configuration : IConfiguration

    {

        public string EndPoint

        {

            get { return ConfigurationManager.AppSettings["EndPoint"]; }

        }

 

        // other properties here//

    }

And they can moke the configuration using a lot of boring code.

 

what about this ?

 

 

    public class Configuration

    {

        public string EndPoint { get; set; }

        // other properties here//

    }

 

    public class ConfigurationLoader

    {

        public Configuration Load()

        {

            return new Configuration

                {

                    EndPoint = ConfigurationManager.AppSettings["EndPoint"]

                    // other properties here//

                };

        }

    }

 

Passing a different configuration in your test is a simple new Configuration {}… and you can use the ConfigurationLoader class in you main function.

 

A good thing here, is that you don’t suffer a read of the configuration file at each call without needing to introduce lazy loading or other tweaks that make things worse..

 

Mocks

When you need to see if a call happened, you can make an implementation of the interface that takes a lambda :

 

    public interface IFancyService

    {

        void DoSomething(int arg);

    }

 

    public class MockFancyService : IFancyService

    {

        private Action<int> doSomething;

 

        public MockFancyService(Action<int> doSomething)

        {

            this.doSomething = doSomething;

        }

 

        public void DoSomething(int arg)

        {

            doSomething(arg);

        }

    }

 

    public class Test

    {

        void DoSomthingHasBenCalled()

        {

            bool wasCalled = false;

            var fancyService = new MockFancyService(i => { wasCalled = true; });

 

            var compoenent = new ComponentThatUseFancyService(fancyService);

            compoenent.MakeSomething();

 

            Assert.That(wasCalled, Is.True);

        }

    }

Or make the fake class record the call, and add a getter to check. It’s not that complicated.

Tuesday, May 19, 2009

IOC Container, Go Hide (part 2)

Ok, there seem to be some misunderstanding with the suggestion from my previous post.

A framework manipulates two kind of objects :

  • its objects
  • your objects

You don’t care about its object, you care about yours.

So you want to be able to take part in your objects instantiation so that you can do your own stuff (inject dependencies, handle differently based on runtime behavior…).

Without container

Look at Asp.net, when it needs to create an Http Handler, it calls a IHttpHandlerFactory.

You can provide your own IHttpHandlerFactory, just implement its two methods (the second one can even be left empty in most cases) :

public interface IHttpHandlerFactory
{
// Methods
IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated);
void ReleaseHandler(IHttpHandler handler);
}

In the GetHandler method, you’re free to use the container you want ! But you can also do this :

return new CustomHttpHandler(theDependency);

Or make a call to another factory, or… or…

With container

The framework ask to provide a container so that the it can simply run. Ok there is also a builtin container so I don’t have to care.

But if I want to do a custom instantiation I have now to implement the following interface :

public interface IServiceLocator : IServiceProvider
{
// Methods
IEnumerable<TService> GetAllInstances<TService>();
IEnumerable<object> GetAllInstances(Type serviceType);
TService GetInstance<TService>();
TService GetInstance<TService>(string key);
object GetInstance(Type serviceType);
object GetInstance(Type serviceType, string key);
}

This interface will be used when any instantiation will occur. If I mess internal framework instantiation. Wooch !

And there is no clear meaning with this interface. It should be able to instantiate any object requested.

It doesn’t give a clean and clear API in my personal opinion !

Using an IOC container as an extension point is clearly an over abstraction !

Provide clear, focused extensibility points

The framework doesn’t need to be extended on every instantiation, especially when instantiation its own internal stuff. There are clear extension points, and a specific interface should be created for each.

This is just a framework design good practice.

Then, there is no need to show the container you use to the outside, and it resolves potential version conflicts.

Friday, May 15, 2009

IOC Container, Go Hide !

558287_49024807While testing NServiceBus and MassTransit – yes I need a service bus framework for my current project – I’ve seen that both library where relying on an IOC container, in two different ways.

Warning: This article is not to flame these two frameworks that seems of great quality. There are still few guidance on using IOC containers in libraries. This is the topic of this post.

The NServiceBus way

NServiceBus relies on Spring or Castle Windsor.

You can notice it when instantiating the Bus :


var bus = NServiceBus.Configure.With()
                .SpringBuilder() // or .CastleWindsorBuilder()
                .MsmqSubscriptionStorage()
                .XmlSerializer()
                .MsmqTransport()
                    .IsTransactional(true)
                    .PurgeOnStartup(false)
                .UnicastBus()
                    .ImpersonateSender(false)
                .CreateBus()
                .Start();

And when looking at the library with Reflector :

image

and

image

Yes, the Spring framework and the Castle.Windsor are ILMerged in the NServiceBus assembly.

NServiceBus abstracts the container with the NServiceBus.ObjectBuilder.IBuilder interface :

public interface IBuilder
{
    // Methods
    T Build<T>();
    object Build(Type typeToBuild);
    IEnumerable<T> BuildAll<T>();
    IEnumerable<object> BuildAll(Type typeToBuild);
    void BuildAndDispatch(Type typeToBuild, Action<object> action);
}

 

The MassTransit way

MassTransit adopts a slightly different strategy.

The base is still the same.

It uses the CommonServiceLocator to have a ‘standard’ interface to hide the actual IOC container implementation.

It provides implementations for the most common IOC frameworks (Castle.Windsor, NInject, StructureMap and Unity – but it doesn’t work so well…) through additional dlls.

The big difference is in the library configuration. You configure the container (through code or configuration). Then encapsulate the container in a Common Service Locator implementation that acts as an adapter. Finally give it to the library.

 

What’s the problem

In both case, the intent is good, but hell is paved with good intentions.

In Mass Transit, the design is clearly made so that you can choose your container and integrate the library seamlessly with it. You can manage the configuration in your container the way you do it in your application.

But wait ! What if I don’t need an IOC container in my application ?

The other problem is that Mass Transit relies on some advanced IOC capabilities like contextual configuration. The object instantiated for IEndPoint should not be the same depending on the parent object. This scenario is not handled by Unity for instance.

Maybe Unity is not good enough, but how can I know which other specific feature Mass Transit relies on ? No clue.

And providing a library configuration through a container doesn’t seem a best practice to me. The API gives no clues of what I should provide to the library in order to run it.

The only way to know is to launch it, see where it throws an unresolved dependency exception, add the dependency and retry !

And I’ll probably never know about optional dependencies.

On the other side, NServiceBus works with a NServiceBus specific configuration (code and app.config) that indicates  clearly what I must provide to the library.

But Jak Charlton had a serious problem with NServiceBus. He’s not using the same version of Castle.Windsor that the one merged in the NSB assembly ! And the assembly load fails.

 

What’s the solution then ?

I clearly prefer the specific configuration scheme of NServiceBus, but how can we solve the version problem ?

I will answer with another question :

Why does NServiceBus need two IOC container implementations ?

For library creators, I will propose this way to go :

  • Choose the container that provides the features you need
  • Use it in your infrastructure
  • Create a clear configuration model that exposes the required and optional dependencies that should be provided by the library user
  • Consider creating a app.config specific configuration (there are good tools in the framework for that)
  • ILMerge your container framework as internal in your assembly.

The alternative to ILMerge is to fork your framework (if it’s open source) and put it as internal directly in your code.

The advantages

  • No conflict with potential other versions of the container framework
  • A clear discoverable configuration
  • No need to use a IOC container to use the library.

What if the container needs to inject dependencies in the user objects ?

Both NServiceBus and MassTransit instantiate user’s objects on the fly.

How can the user add it’s own dependencies if he has no access to the container ?

Let’s step back a little and consider what we would do if there was no container…

  • We would use Activator.CreateInstance to create the object.
  • Then we would consider it would not let the library user enough options, so we would propose a hook so that the user can manage the instantiation himself. It could be a callback or an interface.

When instantiating user objects with the internal framework IOC container, you remove to your users the right to manage the instantiation themselves.

So come back to this good practice. If the user wants to use a IOC container to instantiate his objects with dependencies, let him do this his own way. And his container will not be loaded with all the framework internal dependencies, this will avoid other conflicts.

Conclusion

Hide your IOC container framework inside your library, it’s a private implementation detail of your framework and we don’t wanna know !

Choose the framework you like, hide it so that it cannot conflict with the one I want to use and we will be friends !

It surely advocates for frameworks with a small footprint, but once again, it’s a private detail.

 

Continued on IOC Container, Go Hide (part 2)

Friday, December 19, 2008

Coding and writing - The form

There is a number of common points between coding and writing

Spelling

The most basic mistake... Oops I wrote retrun instead of return... hopefully modern text editors check it on the fly.

Syntax

Correct sentences are made of word in a correct order. Here again, on the fly checking helps a lot.

Presentation

Is your code visibly clear... Enough space between parts, but not too much. Is you code clearly indented.

Style

Style is even more subjective. When coding, usually stay concise, but there are a lot of parameters here.

You can :

  • choose if statements or ?: alternating operator
  • define fluent interfaces to do things on several lines
  • use linq to express your intent more clearly,
  • use var implicit type or not
  • use anonymous types or not
  • use lambdas or functions

The important thing is that your style should fit some purpose, the style should emphasis important parts of your primary intent.

Structure

A book is divided in parts, chapters and paragraphs. The code is divided in files namespaces and classes. The structure of the code should help the reader go straight to what is the most important to him and understand how things are related.

 

Next time, we'll talk about substance. Tell me if you see more analogies !

Monday, December 1, 2008

Problem with the Select N+1 problem

Ayende proposes solutions for the Select N+1 problem in NHibernate.

Some will say it is a sign that lazy load is the work of the devil. But I can remember the time when people were saying that garbage collectors are evil.

We all would like to have non intrusive data fetching strategy that work 99% of the time !

The problem is not about lazy load or not. It is that you must take care about your data fetching strategy whenever you make a data access.

There is currently no technology smart enough to infer the right fetching strategy.

If someone builds it, this won't be a problem anymore.

If you know about it, please tell the world !

Tuesday, November 25, 2008

CSS is too Tricky

I found through Alvin Ashcraft's Morning Dew a post about CSS tricks Six indispensable CSS tips and tricks I use on every project. Very interesting since it gives some ways to make cleaner CSS integration (I really like the Overclear one, don't need the clear both anymore !!).

But while reading this question came to my mind:

Why do we need to find crazy tricks like this for any single thing we want to do with HTML + CSS ?

This is the sign that HTML + CSS is a complete design failure !

When you want to make something as simple as putting several blocks on the same line... you must use float left, but it does not behave exactly has you expect it to do... When using Silvelight and WPF I had none of these problems. There are surely other problems with theses technologies but I have found an important difference :

  • In CSS, the elements decide how the fit in their parent
  • In Silverlight, parents decide the layout of their children

And it makes a huge difference. Because in CSS, the interactions between sibling children using very different placement models make it a n*n combination problem. For sure it's not manageable and no browser can handle every case gracefully.

In Silverlight, you obtain the layout you want by composition, and each rule remains simple. No need to use Jedi tricks to obtain what you want.

Monday, November 24, 2008

Coincidences just happen...

It's quite strange how ideas can appear at the same time in different places. This morning while take a shower I was thinking about a future post series about programming and building architecture and how things had changed in the last few years. Only 1h later I was reading this post by Justin Etheredge, that matches exactly this subject.

I'm still preparing the posts however.

Do you understand what it is all about ?

I want to be sure the title of the blog will not be misunderstood: when I say "Think before coding", I don't mean you should prepare everything before and the start coding like a robot. This is what is called waterfall model, and  and it has always been considered as as non-working model, even by its author. NotUnderstand

Programming is not applying a technique. When confronted twice to a problem, the programmer should not use the same solution, but understand what make both problems so close and build something that solve this class of problems. It can be a simple helper function, a small library or a big framework. This is the DRY (Don't Repeat Yourself) principle.

We all learnt how to implement a Quicksort algorithm at school. When was the last time you had to implement it? Personally I use the Linq Sort() extension method and it does the trick for me.

If you have to implement it for a specific reason, it should be because you understood that your problem was not exactly the same as the one handled by existing implementations.

This is why programming is not about technique or algorithm, if you're smart enough, you can adapt almost anything to any language or technology.

There is still one thing that tools and technology can't do for you :  understanding.

Programming IS about understanding

  • Understand the problems
  • Understand the processes,
  • Understand the people,
  • Understand the other programmers,
  • Understand yourself!

 

You should have a deep understanding of the problems and processes.

This is the base of modeling, wether it is domain models as in Domain Driven Design or infrastructure framework creation, through Separation of Concerns.

You should understand people.

Because they are the one that ultimately will use what you're building. People are usually hard to understand. This is all the matter about User Experience (UX), but even when programming a framework, you should understand how other programmer will use it and understand it, and how they'll build on it software for other people with their one expectations.

You should understand programmers.

You rarely write your code only for you, and you should write your code so that other programmer have the better understanding of what you intended to do, and what you understood about the problem you're solving by writing this code.

You should understand yourself.

Even when you write code only for yourself, you should understand what you wrote in the first place, as Andy Hunt and Dave Thomas say :

All Programming is Maintenance Programming

Bill Venners: You say in your book, The Pragmatic Programmer (Addison-Wesley, 1999), that "programmers are constantly in maintenance mode." Why?

Dave Thomas: All programming is maintenance programming, because you are rarely writing original code. If you look at the actual time you spend programming, you write a bit here and then you go back and make a change. Or you go back and fix a bug. Or you rip it out altogether and replace it with something else. But you are very quickly maintaining code even if it's a brand new project with a fresh source file. You spend most of your time in maintenance mode. So you may as well just bite the bullet and say, "I'm maintaining from day one." The disciplines that apply to maintenance should apply globally.

Andy Hunt: It's only the first 10 minutes that the code's original, when you type it in the first time. That's it.

But you should also understand how you do things, how you did things, how you changed, and how you will change in the future.  Things are moving so fast that you can not simply stay with your current knowledge and expect it to be sufficient in two years.

Thursday, November 20, 2008

'Save' is not a feature anymore

Pete Brown noted in this post that the save icon is still represented by a 3 1/2" floppy by most of the application.Floppy-Word

But what does the Save button really mean ?

Back in the floppy days, there was no fast persistent storage. To work at acceptable speed, you had to manage everything in memory, the take a few seconds to save at some point. At that time, most of the storage mediums were removable.

Today, things are different. You can't find a computer without a hard disk or solid state drive.

When an application proposes a save action you should understand :

  • My application stores my data in memory
  • If I forget to save it, my data will be lost !

As Chase Saunders states  in his comment this is what he calls a 'Make It Work' button !

Is this a feature ? It's a curse !

How would work a program without Save button ?

  • The document would be persisted continuously on disk.
  • It would have a default name (the first sentence ?) in a default location.
  • The program would display a list of available documents.
  • You should be able to Copy (instead of Save As) your document to another place.
  • You should be able to Delete it from its location.
  • For complex documents the program would propose versioning or labeling to mark important documents steps.

The world would then be a better place !