Archive

Archive for the ‘Best practices’ Category

Branching practices

April 6th, 2010 Patrick No comments

In an environment where several developers work at the same code base or several features have to be implemented, then branching will be a topic. I was asked to create a branching guide for my current employer which use TFS as source code repository.

Motivation

In our projects I found the following problems:

  • When the developers want to release a new version, not every feature was finished. So they had to deliver unfinished features. To solve that problem, they need to disable the unfinished features by configuration.
  • Some features which they had to implement were breaking features. In a such case, they were blocked to deliver new fixes or little features.
  • Sometimes they had to produce a hot-fix for the version which was in production. In a such scenario, they had to take manually the labeled version from the repository and build a hot-fix. After that, they had to copy the fixed code into the current code base.

Branching Guide

For those three scenarios branching could minimize the impact. So I described in the branching guide the following patterns to solve our problems:

  • Feature-Branch (and Team-Branch)
  • Developer-Versions
  • Production-Branch
  • Feature-Freeze

image

Feature-Branch

A Feature-Branch is a branch which is created always from the Main-Branch. It’s important to choose the right granularity for a feature. A worst-case-scenario is when you split a feature over several Feature-Branches, so that they become dependent on each other. A good granularity is for example a module or a workflow (several GUIs), something which is self-contained.

With Feature-Branches you have the possibility the use the cherry-picking method. That means, that before you release a new version, you choose by some quality gates (code coverage, code review, documentation, etc.) which Feature-Branches you want to merge back to the Main-Branch.

A special version of a Feature-Branch is the Team-Branch (not visible in the picture). A Team-Branch is a Feature-Branch which will be reused after a completed feature (and reverse integration to the Main-Branch). A Team-Branch will reduce the number of branches and it is assign exactly to one team or team member. It is also important, that on a Team-Branch it is allowed to implement exactly one feature at a time.

Developer-Version

The Developer-Version (in the picture the labels 2.1.2016.1 or 2.1.2016.2) are needed, when you have to create a version of your application or component to deliver it to another team. We had some dependencies of components and for breaking features, all of them were influenced. So we created a Feature-Branch in each component and published for each a Developer-Version. The dependent component could reference that Developer-Version in the corresponding Feature-Branch. A Developer-Version is just for internal use, it isn’t allowed to deliver it to the customer.

Production Branch

The Production-Branch is the representation of the actual delivered version of an application or component. In our situation, it wasn’t possible that there were several versions in production. So, we didn’t need for each release a separate branch, we could reuse a branch – the production branch.

There a two approaches how to refresh the Production-Branch: After the end of the Feature-Freeze, when the new version was shipped. The other possibility is before you create the first hot-fix (refresh with the help of the labeled version).

Feature-Freeze

When you have to create a new version, you have to decide what you will or could deliver. After you merged all good Feature-Branches then the Feature-Freeze begins. During the Feature-Freeze it isn’t allowed to add any features, but it’s allowed to fix the current version. Before the Feature-Freeze ends, you have to release your current version to ship.

When the Feature-Freeze takes a long time, then you have to create Feature-Branches to continue the development for the next version.

Branching and Continuous Integration

Branching and Continuous Integration aren’t the best friends. With Branching you want to isolate the features from each other, but you pay it when you have to merge. Merging is a manual integration of two versions, and it isn’t always fun to do it.

With Continuous Integration you want to prevent a big bang integration. You want to give the developers as early as possible feedback, that the current code is breaking or not.

In our situation, we had Continuous Integration for the Main-Branch, but not for the other branches. I would recommend to add Continuous Integration for the other branches too if they take a longer time. I would recommend also to forward integrate several times to avoid a difficult merge at the end.

Further Reading

Microsoft Branching Guide III

Feature Branch by Martin Fowler

Software Development Stages

  • Share/Bookmark

Mocking frameworks in .Net

March 30th, 2010 Patrick 6 comments

A few month ago I played with some mocking frameworks in .Net. There are already some comparisons available (here, here or here). In this blog post I want to show which frameworks are available and which one fits best for agile development.

You could download the source code from github.com.

Software under Test (SUT)

To demonstrate and evaluate all the different mocking framework I had to create a scenario where it is appropriate to use a mocking framework. So I chose an user entity which I want to validate and in a successful case also to persist in a database.

namespace Mocking
{
	public class User
	{
		public IUserGateway Gateway
		{
			get; set;
		}

		public User()
		{
			this.Gateway = new UserGateway();
		}

		public User(IUserGateway gateway)
		{
			this.Gateway = gateway;
		}

		public bool Persist(IUserValidator validator)
		{
			bool bValid = validator.Validate(this);

			if(bValid) bValid = this.Gateway.Persist(this);

			return bValid;
		}
	}
}

This is the User entity class which implements the active record pattern. As you see, there are three injection patterns realized, the constructor injection and setter injection for the gateway and the parameter injection for the validator.

namespace Mocking
{
	public class UserGateway : IUserGateway
	{
		public virtual bool Persist(User user)
		{
			return true;
		}
	}
}

The UserGateway class is responsible to persist the entity. In my scenario it is just a dummy, because I don’t want to setup a database for this demo.

namespace Mocking
{
	public class UserValidator : IUserValidator
	{
		public bool Validate(User user)
		{
			if(user == null) return false;

			return true;
		}
	}
}

The validator is also more or less just a dummy for this demo.

Both interfaces, IUserGateway and IUserValidator, has the same methods, properties as the classes which implement them.

NMock2

One of the first mocking frameworks in .Net which I was looking at was NMock2. Specially the cheat sheet make it really easy to learn this framework.

namespace MockingTest
{
	[TestClass]
	public class NMock2Test
	{
		[TestMethod]
		public void TestPersist()
		{
			Mockery mocks = new Mockery();

			//Create mocks
			IUserGateway mockGateway = mocks.NewMock<IUserGateway>();
			IUserValidator mockValidator = mocks.NewMock<IUserValidator>();

			//Create user
			User user = new User();

			//Expectations
			using(mocks.Ordered)
			{
				Expect.Once.On(mockValidator).Method("Validate").With(user).
Will(Return.Value(true));
				Expect.Once.On(mockGateway).Method("Persist").With(user).
Will(Return.Value(true));
			}

			//Assign Gateway
			user.Gateway = mockGateway;

			//Test method
			Assert.AreEqual(true, user.Persist(mockValidator));

			mocks.VerifyAllExpectationsHaveBeenMet();
		}
	}
}

You could use the AAA-Syntax (Arrange-Act-Assert). Also more extended features like the ordered calls with the using syntax is very nice.

But, there is are also negative points: NMock2 uses “magic strings”. In your Expectations you have to declare the called method with a strings, which makes your tests very brittle when your refactor your code. For example if you have to rename a method, even the compiler could not help you. An other negative point is, that you can only mock interfaces. When you have to mock a class, you have to change your design by adding an interface just for mocking.

NMock3

Recently I discover, that there is already a follower of NMock2 on codeplex: NMock3.

namespace NMock3Test
{
    [TestClass]
    public class NMock3Test
    {
        [TestMethod]
        public void TestPersist()
        {
            MockFactory factory = new MockFactory();

            //Create mocks
            Mock<IUserGateway> mockGateway = factory.CreateMock<IUserGateway>();
            Mock<IUserValidator> mockValidator = factory.CreateMock<IUserValidator>();

            //Create user
            User user = new User();

            //Expectations
            using(factory.Ordered)
            {
                mockValidator.Expects.One.MethodWith(m => m.Validate(user)).WillReturn(true);
                mockGateway.Expects.One.MethodWith(m => m.Persist(user)).WillReturn(true);
            }

            //Assign gateway
            user.Gateway = mockGateway.MockObject;

            //Test method
            Assert.AreEqual(true, user.Persist(mockValidator.MockObject));

            factory.VerifyAllExpectationsHaveBeenMet();
        }
    }
}

The migration is quite easy: Replace the reference from your test project from the NMock2.dll with a new reference to the NMock3.dll. After that you could use the new approach with the MockFactory and the lambda expressions in your Expectations.

NMock3 introduce type safety and readiness for refactorings combined with the easiness of NMock2. They also keep the tradition of a good cheat sheet.

With NMock3 I couldn’t mock a class (even when I followed the exceptions…"). The creation of stubs should be possible. The project is still a young one and so the documentation isn’t that good as it should be. But NMock3 remain an interesting mocking framework.

Simple.Mocking

When I looked for mocking frameworks I also found this new and not very well known framework Simple.Mocking on codeplex. Its also avoid “magic strings” and you could also use the AAA-Syntax. Simple.Mocking has only one committer, Mikael Waltersson.

namespace MockingTest
{
    [TestClass]
    public class SimpleNetTest
    {
        [TestMethod]
        public void TestPersist()
        {
            //Create mocks
            var expectationScope = new ExpectationScope();
            IUserGateway mockGateway = Mock.Interface<IUserGateway>(expectationScope);
            IUserValidator mockValidator = Mock.Interface<IUserValidator>(expectationScope);

            //Create user
            User user = new User();

            //Expectations
            Expect.Once.MethodCall(() => mockValidator.Validate(user)).Returns(true);
            Expect.Once.MethodCall(() => mockGateway.Persist(user)).Returns(true);

            //Assign gateway
            user.Gateway = mockGateway;

            //Test method
            Assert.AreEqual(true, user.Persist(mockValidator));

            AssertExpectations.IsMetFor(expectationScope);
        }
    }
}

The ExpectationsScope is used to avoid to call AssertExpectations.IsMetFor for each mock. This construct is special and I’m (currently) not a big fan of it.

With Simple.Mocking you could just mocking interfaces and delegates, you couldn’t mock classes.

Rhino.Mocks

Rhino.Mocks is one of the famous .Net mocking frameworks. As Simple.Mocking there is also only one committer to this framework, Oren Eini (alias Ayende Rahien).

namespace MockingTest
{
	[TestClass]
	public class RhinoMockTest
	{
		[TestMethod]
		public void TestPersistWithRecordingReplay()
		{
			MockRepository mocks = new MockRepository();

			IUserGateway gateway = mocks.StrictMock<IUserGateway>();
			IUserValidator validator = mocks.StrictMock<IUserValidator>();

			//Create user
			User user = new User();

			//Expectations
			using(mocks.Ordered())
			{
				Expect.Call(validator.Validate(user)).Return(true);
				Expect.Call(gateway.Persist(user)).Return(true);
			}

			//Stop recording, start replay
			mocks.ReplayAll();

			//Assign gateway
			user.Gateway = gateway;

			//Test method
			Assert.AreEqual(true, user.Persist(validator));

			mocks.VerifyAll();
		}

		[TestMethod]
		public void TestPersistWithArrangeActAssert()
		{
			var gateway = MockRepository.GenerateMock<IUserGateway>();
			var validator = MockRepository.GenerateMock<IUserValidator>();

			//Create user
			User user = new User();

			//Expectations
			validator.Expect(x => x.Validate(user)).Return(true);
			gateway.Expect(x => x.Persist(user)).Return(true);

			//Assign gateway
			user.Gateway = gateway;

			//Test method
			Assert.AreEqual(true, user.Persist(validator));

			//Asserts
			validator.VerifyAllExpectations();
			gateway.VerifyAllExpectations();
		}
	}
}

Rhino.Mocks supports two ways to use the framework: the record-replay and the AAA-syntax. My favorite is clearly the AAA-syntax, because there is much less code needed (reduced accidental complexity). Rhino.Mocks uses also Lambda-Expressions to avoid “magic strings”, so refactoring shouldn’t be a problem.

Moq

Moq is another mocking framework which takes advantage of the .Net 3.0 language features like lambda expressions. So Moq doesn’t use “magic strings” and it enables also the AAA-syntax. There are two ways how to create mocks. You could create mocks directly with the Mock class or you could use the MockFactory class. For both scenarios I created a test.

namespace MockingTest
{
	[TestClass]
	public class MoqTest
	{
		[TestMethod]
		public void TestPersist()
		{
			var gateway = new Mock<IUserGateway>();
			var validator = new Mock<IUserValidator>();

			User user = new User();

			//Expectations
			validator.Setup(x => x.Validate(user)).Returns(true).AtMostOnce();
			gateway.Setup(x => x.Persist(user)).Returns(true).AtMostOnce();

			//Assign gateway
			user.Gateway = gateway.Object;

			//Test method
			Assert.AreEqual(true, user.Persist(validator.Object));

			validator.VerifyAll();
			gateway.VerifyAll();
		}

		[TestMethod]
		public void TestPersistWithFactory()
		{
			MockFactory factory = new MockFactory(MockBehavior.Strict);

			//Class works, but methods have to be virtual -> not nice
			var mockGateway = factory.Create<UserGateway>();
			var mockValidator = factory.Create<IUserValidator>();

			User user = new User();

			//Expectations
			mockValidator.Setup(x => x.Validate(user)).Returns(true).AtMostOnce();
			mockGateway.Setup(x => x.Persist(user)).Returns(true).AtMostOnce();

			//Assign gateway
			user.Gateway = mockGateway.Object;

			//Test method
			Assert.AreEqual(true, user.Persist(mockValidator.Object));

			factory.VerifyAll();
		}
	}
}

I prefer the MockFactory approach, because you don’t need to verify each mock (its reduce the test code which is a good thing). Be sure, that in this scenario you don’t forget the parameter MockBehavior.Strict which makes your mock objects real mocks. Without this parameter they are more like Stubs, which don’t fail and just return a default value.

But there is a little problem: If you want to mock a class, then all the methods have to be virtual, but Moq has no problem to mock an interface.

Typemock Isolator

Unfortunately Typemock Isolator isn’t free, but you could get a trial to try this great mocking framework. As you could see in the TestPersistWithReflectiveMocking Typemock Isolator could mock classes, also non-virtual methods. Great. It also doesn’t use “magic strings”. But wait, you could not mock interfaces? With the new AAA-syntax it is possible and it looks very nice.

namespace MockingTest
{
	[TestClass]
	public class TypeMockTest
	{
	    [TestMethod]
	    public void TestPersistWithNaturalMocking()
	    {
	        MockManager.Init();

	        User user = new User();

	        // Natural mocking
	        using(RecordExpectations recorder = new RecordExpectations())
	        {
	            IUserGateway mockGateway = new UserGateway();
	            IUserValidator mockValidator = new UserValidator();

	            //Expectations
	            recorder.ExpectAndReturn(mockValidator.Validate(user), true);
	            recorder.ExpectAndReturn(mockGateway.Persist(user), true);
	        }

	        //Create instances
	        IUserGateway gateway = new UserGateway();
	        IUserValidator validator = new UserValidator();

	        //Assign gateway
	        user.Gateway = gateway;

	        //Method
	        Assert.AreEqual(true, user.Persist(validator));

	        MockManager.Verify();
	    }

	    [TestMethod]
	    public void TestPersistWithReflectiveMocking()
	    {
	        MockManager.Init();

	        //Create mocks
	        Mock mockGateway = MockManager.Mock<UserGateway>();
	        Mock mockValidator = MockManager.Mock<UserValidator>();

	        //Create user
	        UserGateway gateway = new UserGateway();
	        IUserValidator validator = new UserValidator();
	        User user = new User(gateway);

	        //Expectations
	        mockValidator.ExpectAndReturn("Validate", true).Args(user);
	        mockGateway.ExpectAndReturn("Persist", true).Args(user);

	        //Method
	        Assert.AreEqual(true, user.Persist(validator));

	        MockManager.Verify();
	    }

		[TestMethod]
		[Isolated]
		public void TestPersistWithAAA()
		{
			//Arrange
			//Create mocks
			UserGateway gateway = Isolate.Fake.Instance<UserGateway>();
			IUserValidator validator = Isolate.Fake.Instance<IUserValidator>();
            //Create user
			User user = new User(gateway);
            //Expectations
			Isolate.WhenCalled(() => validator.Validate(user)).WillReturn(true);
			Isolate.WhenCalled(() => gateway.Persist(user)).WillReturn(true);

			//Act
			bool bPersist = user.Persist(validator);

			//Assert
			Assert.AreEqual(true, bPersist);
		}
	}
}

Typemock Isolator also supports the record-replay approach (demonstrated in the TestPersistWithNaturalMocking test method). But as you already know, I prefer the AAA-syntax.

The question about Typemock Isolator is, if it is worth to pay for a mocking framework if there are so much other free opportunities?  Typemock Isolator is very powerful and for some companies it is very important to get support and also guarantee that the product will be continued for example ten years. In such a scenario Typemock Isolator would be definitely an option. In reaction of such scenarios, also other providers of mocking frameworks offer commercial support for their frameworks, for example Rhino.Mocks.

The undocumented – NUnit Mocking

It is not very known that there exists also in NUnit a mocking framework. It is possible to mock interfaces and classes if the inherit from MarshalByRefObject.

namespace MockingTest
{
	[TestClass]
	public class NUnitMockTest
	{
		[TestMethod]
		public void TestPersist()
		{
			//Gateway
			DynamicMock mockGateway = new DynamicMock(typeof(IUserGateway));
			IUserGateway gateway = (IUserGateway) mockGateway.MockInstance;

			//Validator
			DynamicMock mockValidator = new DynamicMock(typeof(IUserValidator));
			IUserValidator validator = (IUserValidator)mockValidator.MockInstance;

			//User
			User user = new User(gateway);

			//Expectations
			mockValidator.ExpectAndReturn("Validate", true, user);
			mockGateway.ExpectAndReturn("Persist", true, user);

			Assert.AreEqual(true, user.Persist(validator));
			mockValidator.Verify();
			mockGateway.Verify();
		}
	}
}

The mocking framework is easy to use and if you already use NUnit, then you don’t need an additional framework.

As I know, it isn’t official and there is no documentation. You have also to use “magic strings” for methods and the limitation for classes also reduce the benefit.

Conclusion

For a modern mocking framework it is essential that its enable refactoring by not using “magic strings”. It is also essential for me that it allows to use the AAA-syntax. A third essential thing is that it allows you to mock classes. You don’t want to create interface just for mocking, for example for your domain model. Avoid accidental complexity is very important, so you shouldn’t add unnecessary code just for mocking. That doesn’t mean that “design for testability” is wrong, “design for testability” means, that you design your code in a way, that you have the possibility to test your code, for example you avoid huge classes (god object anti-pattern) with a lot of private methods or you avoid creation of instances in methods (unable to use dependency injection).

So, which framework fulfill all the requirements? NMock3, which inherit the easiness of NMock2 combined with the elimination of the “magic strings”? Or Typemock Isolator which also eliminate the “magic strings” and could even mock classes?

For me, there isn’t currently a clear winner visible, maybe Typemock makes the race. But there are frameworks which I would no longer use, as NMock2 or NUnit mocking. They don’t fulfill my requirements clearly. That doesn’t mean they aren’t suitable for your scenarios.

Also to be clear: There are other topics that should be considered: mocking events, Stubs, etc. The list of the mocking frameworks isn’t complete, for example Moles is a framework which could be interesting too.

  • Share/Bookmark
Categories: .Net, Best practices, Testing Tags:

WordPress and SyntaxHighlighter

January 8th, 2010 Patrick No comments

I often post code in my blog posts, so the SyntaxHighlighter by is very useful. But there are several plug-ins for WordPress, the question is which one is the most comfortable and has the most configuration options:

Offline blogging tool support

When I post technical blog posts with code in it, then I prefer the way over an offline blogging tool. Currently I use for this use case Windows Live Writer, also because it is free. But when you use a such tool, you should have good support for writing code and support for the SyntaxHighlighter. For Windows Live Writer there exists several plug-ins for the SyntaxHighlighter:

Unfortunately some of those plug-ins aren’t very well tested, but to add code to a blog posts they do their job.

Conclusion

After testing the several plug-ins for WordPress and Windows Live Writer, I prefer currently the following plug-ins:

  • Share/Bookmark
Categories: Best practices, Private Tags:

Useful Firefox Add-ons

January 1st, 2010 Patrick 4 comments

After several years of using Firefox, I’ve got my favourites under the available Add-ons for my preferred Browser Firefox:

Tabs

Links

Language

Downloads

Development

I try to keep the number of the installed Add-ons small to avoid an “Add-ons-hell”. Are there any other indispensable useful Add-ons for Firefox?

  • Share/Bookmark
Categories: Best practices, Private Tags:

Kaizen and Software Engineering

October 27th, 2009 Patrick 3 comments

Kaizen is a very interesting approach, also in the software industry. On Wikipedia you’ll find the following description of Kaizen:

Kaizen is a Japanese word adopted into English referring to a philosophy or practices focusing on continuous improvement in manufacturing activities, business activities in general, and even life in general, depending on interpretation and usage.

Kaizen aims to eliminate waste, to improve the process or activities (techniques). I heard about Kaizen the first time at an economic course, and I found the Muda (seven wastes) very interesting. I tried to find locations or situations where you can detect such wastes:

Overproduction

Overproduction happens each time you engage more resources than needed to deliver to your customer. For instance, large batch production, because of long change over time, exceeds the strict quantity ordered by the customer. For productivity improvement, operators are required to produce more than the customer needs. Extra parts will be stored and not sold. Overproduction is the worst Muda because it hides or generates all others, especially inventory. Overproduction increases the amount of space needed for storing raw material as well as finished goods. It also requires a preservation system.

Overproduction happens then, when you don’t follow the YAGNI principle. Don’t try to make assumptions about the future or the customers. Just produce the things as simple as possible.

Unnecessary transportation

Each time a product is moved it stands the risk of being damaged, lost, delayed, etc. as well as being a cost for no added value. Transportation does not make any transformation to the product that the consumer is supposed to pay for.

Don’t build chatty interfaces, make use of the coarse-grained interface pattern.

Inventory

Inventory, be it in the form of raw materials, work-in-progress (WIP), or finished goods, represents a capital outlay that has not yet produced an income either by the producer or for the consumer. Any of these three items not being actively processed to add value is waste.

Deliver early and often. Don’t wait at the end of the project to deliver the whole software at once. If you deliver your software earlier and often, you will receive more feedback and so the costs to fix bugs will reduce. Also the customer will be happier because he could use much earlier important parts of your software and he could observe better the progress of the software project.

Motion

As compared to Transportation, Motion refers to the producer or worker or equipment. This has significance to damage, wear, safety. It also includes the fixed assets, and expenses incurred in the production process.

Good hardware and a good chair is very important to be productive. Slow computers are just horrible to work with and a bad or cheap chair is not very good for the health of the software engineers. If the software engineer feels comfortable, he’s much more able to be concentrated or work longer.

Defects

Whenever defects occur, extra costs are incurred reworking the part, rescheduling production, etc.

Reduce Defects. Unfortunately there doesn’t exists a programming language where it isn’t possible to make no errors. So testing is absolutely necessary. Do unit testing with or without TDD, but a modern software project should have tests (unit tests, integration tests or acceptance tests, etc.). Without tests you don’t have a safety net (regression tests) if you change something in your project. One of the worst error a customer could find is one which he already found and was fixed.

Over-Processing

Over-processing occurs any time more work is done on a piece than what is required by the customer. This also includes using tools that are more precise, complex, or expensive than absolutely required.

Overengineering and Patternoholics are a danger to do more than it is necessary.

Waiting

Whenever goods are not in transport or being processed, they are waiting. In traditional processes, a large part of an individual product’s life is spent waiting to be worked on.

Slow computers where you have to wait for a build step or just for the compiler are an unnecessary waste. Also if you wait for an answer from your customer or an other teammate. Don’t wait, make a follow-up, make a phone call or write an other mail. Also don’t let the others wait. If you receive an email, answer it or write a short email to say that you will response later, so that the other knows, that you saw his mail and you planed to response him.

Conclusion

One important question is: “Do you add value to your solution, product or service which the customer is ready to pay for?” This question or view isn’t new. It focus all the actions in software engineering on business value, the value which the customer pays for. To reduce the waste you have to improve (Kaizen) your code, methods and communication with others. The seven wastes are a help to find locations or situations where waste could happen.

  • Share/Bookmark