Archive for category fluent interface

My first Fluent Interface experience

The starting point

A pretty standard API involves a factory and an add-method. In between the New/Create method call, we usually set some properties on the created child object. When we’re done, we add it to the collection of its parent/container. The factory and the parent/container are often collocated. Below is the standard API I had as a starting point.

IRibbonItem button = m_view.RibbonMenu.CreateButton();
button.Name = "Save";
button.Image = GetImage("save.jpg");
m_view.RibbonMenu.AddItemLink(button);

IRibbonPage structurePage = m_view.RibbonMenu.CreateRibbonPage();
structurePage.Name = "Standard";
m_view.RibbonMenu.AddPage(structurePage);

IRibbonGroup bsGroup = structurePage.CreateGroup();
bsGroup.Name = "BS";
structurePage.AddGroup(bsGroup);

IRibbonItemGroup moveButtons = m_view.RibbonMenu.CreateButtonGroup();
bsGroup.AddItemLink(moveButtons);

IRibbonItem outButton = m_view.RibbonMenu.CreateButton();
outButton.Image = GetImage("out.jpg");
outButton.Name = "Out";
moveButtons.AddItemLink(outButton);

IRibbonItem inButton = m_view.RibbonMenu.CreateButton();
inButton.Image = GetImage("in.jpg");
inButton.Name = "In";
moveButtons.AddItemLink(inButton);

 

Look at the above code and then tell me you haven’t done it before. Bleh… In the above code I’m setting up a ribbon menu structure (as found in various Office 2007 products). The code is tedious to write, and there’s a lot of it. So what if I tried to wrap the API so I could set up my ribbon menu more elegantly, and how do I do that?

The result

I’m going straight to the point and I’ll show you the resulting code. (Because I’m really pleased with it and must share it!) One thing I additionally might do is to resolve the image implicitly from the name inside the configurator to make the footprint even smaller. Oh, and please don’t get hung up on the literals. I’m trying to get a concept across here, give me a break!

RibbonConfigurator.Configure(m_view.RibbonMenu).With.
    Toolbar.With.
        Button("Save", GetImage("save.jpg"));

RibbonConfigurator.Configure(m_view.RibbonMenu).With.
    Page("Standard").With.
        Group("BS").With.
            ButtonGroup().With.
                Button("Out", GetImage("out.jpg")).And.
                Button("In", GetImage("in.jpg"));

 

Next time

Some other time I’ll talk some more about Fluent Interfaces, and the makings of my RibbonConfigurator.

No Comments