Organizing BDD Context/Specs For Findability

Finding Classes With Resharper

It's no secret that I'm a huge fan of Resharper. It rocks. I don't like to code without it. One of the many features that I love is the Ctl-N shortcut to find a class. Resharper gives you this handy-dandy little search box:

image

What I really love about this box is the ability to not know the entire class name when searching. If I know my class involves the word "Super" and "Sexy", I can type the letters "SS" and the search box will pull up any class with matching uppercase letters.

image

The same holds true for lowercase letters. I can do "SupSeV" and get results just matching those Upper/lower combinations.

BDD Context Specifications Have Long Strange Names

It's also no secret that I'm a fan of BDD and Context/Specifications. I love the language oriented nature of context specifications and how it's easy for me to see what the behavior of the system is supposed to be, in any given context. I've been using BDD style syntax for many months now, and have amassed quite a collection of Context/Specification tests in my current code - especially with 4 other developers using BDD syntax. After having done several hundred tests in this manner, I've found that there is a pretty significant disconnect between how I use SpecUnit.NET and how Resharper's class finder works - the names of my specification classes. Look at this specification class name for example:

image

How am I supposed to search for this class name? I can't remember all those words, none of them are capitalized, and all those underscores are probably going to throw Resharper off in my search string.

Organizing Context/Specification Classes By Parent Class/File Name

To combat this problem, what I've started doing recently is throwing in the use of a parent specification class with the same name as the specification file that I'm working in. Since our team has standardized on the "Specs" suffix for all of our BDD tests, I know that a file name of "ValidationSpecs.cs" will have a class called "ValidationSpecs". In the file itself, my specs will be subclasses, like this:

image

With the file name ValidationSpecs and the parent class ValidationSpecs, I now have much fewer words to remember and a much greater chance that I'll be able to use Resharper's class finder feature. All I need to know that I'm looking for the tests that deal with validation, so by our naming convention, I can type in "VS" or "ValSpecs" and get the list back that I want:

image



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Dems Race to Block Bush Environmental Rule Changes

White House has until Friday to publish changes to rules regarding endangered species for them to take effect.

Categories: FoxNews Science and Technology | News | Science | Science News | Technology | Technology News
Article :: Other Glimpses of Second Life Use

Sandy Carter describes creative marketing uses of Second Life by IBM.

Categories: Computers | InformIT | InformIT Articles | Programming | Technology
Functionally dynamic?

I was just playing with this tonight, but I don't know it's worth anything.  I thought of it after some conversations with Matt Podwysocki back at KaizenConf on how do apply some functional ideas in C#.  First, I started with a simple class:

public class OriginalProduct
{
    public decimal Price { get; set; }
    public decimal Cost { get; set; }

    public decimal CalculateProfit()
    {
        return Price - Cost;
    }
}

To do anything interesting, functional-wise, like swapping implementations or doing things like decorators is annoying or impossible.  But if I went this (albeit weird) direction:

public class Product
{
    public decimal Price { get; set; }
    public decimal Cost { get; set; }

    public Product()
    {
        CalculateProfit = calculateProfit;
    }

    public Func<decimal> CalculateProfit { get; set; }

    private decimal calculateProfit()
    {
        Console.WriteLine("Calculating profit");
        return Cost == 0 ? 0m : Price - Cost;
    }
}

Yes, weird.  But tests look rather normal, except a function is a property:

[Test]
public void No_change()
{
    var product = new Product {Price = 11, Cost = 10};

    product.CalculateProfit().ShouldEqual(1m);
}

Because you can invoke delegate instances directly, it looks like I'm calling a function on the type.  I can do some interesting things with some simple decorator extensions:

public static class DelegateExtensions
{
    public static Func<T> Before<T>(this Func<T> func, Action before)
    {
        return () =>
                   {
                       before();
                       return func();
                   };
    }
    public static Func<T> After<T>(this Func<T> func, Action after)
    {
        return () =>
                   {
                       T value = func();
                       after();
                       return value;
                   };
    }
}

And now I can decorate my the functions at will:

[Test]
public void Decorator_fun()
{
    var product = new Product { Price = 11, Cost = 10 };

    product.CalculateProfit =
        product.CalculateProfit
                .Before(() => Console.WriteLine("Before"))
                .After(() => Console.Write("After"));

    product.CalculateProfit().ShouldEqual(1m);
}

This outputs:

Before
Calculating profit
After
1 passed, 0 failed, 0 skipped, took 1.05 seconds.

That's just some simple decorator implementation.  Finally, I can swap out implementations at runtime:

[Test]
public void Straight_up_replacement()
{
    var product = new Product { Price = 11, Cost = 10 };

    product.CalculateProfit = () => 1500;

    product.CalculateProfit().ShouldEqual(1500m);
}

It's still not dynamic typing, as I can't add new members at runtime.  I have no idea if this is useful or not, as the structure is rather weird, and you'd need to do some interesting things to get polymorphism in play.  But, it might have some interesting applications in some strange scenario.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
PTOM: The Composite Design Pattern

The Composite Design Pattern

This post talks about the Composite Design Pattern and is part of Pablo's Topic of the Month - November: Design Patterns. A Composite is a tree structure where each node can be represented as a common type so that they can be acted on in a consistent manner, regardless of their concrete implementations. This allows a consumer of the composite to avoid the complexity of having to distinguish the objects individually. I believe that the posts for PTOM are going to centered around a coffee shop, but I'm having a difficult time thinking of a good composite example around that, so let's say I'm building coffee machines instead.

Lets pretend that I have a model of a coffee machine and all of its parts. Many of the parts are logical and are made up of only child parts. I might have a class that looks something like the following (simplistically implemented for example purposes):

public class CoffeeMachine
{
    public FluxCapacitor FluxCapacitor { get; set; }
    public PowerCord PowerCord { get; set; }
}
 
Lets say FluxCapacitor is a composite part made up of child parts and those child parts may have their own child parts. I want to build a class that allows me to output all the given parts for a machine, but I don't want my part list generator to know about each specific details of the machine or any of its specific parts. If I did couple the list generator to those implementations, that would force me to modify the list generator every time we added or changed a part, which would be a violation of OCP. We can solve this problem by creating an interface that lets us traverse our structure as a composite.
 
public interface IPart
{
    IEnumerable<IPart> GetChildParts();
}

You will notice that the IPart returns child instances of other IParts. This gives us a recursive structure and lets us act on that structure as a composite. By implementing this interface on all of our parts, when can then walk the hierarchy and perform operations without knowing the details of each implementation. We can implement this on our CoffeeMachine and our other parts like the following:

public class CoffeeMachine : IPart
{
    public FluxCapacitor FluxCapacitor { get; set; }
    public PowerCord PowerCord { get; set; }

    public IEnumerable<IPart> GetChildParts()
    {
        yield return FluxCapacitor;
        yield return PowerCord;
    }
}

public class FluxCapacitor : IPart
{
    public Switch Switch { get; set; }
    public PowerBooster PowerBooster { get; set; }

    public IEnumerable<IPart> GetChildParts()
    {
        yield return Switch;
        yield return PowerBooster;
    } 
}

public class PowerCord : IPart
{
    public IEnumerable<IPart> GetChildParts()
    {
        yield break;
    }        
}

Now we can easily build a part list generator that uses a recursive method to walk through the hierarchy and outputs the names of the parts.

public class PartListGenerator
{
    public void OutpAllParts(IPart part, TextWriter textWriter)
    {
        OuputAllPartsByLevel(part, textWriter, 0);    
    }

    private static void OuputAllPartsByLevel(IPart part, TextWriter textWriter, int level)
    {
        textWriter.WriteLine("{0}{1}", new string('\t', level), part.GetType().Name);

        foreach (var childPart in part.GetChildParts())
        {
            OuputAllPartsByLevel(childPart, textWriter, level + 1);
        }
    }
}

By running our CoffeeMachine through this class, we end up with something similar to the following output:

CoffeeMachine
    FluxCapacitor
        Switch
        PowerBooster
    PowerCord

You may have noticed that we have the GetChildParts() method implemented on the leaf parts as well (see PowerCord). This may be a slight violation of ISP, but it is side effect free and it does not violate LSP therefor it does not bother me too much. In the real world, IPart would probably have other functionality and you could split out the GetChildParts() into a separate interface such as ICompositePart which would only be implemented by non leafs. This would require the PartListGenerator to know about IParts and ICompositeParts which may or may not be desirable. It's really a trade off here as to what makes the most sense for your needs.
 
There are several variations of the Composite Design Pattern and my example can probably be considered one of them. The Composite can also be combined with other patterns such as the Specification or Command patterns. You can find lots of other examples on the web and in Design Patterns : Elements of Reusable Object-Oriented Software. I recommend picking up that book for more information on the Composite and many other must know patterns.
 



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Article :: A Career Changer's Checklist - 12 Common Sense Questions to Find Your Career: How Willing Are You to Change? (Flexibility!)

Warren Wyrostek presents the top 10 questions to assess your attitude, willingness, and flexibility as you prepare to make a career change.

Categories: Computers | InformIT | InformIT Articles | Programming | Technology
Who do you wanna Jott? Twitter

So I recently started twittering... or tweeting. I'm not sure what the correct lingo is, so hook me up if you know. It all started a while back when James announced that he was the newest Twit. He mentioned a WPF client called Witty, and I wanted to see what it was all about. So I setup a Twitter account to play with the app. After I had my fun, I never deleted my account. Or at least I never looked into how to delete my account.

About a week ago I received and email that a couple of people were following me on Twitter. Man that's flattering to read:

Hi, mo_khan.
Kyle Baley (kbaley) is now following your updates on Twitter.
Check out Kyle Baley's profile here:
http://twitter.com/kbaley
You may follow Kyle Baley as well by clicking on the "follow" button.
Best,
Twitter

Whaa... a celeb is interested in what I'm up to? *blush* So I jumped in, and so far it's been pretty fun. I found another service called "Jott". Jott's pretty cool, because I can call in to a number and I get an automated message that says:

"Who do you want to jott?"

I say ... "Twitter". Then I record my voice message.

Jott then takes that message transcribes it in to text, pushes it up to my twitter page, and drops a tinyurl to the actual audio. Sweet... that saves me a few pennies worth of text messages. But there's more...

I'm one of the poor saps who pay to much for mobile service up here in Canada, eh! I subscribe to Rogers Wireless, and the plan called "My5". I get to make unlimited phones calls to the 5 numbers that are in My5? So I put Jott on My5, and now I can shoot off messages to everyone for....

Free Ninety Nine.... well almost! If you're young, fabulous and ghetto broke (it aint funny) like myself then you ought to give Jott a try!



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Lazy Loaded Interceptors

Patterns of Enterprise Application Architecture defines Lazy Load as:

An object that doesn't contain all of the data you need but knows how to get it.

 

A while back I was trying to figure out how to lazy load objects from a container, so that I didn't need to depend on the objects dependencies needing to be wired up in the correct order. The syntax I was looking for was something like the following....

 
container.AddProxyOf(
    new ReportPresenterTaskConfiguration(),
    new ReportPresenterTask(
        Lazy.Load<IReportDocumentBuilder>(),
        Lazy.Load<IApplicationSettings>())
    );

Lazy.Load<T> will return a proxy in place of an actual implementation. This is just a temporary place holder that will forward the calls to the actual implementation. It wont load an instance of the actual type until the first time a call is made to it.

public class when_calling_a_method_with_no_arguments_on_a_lazy_loaded_proxy : lazy_loaded_object_context
{
    [Observation]
    public void should_forward_the_original_call_to_the_target()
    {
        target.should_have_been_asked_to(t => t.OneMethod());
    }

    protected override void establish_context()
    {
        target = dependency<ITargetObject>();

        test_container
            .setup_result_for(t => t.find_an_implementation_of<ITargetObject>())
            .will_return(target)
            .Repeat.Once();
    }

    protected override void because_of()
    {
        var result = Lazy.Load<ITargetObject>();
        result.OneMethod();
    }

    private ITargetObject target;
}

So when the method "OneMethod" is called on the proxy. It should forward the call to the target, which can be loaded from the container. The implementation depends on Castle DynamicProxy, and looks like the following...

public static class Lazy
{
    public static T Load<T>() where T : class
    {
        return create_proxy_for<T>(create_interceptor_for<T>());
    }

    private static LazyLoadedInterceptor<T> create_interceptor_for<T>() where T : class
    {
        Func<T> get_the_implementation = resolve.dependency_for<T>;
        return new LazyLoadedInterceptor<T>(get_the_implementation.memorize());
    }

    private static T create_proxy_for<T>(IInterceptor interceptor)
    {
        return new ProxyGenerator().CreateInterfaceProxyWithoutTarget<T>(interceptor);
    }
}

internal class LazyLoadedInterceptor<T> : IInterceptor
{
    private readonly Func<T> get_the_implementation;

    public LazyLoadedInterceptor(Func<T> get_the_implementation)
    {
        this.get_the_implementation = get_the_implementation;
    }

    public void Intercept(IInvocation invocation)
    {
        var method = invocation.GetConcreteMethodInvocationTarget();
        invocation.ReturnValue = method.Invoke(get_the_implementation(), invocation.Arguments);
    }
}

public static class func_extensions
{
    public static Func<T> memorize<T>(this Func<T> item) where T : class
    {
        T the_implementation = null;
        return () => {
                   if (null == the_implementation) {
                       the_implementation = item();
                   }
                   return the_implementation;
               };
    }
}

"resolve" is a static gateway to the underlying IDependencyRegistry. This idea was totally inspired by JP's strongly typed selective proxies. If you haven't already, you should definitely check it out.

Download the source.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Article :: Eclipse Infrastructure

This chapter gives you a more in-depth understanding of Eclipse and its structure in relation to creating plug-ins.

Categories: Computers | InformIT | InformIT Articles | Programming | Technology
Announcing: ALT.NET Online Open Meeting

For a few months now, Zachariah Young, various other folks, and I have been meeting online via Skype+SharedView or LiveMeeting (depending on the size of the crowd) every Wednesday night to discuss various .NET and general technology-related issues. We met at the Agile Austin Open Spaces 2008 conference where I made the foolish statement, out loud, "If anyone wants to remote pair and learn some of this stuff, I'll pair with you, just name the time and IP address" (or something like that).  Zach took me up on that offer and the rest was history.

Anyhow, it turned into a weekly thing with various other folks joining in or not and so we decided that we should open it up a little more and make it a bigger deal.

Last Week's Meeting

Last Wednesday (12-NOV-2008), I posted on Twitter to see if anyone was interested and we had 15 or 16 people show up (I think at it's height it was bigger, but I can't remember the exact number).  The topics included:

  • Basic Subversion usage (how to arrange repositories, when to branch, how to branch, etc)
  • NHibernate usage (Unit of Work pattern, IRepository<T> vs. IRepository.FindAll<T>(), etc)
  • Managing NHibernate ISession and Unit of Work instances through StructureMap (or any IoC)
  • Oslo, M, DSLs, object models, etc
  • Several others which I can't remember right now

Encouraged by this success, we decided to open it up again, but publicize it more to see if that would be a good thing.

This Week's Meeting

I'm not sure if having a lot more people is a good thing or not, but I figured we won't know until we try it and conclude whether it was a success or failure.

Topics

The best part: There are no set topics!  As you'll see below, this meeting will follow an "open" format (in the spirit of Open Spaces – though not necessarily in form since it's 100% online).  The idea is that YOU (all of us) organize it according to what interests YOU.  We may not get to cover everything everybody wants, but there will likely be another one of these next week or next month.

In order to see the meeting in case no one has anything to talk about, I'm prepared to discuss the following things:

  • StructureMap and IoC in general
  • NHibernate, Fluent NHibernate, and ORM in general
  • Internal DSLs and language-oriented programming with C#

Hopefully others will attend that can speak on subjects that other attendees are interested in. If you have a subject you're particularly jazzed about right now and can update the rest of us on it, please come with some talking points just in case! That'd be awesome!

Logistics

The plan is connect via LiveMeeting (Mac users see note below) at around 9:00PM CST (2100 UTC –0600) for about 2-3 hours on Wednesday, November 19th, 2008.

LiveMeeting URL:

http://snipr.com/5qilf

NOTE: Please hit this URL and make sure you have the LiveMeeting client installed BEFORE the meeting starts. This will help prevent you from missing the first 5-10 minutes.

NOTE: Yes, we will try to record it, but sometimes it doesn't work that great, so not guarantees.

NOTE: Mac Users: LiveMeeting doesn't support Audio on the Mac (for some reason) and I'm told that the audio support in VMWare Fusion doesn't work right through it either. I'm told that booting into Parallels works, however. That's all I know about that, if you need help, please post in the comments and hopefully another Mac user can help (or, you can buy a PC that supports audio without hassle ;))

 

How to Sign Up

Don't!  Just show up. If things get out of hand, we'll figure something else out.  NOTE: No refreshments or meals will be provided, so you're on your own! ;)

Multiple LiveMeetings?

I have no idea whether 5 people will show up or 100.  If you access to a LiveMeeting account and can spare the time, it'd be great maybe to have multiple meetings going so that the "Law of Two Feet" can apply properly (see below).  Please let me know if you're interested in doing this and we can coordinate.  Or, just set one up and announce it during the main meeting. REMEMBER: This is self-organizing, so YOU folks figure it out! I'll help coordinate or arrange where necessary, but ultimately YOU get it going.

Kinda like Open Spaces, but not exactly

We'll try to stay true to the Open Space Technology tenants. OST requires a facilitator and (usually) multiple rooms to break out the sessions, so we won't have that and therefore we won't be technically OST, but we can still try to abide by it's higher points, namely:

    1. Whoever comes is the right people: this alerts the participants that attendees of a session class as "right" simply because they care to attend
    2. Whatever happens is the only thing that could have: this tells the attendees to pay attention to events of the moment, instead of worrying about what could possibly happen
    3. Whenever it starts is the right time: clarifies the lack of any given schedule or structure and emphasizes creativity and innovation
    4. When it's over, it's over: encourages the participants not to waste time, but to move on to something else when the fruitful discussion ends

Also, with OST there is a concept of "The Law of Two Feet Clicks": If at any time during our time together you find yourself in any situation where you are neither learning nor contributing, use your two feet clicks. Go to some other place where you may learn and contribute.

Normally, the Law of Two Feet Clicks works better when you have another room/session to go to. Since we only have ONE LiveMeeting room, I'm not quite sure how that'll work.  As I mentioned above, if you have access to a Live Meeting hosting account, maybe we can get multiple rooms running.



Categories: Computers | CSharp | Dot Net | Los Techies | Programming | Technology
Article :: The Google Phone: Understanding Android

Michael Miller takes a look at what Android is and what the first Google phone will look like.

Categories: Computers | InformIT | InformIT Articles | Programming | Technology
Two-Faced Kitten Born in Australia

A kitten with two faces that meows out of both mouths at the same time was born Wednesday near Perth, Western Australia.

Categories: FoxNews Science and Technology | News | Science | Science News | Technology | Technology News