Friday, January 29, 2016

How To Write More Maintainable BDD Tests

Given we are writing BDD style requirements
And we are using cucumber syntax
And we want to be able to respond to changes
When we write our requirements
Then we should write them in a way that requires as few changes to them when requirements change
And we should minimize the number of tests that are impacted by changes in requirements.


We can write such tests in the following way:

Feature: Say Hello
User Story: As a marketer, I want the system to greet users by name when they log in so that the system feels more user friendly.

Given a user with the name "bob"
When bob logs in
Then the system should say "Hello, Bob!"

Since this is a simple case, it is sufficient to write the test in this way.

For a more extensive use case that is dependent on bits and pieces of data from many sources with complex business rules, it would be better to define the test cases in the following way:

Feature: Greet User
User Story: As a marketer, I want the system to provide customized greetings to users based on their purchasing habits so that the users will be more likely to increase their overall purchases.

Wednesday, January 27, 2016

Lean Change

I've recently caught wind of Lean Change - basically a way to achieve continuous improvement. It seems the key is regular open communications. I was in the hot-seat for representing our team of five recerly in a QA event put on by CQAA(Chicago Quality Assurance Association). The lab was to put together an elevator pitch to sell BDD to an executive (for some reason we chose executive). So here's me as a developer "pitching" the event speaker acting as an executive.


We thought we'd try to sell on cost reduction, reduced time to market, improved quality, and Google does it so should we. I did my best but was met with resistance and the proposition that QAs and BAs were not doing their jobs and/or would not be needed in the new world order of BDD. Since I was a developer in a room full of QA engineers, I jokingly confessed that we would no longer need QA engineers if we used BDD.


This was basically a sweeping change approach and the pitch was a hard sell. I would not recommend selling directly to execs in most cases. Follow Lean Change - get folks involved in the change. Change a little at a time, but don't make anyone feel like they are the ones you want to change - QAs don't do this to DEV and DEV don't do this to BAs. It's really about working together as a team to resolve the issues, not about imposing change on others.

Tuesday, January 26, 2016

QA Perspective

I  gained a new perspective today after attending an event hosted by a QA group. The event was about how to influence change towards BDD (Behavior Driven Development). There was a remarkable turnout with a packed house and some folks sitting in the back without tables. I (as a developer) was in a room with a bunch of QA folks. The topic was BDD, which from my understanding so far was of more interest to developers than QA.


As it turns out...the focus from the QA standpoint was on changing the way development works. I've always viewed BDD as a fundamental change in the BAs worked. I guess it really goes to show that the ones downstream in any hand-off type of work are going to have the most interest in changing the patterns of those directly upstream.


This FURTHER reinforced this same realization I had last week when doing a penny passing experiment while in Agile training. The experiment, which seeks to show efficiency gains in iterative work over waterfall, goes like this -


setup - form groups of four, one person keeps time, the rest pass coins.


first run - pass a batch of coins one at a time from one person to the next. Each passer can't pass coins until he/she has the whole batch. Timer times from start to receiving all coins. This mimics waterfall and the coins represent deliverables.


second run - pass coins one at a time as soon as you have coins to pass. Time when the first coin reaches the end and when all coins reach the end. This is iterative.


In the waterfall process, ever one who is not passing coins is watching the coin passer. Clearly this takes longer and results in waste. In iterative, everyone is working with excitement and fervor to pass those coins along. Each is paying close attention to the upstream passer because that's where the coins are coming from. How about that?


Think of the iterative approach for a bit. If we do this over and over again, and we can talk in between each attempt - then we can make incremental improvements to the process of passing coins and seriously reduce our throughput over time. This is old-hat by now in software. Yet it seems that so many organizations are still struggling to work together to make improvements. Another antiquated notion seems to be the hand-off. Clearly the handoff leads to waste. Imagine the same penny experiment, but where each coin from the pile is passed by the whole team at once.







Wednesday, January 20, 2016

C# to JavaScript: Namespacing

Namespacing is one of the most important things you can do when using js. While namespaces are built-in constructs in C#, they are not an official part of the js language. That doesn't mean that you can't or shouldn't use them, on the contrary. In this post, I'm going to show you how to create namespaces and how to add your code to the namespace to not only avoid polluting the global context, but also to avoid potential collisions with variables and functions from other js libraries.

If you are foggy on what exactly a namespace is - my definition is that it's a logical container used to provide identity and scope to related code. If a class "Languages" in C# is defined in a namespace "TDLL.Countries", the class would be accessible from code in other namespaces via TDLL.Countries.Languages or Languages if the code file is has the "using TDLL.Countries" statement outside the class definition. Now that a baseline has been established, let's take a look at some common namespaces in js.

JQuery is definitely one of those libraries that is ubiquitous. I'd say it's the most commonly used js library in the world, but then again I don't have the numbers but I bet you've used it in some capacity. The JQuery library has a namespace - 'jQuery'. Also, that namespace has an alias '$'.

Click each "Say Hello" button in the jsbin demo below to see that both jQuery and $ are the same.


jQuery Namespace on jsbin.com

JQuery has some interesting documentation on the jQuery global namespace and the $ alias here.

And this snippet from the jQuery source code on GitHub is exactly how the global namespaces are assigned:


define( [...], function( jQuery ) {
    return ( window.jQuery = window.$ = jQuery );
});

in this case "define" is a function from RequireJS which is out of scope for this post. There's a lot that goes into the "jQuery" arg that is passed to the define callback function. It is defined in the files that are omitted in the sample shown then passed into define during build time to eventually add the function to the window object (global). jQuery gives you an option to release '$' in case there is a namespace collision with other libraries - also a good practice if you are aliasing.

Another way to create a namespace is to create the namespace first, then add everything to the namespace.


window.TDLL = {};
TDLL.learnSomething = function(){ ... };

Also you could do it using object notation like this:


window.TDLL = {
    learnSomething : function(){ ... },
};


One of the challenges in defining a namespace in either of those ways is that if the namespace is already defined, you'd basically overwrite it in subsequently loaded files. To avoid that you can do the following:


window.TDLL = window.TDLL || {};
TDLL.everyDay = function(){ ... };

This neat trick evaluates the first operand of the OR (||) expression as false if it is undefined.

Another way to do this is to use jQuery to merge your new object with the existing one.


window.TDLL = $.extend(window.TDLL, {
    everyDay : function(){ ... },
});

https://api.jquery.com/jquery.extend/

jQuery Merge Demo on jsbin.com

Using your namespace is simple (once you know it has been loaded anyways).


TDLL.learnSomething();
TDLL.everyDay();

There are ways to ensure that your namespace has been loaded (by packaging all of your javascript together), but those are beyond the topic of this post and will be a topic for a future post.

Tuesday, January 19, 2016

JavaScript Logical NOT Operator

There are some interesting things to note about the logical NOT operator in JavaScript. What I've found is that if you aren't aware of these, you may find yourself coding up some defects without knowing it. Also, being aware of some important usages may improve your code by reducing complexity.


If you are coming from a strongly typed language or just getting started in JavaScript from ground zero, you may interested to know that the NOT operator (!) has different behaviors depending on the value type that the variable represents at runtime.


For example you may have a statement:
var x = !y;
while x will be assigned a boolean value when this statement is executed, y could be any type (string, number, object, NaN, undefined, null, function) and how each is negated depends on the type.


Plus the process of negation involves first converting the value of the variable to boolean, then negating the result.


When converting to boolean, the following types are always false - null, undefined, NaN.


These are always true - object, function.


But string and number depend on the value - 0 is false and an empty string "" or '' is always false, while any other number or string is true.


An array is an object so it is always true even if it is empty.


{} is also true.


How much fun is that!?


Coming from C#, it would be great to write:


if(!x){
return;
}


instead of


if(!string.IsNullOrEmpty(x)){
return;
}


But when you cam expect x to be of any type, it would get much more complex.


In js, if you are in a position where you cannot use a guard, but need some logic to check for a value you can do the following:


if(!!x){
//do something useful
}


The underlying definition according to ecma 262 v5.1 of the ! is defined as negation of ToBoolean(GelValue(x))


where ToBoolean is defined here http://www.ecma-international.org/ecma-262/5.1/#sec-9.2


and GetValue, which is more complex, is http://www.ecma-international.org/ecma-262/5.1/#sec-8.7.1


Even though the abstract ToBoolean does not cover off on function type or array type (both object types) I listed those above for more clarity.


Since there is no ToBoolean in the JavaScript language, and there is a Boolean function (not to be confused with the constructor [new Boolean]), you'd be better of writing Boolean(x) instead of !!x for sake of clarity AND efficiency. Why have the runtime perform GetValue and ToBoolean twice?


The ecma standard defines the Boolean(x) function as simply calling the abstract ToBoolean(value)
http://www.ecma-international.org/ecma-262/5.1/#sec-15.6.1

Tuesday, January 5, 2016

Abtracting Service Calls Using the Adapter Pattern

Consider the following scenario:

Given an environment which contains the following:

UserResource - a service which allows clients to lookup users and user information.
AdminResource - a service which allows clients to lookup admin details.
TaskApplication - an application which consumes the UserResource.
DocumentApplication - an application which consumes the UserResource.
AdminApplication - an application which consumes the UserResource and AdminResource.

And each of these applications have variances in their domain specific usage of the data provided by the UserResource.

When the applications are developed
Then you may want to build domain specific classes to represent the data you are using in each application.


For Example:

Suppose the AdminApplication needs to make a distinction between SystemAdminUser and User such that it would be appropriate to create a subtype of User for the SystemAdminUser (with additional detail) which the UserResource does not provide, the additional data would come from the AdminResource.

It may be better to create a new type rather than a subtype, I'll get into why in a bit. For now let's create a subtype from the UserResource like so...


namespace AdminApplication.Objects
{
    public class SystemAdminUser : User
    {
        public int[] SystemIds { get; set; }
    }
}
.
.
.
namespace AdminApplication.Adapters
{
    public interface ISystemUserResource
    {
        SystemAdminUser GetSystemAdminUser(int id);
    }

    public class SystemUserResource : ISystemUserResource
    {
        IUserResource _userResource;
        IAdminResource _adminResource;
        public SystemUserResource(IUserResource userResource, IAdminResource adminResource)
        {
            _userResource = userResource;
            _adminResource = adminResource;
        }

        public SystemAdminUser GetSystemAdminUser(int id)
        {
             var user = _userResource.GetUser(id);
             var admin = _adminResource.GetSystemAdmin(id);
             return Mapper.MergeMap(user, admin);
        }
    }
}

And when this adapter is consumes in the application, the application code no longer will need to have the dependency on the IUserResource and IAdminResource interfaces (assume this example uses DI/IoC to inject the concrete classes) but only on the one ISystemUserResource interface. There is an added benefit to the simplicity and reuse that will make the rest of the application code flow more naturally.

However, we do have a deeper issue with this choice. To illustrate, note the following consumer of ISystemUserResource:



using AdminApplication.Adapters;
using AdminApplication.Objects;
using UserResource.Proxies;

namespace AdminApplication.Web
{
    public class HomeController
    {
        ...
    }
    ...
}

See how we have the dependency on the UserResource library due to the class being derived from one of its types? This dependency will bleed all over the application code, the test code, etc. Additionally, we may also be passing quite a bit of information around the application that we do not need by way of properties on the User instances. Additionally, though not likely in this specific scenario, there may be differences in terminology in different domains for the same thing. It would be confusing to have an EmployeeId when in the context it is always referred to as the UserId.

In order to minimize the bleeding of dependencies through consumer code, it would serve well to abstract the services behind a domain specific adapter using an Adapter pattern, Façade pattern, or a combination of both.




namespace AdminApplication.Objects
{
    public class SystemAdminUser
    {
        public int UserId { get; set; }
        public string UserName{ get; set; }
        public int[] SystemIds { get; set; }
    }
}
.
.
.
namespace AdminApplication.Adapters
{
    public interface ISystemUserResource
    {
        SystemAdminUser GetSystemAdminUser(int id);
    }

    public class SystemUserResource : ISystemUserResource
    {
        IUserResource _userResource;
        IAdminResource _adminResource;
        public SystemUserResource(IUserResource userResource, IAdminResource adminResource)
        {
            _userResource = userResource;
            _adminResource = adminResource;
        }

        public SystemAdminUser GetSystemAdminUser(int id)
        {
             var user = _userResource.GetUser(id);
             var admin = _adminResource.GetSystemAdmin(id);
             return Mapper.MergeMap(user, admin);
        }
    }
}


There will be a slight increase in code complexity at first. But the long-term benefits of being able to upgrade services without much change, testability, and the reduction of the reference bleeding will be a future asset worth investing in.

New look

I changed up the template on this blog today to make it easier for readers to find more blog content. I thought the scrolling template presented to much to look at all at once and that it would be more useful to home in on specific posts.

Monday, January 4, 2016

Constraints Increase Creativity


In this episode of StarTalk, Neil is interviewing David Byrne (formerly of the Talking Heads). Early in the interview they touch on constraints and how they affect creativity. The basic idea is that complete freedom does not stimulate creativity like constraints. Constraints give us problems to solve. This is where creativity comes into play.


What this means in the Software arena is that when we are taking on some new requirement, we should be sure that the constraints are well defined. Having well defined constraints will stimulate our creativity. If they are not, that is the starting point of our work.


On the other hand, if there are too many constraints it is possible to completely stifle creativity. It's possible to be left with only one option or zero options. If this is the case, then it may be necessary to see which constraints can be relaxed. It would be best to come with options when asking to relax constraints. It would be useless to remove a constraint which does not improve options. So maybe find out which constraints are the linchpins first.