Super Easy SPA with Durandal

I have not been very active from almost one and half year on this blog. There has been lot of learning, unlearning had happened in this duration. By the way, to revive my blog, I have invited my good friend Akhlesh Tiwari to share his overall JavaScript expertise with all of us. He happily agreed and here is the first article on his favorite subject i.e. Single Page Applications. Please do encourage the new author and share your feedback so that we all can improve.

Durandal is open source JavaScript library for SPA. Durandal is built on libs like jQuery, Knockout and RequireJS. So if you are already familiar with these libraries then very easily you can start making amazing single page apps.

Durandal is technology agnostic SPA framework so you can use it with any backend technology or make pure html/JavaScript app. To get start with Durandal all you need to get JavaScript libraries and modules and follow folder structure. So for this tutorial we take asp.net MVC4 as backend.

Get Start with Durandal in .Net

In .net we can download Durandal template from  VSIX file . Durandal is also available through nuget or you can install Durandal starter kit with this command Install-Package Durandal.StarterKit .but I will use manual setup for Durandal for better understanding of the framework. For manual setup just download all startup files. Startup project has basic examples in Durandal and navigation setup that can be modified as per requirement. After downloading startup project, we will go step by step to create Durandal app.

Step-1 Create MVC Project

First we will create mvc4 internet application in visual studio named as DurandalApp.

New Project

You can also take empty MVC project but then you have to write your own controller and starting cshtml page.

Step-2 Folder Structure

Durandal follows the folder structure to create application so here is application organization:-

Durandal Folder Structure

I recommend creating “App” folder with in project as shown above. Durandal applications are built as a collection of AMD modules. In fact, Durandal itself is just a set of modules. Here is what each folder used for:-

“viewmodels folder”- contains application-specific code (js file)

“views folders” contains the application-specific views(html).

“main.js” contains all of the JavaScript startup code for your app including the route configuration, module configuration etc. your app execution always starts with main which is referenced by the RequireJS script tag in the index.html file (.cshtml for .NET).

After setting up this folder structure, copy Durandal library under Script folder of your MVC project (You can keep Durandal library anywhere as per requirement, I keep it in Script folder because it just like a 3rd party JavaScript library). Durandal library has all core modules.

Durandal library folder structure

Durandal Lib Folder Structure

We also need RequireJS and knockout js(Jquery is optional) so I have added two more folders under lib folder. These folders have respective js library.

Step-3 Index.cshtml

A Durandal app is a Single Page App. When you navigate between pages, you are not navigating to new pages on the server. Instead, you are loading new virtual pages into the one-and-only-one server-side view(index.cshtml). For this sample I have created MVC HomeController.

namespace DurandalApp.Controllers{

public class HomeController : Controller{

public ActionResult Index(){

return View();

}

}

}

So it is just typical MVC code. I created the following server-side MVC view. This is the one-and-only server-side view used by the application.

Index.cshtml

<div id=”applicationHost”>

<div>

<div>

Sample App Durandal

</div>

<i></i>

</div>

</div>

<script type=”text/javascript” src=”../Scripts/lib/require/require.js” data-main=”/App/main”></script>

The “applicationHost” is where your app’s views will live. Below that is the script tag that references RequireJS. It points to our application’s entry point, declared in the data-main attribute. At runtime, this resolves to the main.js file.

In layout.cshtml we will setup css and js libraries. @RenderBody() has nothing special.it just renders the cshtml view.

<!DOCTYPE html>

<html lang=”en”>

<head>

<link rel=”stylesheet” href=”Content/bootstrap/css/bootstrap.css” />

<link rel=”stylesheet” href=”Content/bootstrap/css/bootstrap-responsive.css” />

<link rel=”stylesheet” href=”Content/font-awesome/css/font-awesome.css” />

<link rel=”stylesheet” href=”Scripts/lib/durandal/css/durandal.css” />

<link rel=”stylesheet” href=”Content/site.css” />

</head>

<body>

@RenderBody()

</body>

</html>

You can see that I have put all style sheets under content folder and JavaScript under Scripts folder. In Durandal app durandal.css is used to render message box and dialog box and other css are optional.

Step-4 main.js

In 4th step we will see entry point of app that is main.js. It is the first code that get executed and where you can configure Durandal setting and tells to start the application.

main.js

requirejs.config({

paths: {

‘text’: ‘../Scripts/lib/require/text’,

‘durandal’: ‘../Scripts/lib/durandal/js’,

‘plugins’: ‘../Scripts/lib/durandal/js/plugins’,

‘transitions’: ‘../Scripts/lib/durandal/js/transitions’,

‘knockout’: ‘../Scripts/lib/knockout/knockout-2.3.0′,

‘bootstrap’: ‘../Scripts/lib/bootstrap/js/bootstrap’,

‘jquery’: ‘../Scripts/lib/jquery/jquery-1.9.1′

}

});

define(['durandal/system', 'durandal/app', 'durandal/viewLocator'], function (system, app, viewLocator) {

system.debug(true);

app.title = ‘Durandal Starter Kit’;

app.configurePlugins({

router: true,

dialog: true,

widget: true

});

app.start().then(function () {

viewLocator.useConvention();

app.setRoot(‘viewmodels/shell’, ‘entrance’);

});

});

This code shows main functionality but it can be different according to application. Here is the list of main task in main.js:-

  1. RequireJs: – Configuration:- first few lines of main js used for configuring the durandal module path.
  2. Debugging: – Durandal have debugging functionality which can be used by turning on the debugging.
  3. Title: – You can set your application title.
  4. ConfigurePlugins: – here you can tell which plugin will available to your app.
  5. app.start():- this is actually used to kick off the application and it returns a promise which resolved when DOM is ready and framework is prepared for configuration.
  6. UseConvention: – here we set up our viewLocator with basic conventions.
  7. app.setRoot():- This is what actually causes the DOM to be composed with your application. It points to your main view model (or view). When this is called, Durandal’s composition infrastructure is invoked causing RequireJS to require your root view model, use the viewLocator to locate its view, data-bind them together and inject them into the applicationHost element. Additionally, the ‘entrance’ transition animation is used to animate the app in.

Step-5 Shell

shell is just like master page of durandal app where put all static content which you want to remain constant throughout the durandal app. So this is great place to have navigation, header and footer etc.  So first we will create the shell.js in App/viewmodel and shell.html in App/views.

shell.js

define(['plugins/router', 'durandal/app'], function (router, app) {

return {

router: router,

activate: function () {

router.map([

{ route: '', title: 'home', moduleId: 'viewmodels/home', nav: true },

]).buildNavigationModel();

return router.activate();

}

};

});

Shell.html

<div>

<div>

<div>

<ul data-bind=”foreach: router.navigationModel”>

<li data-bind=”css: { active: isActive }”>

<a data-bind=”attr: { href: hash }, html: title”></a>

</li>

</ul>

</div>

</div>

<div data-bind=”router: { transition:’entrance’ }”></div>

</div>

When you call setRoot, Durandal requires both the module and the html and uses Knockout to data-bind them together. It then injects them into the DOM’s applicationHost. As we see in shell.js, router plugin is used for registering the route.then we have used router’s navigationModel to dynamically generate or link in shell.html.

Here in shell.html knockout is used for view composition i.e. router keep track of current route and when route is changed new view is composed according to new route. Here is how exactly it happens?

  1. A route is triggered and the router finds the corresponding module and sets it as active.
  2. The router binding detects that the active module has changed. It examines the value and uses that to find the appropriate view (using the viewLocator).
  3. The module and the located view are data-bound together.
  4. The bound view is inserted into the DOM at the location of the router binding.
  5. If the router binding specifies an animation, it is used to smoothly show the new view.

Step-5 View and Viewmodels (Final Step)

Each page in application is comprised of view and viewmodel. Once you’ve setup the application as described above you can extend the application by adding new view in views folder and viewmodel in viewmodels folder. Then you just register with router in shell.js and when you go to that route, router will locate viewmodel and compose the view(insert the view in DOM). For example I am taking new page home.html.

So first create test.html under views folder and with the same name create js file under viewmodels folder.

home.js

define(function (require) {

var app = require(‘durandal/app’);

return {

displayName: ‘home Page’,

showMessage: function () {

app.showMessage(‘This is my first home page!’);

}

};

});

home.html

<div>

<h2 data-bind=”html: displayName”></h2>

<button data-bind=”click: showMessage”>Click Me</button>

</div>

Finally, go to the shell.js module and add update the router’s mappings whenever you add new page. In our application we have already added router mapping for home page.

define(['plugins/router', 'durandal/app'], function (router, app) {

return {

router: router,

activate: function () {

router.map([

{ route: '', title: 'home', moduleId: 'viewmodels/home', nav: true }

]).buildNavigationModel();

return router.activate();

}

};

});

Note-when you add new page, for registering your route, update the route mapping under shell.js. route property will have different value according to route.

e.g. If you add two new page like about and contact then route.map will have :-

router.map([

{ route: '', title: 'home', moduleId: 'viewmodels/home', nav: true },

{ route: 'about', title: 'about', moduleId: 'viewmodels/about', nav: true },

{ route: 'contact', title: 'contact', moduleId: 'viewmodels/contact', nav: true }

]).buildNavigationModel();

Now, run the application (make sure your browser isn’t caching resources) and you should see a new navigation option called ‘test’. Click on it and you will navigate to your new page. It’s that simple. I hope you like this blog post and will now start your journey of SPA-Single Page Applications.

Considerations for PCI-DSS Compliant Solution Development – Part 2

For earlier 9 points kindly refer to my earlier blog at Considerations for PCI-DSS Compliant Solution Development – Part 1

  1. Develop applications based on secure coding guidelines. Prevent common coding vulnerabilities in software development processes, to include the following:a. Documentation of impact: document the impact of change in code or customization of software.b. Documented change approval by authorized parties.c. Functionality testing to verify that the change does not adversely impact the security of the system.d. Back out Procedures
  2. Testing should be done to avoid any flaws like SQL injection. Also consider OS Command Injection, LDAP and XPath injection flaws, Buffer overflows, cross site scripting attacks and cross site request forgery (CSRF).
  3. Develop all web applications based on secure coding guidelines such as the Open Web Application Security Project guidelines. Review custom application code to identify coding vulnerabilities. Cover prevention of common coding vulnerabilities in software development processes, to include the following:
    • Un-validated input
    • Broken access control (for example, malicious use of user IDs)
    • Broken authentication and session management (use of account credentials and session cookies)
    • Cross-site scripting (XSS) attacks
    • Buffer overflows
    • Injection flaws (for example, structured query language (SQL) injection)
    • Improper error handling
    • Insecure storage (cryptographic or otherwise)
    • Denial of service
    • Security Misconfiguration
    • Insecure Direct Object References
    • Cross-Site Request Forgery (CSRF)
    • Failure to Restrict URL Access
    • Insufficient Transport Layer Protection
    • Unvalidated Redirects and Forwards
  4. SSL protects data that is transmitted between a browser and web server. It is critical that you have SSL enabled on the web server, and this should be among the first steps taken after installation.
    • Web server must be configured to use SSL v3 or TLS v1 protocols with strong encryption (128-bit or longer key is required)
    • Install SSL certificate issued for specified web domain.
  5. PCI compliance requires that you use unique user names and secure authentication to access any PCs, servers, and databases with payment applications and/or cardholder data. This means that you should use different user names/passwords:a. For your Web hosting account administration area (Web hosting account where your online store is hosted)b. For FTP access to the Web serverc. For Remote Desktop Connection to the Web server (if available)d. To connect to the MySQL server that contains your store data.
  6. Audit trails
    Audit trails/logs are should be automatically enabled with the default installation of software solution. There should be no option to disable audit logging.
    The following types of activity should be logged:a. All actions taken by any individual with root or administrative privilegesb. Initialization of the audit logsc. User sign in and sign out.Individual access to cardholder data is not logged, because cardholder data is not stored before and after authentication. Access to audit trails must be provided on the operating system level.Each log event includes:1. Type of event

    2. Date and time of event

    3. Username and IP address

    4. Success or failure indication

    5. Action which led to the event

    6. Component which led to the event

  7. Wireless communicationsa. If you use wireless networking to access software, it is your responsibility to ensure your wireless security con figuration follows the PCI DSS requirements.b. Personal firewall software should be installed on any mobile and employee-owned computers that have direct access to the internet and are also used to access your network.c. Change wireless vendor defaults, including but not limited to, wired equivalent privacy (WEP) keys, default service set identifier (SSID), passwords and SNMP community strings. Disable SSID broadcasts. Enable WiFi protected access (WPA and WPA2) technology for encryption and authentication when WPA-capable.d. Encrypt wireless transmissions by using WiFi protected access (WPA or WPA2) technology, IPSEC VPN, or SSL/TLS.e. Never rely exclusively on wired equivalent privacy (WEP) to protect confidentiality and access to a wireless LAN. If WEP is used, do the following:f. Use with a minimum 104-bit encryption key and 24 bit-initialization value

    g. Use ONLY in conjunction with WiFi protected access (WPA or WPA2) technology, VPN, or SSL/TLS

    h. Rotate shared WEP keys quarterly (or automatically if the technology permits)

    i. Rotate shared WEP keys whenever there are changes in personnel with access to keys

    j. Restrict access based on media access cod e (MAC) address.

    k. Install perimeter firewalls between any wireless networks and the cardholder data environment, and configure these firewalls to deny any traffic from the wireless environment or to control any traffic if it is necessary for business purposes.

  8. Remote access
    Software provides web-based access using two-factor authentication based on one-time PIN codes.a. If you enable remote access to your network and the cardholder data environment, you must implement two-factor authentication. Use technologies such as remote authentication and dial-in service (RADIUS) or terminal access controller access control system (TACACS) with tokens; or VPN (based on SSL/TLS or IPSEC) with individual certificates. You should make sure that any remote access software is securely configured by keeping in mind the following:b. Change default settings in the remote access software (for example, change default passwords and use unique passwords for each customer)c. Allow connections only from specific (known) IP/MAC addressesd. Use strong authentication or complex passwords for loginse. Enable encrypted data transmissionf. Enable account lockout after a certain number of failed login attempts

    g. Configure the system so a remote user must establish a Virtual Private Network (“VPN”) connection via a firewall before access is allowed

    h. Enable any logging or auditing functions

    i. Restrict access to customer passwords to authorized reseller/integrator personnel

    j. Retain audit trail history for at least one year, with a minimum of three months immediately available for analysis (for example, online, archived, or restorable from backup).

Considerations for PCI-DSS Compliant Solution Development – Part 1

Following are the considerations for the development and Implementation of software solutions in a PCI-DSS Compliant Environment. These should be treated as functional and/or quality requirements while developing PCI DSS Compliant solution.

  1. Ensure that all system components and software are protected from known vulnerabilities by having the latest vendor supplied security patches installed. Install critical security patches within one month of release. This applies to all frameworks as well as operating systems and other software installed in production environment.
  2. The PCI-DSS requires that access to all systems in the payment processing environment be protected through use of unique users and complex passwords. Unique user accounts indicate that every account used is associated with an individual user with no use of generic group accounts used by more than one user. Additionally any default accounts provided with operating systems, databases and/or devices should be removed/disabled/renamed as soon as possible.E.g. Default administrator accounts include “administrator” (Windows systems), “sa” (SQL/MSDE), and “root” (UNIX/Linux) should be disabled or removed.The PCI-DSS standard requires the following password complexity for compliance (often referred to as using “strong passwords”):

    a. Passwords must be at least 7 characters

    b. Passwords must include both numeric and alphabetic characters

    c. Passwords must be changed at least every 90 days

    d. New passwords can’t be the same as the last 4 passwords

    The PCI-DSS user account requirements beyond uniqueness and password complexity are as follows:

    a. If an incorrect password is provided 6 times the account should be locked out

    b. Account lock out duration should be at least 30 min. (or until an administrator resets it)

    c. Sessions idle for more than 15 minutes should require re-entry of username and password to reactivate the session.

    d. Do not use group, shared or generic user accounts

     

  3. PCI DSS applies wherever account data is stored, processed or transmitted. The primary account number is the defining factor in the applicability of PCI DSS requirements. PCI DSS requirements are applicable if a primary account number (PAN) is stored, processed, or transmitted. If PAN is not stored, processed or transmitted, PCI DSS requirements do not apply.The following table illustrates commonly used elements of cardholder and sensitive authentication data, whether storage of each data element is permitted or prohibited, and whether each data element must be protected. This table is not exhaustive, but is presented to illustrate the different types of requirements that apply to each data element.

     

  4. Removal of custom application accounts, user IDs, and passwords before applications become active or are released to customers.
  5. Review of custom code prior to release to production or customers in order to identify any potential coding vulnerability.
  6. There should be separate development/test and production environments.
  7. Reduce the number of personnel with access to the production environment and cardholder data minimizes risk and helps ensure that access is limited to those individuals with a business need to know.
  8. Production data (live PANs) are not used for testing or development.
  9. Test data and accounts should be removed from production code before the application becomes active.

PCI Compliance Overview

 

PCI DSS version 2.0 must be adopted by all organizations with payment card data by 1 January 2011, and from 1 January 2012 all assessments must be against version 2.0 of the standard.

It specifies the 12 requirements for compliance, organized into six logically-related groups, which are called “control objectives”.

Control Objectives PCI DSS Requirements
Build and Maintain a Secure Network 1. Install and maintain a firewall configuration to protect cardholder data

2. Do not use vendor-supplied defaults for system passwords and other security parameters

Protect Cardholder Data 3. Protect stored cardholder data

4. Encrypt transmission of cardholder data across open, public networks

Maintain a Vulnerability Management Program 5. Use and regularly update anti-virus software on all systems commonly affected by malware

6. Develop and maintain secure systems and applications

Implement Strong Access Control Measures 7. Restrict access to cardholder data by business need-to-know

8. Assign a unique ID to each person with computer access

9. Restrict physical access to cardholder data

Regularly Monitor and Test Networks 10. Track and monitor all access to network resources and cardholder data

11. Regularly test security systems and processes

Maintain an Information Security Policy 12. Maintain a policy that addresses information security

Eligibility for PA-DSS Validation:

Applications won’t be considered for PA-DSS Validation, if the ANY of the following point is “TRUE”:

  1. Application is released in beta version.
  2. Application handle cardholder data, but the application itself does not facilitate authorization or settlement.
  3. Application facilitates authorization or settlement, but has no access to cardholder data or sensitive authentication data.
  4. Application require source code customization or significant configuration by the customer (as opposed to being sold and installed “off the shelf”) such that the changes impact one or more PA-DSS requirements.
  5. Application a back-office system that stores cardholder data but does not facilitate authorization or settlement of credit card transactions. For example:
    • Reporting and CRM
    • Rewards or fraud scoring
  6. The application developed in-house and only used by the company that developed the application.
  7. The application developed and sold to a single customer for the sole use of that customer.
  8. The application function as a shared library (such as a DLL) that must be implemented with another software component in order to function, but that is not bundled (that is, sold, licensed and/or distributed as a single package) with the supporting software components.
  9. The application function as a shared library (such as a DLL) that must be implemented with another software component in order to function, but that is not bundled (that is, sold, licensed and/or distributed as a single package) with the supporting software components.
  10. The application a single module that is not submitted as part of a suite, and that does not facilitate authorization or settlement on its own.
  11. The application offered only as software as a service (SAAS) that is not sold, distributed, or licensed to third parties.
  12. The application an operating system, database or platform; even one that may store, process, or transmit cardholder data.
  13. The application operates on any consumer electronic handheld device (e.g., smart phone, tablet or PDA) that is not solely dedicated to payment acceptance for transaction processing.

For custom software development projects, “Requirement 6: Develop and maintain secure systems and applications” section is more applicable and needs to be taken care while doing the system design and in coding.

PCI Compliance Introduction

The Payment Card Industry (PCI) has developed security standards for handling cardholder information in a published standard called the PCI-DSS Data Security Standard (DSS). The security requirements defined in the DSS apply to all members, merchants, and service providers that store, process or transmit cardholder data.

The PCI-DSS requirements apply to all system components within the payment application environment which is defined as any network device, host, or application included in, or connected to, a network segment where cardholder data is stored, processed or transmitted.

The purpose of this document is to guide help software development of project which require PCI-DSS compliance implementation.

This document also explains the Payment Card Industry (PCI) initiative and the Payment Application Data Security Standard (PA-DSS) guidelines. The document then provides specific installation, configuration, and on-going management best practices for PA-DSS Certified application operating in a PCI-DSS compliant environment.

Difference between PCI-DSS Compliance and PA-DSS Validation:

As a software vendor, our responsibility is to ensure that our solution does conform to industry best practices when handling, managing and storing payment related information.

PA-DSS is the standard against which Solutions has been tested, assessed, and certified.

PCI-DSS Compliance is then later obtained by the merchant, and is an assessment of end-client’s actual server (or hosting) environment.

Obtaining “PCI-DSS Compliance” is the responsibility of the merchant and client’s hosting provider, working together, using PCI-DSS compliant server architecture with proper hardware & software configurations and access control procedures.

The PA-DSS Certification is intended to ensure that the solutions will help you achieve and maintain PCI-DSS Compliance with respect to how solutions handles user accounts, passwords, encryption, and other payment data related information.

PCI Security Standards Council Reference Documents:

The following documents provide additional detail surrounding the PCI SSC and related security programs (PA-DSS, PCI-DSS)

Introduction To Specification Pattern

Specification pattern has emerged out of “Domain Driven Design” phenomenon. It is first identified and articulated here by Eric Evans and Martin Fowler. Specification Pattern is based on method chaining technique and beautifully uses fluent interfaces. In method chaining, we get desired results by operating over the object through series of methods which returns the same type of object. One of the examples of method chaining is given below,

var Television = televisionFactory.New()
    .SetColor("blue")
    .SetHeight(1)
    .SetLength(2);

With the help of specification pattern, business logic or business rules management inside the application can be simplified and code becomes more readable and you can remove those ugly “if else” ladders. Specification immensely helps out to refactor the existing code so as to consolidate the business rules of the system. More benefits of specifications are; you can change the business rule either in terms of hard values or also in terms of business rule composition itself.

Let’s take a following code sample inside order class, which is pretty common use

public bool HasDiscountWithoutSpecification()
{
	if (SKUs >= 10000 && ModeOfPayment == PaymentMode.CashOnDelivery && ShippingAddress.Country == "USA" && OrderAmount >= 50000 && IsTaxApplicable == false)
	{
		AllowDiscount = true;
	}

	return AllowDiscount;
}

With Specification pattern we can turn above code into something like

public bool HasDiscountWithSpecification()
{
    var spec = new DiscountSpecification();
    return spec.IsSatisfiedBy(this);
}

With Specification pattern while we are dealing with flow of information business rule complexity is abstracted and code looks pretty simple.

If you explore the code provided with this post (source code pointer at the end of the post) further, you will see the beauty of construction of specification named “DiscountSpecification”. Discount Specification has method called SatisfiedBy method which utilizes other specifications and builds the business rule whether on specified order, discount is applicable or not. Since Discount specification is built on other specifications it’s a “Composite specification”. Sometimes, this terminology is used to indicate the construction of specifications.

Here is the code for IsSatisfiedBy method.

public override bool IsSatisfiedBy(Order candidate)
{
	return domesticOrderSpec
		.And(highValueSpec)
		.And(highStockSpec)
		.And(taxableSpec.Not())
		.IsSatisfiedBy(candidate);
}

The beauty above code is, even in future, if business rules for discount applicability changes, we just need to change the IsSatisfiedBy method in DiscountSpecification and we are done. For e.g. If business has removed Stock requirements of having 1000 SKUs. Then we just need to remove the highstockSpec AND operation”. So the code after High stock rule is removed will be simply

public override bool IsSatisfiedBy(Order candidate)
{
	return domesticOrderSpec
		.And(highValueSpec)
		//.And(highStockSpec)
		.And(taxableSpec.Not())
		.IsSatisfiedBy(candidate);
}

And this business rule change will be reflected across the application. Now, consider that business changed the rule and now discount will be only given to orders having order total more than 50000 USD. Then, we just need to reflect this change inside our HighValueSpecification class.

In similar fashion, we can also add new Specifications to satisfy the new business rules.

The useful scenarios where specification pattern can be used inside the application are as follows:

  1. While Applying Filtering/Search Criteria
  2. Extraction of Business Rules from code
  3. Handling Error logs
  4. Carrying out Unit Testing
  5. Component/specific object selection
  6. Building out some complex Parsing logic

You can find the Code sample for this post on github here. I have not included tests with this sample. The code sample also contains a small specification framework that you can reuse. Please note that, this code is not a production code and posted on github for the explanatory purpose.

(This post was originally posted at http://www.e-zest.net/blog)

Combination Therapy for Requirements using BDD and UML

Problem

Generally, we write requirements in use case structure. Use case structure gives us all elements required but by design , it is a vague format which are devised around use case diagrams. Every software professional has its own flavor of writing use cases. Even the sections of use case structure varies person to person.The intrinsic details of the parts of use case specially use case description, preconditions and post conditions etc] are vaguely defined. Writing use cases in clear format is also a skill and that depends upon the person who is responsible for collecting requirements.Use case are still useful in mature kind of organization but it is not so much effective way when we do not want to have upfront big designs. So dilemma here is how to collect the requirements and the new approach should be better than standard use case structures and should be fairly objective.

There is also a second angle to this use case discussion. Requirements have bigger impact on business and cost part of IT projects. Many times, due to not so clear communication between IT vendor and client over the requirements, this cost of lot of rework and hence the cost to client.From client’s viewpoint ,it is difficult to understand use case type of language and there is a chance to miss out or assume requirements/scenarios ,which becomes cost(in terms of money or time) for them afterword. Situation becomes bad in fixed cost projects. I had experienced this bitter pill many times.

Solution

So the solution I am proposing here is , Behavior Driven Development [BDD] kind of requirements collection for even the people who are not practicing BDD. From past few months,I am sort of wandering in TDD,BDD forest. Now I am going ahead with nBehave and Specflow and Gherkin which has changed whole lot of things for me on coding front.

I totally understand that BDD can’t be fully rolled out in some scenarios/in some organizations[no silver bullet!, lack of expertise, no enthusiasm to learn, cost of learning curve and transformation etc] but I am sure that, we can at least move to BDD style of requirement writing which is kind of closer to silver bullet:). See the following example. I had directly taken this example from Dan North’s blog. BTW, Dan is pioneer in BDD and I guess, he is the first who coined the term "BDD". He has also compared use case format with BDD style. Here I think, interesting angle from my side is merge both of them to take advantage from both styles of requirements collection.

In BDD, The requirements are collected in story form like:

Title (one line describing the story)

Narrative:

As a [role]

I want [feature]

So that [benefit]

Acceptance Criteria: (presented as Scenarios)

Scenario 1: Title

Given [context] And [some more context]…

When [event]

Then [outcome] And [another outcome]…

Scenario 2: …

ACTUAL EXAMPLE:

Story: Account Holder withdraws cash

As an Account Holder

I want to withdraw cash from an ATM

So that I can get money when the bank is closed

Scenario 1: Account has sufficient funds

Given the account balance is \$100 And the card is valid And the machine contains enough money

When the Account Holder requests \$20

Then the ATM should dispense \$20 And the account balance should be \$80 And the card should be returned

Scenario 2: Account has insufficient funds

Given the account balance is \$10 And the card is valid And the machine contains enough money

When the Account Holder requests \$20

Then the ATM should not dispense any money And the ATM should say there are insufficient funds And the account balance should be \$20 And the card should be returned

Scenario 3: Card has been disabled

Given the card is disabled

When the Account Holder requests \$20

Then the ATM should retain the card

And the ATM should say the card has been retained

Scenario 4: The ATM has insufficient funds

I think Along with story, if we have mockup/screenshot[off course with Balsamiq mockups! ] of proposed screen and control, data type range chart we used to have with our existing UML format, we can move towards clear requirements.

Benefits

This will benefit in following ways:

  1. It will help to gain common understanding between client and IT Vendor,about what has been covered as requirements and what has not.
  2. Client will find easy to go through requirements since requirements are written in very structured fashion and in plain English.
  3. Organization wide, requirements will be captured in same fashion and we can really estimate based on stories and find how simple or complex the story is based upon no. and complexity of scenarios it had. Hence its really easy for going with statistical process control for estimation.
  4. Change Requests are dealt with adding/removing/updating the feature/story/scenarios.My observation here is they only change the scenarios. In very rare cases, features or stories are changed.
  5. Testing team will reap the greater benefits here since they can write these stories as per their understanding and take part in RE process in very active way like finding out the missing/not clear scenarios etc.
  6. Testing team do not have to write any other test cases, This can serve as live requirements as well as test cases for them.
  7. Unit Testing for Developers will be easy since now they clearly know what kind of scenarios they have to cover which is bit difficult and time consuming in Use case format.

Let me know your thoughts, specially BDD and UML experts…

Many good points are noted as what should be in story by BDD pioneer Dan north in his post (http://dannorth.net/whats-in-a-story).

It’s really refreshing for me to see the BDD light. I will cover an example of my solution and more on requirements collection thought process that I follow, in next post.

 


Share this post :