Archive

Archive for the ‘Software Development’ Category

Two Week Tetris Applying Otazo’s Truths to Managing Development

March 25, 2010 1 comment

Two Week Tetris

March 25th | 2010

Two Week Tetris: Applying Otazo’s Truths to Managing Development

Managing a development team is a lot like maneuvering falling blocks in Tetris; the blocks of work never stop, they often need to be rotated mid-course, and as you go the shapes don’t always easily match up.

Applying the “truths” from Dr. Karen Otazo’s book, “The Truth About Being a Leader”, is effective for meeting the challenges of coordinating development; it offers key advice for maximizing your figurative score. As team lead for the product team, I manage a two-pair development team that tackles fixes and features for our company’s products. Being an Agile shop, we use Test-Driven Development with paired programming and a Scrum sprint structure. The main responsibility of a team lead is to produce high quality software at the fastest sustainable pace. Using a modified Scrum process, we employ a two-week sprint system where the development calculates points (block of work) for each story (requirement / feature) from the product owner and ultimately commits to getting a chunk of points/stories done for that dev cycle. It is these blocks of work that come off feeling like Tetris with the goal to clear the stories from the task board getting them all to “Done” (Code Complete, Reviewed, and QA’d). Otazo’s truths on the Player/Coach role—sharing forward thinking and managing the mental bandwidth—offer insight into winning in a leadership role.

Maintaining the Player / Coach Role

One of the challenges of a team lead is the constant straddle of the Player/ Coach role. Karen Otazo summaries this with Truth 8: “Player/Coach is a Tricky Role, So Make Sure That You Do Both Well” and questions when you should focus on being a player and when being a manager, to maximize the team’s output. Our team’s paired programming format helps me integrate with the team and gives each developer a voice for their own creativity and innovation. When pairing, the team lead is in the player role and has to defend his code choices and be open to alternative approaches. Pairing provides the benefits of learning from the lead’s experience while fostering the best collective approach. In the management role, the focus is on tracking the stories that are being completed, keeping the queue full, and occasionally stepping in on a pair disagreement.

Shared Vision

One way I keep a successful flow of the task board is by sharing my vision of the events coming up next. Otazo makes the case for this with Truth 19: “Playing Out the Tape Helps Others Prepare for the Future.” Truth 19 argues effective leaders learn to fast-forward by establishing a vision of what they see the future being. During the development sprint this means steering in the right blocks of work and expressing what would fit best for the next block. The taskboard is also designed with this in mind. By having, in addition to the In Process portion, the On Deck stories for the next chunk of work and the backlog visible, developers can get a quick sense of what’s in the pipeline. Telling the team how I see the board playing out helps the team get more lines cleared and avoid the gaps that form as developers remain focused on a single work stream.

Fill Your Mental Bandwidth

I have found Otazo’s first truth to be both necessary and demanding ; “More-Responsible Roles Require More Mental Bandwidth.” Most of my responsibility comes down to keeping track of everything for the development space while mentally organizing the requirements to stand in for the product owner and the customer. Going from developer to team lead, I have a new appreciation for the coordination that is required in all the stuff outside of getting the development done, and the significance of brainstorming / prep for the next sprint. Being able to maintain a handle on all the moving features and issues keeps the team on the right path and allows the product owner to trust the production process.

My Truth: Avoid Too Much To Clear

My advice is: put thorough thought into each story to obtain an accurate estimate, and avoid the clog of “almost” finished stories. When we take on too many stories or fail to plan completely for difficult tasks, just like Tetris, the task board is full of tasks and stories in process, but too full to be able to clear them all out by the end of the cycle. The stories on the board take on an oblong, ill-fitting shape, as Developers would much rather start a new code task than pick up code review or QA. The tasks don’t get cleared to Done and this quickly sours the sprint as every story is code complete but QA has to be carried over.

As team lead, I help mitigate the choke points by providing direction for the constant goal of clearing a story before taking on another one. By limiting the items in process or number of items allowed in a column, such as in Kanban, I keep the team driving to pull a story all the way across the board. And by implementing a proper planning phase and continually striving to complete the row and clear that difficult line—I achieve a consistent flow.

Tucker Croft is a Team Lead at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

Bringing Plausible Deniability to Development: the Strategy Pattern

July 30, 2009 3 comments

July 30th 2009 | David Cooksey

Bringing Plausible Deniability to Development: the Strategy Pattern

If the template pattern is a benevolent dictator the strategy pattern is a politician concerned with plausible deniability: Don’t tell me the details, just do it. The strategy is defined solely in terms of its inputs and outputs.

Let’s say you are writing a program that cuts checks for employees. The code that handles the physical printing of the checks is complete, all that remains is determining how much to print on the check for each person. The company contains both salaried and hourly employees in addition to salesmen whose pay is based on commissions. Also, the company sends out holiday checks to all employees at various times of the year based on how the company performed recently.

You want to be flexible, so your payment generator is designed as a windows service that polls a PaymentRequest table periodically. It then examines the type of payment to determine how the amount should be calculated. The next step is to write and organize implementations of the different ways to calculate payments.

The design should be flexible enough that it makes adding new payment types as simple as possible, while also providing as much flexibility as possible with respect to implementation details. You don’t want to mandate that a particular step in calculation occur, because you don’t know what future payment types might require.

This is where the strategy pattern comes into play. You can use a simple interface that defines your payment strategy to streamline your code and cut down on the number of decision points. All you really need is a block of code that looks at the payment record and decides what strategy to use. The other code should be the same regardless of the payment type. Here is some pseudo code for what this would look like:

public interface IPaymentStrategy
  {
    double CalculateAmount(IPaymentRequest paymentRequest);
  }

public class PaymentGenerator
  {
    public void LookForPaymentRequests()
    {
      IPaymentRequest[] paymentRequests= GetNewPaymentRequests();
      foreach (IPaymentRequest paymentRequest in paymentRequests)
      {
        Process(paymentRequest);
      }
    }

    private void Process(IPaymentRequest request)
    {
      IPaymentStrategy strategy;
      switch (request.PaymentType)
      {
        case 1:
          strategy = new HourlyPayment();
          break;
        case 2:
          strategy = new SalariedPayment();
          break;
        case 3:
          strategy = new CommissionPayment();
          break;
        case 4:
          strategy = new HolidayPayment();
          break;
        default:
          strategy = new FlatPayment();
          break;
      }
      double amount = strategy.CalculateAmount(request);
      WriteCheck(amount);
    }
}

IPaymentStrategy defines a simple interface that accepts an IPaymentRequest and returns the amount calculated. The PaymentGenerator pulls in new payment requests from a table. It picks the appropriate payment calculation method based on the payment type Id and uses it to generate the correct payment amount.

If a new payment type is added, it requires no code restructuring other than the creation of a new class that inherits from IPaymentStrategy, a new case block, and a new row in the PaymentType table.

This code structure places no restrictions at all on the implementation details of the individual payment types. If a lot of code is shared among the payment types, inheritance, a common dependency, or any other method can be used to reduce or eliminate code duplication entirely at the discretion of the programmer.

This makes it easier to ignore the gritty details of payment calculation which a more strict pattern such as the Template Pattern would force you to consider.

Flexible

Maintainable

Plausibly Deniable

The Strategy Pattern.

David Cooksey is a Senior .NET Consultant at Thycotic Software, an agile software services and product development company based in Washington DC. Secret Server is our flagship password management software product.

The Template Pattern A Benevolent Dictator

July 22, 2009 1 comment

Ben Yoder the Template Pattern

July 22nd 2009 | Ben Yoder

The Template Pattern: A Benevolent Dictator

The Template Pattern is unique because of the level of control maintained at the top level. An abstract class controls the steps and the possible default implementations of the algorithm, but it’s kind enough to let its subclasses modify the behavior in pre-defined methods.

Similar design patterns, and specifically the Strategy pattern, prescribe the encapsulation of individual algorithms and logic into single classes that can be called independently.

The Template Pattern is useful for avoiding code duplication and keeping code maintainable. When you copy and paste the same—or very similar—logic across code you should encapsulate that code to prevent drift. This is when a benevolent dictator class helps clean up your code.

Drift may occur due to a change in requirements. Imagine you are working on an application that has a requirement to create an audit record whenever a user edits information on a form. During version 1.0, you created an AuditLogger class that simply writes a record to the database.

public class AuditLogger
{
    public void InsertAuditRecord(){...}
}

However, for version 2.0 you have this requirement: whenever a regular user edits information on certain forms, an email should be sent to a system admin. Additionally system admins, due to their higher level of access, require separate security audit records to be created elsewhere. As quick fix, you could add methods called EmailNotification() and InsertAdminAuditRecord() to AuditLogger which can be called from the Save() method on the forms depending on the user type.

But after that’s been wrapped up, requirements change and a new power user type has been added to the system. This user type requires a single audit record, but this time there is no need to send an email notifying administrators. You could create a mess on all your forms by adding methods to AuditLogger and making decisions on the form, or you could encapsulate what differs between the auditing logic per user-type, recognizing that requirements may change again.

In this case, AuditLogger currently looks like:

public class AuditLogger
{
    public void InsertAuditRecord(){...}
    public void InsertAdminAuditRecord(){...}
    public void EmailNotification(){...}
}

In refactoring this to a Template Pattern, you’ll notice that InsertAuditRecord() and InsertAdminAuditRecord() are essentially the same logical step. By default, users should write a standard audit record, but administrators should write a special audit record. So in creating your Template class, you should define just a single virtual InsertAuditRecord() method that inserts a standard record and a virtual Notify() method that sends emails by default.

public abstract class AuditLogger
{
    public void Audit()
    {
        InsertAuditRecord();
        Notify();
    }

    public virtual void InsertAuditRecord()
    {
        Console.WriteLine("Auditing User...");
    }

    public virtual void Notify()
    {
        Console.WriteLine("Emailing Admin...");
    }
}

Next, create concrete implementations to define specific implementations of the methods, where needed. Your standard AuditLogger will simply be a concrete that extends AuditLogger with the default implementations, but your Admin and PowerUser loggers will override separate methods.

public class StandardAuditLogger : AuditLogger
{
}

public class AdminAuditLogger : AuditLogger
{
    public override void InsertAuditRecord()
    {
        Console.WriteLine("Auditing Admin User...");
    }

    public override void Notify()
    {
        return;
    }
}

public class PowerUserAuditLogger : AuditLogger
{
    public override void Notify()
    {
        return;
    }
}

The advantage of this is as requirements change, your specific logic is encapsulated, but you can continue to define default implementations. So if everyone except admins needs to send email notifications, you could pull the Notify() override out of the PowerUserAuditLogger and be done. And if another step was to be added to the audit process, a default method could be defined and called in the template without having to touch anything else.

The Template pattern becomes less useful the more the algorithms diverge. If you find yourself overriding every single method of the abstract Template class and adding in a lot of hook methods to control the flow from the subclasses, then the Template Pattern may not be your best choice. But if it looks like your code could use some iron fisted governing, let the Template call all the shots—and see how much simpler maintenance becomes.

Ben Yoder is a Senior .NET Consultant at Thycotic Software, an agile software consulting and product development company based in Washington DC. Secret Server is our flagship password management software product.

StrictMock vs. DynamicMock: What are You Testing Here Anyway?

July 16, 2009 3 comments

Dynamic Mock vs Strict Mock

July 16th 2009 | Jimmy Bosse

StrictMock vs. DynamicMock: What are You Testing Here Anyway?

Here at Thycotic, we are TDD enthusiasts and pair developers. Test Driven Development and Pair Programming go together like chocolate and peanut butter, especially when you tackle a brand new piece of functionality and practice some green-field Ping-Pong programming.

For those unfamiliar with the concept of Ping-Pong programming, it’s a fun way to develop a new piece of business logic when you are not sure what the best method of implementation will be.

To start, one of you writes a failing test. The other makes the test pass, and then writes the next failing test (refactoring as needed). You make that test pass and write a new failing test. The goal of the session is to write the smallest amount of code possible, then try to write a test that effectively tests the desired functionality while providing a challenge to your pair. The session is easy at first, but as the tests move toward satisfying the more complicated requirements of the business, the exercise becomes more challenging.

Once your code becomes suitably complex, you’ll start to have multiple classes with dependencies—and with these dependencies come mock tests.

Then you have to decide: StrictMock or DynamicMock?

The problem with Strict Mocks is that you are required to set up your entire mock dependency far beyond the scope of the subject/system under test (SUT).

Take the following example.

[Test]
public virtual void ShouldSubscribeToViewEventWhenConstructed()
{
    MockRepository mocks = new MockRepository();
    IView mockIView = mock.StrictMock<IView>();
    mockView.SomeEvent += delegate{};
    LastCall.Constraints(Is.NotNull());
    mocks.ReplayAll();
    IPresenter presenter = new Presenter(mockView);
    mocks.VerifyAll();
}

To implement a presenter:

public class Presenter : IPresenter
{
    private IView _view;

    public Presenter(IView view)
    {
        _view = view;
        BindToEventsOn(_view);
    }

    private void BindToEventsOn(_view)
    {
        _view.SomeEvent += SomeEventHandler;
    }

    private void SomeEventHandler()
    {
        //Do something…
    }
}

The test is now green because you’ve subscribed to the event. But now that you’ve bound to the view in your constructor, you must always expect a call in your test whenever you mock IView with a StrictMock. This will make your tests verbose and it will be difficult to determine the actual SUT in each test.

Another issue is this: When you use a StrictMock you are essentially telling your pair what to program. Let’s say you and your pair sit down to create a calculator business object that must be able to add numbers together.

Your pair writes the following test:

[Test]
public virtual void ShouldReturnFourWhenGivenThreeAndOne()
{
    int firstNumber = 3;
    int secondNumber = 1;
    int expectedSum = 4;
    MockRepository mocks = new MockRepository();
    IAdder mockIAdder = mock.StrictMock<IAdder>();
    IAdderFactory mockIAdderFactory = mock.StrictMock<IAdderFactory>();
    Expect.Call(mockIAdderFactory.Create()).Return(mockIAdder);
    Expect.Call(mockIAdder.Add(firstNumber, secondNumber)).Return(4);
    mocks.ReplayAll();
    ICalculator calculator = new Calculator(mockIAdderFactory);
    int result = calculator.Add(firstNumber, secondNumber);
    mocks.VerifyAll();
    Assert.AreEqual(expectedSum, result);
}

Well, there’s nothing to think about here is there? If this is the way you want to write tests, invest some time and write a tool that will parse your test and create your business object for you. The test tells you “use the factory, create an adder, call the add method on the adder and return the result. Where’s the fun in that? What are you actually testing? Does it really matter how the calculator does what it needs to do?

Actually, I think the above test could be a good one if it was created three days into the calculator object—when you were refactoring the different pieces of the calculator into distinct service objects.

But right now, all you need is a calculator that can add two numbers together:

[Test]
public virtual void ShouldReturnFourWhenGivenThreeAndOne()
{
    ICaclulator calculator = new Calculator();
    Assert.AreEqual(4, calculator.Add(3, 1));
}

This should be your first failing test. I don’t care how you add it, but by golly you’d better give me back 4 when I give you 3 and 1.

I love DynamicMock because I am a believer that a test should test a very specific piece of code. Recently, however, I came across this poignant counterpoint that shattered my DynamicMock utopia. I had written tests and an object that looked something like this:

[Test]
public virtual void ShouldReturnTrueIfBigIsTrueAndBadIsFalse()
{
    MockRepository mocks = new MockRepository();
    IDataWrapper mockIDataWrapper = mock.DynamicMock<IDataWrapper>();
    SetupResult.For(mockIDataWrapper.IsBig).Return(true);
    SetupResult.For(mockIDataWrapper.IsBad).Return(false);
    mocks.ReplayAll();
    IDad dad = new Dad();
    Bool result = dad.IsABigBad(mockIDataWrapper);
    mocks.VerifyAll();
    Assert.IsTrue(result);
}

[Test]
public virtual void ShouldReturnTrueIfBigIsFalseAndBadIsTrue()
{
    MockRepository mocks = new MockRepository();
    IDataWrapper mockIDataWrapper = mock.DynamicMock<IDataWrapper>();
    SetupResult.For(mockIDataWrapper.IsBig).Return(false);
    SetupResult.For(mockIDataWrapper.IsBad).Return(true);
    mocks.ReplayAll();
    IDad dad = new Dad();
    Bool result = dad.IsABigBad(mockIDataWrapper);
    mocks.VerifyAll();
    Assert.IsTrue(result);
}

[Test]
public virtual void ShouldReturnFalseIfBigIsFalseAndBadIsFalse()
{
    MockRepository mocks = new MockRepository();
    IDataWrapper mockIDataWrapper = mock.DynamicMock<IDataWrapper>();
    SetupResult.For(mockIDataWrapper.IsBig).Return(false);
    SetupResult.For(mockIDataWrapper.IsBad).Return(false);
    mocks.ReplayAll();
    IDad dad = new Dad();
    Bool result = dad.IsABigBad(mockIDataWrapper);
    mocks.VerifyAll();
    Assert.IsFalse(result);
}

public interface IDataWrapper
{
    public IsBig { get; }
    public IsBad { get; }
}

public class Dad : IDad
{
    public virtual bool IsABigBad(IDataWrapper dataWrapper)
    {
        return dataWrapper.IsBig || dataWrapper.IsBad;
    }
}

My test was green and I was happy, but my pair informed me that a bug could be introduced accidentally and no one might ever notice:

public interface IDataWrapper
{
    public IsBig { get; }
    public IsBad { get; }
    public IsFat { get; }
}

public class Dad : IDad
{
    public virtual bool IsABigBad(IDataWrapper dataWrapper)
    {
        return dataWrapper.IsBig || dataWrapper.IsBad || dataWrapper.IsFat;
    }
}

Because a DynamicMock will not throw an exception for unexpectedly calling IsFat and will return false as the default for the bool base type, my tests will all remain green. But in production my code might not work as expected.

There is seldom a single solution that works in every situation. I have learned to find the proper place for both Dynamic and Strict Mocks in my TDD toolbox and hope that this encourages you to think more deeply about your own toolbox.

Jimmy Bosse is a Senior .NET Consultant and Team Lead at Thycotic Software, an agile software consulting and product development company based in Washington DC. Secret Server is our flagship password management software product.

The Facade Pattern – Don’t Talk to Strangers

June 18, 2009 2 comments

Ben Yoder the Facade Pattern

June 19th 2009 | Ben Yoder

The Facade Pattern – Don’t Talk to Strangers

The Facade and Adapter patterns are two closely related and easily confused designs. Both patterns create a layer between two interacting classes but the objective of each is significantly different.

While the Adapter pattern encapsulates the communication between two classes, the goal of the Facade pattern is to simplify wiring in a set of actions leveraging a complex subsystem of code, such as a group of legacy classes, or a third party vendor’s class library or API. If you ever need to integrate a third party system or an open source library and find yourself entangled in outside dependencies and overly-complicated sets of method calls, a Facade refactoring can help you.

There’s a good chance you’ve created a facade pattern on occasion without realizing it. As an oversimplified mechanical analogy—when you start a car, you don’t go through the separate steps of combining an electrical spark with gasoline in the engine cylinder while simultaneously cranking the engine to achieve compression. Instead of worrying about the complicated series of steps involved in making a car start, you simply turn a key which creates some magical action that starts a car.

The engine ignition switch is our facade class. It hides the ugly workings of the engine from us and we simply say “Make Go” and it works.

    public class SparkPlug
    {
        public void Spark(){…}
    }
    public class FuelPump
    {
        public void PumpFuel() {…}
        public void ShutOffFuel(){…}
    }
    public class Starter
    {
        public void Crank() {…}
    }
    //Encapsulates starting logic
    public class IgnitionSwitchFacade
    {
        public void StartEngine()
        {
            FuelPump pump = new FuelPump();
            SparkPlug plug = new SparkPlug();
            Starter starter = new Starter();
            pump.PumpFuel();
            starter.Crank();
            plug.Spark();
        }
    }
    //Client Code that interfaces with the Facade
    class You
    {
        static void Main(string[] args)
        {
            IgnitionSwitchFacade ignitionSwitch = new IgnitionSwitchFacade();
            ignitionSwitch.StartEngine();
        }
    }

This bit of code is contrived, but it demonstrates what’s so powerful about the Facade pattern and how it differs from the Adapter.

While the Adapter is concerned about sitting between the client and an interface, the Facade’s aim is to encapsulate common logic or instructions of a subsystem for the client’s consumption.

The goal of the Facade is simplicity. It provides a common gateway to the class library which can be easily modified and called rather than dealing directly with the logic and classes it hides.

Read David Cooksey’s The Adapter Pattern, A Code Diplomat

Ben Yoder is a Senior .NET Consultant at Thycotic Software, an agile software consulting and product development company based in Washington DC. Secret Server is our flagship password management software product.

Registration forms: Breaking down the barriers between your Web visitor and your product

May 6, 2009 5 comments

Jonathan Cogley: Registration forms: Breaking down the barriers between your Web visitor and your product

May 6th 2009 | Jonathan Cogley

Registration forms: Breaking down the barriers between your Web visitor and your product

You’ve just found a really neat utility you’d like to download. So…you click ‘download’, and bam! You find yourself gazing at a mile-long ‘registration’ form coupled with email verification:

On one hand, you really want to try out this neat new utility.

On the other hand, you really don’t want to have to part with a load of personal information; fill in a dozen ‘required’ fields; dream up a user name, a display name, and a unique password; and type your email address twice.

Jonathan Cogley: Registration forms: Breaking down the barriers between your Web visitor and your product

What is the value of this additional information anyway? Is this company going to display your real name to anyone? Why do they need your address if you’re not mailing anything to you? Why do they need your phone number if they have no reason to call you? What are they going to use your ‘prefix’ for? This information is of no real use to them and it represents a series of barriers between you and the product you desire.

What information should be required in order to complete a simple download?

Every ‘required’ field on your form is one more barrier between your Web visitor and your product. Request only the information you need in order to perform the action for the user. While it’s tempting to use the opportunity to capture other useful information about your target market, online audiences have become more protective of their personal data and may decide that their privacy is worth more than your download.

Also reconsider the email validation – does it really matter to force a valid email address by sending an email to it and delaying the process? A customer who is genuinely interested is likely to give their real email address anyway.

Thycotic’s Web site registration form requires only an email address, full name, and password. We don’t verify your email address since that isn’t foolproof (most people have a free webmail junk account for such things). In the past we rejected email from free Web mail providers (Gmail, Yahoo, Hotmail, etc) but now we ask for a phone number instead. If a customer is genuinely interested in our product, then they actually appreciate a call to discuss their problem and receive an appropriate solution.

So take the time to consider your audience, then reduce barriers by requesting only information you genuinely need to successfully process the transaction.

Jonathan Cogley is the CEO of Thycotic Software, an agile software consulting and product development company based in Washington DC. Secret Server is our flagship enterprise password management product.Are you on Twitter? Follow Jonathan