Service Oriented Architecture – Basics
 

The Service Oriented Architecture (SOA) is not a technology instead it is a collection of Services. Precisely it is an architectural style for building business applications using loosely coupled services which communicates with each other.

SOA      =    Messages + Services

Services – Self-contained business functionality and communicate using messages.

Messages – It is a discrete unit of communication.  It should be cross-platform, secure, asynchronous, reliable, follow industry standard and able to describe and discovery service.

The SOA shifts your thinking from classes and objects to messages.

The webservice is nothing but a service available over the web (Or method of communication between two devices over a network) while API (Application Programming Interface) acts as an interface between two different applications so that they can communicate with each other. The API may or may not be web-based.  Having said that all the all the web services are APIs but all APIs are not web services. The webservice always needs a network while for API it may/may not be needed.

WebServices are mainly of two types

  1. SOAP
  2. RESTFul

Let’s understand the differences between SOAP and REST

  1. SOAP stands for Simple Object Access Protocol. REST stands for Representation State transfer.
  2. SOAP is an XML based protocol which uses WSDL for communication between source and recipient. REST is an architecture style protocol which uses XML and JSON to communicate between consumer and provider.
  3. SOAP uses RPC while REST directly uses URL.
  4. The transfer is over HTTP, FTP, SMTP and other protocol for SOAP while for REST it is HTTP only.
  5. SOAP is hard to implement over REST.
  6. The performance is slower compared to REST.
  7. SOAP is more secure since it does define its own security. The REST is less secure. The transport defines the security. (Smart consumer and provide while dumb pipe).

The SOAP message is large.  The core element of SOAP message is a SOAP envelope. The SOAP envelope defines the start and end of the message. It has two parts 1. SOAP HEADER 2. SOAP BODY

WSDL – Web Service Description Language

The WSDL is an XML based interface that is used to describe the functionalities of the webservices .

Social Experiment : Do we need a Scrum Master in a self organising team?
 

In a typical agile team, the scrum master is the coordinator/facilitator who makes everything going in the team properly. However, when the team is highly self-organising, do we even need a facilitator? We have a detailed post on the role of a scrum master here.

We have asked this question to a group of experts in different social forums and we have received around 1200+ responses. Here is a quick stats around the same.

  • 9% feels we don’t need scrum master at all.
  • 14% believes that the SM is a full-time role.
  • Rest 77% strongly believes that full-time SM is effective in the start, or in an immature team.

This survey reflects what we have observed in our agile projects.

When we are building a team or team is immature(staffing changes etc), we need SM to help and coach the team by asking right questions.  As the team grows up in maturity, the individual team members know how to organize themselves and hold each other accountable. This is one of the important reason why SM role becomes redundant after some time. And this is also the reason why organizations prefer to hire technical people who can play scrum master role. But in order to attain this maturity, the team members will have to be open for new learnings and continually improve.

Here we have picked some (not limited to) of the comments from the experts we did experiment with. The question being asked was

Do we really need a scrum master in Scrum project? If so, does it have to be full time? Isn’t self-organizing team killing the concept of SM? 

Comments from experts

1. Yes….as much it seems like an oxymoron to have both concepts in concert with each other, you need to have the “check and balance system” embodied by having a separate SM from the team. The team is made up of humans, who are fallible and will attempt to take shortcuts over time. The SM is a check against the scrum team’s desire to “get things done” and circumvent the scrum process.

2. Ideally any team member can be called as a Scrummaster. I can only call the SM designated as a process expert contributor.
The key responsibilities certainly needs a defined role to drive it so it reduces the burden on either the Manger or team.

Also , with value and business ask in mind its challenging for the Manager to inspire, create value, and follow the princple 5 ” build projects across motivated indivduals and trust them that the job can be done” whilst if it can be done, it can be tried out.

3. Scrum is a smallish change to jow people work. 5 hours a week. That said…if you’re running scrum in a not friendly to agile work environment….scrum is essential. However, if you’ve got a long term agile team, whose environment lets them work, the role is less necessary.

Really…the scrum master role as practiced is NOT about scrum, but rather about making the team work effectively together. Once that’s good…?

The XP model creates agile team functionality differently, by shifting work patterns for 35 hours a week, rather than scrums 5 hour change. Honestly, that changes team culture far faster than scrum, and the tech practices shops dont find the role necessary.

Without a deep established culture or hardcore paired-tdd-ci practices, you want a scrum master.

4. Real professionals don’t need a SM. It will save them time.

5.  Once the team is self reliant, scrum masters role becomes redundant.. Either scrum master has to be one of the tech leads or a contractual role to train the teams.

6. Looking at this link, we need SM to fix these scenarios.

7. That depends on the nature of the project. If it is a fairly large sized project with multiple dependent upstream and downstream systems, there would be a fair amount of communication and coordination required. This should happen before, during and after sprint planning. Team members do not need to worry about all these administrative work. They can concentrate on actual tasks. Also, in my personal experience, however well planned you are, things do not go smooth as planned. In that case, there is a need to capture details around any delays by our own team or any other dependent systems and review and revise the integration tests, release plans, deploys to higher environments and finally present the cost of delay and value being delivered to business. This is all just a few tasks for an SM when the project is fairly large sized with up/downstream dependencies. Other typical tasks include, communications with end users whenever required, challenging and motivating teams, conducting team building activities which helps team not only build relationships but provides some relief from day to day and hour to hour work.

8. However mature teams are, if a candid discussion happens during grooming, planning team members need someone else to facilitate their conversations, disagreements and help them come to an agreement. SM can apply various techniques in these situations and it would be totally unreasonable to expect a participant team member to play that facilitator role and be neutral (just not practical)

9. I’ve had the great pleasure to work with many different teams across many organization types, development processes, and industries. Whenever a team loved Scrum Masters, it was because the Scrum Masters were properly performing their role and getting things done, removing road blocks for the team, facilitating effective meetings and conversations, and so much more.

All of the projects I’ve been on where there was no formal Scrum Master role were teams that had one at one point, but dropped them because they were not effective. They blamed the role instead of the individual.

Find effective Scrum Masters and hold them accountable just as you would any other team member. If they aren’t getting the job done for you, find one that will!

10. When a team is mature enough, this is true that need for a Scrum Master is over.
If the team is self-organizing, cross-functional and respects naturally Scrum ceremonies ; if communication with the PO is smooth, there is no misunderstandings, it means that a Scrum Master would be superfluous.
On top of that, the role of Scrum Master still exists: the difference is that it is endorsed by team members, with no prior assignation, but spontaneously, depending on the context.

11. The need of a SM depends on the tasks that he performs. So whether a SM will be required or not will be determined by the availability of resource to perform that role. So if there are skilled resources who is available to perform those tasks then I think the need for SM is already fulfilled.

12. Although SM role is critical but if thats the case all the times it means your team in not improving. If the team is improving, you need to assign other work to SM (Assign other projects, ask to contribute on technology, design etc). If that is not happening, you should plan to bring new SM.

13. Scrum master is ‘Servant Leader’ in practice. Which means he/she has to adapt to leadership style based on ‘Team’ is at what stage. Whether ‘Forming’, ‘Storming, ‘ Norming’ or ‘Performing’. Once the team reaches ‘Performing’, SM job becomes redundant. And at ‘Adjourning’ the last stage SM is no more needed team to do its function effectively, independent and consistent performance. At this SM would also reach its peak of leadership ‘Pinnacle’.

14. A team can gel despite all kinds of organizational impediments to agility. The SM is not obsolete until those impediments are identified and addressed effectively.

15. For a program with multiple streams and releases, a dedicated SM is more or less a necessity. With obvious(more) focus during the initial stages, the SM involvement can reduce as the team imbibes the mindset that is expected of a proper self organised team. He or she will ideally bring in the culture that sets the team on the progressive path

16.  A dedicated Scrum Master is not needed in a Performing team. However, it is frequently the case that a team degrades over time after the Scrum Master leaves – so unless the team is able continuously keep focus on improving they might at least need regular check-ins from an agile coach (could be an actual agile coach or a leader in the organization or a Scrum Master from another team).

17. I don’t think need of SM can be completely eliminated, whether it is performing team or not as there are lot of things SM take care of such as improvement in processes, removing impediments, taking care of backlog, running sprint etc.

Someone from team should not be SM as this is independent role and it has to be a specialist for the job.

18. A team does not mature takes the time to mature. In a mature team, Scrum Master may not require, so a lot of other things e.g. sprint planning and refinement sessions merging, On demand retro instead of one retro per sprint, time boxing of sprint ( may be kanban), etc.

19. I don’t think the role of SM can be completely eliminated and not at least until the team is mature enough to identify impediments and able take actions to remove them or retrospect themselves. Yes, it would be a good idea to have a team member with willing to serve as SM as well, but that should happen at a later stage only as in SCRUM SM is a separate entity and can be supposed to serve multiple teams at the same time.

20. I think a SM is need at the start of the POD, but as stated above once the team starts moving and has proved they can produce and become self serving then the SM has be become obsolete. Now this can only happen if your product owner and B.A. are in tuned with the POD.

21. Instead of picking SM from outside, you can identify a good fit for this role within team and keep rotating. This would certainly increase your chances of getting better results and at the same time you are helping you team member to play interesting role who aspire to get into management.

Stand up: Why you should talk about your next actionable?
 

Lots of teams that I work with generally follow the best practices of a Scrum stand up meeting. However, as time goes by team tend to fall into the slippery slope of just reporting what they have accomplished the previous or the current day and completely ignore the next actionable & impediments. This happens more when the team/scrum master is not very strict about the process. In this article, we will see the reasons why this is important and the benefits of the same.

Life without goals

Before we delve deep into practices of Scrum method, we will talk about few general principles how our subconscious works. As per the basic behavioral psychology, there are three parts of the self-concept.

a) Self-Ideal – Goals, aspirations, dreams etc.

b) Self Image – impression about self-based on previous experiences.

c) Self Esteem – Emotional component of how much we like ourselves.

When someone sets goals and achieves them, the self-image corrects and the self-esteem improves. And they start setting bigger goals and continues to go on an upward spiral.

How Psychology relates to Scrum

Whenever a team member talks about “What they will do ” before the next meeting, they are indirectly setting a time-bound goal for themselves. When they come and report the achievement of the same the next day, the self-image and the self-esteem goes up. This will bring more success as the time goes by.

The Sprint is systematically designed methodology using the basic psychology of commit and achieve cycle.

Let’s do an experiment. If you are part of an Agile team, state your goal for the day loudly to your team during the stand-up meeting. You would have that in your back of your mind entire day. At the end the of day, if you accomplish what you stated, you will have an amazing sense of accomplishment.  Otherwise, you feel that you have not done enough. This comes to most members as long as they care about the company and their career. All you have to do is take that seriously and you would find yourself growing much faster than your peers.

I have personally asked this to many people and every time I had the same result. Isn’t it amazing? How simple it is to grow in an Agile team. Isn’t it?

So Next time you are in a stand-up meeting, would you talk about “what you are going to do “?

 

If you like this article, please share and provide comments.

 

 

The most basic Java Script Interview Questions
 

JavaScript developed by Netscape. JS is a client side as well as a server-side scripting language. It is interpreted programming language as well with object orientated capabilities.

1. How do you create a class in JavaScript?

Answer – There are multiple ways you can create a class in JS. For example

Method 1 – Using functions

// This is a class name

function Flat(aptName, location){

// You can define object properties

this.aptName = aptName;

this.location = location;

this.getLocation = getLocationInfo

}

// The method can be defined as

function getLocationInfo{

return “The location is “ + this.location;

}I

// You can even define function of a class like this

Flat.prototype.getFlatInfo = function() {

alert (“The apartment name is” +   this.aptName + “ and the location is “ + this.location = location);

// Instantiate new object of Flat class

var myFlat = new Flat(“Manjeera”, “Kukatpally”);

// Invoke methods like this

alert myFlat.getLocationInfo();

Method 2 – Using object literals

Var Flat = {

this.aptName = “manjeera”;

this.location = “kukatpally”;

this.getLocation = function() {

return “The location is “ + this.location;

}

}

Apart from using functions, and object literals, you can use object constructor as well to create JavaScript class.

2. What is the difference between ‘==’ and ‘===’?

Answer –       ‘==’ checks for equality only

‘===’ checks for equality and type

For example

false == 0 returns TRUE

false === 0 returns FALSE

3. What is isNan? Give example?

Answer – This would return true of the argument is not a number. For example

isNaN(23) returns false

isNaN(“2/3/2017”) returns true

4. What are the difference comments available in JavaScript?

Answer – There are two types of comments available in JavaScript

A. Single line comments

// This is a single line comment

B. Block comments

/*

This can be used

For block comments

..

*/

5. What are the types used by JavaScript?

Answer – There are six types used in Java Script

Boolean (True and False)

Null (null)

Undefined (undefined)

Number (Integers, floating etc.)

String

Object (Objects, Array, Functions etc.)

6. Is JavaScript a case sensitive?

Answer – Yes, JavaScript is case-sensitive.

7. How can you create an object in JavaScript

Answer – You can use object literal as shown below

var student  = {

name: “Sandeep”,

age: 36

};

Alternatively, you can use below (As explained in question number 1)

var myFlat = new Flat(“Manjeera”, “Kukatpally”);

8. Does JavaScript support exception handling?

Answer – Yes, it does support exception handling by means of try and catch. It supports try, catch, finally, throw etc. keywords to handle exceptions.

9. What is the difference between break and continue?

Answer – Break statement causes program control to exit from the loop.

The continue statement causes program control to continue with next statement.

10. What is the primary difference between ViewState and SessionState?

Answer – ViewState represents a page in session while SessionState is specific to user specific data which can be accessed all across in the web application.

 

 

 

 

 

 

 

 

Bloated Domain Objects And CQRS (Command, Query Responsibility Segregation)
 

Problem of Bloated Domain objects

In business software applications, the domain objects (entities) are used to represent the business domain. As the application grows and adds more business logic, the service layer, mappers and other patterns gets applied. Often this leads to domain object becomes bloated and the related components become huge & un-maintainable.

CQRS solves the common problem of having a bloated Domain objects. The domain objects get bloated largely because of bounded context. The series of contexts which makes developers think that a single domain object is sufficient to handle all the related things. For example, a large Invoice object for handling Invoice, Shipment and handling change of address for customer . But in reality, these contexts (invoicing, shipment and change) need not be related to same Invoice entity.

What is Command, Query Responsibility segregation (CQRS)?

In order to simplify the Domain objects, CQRS proposes to have two types of domain entities.

  • those serving the command (ordering/assertion services)  – For example, SaveCustomer, CreateInvoice, ShipProduct etc
  • those serving a Query (request) – examples include GetCustomerAddress, SearchCustomer etc

With this separation, the complexity (number of fields, methods) of entities used becomes simplified. And hence the Data mapper layers & the service layers becomes more simplified.

Where can I use CQRS?

  • Largely complex system: Applying CQRS on a simple CRUD operation based system is a over kill. When there is a domain heavy system, like banking and financing systems, LOB applications where business logic, lots of boundary conditions are heavy. Where it makes DDD (Domain driven design) provides high value.
  • Situations where you will apply Microservices, Eventual consistency and Event Sourcing. When we have separation of concerns using CQRS, the microservices becomes much simpler to design and maintain. With Event sourcing we are focused on getting the data (query) from other related sources and is what CQRS propagates.

Final words

CQRS is a carefully thought out pattern for simplifying large and complex systems. And it should not be applied for simple green field applications. Do let me know what you think.

50 Web Performance Tips and Tricks
 

I came across the below video on the web performance improvement tips and tricks. This is fantastic.

http://channel9.msdn.com/Events/Build/2012/3-132

In this video, Jatinder talks about Six fundamental principles for improving web application performance. He also talks a lot about how we go about Decreasing CPU time and increasing parallelism on the client machine to achieve faster web performance.

While I went through the video, I captured all the tricks he talks about. And thought will be useful for others while they watch it. Please find below the tricks.

Quickly respond to network request

  • Avoid 3XX Redirections (63% of top websites use redirect)
  • Avoid Meta refresh
  • Minimize Server time for Requests
  • Use Content distribution Networks (CDN)
  • Maximize concurrent connections.
  • Reuse connections – don’t sent connection close.
  • Know your other servers – you are only fast as your weakest link
  • Understand your network timing

Minimize bytes downloaded

  • GZIP Compression Network traffic
  • Persist application resources locally (Windows 8 applications)
  • Cache dynamic resources in the application Cache (html5 app cache)
  • Provide cacheable content
  • Send Conditional request
  • Cache Data requests (jQuery AJAX calls)
  • Standardize File name capitalization convention.

Efficiently structure markup

  • Load pages in latest browser mode
  • Use http header to specify legacy IE mode
  • Link CSS in the top of the page header, never on the bottom.
  • Avoid using @import of hierarchical styles
  • avoid embedded and inline CSS
  • Only include necessary styles in the page.
  • Always link JS at the end of the page.
  • Avoid linking JS in the header (use the defer & async attribute)
  • Avoid Inline JS
  • Remove Duplicate code (52% of the web have duplicate code
  • Standardize on a single framework

Optimize your media usage

  • Avoid death by too many images
  • If possible use Image Sprites
  • Use png image file format
  • Use Native image resolutions
  • Replace Images with CSS3 Gradients, border Radius
  • Leverage CSS3 Transforms
  • Use Data URI’s for Small Single view images
  • Avoid complex SVG paths
  • Video : Use preview images
  • Minimize media plugin usage
  • Proactively download Future media

Write Fast JavaScript

  • Stick to Integer math (Math.Floor)
  • Minify your JavaScript
  • Initialize JavaScript on Demand
  • Minimize your DOM Interactions
  • Built in DOM methods always more efficient (firstchild, nextsibling methods are faster)
  • Use Selectors for Collection access (document.querySelectorAll)
  • Use .innerHTML to construct your page
  • Batch your markup changes
  • Maintain smaller DOM (less than 1000 elements)
  • Json always faster than XML
  • Use Native Json methods
  • Use regular expressions Sparingly

Know what your app is doing

  • Understand JavaScript Timers (setTimeout, SetInterval)
  • Combine Application Timers
  • Ensure dormant timers are not running
  • Align timers to display Frame (16.7)
  • Use window.requestAminationFrame(renderLoop) for Animations
  • Know when your application is visible (document.hidden, Visibilitychange (event))

Conclusion

The web optimization is not easy and needs exhaustive deep look and hopefully this check list helps while optimizing your pages. Enjoy coding high performing applications. If you have more tips please provide them in the comments.

 

Micro-Services, Eventual Consistency and Event sourcing patterns
 

Microservices is a really becoming a famous architectural pattern that most of the new software written these days, just apply them. One of the most important differentiation between the traditional web services and micro-services pattern is the amount of common stuff across different subject areas. This calls for a discussion on how Eventual Consistency pattern is mandatory for successfully implementing microservices.

The micro frontend if gaining lots of popularity.  You can read about microservices principles and micro frontends at

Microservices and Microfrontends

Micro-Service Pattern

Generally, in a micro-service pattern, the API’s are split into small subject areas. For example for a CRM application, the subject areas are

  • Customer information – like name, address, email, phone
  • Appointment information – which customer, salesperson, when, where
  • Relationship management – sales/manager, what products, interests
  • Campaign data – offers, deals etc

Then micro-services are built for each of the subject areas.  The microservices are logically and physically separated from each other. ie there is no sharing (code, database, component etc) between any of these micro-services of these subject areas. Pictorially its looks something like this.

Applying Eventual Consistency Pattern

In Micro-services, there is no data that is shared across the micro services. In order to synchronize the data across these isolated storages of these services, we need to apply the eventual consistency pattern. You can read more about applying the pattern correctly here. The simpler way we can achieve consistency across these micro-services is through Event Sourcing pattern.

Event Sourcing

Event sourcing is a process of capturing application state changes in the form of events.  An example of events are customer created, customer updated, Deal created, etc.  Other systems listen to these events and they take relevant action. You can read more about event sourcing here.

Conclusion

Event sourcing is the new way of storing changes to systems and help in making micro-services eventually consistent. These patterns together form well maintainable, reliable and scalable systems in the modern world.

 

 

BDD (Behavior Driven Development)
 

In the previous article we looked at how to do Test Driven Development (TDD) while doing the XP (Extreme Programming). In XP, the implementation of the tasks are done in the steering phase of the iteration planning. One of the tenets of the steering phase is “functional tests are run”. In this article we will see how to create functional tests using Behavior driven development (BDD) and its benefits.

Following are the some of the benefits of automated functional tests.

  • Functionality experienced by the User is tested
  • Saves testing time for the developers
  • Test in every environment (Dev, QA, Stage) without much effort
  • Generates confidence in every stake holder

Tools required for doing BDD in .Net

There are various tools available to do BDD in .Net. I have listed few of them below

SpecFlow is one of the most popular tools used in the .Net/C# community. And in this blog lets use the same. The tool comes as a Visual Studio Extension and can be downloaded directly from VS.

Creating a SpecFlow Project

Once SpecFlow extension is installed, the template required for doing BDD will be installed.

  • Create a simple “Class Library” Project in Visual studio
  • In the project, create a SpecFlow Feature file

Selecting the test framework

Before we Create/execute the scenario, we need to wire the SpecFlow with a compatible test framework. To do that we need to make changes to the app.Config file of the project.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
  </configSections>
  <specFlow>
    <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
  <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
    <unitTestProvider name="xUnit" />
  </specFlow>
</configuration>

In this example we are using XUnit as the testing framework. SpecFlow supports a series of testing frameworks and more details can be found here.

Creating the Behavior

Now, let us look at how to create a functional test using behavior driven approach. Let’s consider the following story while creating a POS (point of sale) application for a super market.

“As a Supermarket POS app developer,  i would like the API to Give the total amount while billing so that I can wire up API against the UI.

Let’s write the Behavior required in order to implement the above API requirement .

Feature: SuperMarketProductsAPI
	As a Supermarket Biller 
	i would like the API to
	Give the total amount while billing
@SmokeTest
Scenario: Find the total amount while billing
	Given Shopping cart is filled with all the items required by consumer
	And Campaign information for the month is available in the system
	When I pass the cart to create bill API
	Then the total bill amount should be calculated

The above specification is written using the custom language (testing DSL) create by the specflow.org. (Please read about what is DSL here.)

There are 2 parts to the above Specflow specification

  • Feature – Denotes bigger context (description/story) of the application
  • Scenario – Specific workflow or behavior of the system under the feature. Each scenario has the following sub-parts
    • Given, And – describes what we already assumed available
    • When – The specific action which will trigger the workflow/behavior
    • Then  – expected behavior

 

Creating step definitions

When we run the unit test corresponding to the above test we it will fail as there are no definitions corresponding to the above scenarios.

Now Right Click on the feature file and select “Generate step Definitions”

You will see the pop-up like below, select “Generate” and then “Save” the file.

The file will have the details about “what SpecFlow should do when test is executed”.

using System;
using TechTalk.SpecFlow;

namespace SuperMarketFunctionalTests
{
    [Binding]
    public class SuperMarketProductsAPISteps
    {
        [Given(@"Shopping cart is filled with all the items required by consumer")]
        public void GivenShoppingCartIsFilledWithAllTheItemsRequiredByConsumer()
        {
            ScenarioContext.Current.Pending();
        }
        
        [Given(@"Campaign information for the month is available in the system")]
        public void GivenCampaignInformationForTheMonthIsAvailableInTheSystem()
        {
            ScenarioContext.Current.Pending();
        }
        
        [When(@"I pass the cart to create bill API")]
        public void WhenIPassTheCartToCreateBillAPI()
        {
            ScenarioContext.Current.Pending();
        }
        
        [Then(@"the total bill amount should be calculated")]
        public void ThenTheTotalBillAmountShouldBeCalculated()
        {
            ScenarioContext.Current.Pending();
        }
    }
}

When you build the project and execute the test corresponding to this, it will fail. This is because none of the parts of the test (given, when, then) are having implementation.

Writing code to make it work

Now that the behavior has been created, we are good to validate that with the team and implement the code/functionality corresponding to the requirement. Of course using best coding practices like TDD 🙂

Making the behavior test pass

In order to make the behavior test pass we need to write the implementation in the “Step Definition” file.

namespace SuperMarketFunctionalTests
{
    using Newtonsoft.Json;
    using System.Collections.Generic;
    using System.Net.Http;
    using TechTalk.SpecFlow;
    using Xunit;

    [Binding]
    public class SuperMarketProductsAPISteps
    {
        Product P1 = new Product { Name = "test1", Cost = 5 };
        Product P2 = new Product { Name = "test2", Cost = 10 };
        ShoppingCart cart;
        List<Campaign> campaign;
        Bill bill;
        [Given(@"Shopping cart is filled with all the items required by consumer")]
        public void GivenShoppingCartIsFilledWithAllTheItemsRequiredByConsumer()
        {
            cart = new ShoppingCart { Products = new List<Product> { P1, P2 } };
        }
        
        [Given(@"Campaign information for the month is available in the system")]
        public void GivenCampaignInformationForTheMonthIsAvailableInTheSystem()
        {
            campaign = new List<Campaign> { new Campaign { product = P1, discount = 1 } };
        }
        
        [When(@"I pass the cart to create bill API")]
        public void WhenIPassTheCartToCreateBillAPI()
        {
            var client = new HttpClient();
            var response = client.PostAsync("http://myapi.supermarket.com", new StringContent(JsonConvert.SerializeObject(cart))).Result;
            var output = response.Content.ReadAsStringAsync().Result;
            bill = JsonConvert.DeserializeObject<Bill>(output);
        }
        
        [Then(@"the total bill amount should be calculated")]
        public void ThenTheTotalBillAmountShouldBeCalculated()
        {
            Assert.True(bill.totalAmount == 14);
        }
    }
}

Once the code is there we can see the behavior test pass.

Conclusion

BDD is very powerful way of ensuring high code quality in conjunction with business requirement. In Extreme programming (XP) , BDD is considered to be a very important practice where functional tests are mandated to run at least once during the iteration.  Is BDD/Functional tests helping your team/business in achieving success or not ? Do let us know your thoughts.