Filed under Architecture, Design

Ensure.That – a simple guard clause project

Yes I know there’s a bunch of these projects out there already and that there’s built in support for using code-contracts in .Net, but even so we found a need for a custom API, hence Ensure.That was created. Also, I think Microsoft’s Code-contracts fails on the part of having to install an add-on to VS2010 to actually put the Code-contract requirements to use. Until it’s a first class citizen of VS, it’s not useful in my eyes. Enough about that.

Why

Easy, to provide a clean API for validating arguments and a solution that throws natural argument exceptions with informative exception messages.

NuGet

It’s distributed using NuGet. You could consume it as a normal lib or as a source distribution. The later gives you the possibility of incorporating it into any existing “common core lib” that you already use for these kind of utils.

Some code

The API is continuously evolving and it hasn’t reached v1.0 yet, hence there might be braking changes, but that’s not very likely. There will probably only be new stuff added.

Without parametername

Will throw ArgumentNullException or ArgumentException without ParameterName.

public void MyMethod(string myString, int myInt, Guid myGuid)
{
    Ensure.That(myString).IsNotNullOrEmpty();
    Ensure.That(myInt).IsInRange(10, 20);
    Ensure.That(myGuid).IsNotEmpty();
}

Using Lambdas

Note, that since the value also is extracted via the Lambda there’s a compile of it, hence the other overloads or more performant.

public void MyMethod(string myString, int myInt, Guid myGuid)
{
    Ensure.That(() => myString).IsNotNullOrEmpty();
    Ensure.That(() => myInt).IsInRange(10, 20);
    Ensure.That(() => myGuid).IsNotEmpty();
}

Providing parameter name explicitly

Will work as the first example with the difference of including the parameter name in the exception’s _ParameterName _property.

public void MyMethod(string myString, int myInt, Guid myGuid)
{
    Ensure.That(myString, "myString").IsNotNullOrEmpty();
    Ensure.That(myInt, "myInt").IsInRange(10, 20);
    Ensure.That(myGuid, "myGuid").IsNotEmpty();
}

More information and sourcecode is available on the GitHub site.

//Daniel

Tagged , ,

I like to dance

A couple of years ago me and my wife took dance lessons. I thought it was very challenging since I had no idea of how to get my body to move like the instructor showed us, in pace with the music and at the same time leading my partner and protecting her on the dance floor from getting hit by other dancers. After weeks and months of practice I managed to master dance after dance and it just got more and more of a joy. Why? Simple! I had learned to master the steps. Learned how to feel the music. Learned how to plan and create a choreography that was suitable for me and my partner – for our team.

As a software developer I have made many mistakes. I have been in scenarios where I have been to junior for the responsibility given to me. I have produced bugs and misinterpreted specifications. I have produces architectural solutions that didn’t make the cut. For every failure though, I have gone home, sat my self down, trying to evaluate and come up with other ideas. Studying other developers work to see alternative solutions. Everything for evolving my skills. And that’s a good start but still, no matter how smart solutions you produce, they mean nothing if the team isn’t on the same track. It doesn’t matter if you understand how every part works together. What matter is that everyone in the team feels comfortable with the solution and feel that they can be productive. It should also be easy to introduce new members in the team. That’s something I think is foreseen. To much focus is put on creating “hyped solutions” using the latest frameworks and “buzziest” patterns without looking at the maturity of the team. Without thinking about the developers that will administer the software when all consultants and/or initial staffing has left.

Balance. Yes, I know it’s a vague word, but you must try to balance the complexity of the solution seen to the team. That’s one of the most important thing I have learnt and used. Listen, back down and adapt and you will conquer. I know it’s tempting to be “cool”, but sometimes a step in another direction might be better. Keep this in mind and remember to be open minded.

//Daniel

Tagged , ,

C#, Clean up your Linq-queries and lambda expressions for Non Linq to objects

This is an update to my post “C#, Clean up your Linq-queries and lambda expressions”, where I got a comment that it will not work other than against Linq to objects. That is somewhat true. It will work but the query will fetch all posts from the database and then apply the where clause to objects in memory which should trigger a sign DANGER!. In my case I only needed in memory but I thought, why not provide an example….

This example will be targetting Entity framework Code first, CTP 5.

The test

[Test]
public void AgainstEfCodeFirstCtp5()
{
    using (var dbContext = new StorageContext())
    {
        DbDatabase.SetInitializer(new DropCreateDatabaseAlways<StorageContext>());

        foreach (var customer in _customers)
            dbContext.Customers.Add(customer);

        dbContext.SaveChanges();
    }

    using (var dbContext = new StorageContext())
    {
        //Will not call the database
        var bonusCustomers = dbContext.Customers.Where(new IsBonusCustomer());

        //Will invoke call to database
        CollectionAssert.AreEqual(_expectedBonusCustomers.Select(c => c.Id), bonusCustomers.Select(c => c.Id));
    }
}

The sql-query will not be executed against the database until I access the deferred executable collection “bonusCustomers”. The query will look like this (interceptet with the Sql Profiler).

SELECT 
[Extent1].[Id] AS [Id]
FROM [dbo].[Customers] AS [Extent1]
WHERE
(
	(0 = [Extent1].[NumOfYearsAsMember])
	AND
	([Extent1].[CashSpent] >= 3000)
)
OR
(
	([Extent1].[NumOfYearsAsMember] > 0)
	AND 
	(
		([Extent1].[CashSpent] / [Extent1].[NumOfYearsAsMember]) >= 5000
	)
)

It matches our rule of the c-sharp code, but the generated Sql will of course brake, since it will give a divide by zero for the customers with less than one year of membership, but that is not the point of this blog post.

The changes from the last blog post

Instead of letting the implicit operator return a Func<T> it now returns Expression<Func<T>>. To let the Evaluate member work I also compiled the lambda to a Func.

public class ExpressionRule2<T>
    : IRule<T> where T : class
{
    public Expression<Func<T, bool>> Expression { get; private set; }

    public Func<T, bool> Compiled { get; private set; }

    public ExpressionRule2(Expression<Func<T, bool>> expression)
    {
        Expression = expression;
        Compiled = expression.Compile();
    }

    public static implicit operator Expression<Func<T, bool>>(ExpressionRule2<T> item)
    {
        return item.Expression;
    }

    public bool Evaluate(T item)
    {
        return Compiled(item);
    }
}

Yes, I know, not the best naming with ExpressionRule2 but it’s a quick hack to get the blog post compatible with non linq to object sources. There’s actually nothing more to it. Of course I have put up a custom DbContext for Entity framework Code-first CTP 5, as well as added an Id to the customer.

public class StorageContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }

        public StorageContext()
            : base(@"data source=.;initial catalog=NiceLambdas;integrated security=SSPI;")
        {
        }
    }

public class Customer
{
    public int Id { get; set; }

    public int NumOfYearsAsMember { get; set; }
    public int CashSpent { get; set; }
}

Why this solution at all?

What this gives me:

  • A name to my rule.
  • I can have interfaces represent it and have a factory or IoC returning variations of the rule.
  • I can isolate it for testing.

Happy coding!

//Daniel

Tagged , , , ,

C#, Clean up your Linq-queries and lambda expressions

Part 2How to get it to work against non Linq to object sources

Last week something caught my eyes. How scattered business logic can become if you let your binary expressions be used “here and there” when matching entities against certain rules. Logic for a single entity, e.g Customer can be used all over your codebase. This article will show you a way to get around this and to get a central repository of rules/predicates that can be applied to entities and makes your daily unit test writing easier. I will use simple operator overloading for accomplishing this.

The example code can be downloaded here.

I have put together a testfixture with test going from ugly code to “more” beautiful code. The example is fictive and therefore not the best example for what I’m showing. The problem below might be best solved with simple code as Customer.IsBonusCustomer() which then contains the logic for determening this. But I want to show you a way to handle this if you instead want the logic outside the customer and don’t want the lambdas/linq queries scattered all over your codebase.

In the code I have made use of Func but you can of course use Expression<Func> if you need to parse the expression tree.

The problem

Identify customers that are considered to be bonus customers.

Rules:

  • A customer that has been member shorter than one year and has spent 3000 or more in our store.
  • A customer that has been member for one year or more and where money spent divided by the years is equal to or greater than 5000.

The solution

Lets start with the entity example which of course intentionally have been made simple.

public class Customer
{
    public int NumOfYearsAsMember { get; set; }
    public int CashSpent { get; set; }
}

The ugly ways

First, lets be clear: “No I don’t mean the Linq or Lambda syntax in it self when I say ugly”. I mean ugly as you get “small” (in best case) pieces of logic lying around in your queries.

[Test]
public void TheUglyWayUsingLinq()
{
    var bonusCustomers = 
        from c in _customers
        where
        (c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000) ||
        (c.NumOfYearsAsMember > 0 && (c.CashSpent / c.NumOfYearsAsMember) >= 5000)
        select c;

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}

[Test]
public void TheUglyWayUsingLambdas()
{
    var bonusCustomers = _customers.Where(c =>
        (c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000) ||
        (c.NumOfYearsAsMember > 0 && (c.CashSpent / c.NumOfYearsAsMember) >= 5000));

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}

Both of these examples are rather simple (seen to what you meet in different enterprise applications) but yet rather hard to read. Well of course not if you concentrate on just the algorithm but as a whole it is. First lets make it somewhat nicer. Lets extract the selectors so that we get a name in the Linq and Lambda expressions.

[Test]
public void SomewhatNicerUsingLinq()
{
    Func<Customer, bool> isFirstYearBonusCustomer = c => 
        c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000;

    Func<Customer, bool> isAfterFirstYearBonusCustomer = c => 
        c.NumOfYearsAsMember > 0 && ((c.CashSpent / c.NumOfYearsAsMember) >= 5000);

    var bonusCustomers = from c in _customers
                            where isFirstYearBonusCustomer(c) ||
                            isAfterFirstYearBonusCustomer(c)
                            select c;

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}

[Test]
public void SomewhatNicerUsingLambdas()
{
    Func<Customer, bool> isFirstYearBonusCustomer = c =>
        c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000;

    Func<Customer, bool> isAfterFirstYearBonusCustomer = c =>
        c.NumOfYearsAsMember > 0 && ((c.CashSpent / c.NumOfYearsAsMember) >= 5000);

    var bonusCustomers = _customers.Where(c =>
        isFirstYearBonusCustomer(c) ||
        isAfterFirstYearBonusCustomer(c));

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}

Slightly better and if we put the selectors in a class they can be reused.

The more beautiful way

Now lets write a test in a way I would like to read it.

[Test]
public void MaybeMoreBeautifulUsingRules()
{
    var bonusCustomers = _customers.Where(new IsBonusCustomer());

    CollectionAssert.AreEqual(_expectedBonusCustomers, bonusCustomers);
}

How can I accomplish this?

Well it’s easy. Create a class that implements a implicit operator overloading for Func which then allows you to pass instances of this class into the IEnumerable.Where function.

public class ExpressionRule<T> 
    : IRule<T> where T : class
{
    public Func<T, bool> Expression { get; private set; }

    public ExpressionRule(Func<T, bool> expression)
    {
        Expression = expression;
    }

    public static implicit operator Func<T, bool>(ExpressionRule<T> item)
    {
        return item.Expression;
    }

    public bool Evaluate(T item)
    {
        return Expression(item);
    }
}

The next step is to create one representing the rule at hand IsBonusCustomer.

public class IsBonusCustomer 
    : ExpressionRule<Customer>, IIsBonusCustomer
{
    public IsBonusCustomer()
        : base(c =>
                (c.NumOfYearsAsMember == 0 && c.CashSpent >= 3000) ||
                (c.NumOfYearsAsMember > 0 && (c.CashSpent / c.NumOfYearsAsMember) >= 5000))
    {
    }
}

Again, if you need to parse the expression tree the ExpressionRule class would look something like this.

public class ExpressionRule<T>
    : IRule<T> where T : class
{
    public Func<T, bool> Expression { get; private set; }

    public ExpressionRule(Expression<Func<T, bool>> expression)
    {
        //Do something with the lambda
        //...
        //...
        Expression = expression.Compile();
    }

    public static implicit operator Func<T, bool>(ExpressionRule<T> item)
    {
        return item.Expression;
    }

    public bool Evaluate(T item)
    {
        return Expression(item);
    }
}

Easier to test

By having the solution above you open up your code to be easy to test. Lets say we have a PriceLocator that uses this rule to determine the price for a customer. We want to test the discount algorithm and be sure that the rule for determining if a customer is a bonus customer, always evaluates to true.

public class PriceCalculator
{
    public IIsBonusCustomer IsBonusCustomer;

    public PriceCalculator()
    {
        IsBonusCustomer = new IsBonusCustomer();
    }

    public decimal Calculate(decimal basePrice, Customer customer)
    {
        return IsBonusCustomer.Evaluate(customer)
                    ? basePrice * 0.8M : basePrice;
    }
}

Now I can put up a fake and inject it to the price locator, so that the code under test becomes isolated.

[Test]
public void CanBeEasilyBeFaked()
{
    var alwaysBonusCustomerRuleFake = new Mock<IIsBonusCustomer>();
    alwaysBonusCustomerRuleFake.Setup(f => f.Evaluate(It.IsAny<Customer>())).Returns(true);

    var priceCalculator = new PriceCalculator { IsBonusCustomer = alwaysBonusCustomerRuleFake.Object };
    var priceWithDiscount = priceCalculator.Calculate(100, new Customer());

    Assert.AreEqual(80, priceWithDiscount);
}

I can now of course also test the IsBonusCustomer rule.

[Test]
public void CanBeTestedInIsolation()
{
    var firstYearBonusCustomer = new Customer { CashSpent = 3000, NumOfYearsAsMember = 0 };

    var rule = new IsBonusCustomer();

    ExpressionAssert.EvalAsTrue(rule, firstYearBonusCustomer);
}

That’s it. Again the examples above might be overkill since you could have placed methods directly on the Customer, but….

Why this solution at all?

What this gives me:

  • A name to my rule.
  • I can have interfaces represent it and have a factory or IoC returning variations of the rule.
  • I can isolate it for testing.

//Daniel

Tagged , ,

C# and abusive dynamic APIs

I read a blogpost last night about dynamic code and how it could be used to handle arguments passed in to a method, and it got me thinking. I exchanged a couple of tweets with about this and I really didn’t get any wiser, hence I guess I have to go and try out some Ruby, but thats another day.

The thing I don’t get is how someone, in a public API designed for use by others, generally can think dynamic args or a collection of args can be received by a method which in turn just selects X of the passed in args without even bother looking at the rest of them? How are the consumer supposed to know what to name the keys/members to get their elements processed? If a method takes a collection of arguments, I as a consumer, kind of expect all the elements to be visited. I don’t wan’t to crank up Reflector and look at the source to see what I should name the keys and members to get them processed.

Lets start with an over exaggerated example using say a generic Dictionary.

public class AddressParser
{
    public string BuildAddress1(Dictionary<string, string> args)
    {
        return string.Format("Street: {0}\r\nZip:{1} City: {2}\r\nCountry: {3}.",
            args["Street"], args["Zip"], args["City"], args["Country"]);
    }

    public string BuildAddress2(dynamic args)
    {
        return string.Format("Street: {0}\r\nZip:{1} City: {2}\r\nCountry: {3}.",
            args.Street, args.ZipCode, args.City, args.Country);
    }
}

So, how would you as a consumer know that the args being processed are:”Street, ZipCode, City and Country”. Should you test all of the common names of address attributes? “StreetName, StreetNumber, Zip, Area….”

I asked:

And how would I now as a consumer that every element has been visited?

Because you’re an awesome tester and you don’t rely on your API method signatures to tell you what to do.

So pull up your sleeves and put on that monkey suite. It’s time to do some exploratory API programming.

To be fair, the dynamic example has one huge advantage. If I miss to pass something to the Dictionary method I get a not so informative KeyNotFoundException. If I instead use the dynamic example I get a more detailed exception:

'f__AnonymousType0' does not contain a definition for 'Country'

Ok, of course you could be a good citizen and document your method but we all know where that ends up.

I don’t know about you, but in this scenario, I don’t want to be forced to be a Curious George programmer.

//Daniel

Tagged

Let business scenarios be reflected in your code

I’m working with a project where I use something I call “scenarios”. The idea is that each scenario in the businessmodel is represented by three classes.

Command – Contains the inputdata needed to perform the Scenario. Is optional since the operation might not need any input parameters.

Scenario – Validates and Executes the Command and is where the logic is kept. It is not ment to cross boundraries. It also provides an eventmodel, publishing events for Validated, Executed etc.

Result – Contains the command (input data), any exception and violations generated by the Validation- or Execution step in the scenario, as well as scenariospecific outputdata.

The reason for why I wan’t this is that I want each scenario easily detected in my coding-model. I want to be able to quickly look in the solutionexplorer in the Scenarios namespace, and directly see what the system targets in the domain. By looking at the Command- and the Result-classes I can also see what the scenario accomplishes. By isolating each scenario-flow-logic to one single class, I hopefully achieve a more cohesive and readable class.

An example

The example is not drawn from the business model since it’s about signing in to the system, hence it’s sort of an indirect business scenario, since you can’t run the “Place order scenario” if you’r not an authorized user.

The shown example is about logging in to the system and is using OpenId in an Asp.Net Mvc 2 application. This concludes two steps. First a request has to be initiated to an OpenId-provider. Second, we need to handle the callback request from the provider, hence the enum LogOnSteps. (I guess it would have been more clear to put these in two different scenarios.)

[Serializable]
public enum LogOnSteps
{
    Initiate,
    Finalize
}

The Command contains properties that are required for Step 1 as well as a flag indicating where we are in the process so that the validation and execution in the scenario-class nows what to do.

[Serializable]
public class LogOnCommand
{
    public LogOnSteps Step { get; set; }

    public string OpenId { get; set; }

    public string ReturnToUrl { get; set; }

    public LogOnCommand(LogOnSteps step)
    {
        Step = step;
    }
}

The implemented scenario extends a baseclass so that boilerplate code for catching exceptions etc. is kept away. The scenario is defined in an interface and is accessed via an IoC-container.

public class LogOnScenario : Scenario<LogOnCommand, LogOnResult>, ILogOnScenario
{
    public IOpenIdAuthenticationService AuthenticationService { protected get; set; }

    public IMembershipService MembershipService { protected get; set; }

    public LogOnScenario(
        IOpenIdAuthenticationService authenticationService,
        IMembershipService membershipService)
    {
        AuthenticationService = authenticationService;
        MembershipService = membershipService;
    }

    protected override IViolations OnValidate(LogOnCommand command)
    {
        var violations = new Violations();

        if (command.Step == LogOnSteps.Initiate)
        {
            violations.AddIf(command.OpenId.IsNullOrEmpty(), new Violation(
                ResourceStrings.LogOnCommand_OpenId_IsRequired, CommandName, "OpenId"));
            
            violations.AddIf(command.ReturnToUrl.IsNullOrEmpty(), new Violation(
                ResourceStrings.LogOnCommand_ReturnToUrl_IsRequired, CommandName, "ReturnToUrl"));
        }

        return violations;
    }

    protected override LogOnResult OnExecute(LogOnCommand command)
    {
        return command.Step == LogOnSteps.Initiate
            ? HandleInitiateStep(command)
            : HandleFinalizeStep(command);
    }

    private LogOnResult HandleInitiateStep(LogOnCommand command)
    {
        var logOnResult = new LogOnResult
        {
            Command = command,
            MvcActionResult = AuthenticationService
                                .InitiateMvcAuthentication(command.OpenId, command.ReturnToUrl)
        };

        return logOnResult;
    }

    private LogOnResult HandleFinalizeStep(LogOnCommand command)
    {
        var logOnResult = new LogOnResult { Command = command };
        var openIdAuthentication = AuthenticationService.AuthenticateRequest();

        if (openIdAuthentication.Violations.IsNotEmpty)
        {
            logOnResult.Violations.Add(openIdAuthentication.Violations);

            return logOnResult;
        }

        var mapper = IoCContainer.Instance.GetInstance<IObjectMapper>();
        var identity = mapper.Map<OpenIdAuthentication, Identity>(openIdAuthentication);
            
        logOnResult.UserSession = new UserSession(identity);
        logOnResult.Member = MembershipService.GetByOpenId(identity.OpenId);

        return logOnResult;
    }
}

Since we want every scenario to return any caught exception and violations, we have a base-class that the ScenarioResults can extend, which contains members for this.

[Serializable]
public class LogOnResult : ScenarioResult
{
    public LogOnCommand Command { get; set; }

    public ActionResult MvcActionResult { get; set; }

    public IUserSession UserSession { get; set; }

    public Member Member { get; set; }
}

Now if we take a look at some consumer code, I think it gets a bit easier to understand, and the application controller only handles logic for controlling which view and viewdata should be presented.

Step 1 – Initiate the scenario

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogOn(LogOnViewModel viewModel)
{
    if (!ModelState.IsValid)
        return View(viewModel);

    var returnToUrl = Url.AbsoluteUrlFromAction("AuthenticateOpenIdRequest");
    var command = new LogOnCommand(LogOnSteps.Initiate)
                      {
                          OpenId = viewModel.OpenId, 
                          ReturnToUrl = returnToUrl
                      };

    var scenario = IoCContainer.Instance.GetInstance<ILogOnScenario>();
    var scenarioResult = scenario.Execute(command);

    if (!scenarioResult.Succeeded)
    {
        this.HandleScenarioResult(scenarioResult);
        return View(viewModel);
    }

    return scenarioResult.MvcActionResult;
}

Step 2 – Finalize the scenario

public ActionResult Authenticate()
{
    WebUserSession.SetGuest();

    var viewModel = new LogOnViewModel(OpenIdProviders);
    var command = new LogOnCommand(LogOnSteps.Finalize);
    var scenario = IoCContainer.Instance.GetInstance<ILogOnScenario>();

    var scenarioResult = scenario.Execute(command);
    if (!scenarioResult.Succeeded)
    {
        this.HandleScenarioResult(scenarioResult);

        return View("LogOn", viewModel);
    }

    if (scenarioResult.Member == null)
        return View("SetupNewMembership");

    if (!scenarioResult.Member.IsActivated)
        return View("ConfirmMembership");

    WebUserSession.Set(scenarioResult.UserSession);

    if (WebUserSession.Current.IsAuthenticated)
        return Redirect("~/");

    return View("LogOn", viewModel);
}

That’s it.

//Daniel

Tagged , ,

Use extension methods to let your enums hold the logic.

I often stumble upon code checking values on enumerations to determine the state of some object or rule. At best, this code is extracted and put in a helper or utils class of some sort. Don’t! Use extension methods instead. It let’s you provide a name for the condition (rule) that you are checking, and it put’s it together with the enumeration.

Example
Lets say I have an enumeration with storage providers. Each provider might be able to store data virtually, hence I need the possibility of determining if it’s capable of this.

[Serializable]
public enum StorageProviders
{
    LuceneIo = 0,
    LuceneVirtual = 1
}

public static class StorageProvidersExtensions
{
    public static bool IsVirtual(this StorageProviders provider)
    {
        return provider == StorageProviders.LuceneVirtual;
    }
}

I can now act on the enumeration value it self.

...connectionInfo.ProviderType.IsVirtual()...

//Daniel

Tagged ,

Tip – When writing custom assertion methods – Keep your assertion stack trace clean

I have bumped in to a couple of custom assertion methods which lets the assertion stack trace contain the assertion method itself. Hence, if I use, e.g. Testdriven.Net, I might double-click on the wrong line and end up in the assertion method, instead of the test. It’s really easy to prevent this, just add the DebuggerHiddenAttribute (read more) to the assertion method.

Example

First, lets be clear. The taken example is not realistic and there’s already support for array assertions but lets pretend I want an assertion method that asserts string arrays and ensures that:

  • the number of elements are the same
  • the order of the elements are the same

I’m using Galio, MbUnit and Testdriven.net

The test

[TestFixture]
public class DummyTests
{
    [Test]
    public void GetAsSortedStringArray_WhenManyParams_ReturnsSortedStringArray()
    {
        var values = new int[] {0, 4, 5, 1, 3, 2};
        var expectedResult = new[] {"0", "-1", "2", "3", "4", "5"};

        var dummy = new Dummy();
        var sortedStringArray = dummy.GetAsSortedStringArray(values);

        ArrayAssert.AreMatches(expectedResult, sortedStringArray);
    }
}

The test will fail (which is expected in this blogpost) since The expected element number "2" should have value "1" and not "-1"

What is wrong with the test

The implementation of Dummy

public class Dummy
{
    public string[] GetAsSortedStringArray(params int[] values)
    {
        return values.Select(v => v.ToString()).OrderBy(v => v).ToArray();
    }
}

The Assertion method

public static class ArrayAssert
{
    public static void AreMatches(string[] expectedValues, string[] actualValues)
    {
        var numOfExpected = expectedValues.Count();
        var numOfActual = actualValues.Count();

        if (numOfExpected != numOfActual)
            throw new AssertionException(string.Format(
                @"The expected values and the actual values have 
                different number of elements.
                Expected: '{0}'; Actual: '{1}'.", numOfExpected, numOfActual));

        for(var c = 0; c < numOfExpected; c++)
        {
            var expected = expectedValues[c];
            var actual = actualValues[c];

            if(!expected.Equals(actual))
                throw new AssertionException(string.Format(
                    @"The values in element-position '{0}' are not the same.
                    Expected: '{1}'; Actual: '{2}'.", c, expected ?? "", actual ?? ""));
        }
    }
}

What’s wrong?

The result of the assertion will be:

Testdriven.Net – Result
Testdriven.Net - Result - Not friendly

Gallio – Result
Gallio - Result - Not friendly

I have tried to mark the lines that I think pollutes the result. It’s the lines stating something like:

Class1.cs(44,0): at ClassLibrary1.ArrayAssert.AreMatches(String[] expectedValues, String[] actualValues)

This is not of interest. And by adding the attribute DebuggerHidden I will get another assertion result, which in my opinion is slightly more friendly.

The corrected assertion method

public static class ArrayAssert
{
    [DebuggerHidden]
    public static void AreMatches(string[] expectedValues, string[] actualValues)
    {
        ...
    }
}

More friendly assertion result

Testdriven.Net – Result
Testdriven.Net - Results - Friendly

Gallio – Result
Gallio - Results - Friendly

Nothing more to say.

//Daniel

Tagged , , ,

Some thoughts about O/RMs.

1. The Mappings:
Whether it’s rolled via XML, attributes, or some fluent API, it’s something you as a developer have to maintain, so even if you let the conceptual object-model drive the design of your database, you are implicitly DDL through the mappings.

2. HQL, EQL, XQL:
It is just a DSL over SQL, which means that I still write SQL, just in another dialect. So if I can not use IQueryable, I will still write SQL, which I probably could have done more conveniently in Management Studio against my SQL DB.

3. POCO:
We are so concentrated on getting “pure” classes and have troubles acceptiong a generated code base either created by a designer or T4 templates. We feal that these kind of solutions are highly dangerous. Why? If you handcraft your entities yourself, you usually end up with “POCO” classes that have to extend a certain base-entity and implement value-compare and INotify, etc. Isn’t it clearer and easier for future maintenacestaff, to open a designer, get an overview, being able to easilly maintain references, attributes etc? What’s so terrifying of getting the properties/state generated for you?

Thoughts?

//Daniel

Tagged

Where are your Scenarios in your domain?

If you design your entities before you design your scenarios, you are data-driven! The Scenarios are primary – The entities are secondary!

- Daniel Wertheim

My words of what I think is wrong in many projects, and thats what this post is about.

Definition of Scenario

a postulated sequence of possible events

- http://wordnetweb.princeton.edu/perl/webwn?s=scenario

In computing, a scenario is a narrative describing foreseeable interactions of types of users (characters) and the system. Scenarios include information about goals, expectations, motivations, actions and reactions. Scenarios are neither predictions nor forecasts, but rather attempts to reflect on or portray the way in which a system is used in the context of daily activity.

http://en.wikipedia.org/wiki/Scenario_(computing)

I tend to bump into situations where I meet people that are proclaiming they are adapting DDD in their projects and that they are writing object-oriented systems. As I’m always interested in learning, I fire of a couple of questions about what they mean by DDD and OO. I will not bother you with the dialog, but will rather skip to a summarize of the conversation. and present five of the artifacts that they think significates that they are conforming to DDD which I think is well worth to notice and discuss about:

  • They are object-oriented
    Meaning “that they are not using datasets anymore to keep track of the state and simple validation.”
  • They have POCO entities
    Meaning “that they have an OR/M that to some extent hides some of the artifacts of dealing with persisting the entities.”
  • They have repositories
    Meaning “there’s at least one repository per aggregate root (most often more), dealing with CRUDs.”
  • They have domain-services
    Meaning “they have some objects named [Entity][Service/Manager] which contains logic and calls to repositories”.
  • They have a model
    Meaning “they have a bunch of the above objects collaborating together”.
  • Ok, so I have designed system like these to. I will probably do it again. But lets look at what I mean by “systems like these” and what I think is wrong.

    Whats wrong?
    So I think we tend to create a model with an emphasis on entities, which more or less becomes a representation of tables in a traditional database. I like to define these entities as “an intelligent data-row” and by intelligent I mean that it might have simple validation of state and some logic for aggregating values, e.g. “Sum of the contained order lines in the order”. Furthermore we tend to create a bunch of services/managers that is named: “[Entity][Service/Manager]“; which to some extent holds together the flow – which most often means, they do some simple validation/rule-evaluation and they interact with a repository. I think these Services/Manager-classes arise from a mental mind of the developer looking like this: “The entity must be POCO and can’t have anything to do with persisting entities. I’ll just create a service that calls the repository and since I’m working with my order-entity, I’ll name it “OrderService”.

    Again, we end up here because we are thinking objects and state and how the objects correlate to each other. And when sitting there, performing TDD with a shallow understanding of the domain; it’s probably the easiest way to get started. Classic example: “Customer places a new order” => “OrderService.PlacerOrder” which receives an order entity with some contained lines and a customer. So my question to you then is: “What exactly is OrderService in the business”? If it is the customer that makes the request, why can’t it be “Customer.PlaceNewOrder”? Or a domain-object named something that mimics the scenario/process, e.g.: “PlaceNewOrder” or “OrderRegistration”.

    To sum it all up: The scenarios/processes in the domain is the core of the business. It’s what make the business unique and is what they are competing with against other competitors. This is what should drive your design. Without a fair understanding of the domain you will risk, getting data centric. The Domain should drive the design of your model, not TDD. Get a deep knowledge of the business and it’s processes and not only the binary rules and the state. These are the aspects that should be reflected in your code.

    //Daniel

    Tagged , , , ,
    Follow

    Get every new post delivered to your Inbox.