fuzzelogic Solutions

February 16, 2010

Specification pattern revisited

Filed under: BDD, OO, Programming, c#, design — Tags: , — admin @ 7:09 pm

Hi!

I’ve spoken about the specification pattern before. The first thing to note is that article is on the older 1.1 stuff, so no generics.  However,in c# 3.5, we can crunch the specification pattern considerably. Here’s one idea..
First off the interface :-) [ Here's the code ]  = [ignore this 8JKPNVRYP3CT ]

public interface Ispecification<T>{
        bool is_satisfied_by(T this_item);
    }

Next the implemenation. Its not too different from the original

public class specification<T>: Ispecification<T>{
        private readonly Predicate<T> specification_predicate_test;

        public specification(Predicate<T>specification_predicate_test){
            this.specification_predicate_test = specification_predicate_test;
        }

        public bool is_satisfied_by(T this_item){
            return specification_predicate_test(this_item);
        }
    }

First off.. attach the interface. Then in the constructor give it the Predicate<T> (that’s the built in dot net predicate). In the “is_satisfied_by” method pass the item to the stored predicate and let it do the job.
That’s the specification done. Now to attend to the composite part.. the AND, OR combiniations…
Well, again, built in dot net to the rescue - extension methods..

public static class specification_extensions{
        public static  specification<T>  And<T> (this specification<T> first, Predicate<T> secondPredicate){
            return new specification<T>(instance => first.is_satisfied_by(instance) &amp;&amp; new specification<T>(secondPredicate).is_satisfied_by(instance));
        }
        public static specification<T> OR<T>(this specification<T> first, Predicate<T> secondPredicate){
            return new specification<T>(instance => first.is_satisfied_by(instance) || new specification<T>(secondPredicate).is_satisfied_by(instance));
        }
        public static specification<T> Negate<T>(this specification<T> first){
            return new specification<T>(instance => !first.is_satisfied_by(instance) );
        }
    }

Thats ok.. so how do we use it.. well. First define what specification. (our sample usage is bad invoices - pretty original :-) )

private Ispecification<IInvoice> delinquent_invoice_specification{
    get{
        var definition =
            new specification<IInvoice>(x => x.due_date.CompareTo(DateTime.Now) > 0)
                                    .And(x => x.total_amount > 1000)
                                    .And(x => x.months_over_due > 3)
                                    .OR(x => x.has_had_last_chance);
        return definition;
    }
}

And the sample usage. We have a bunch of invoices that we want to check..

public void sample_usage(){

    var all_invoices_in_our_company = new List<IInvoice>();

    all_invoices_in_our_company.Add(a_bad_invoice);
    all_invoices_in_our_company.Add(a_bad_invoice);
    all_invoices_in_our_company.Add(a_good_invoice);
    all_invoices_in_our_company.Add(a_good_invoice);
    all_invoices_in_our_company.Add(a_good_invoice);
    all_invoices_in_our_company.Add(a_good_invoice);
    all_invoices_in_our_company.Add(a_bad_invoice);

    foreach (var invoice in all_invoices_in_our_company){
        if (delinquent_invoice_specification.is_satisfied_by(invoice))
            send(invoice).to_legal_department();
    }

}

private IInvoice a_bad_invoice { get { return new Invoice(DateTime.Now.AddMonths(-10), 5000, 8, true); } }
private IInvoice a_good_invoice { get { return new Invoice(DateTime.Now.AddMonths(1), 1205, 0, false); } }

And there we have it.. crunched composite specification. [ Here's the code ]
Hope that helps
Zak

February 8, 2010

Auto mocking coolness

Filed under: BDD, OO, Programming, c#, design — Tags: , , , — admin @ 5:57 pm

Hi! All

Say a big thank you to the structure map guys :- the dependency injection framework with a bit more. It now has Auto mocking. This is great for removing the chattiness of creating mocks for your test classes, and becuase it can use the Rhino AAA style you can don’t have to explicitly define your expectations. :-)

Assume you have a the following class

public class LicenseCatalog {
// this has a dependency on an ILicenseRepository implementation
    public LicenseCatalog (ILicenseRepository repository, ILicenseUpdater updater) {
//….
}
}

Here’s a test using it..

public abstract class get_the_licenseFeature: is_a_feature_provided_by<ILicenseCatalog>{
        [Scenario][Category("in_a_scenario_where<we_get_the_license_file>")]
        public class if_the_settings_file_has_all_the_settings: in_a_scenario_where<we_get_the_license_file>{

            [Observation]
            public void it_should_tell_the_repository_to_load_the_license_file_and_update_the_license(){
                If(x => x.settings_file = new Settings(){hidden_file_name = "hidden", license_file_name = "license"})
                    .when_you_tell(x => x.the_system_under_test.get_license())
                    .observer_that(x => x.repository.was_told_to(r => r.get_license()))
                    .And (x=>x.updater.was_told_to(u=>u.update_license_file());
            }
        }

        public class we_get_the_license_file : baseContext {
            public Settings settings_file;
        }

        public class baseContext : get_the_licenseFeature{
            <strong>RhinoAutoMocker<LicenseCatalog> mocker = new RhinoAutoMocker<LicenseCatalog>();</strong>
            public ILicenseRepository repository;
            public ILicenseUpdater updater;

           protected override ILicenseCatalog create_the_system_undertest(){
// Here we can get the auto mocked dependency back.
                repository = mocker.Get<ILicenseRepository>();
                updater = mocker.Get<ILicenseUpdater>();
                return mocker.ClassUnderTest;
            }
        }
    }

So far it seems great. I don’t have to explicitly mock out the dependencies, and I can only get the ones that used in this test. Its still a little work (but less) so I’m sure its a step in the right direction.
Hope this helps
Thanks
Zak

January 5, 2010

alternatives

Filed under: BDD, OO, Programming, c#, design, projects — Tags: , , — admin @ 6:38 am

Hi All!
Since the last bdd sugar post, I’ve been using a slightly different layout on the bdd “style” tests. First off, maybe a little clarification is in order - to set the record straight. BDD - is a phase coined by Dan North and (in simplistic terms) uses a Given, When, Then grammer. The other grammer used is highlighted in the context specification style of writing these [tests]. At a high level both try to achieve the same thing of shifting the focus onto the behaviour of the system under development and to make this a design effort. Both also focus on a AAA style . There are differences, and (to me) both provide benefit.

Some terms that I’ll be using, and what they are intended to mean.
Context:   the bits that are setup and used within a particular story/feature/behaviour
Scenario : a condition/set of conditions that contribute to a scenario
Observation: the outcome of executing the Context  + Scenario.
If: the actual scenario / alternate path.
So what are the changes. Well, I’ve tried to bring the observation more into focus, and moving the context “lower” to not distract from what we want to achieve. here’s an example…

[Scenario][Context("when<transfering_money_between_accounts>")]
public class if_the_FROM_account_has_sufficient_funds : when<transfering_money_between_accounts>{
[Observation]
public void it_should_debit_the_amount_from_the_FROM_account_and_credit_it_to_the_TO_account(){
/// setup for the scenario....
/// observe the outcome..
  }

}

Thats cleared up the context, provided us a path to explore different scenarios and observe their outcomes. The only setting up we are doing at that point is for the change in the scenario. The actual context remains unchanged. Thats taken care of in the implementation of the when<transfering_money_between_accounts>. Here’s a sample of the context

 #region-[ Contexts ]-

        public class transfering_money_between_accounts : AccountManagerSpecs{
            public IMessageService message_service;
            public override void setup_the_context(){
                the_to_account = a_mock_of<IAccount>();
                message_service = a_mock_of<IMessageService>();
            }
            protected override IAccountManger create_the_system_undertest(){
                return new AccountManager(message_service);
            }

            public IAccount the_from_account;
            public IAccount the_to_account;
        }
        #endregion

BDD: Given when then
Implementing the given when then grammer we have the following

[Scenario][Context("when<transfering_money_between_accounts>")]
public class if_the_FROM_account_has_sufficient_funds : when<transfering_money_between_accounts>{
 [Observation]
 public void it_should_debit_the_amount_from_the_FROM_account_and_credit_it_to_the_TO_account(){
  Given(x => x.the_from_account = new Account(200))
   .When(x =>x.the_system_under_test.transfer(100,x.the_from_account, x.the_to_account))
      .Then(x => x.the_from_account.debit(100))
      .And(x =>x.the_to_account.was_told_to(y => y.credit(100)));
  }
}

Context Specification:
Implementing the context specification grammer we have the following

[Scenario][Context("when<transfering_money_between_accounts>")]
public class if_the_FROM_account_has_sufficient_funds : when<transfering_money_between_accounts>{
 [Observation]
 public void it_should_debit_the_amount_from_the_FROM_account_and_credit_it_to_the_TO_account(){
  If(x => x.the_from_account = new Account(200))
   .because(x =>x.the_system_under_test.transfer(100,x.the_from_account, x.the_to_account))
      .observer_that(x => x.the_from_account.debit(100))
      .observer_that(x =>x.the_to_account.was_told_to(y => y.credit(100)));
  }
}

For me, this moves the context slightly out of focus , and moves the scenario and observation more in focus. Is this better?? Well, I’m using it on a current project, and will let you know.

Hope that helps
Thanks
Zak

December 3, 2009

Bdd Sugar

Filed under: BDD, OO, Programming, c#, design — Tags: — admin @ 6:44 pm

Hi all!

Just a short one for now, I’ll update this with a few more usage samples in the near future.
You can download the bdd framework I used in most of the presentations. Its a mix of things inspired from  a couple different sources (nSpec, jpboodhoo, dan north and couple others) . It really is syntax sugar over whats already available - nUnit and rhino mocks.

In the download, I’ve included a test from the nUnit samples on MoneyBag using nUnit natively, and the same thing done using sugar. There’s also a sample on setting the expectations for the mocked objects.

From a Test first approach, BDD does provide a more fluent transition into thinking about the design of your objects, and how they collaborate with each other.

Hope this helps! (incase you missed it : you can download it from here )
Zak

November 11, 2009

Dependency Inversion Principle - DIP = POSTPONED

Filed under: BDD, OO, Programming, c#, design — Tags: — admin @ 2:57 pm

Hey !!

The last in the soliD series. Dependency Inversion Principle - DIP, will be held on the 18th November 2009 -  25th November 2009 . Due to popular demand it was decided to postpone this as many could not make it. It should be at the same place (Dimension data-Isle of man) and for around the same time - start at 6:30pm. This will also be a good time to discuss the plans for the new year and finalize the curry night, so if you can make - great!!

So, back to DIP.

 

 High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend upon details. Details should depend upon abstractions.

 Zak

 

 

 

 

Older Posts »

Powered by WordPress