Test Driven Development – But Why?

An introduction to the TDD methodology

Everyone knows that tests are needed, but do you know really why? What are the benefits?

smiling-business-person-300x199In the beginning of our projects, we are in a green field where every code we write is nice and works, the speed of the project is high, the number of bugs is low and developers and clients are happy.

As the project advance the code start to get messy, every time we have to make a change is harder, in more places and force us to hack our own code or add some nasty code.

manzanaAfter a few months our code is rotten, becomes rigid and fragile. The speed of the team decreases and the number of bugs increases. The developer is scared to introduce changes to the code and to refactor because he doesn’t know if he will break another functionality, all the bug fixes or changes to existing code are small hacks.

So the developer is scared to touch the code because it is too fragile, he needs some kind of protection that he doesn’t break any functionality. This protection are the Tests.

Imagine to have a suite of test that could detect the vast majority of the bugs that could be run just with the click of a button in a few minutes… this is what TDD aims for.

What is TDD?

Kent-Beck-ingeniero-de-softwareIt is an Agile methodology which consists in letting our tests drive the development of the product writing them first to force us to write the exact code that makes those test pass.

This technique was created/redefined by Kent Beck one of the 17 original signatories of the Agile Manifesto and is related to Test-First programming concepts of the Extreme Programming.

But why?

Reduce the debug time

imagesIf we have a complete suite of tests we keep writing and updating them and running quite often, every time there is a bug, this bug will appear in the test as an error, so is already spotted just when it was created, and it will be easier to fix since it is located in the code that we just wrote so it is fresh to our mind. You don’t have to spend hours debugging through the whole call stack to check when, where and about what is the bug.

Living documentation

imgresNormally when we try to use a new API we go directly to the examples of code that shows how to use the API, and sometimes we even copy & paste the example and try to tweak it to use it in our code. So well, the Unit tests are those examples. If you have a complete set of Unit test in your product you only need to take a look at them in order to know how your code works.

You have in your set of tests an example of every possible way to use your code. Is the perfect documentation that is reliable and is always updated.

The courage for change

hqdefaultThanks to the suite of unit tests that covers most of your code you can be sure that your code is working, this will eliminate the fear of the developer to change anything allowing him to clean the code and refactor freely. Tests stop the code from rotting.

Why to write tests first?

tddWriting tests first makes the production code testable. Ok that’s obvious but what is de benefit? If the production code is testable it means that it is decoupled, if you can test a part of the production code by separate in one unit test then that part is decoupled from the rest of the components. The more decoupled the system is the more flexible and extensible is.

You get a better design just by writing test first.

Normally if you write your tests after writing your production code they won’t be as complete as if they were written first because you already know your code works and it is boring to write only tests, sometimes you are tempted to take shortcuts and you miss some tests.

If you write the test first you are writing code to pass those test, so every line of production code is covered by a test. You trust your test, they are more complete than if you write them after.

And how do we do TDD?

It consists in a 3 phases cycle, known as red, green, refactor. This cycle must be very short and the iterations must be quite fast in order to not be much time outside of the green phase where all your code is working.

tdd-cycleThere are 3 phases:

Writing a failing test first.

Writing the production code to pass the test.

Refactoring the production and the test code.

In the Red phase we write a unit test that fails that will force us to write the production code that we want to write.

In the Green phase we are able to write the production code to make that failing unit test pass. We write no more no less.

In the Blue phase, when our production code works as desired, we clean the production and the test code, making it more sustainable, extensible, removing duplication, in other words, we clean the code.

The 3 laws of TDD.

TDD is a discipline, as any discipline it has a set of rules that for the beginners can sound a little extreme, but with time they will become more and more logical. Here are the 3 Uncle’s Bob TDD rules, read them well and understand them well:

• You are not allowed to write any production code unless it is to make a failing unit test pass.

• You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.

• You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

Follow these 3 rules and they will force you to write alternating between test and production code in short time periods and you will always have production code that is passing all the tests or at least was not long time ago.

At the beginning coding in the TDD way will be slow and hard, but with time you will change your mindset and you will be automatically thinking about features that your code should do, instead of solutions, writing tests for it instead of implementing the production code directly and thinking how to write your production code to be easily testable and decoupled from other functionality.

Most of the information was obtained from the teachings of Robert C. Martin Aka Uncle Bob in his videos. You can download his videos at CleanCoders.com and follow his company blog for more interesting articles 8thLight Blog.

Recommended lectures:

Clean Code – by Robert C. Martin

http://www.amazon.es/Clean-code-Handbook-Software-Craftsmanship/dp/0132350882

Growing Object-Oriented Software, Guided by Tests – by Steve Freeman and Nat Pryce

http://www.amazon.es/Growing-Object-Oriented-Software-Addison-Wesley-Signature-ebook/dp/B002TIOYVW

Test Driven Development. By Example – by Kent Beck

http://www.amazon.es/Driven-Development-Example-Addison-Wesley-Signature/dp/0321146530

 

Why your project needs up to date HTML slices

Ok, here’s the situation: you’ve started your project, currently your team has frontend developers and backend developers. Everyone is happy and doing their parts.

As frontend developer I can tell you that the fastest way to slice or prototype pages is working with plain HTML files. It allows you to work with your (S)CSS and JavaScript files without any issues of caching, server-side compiling, etc. It just works.

What happens when the pages are ready for implementation?

You guessed it, it goes to the hands of the backend developers who will do their magic: create the components for choose your favourite CMS here.
At this point we’re still happy, everything is working just fine and the project will be delivered on time.

First iteration

A couple of days have passed and some JIRA tickets have been raised: we need to fix something in the frontend.

No problem, the frontend developer will open up the HTML files and do the proper edits.

Iteration two hundred seventy six

At some point between revision 1 and revision 276 someone updated the backend CMS component and not the HTML static file. Probably the change was simple enough, there was no need to involve any frontend dev.
That is actually fine! It’s way cheaper, project-wise, and faster to develop.

Now, be careful, that decision might cause a lot of trouble in the future, when new major features will need to be added. An out of date slices will force us to download source files from production. We all know those files can be messy, with random ID’s everywhere, extra empty divs, inline styles, uncommented code…

So, what’ the proper way of applying frontend changes?

frontend-workflow-v2

 

I would add that in case of a JavaScript change, even if we’re using Grunt or similar you might be able to do the change yourself. The issue might be that not everybody has it installed locally. Although I would certainly recommend it 😉

Also, if the project has enough budget to have a frontend developer on board, the above workflow is useless. Just send everything to the frontend dev.

Conclusion

Try finding balance!

This best practices should not be a burden, if you get used to it I think you’ll get real benefits. If someone is capable of changing a component’s markup, is also capable of editing plain HTML files.

You should always keep your static HTML files up to date. Not with content changes but markup. I’m not saying it’s easy or cheap but it’s the right way to iterate. Not all projects will have the budget or client will to maintain this code standards. We, as professional, need to advice and convince our clients this is mandatory. In the end, it will probably save them money.

I hope now you have better insight of how you can be more productive and have a better future-proof code in your projects.

Have something to add? Leave a comment down below.

Our motto: Deliver with Efficiency & Quality

Over the past 10 years we have been involved in a whole host of CMS/DAM/web implementation projects of many different kinds (clients of different types and sizes, as a prime contractor, a vendor integration partner or onsite with the client’s teams), and throughout that time we have always stuck to a single mantra: deliver with efficiency & quality to guarantee maximum customer satisfaction.

No matter what constraints we have faced in terms of managing the different projects, we have had to adapt and adopt. It has never been our goal to simply turn up and impose our rules, and it goes without saying that project management is deeply intertwined with corporate governance and enterprise policies.

In that sense, our project managers have their own cultural backgrounds that constantly enrich our internal Project Management Practices. Their principal goal is to deliver “good work, on-time and on-budget”.

We have nonetheless had the latitude to come up with our own PM approach, notably for fix-time projects. We made the decision to rationalize our position by taking account of 2 fields of perception: observations and corporate values.

Perception is where you look and how you look.

jim-denevan-02
Jim Denevan or how to leverage our perception

 

First of all let’s talk about our observations

  • A software development process should be undertaken within the framework of a broader business commitment. That is why it is vital we understand exactly where the needs are coming from.
  • A more easily accessible knowledge, a Do-It-Yourself attitude and the product-oriented marketing have led everyone to think solution before needs, and unfortunately the vital phase of defining the real needs is sometimes skipped altogether.
  • Methodologies and organizations are intrinsically linked by culture, people and processes.
  • Agile methods demand mature relationships between business and IT, something which is often underestimated.
  • Corporate governance policies demand structured and uniform reporting procedures in projects that influence the choice of methodology.
  • Profound shifts don’t happen overnight in big organizations.
  • It is important to remember what the initial idea was: why are you doing the task in hand?
  • We can’t expect an all-encompassing model from the start.
  • The same tool in a different context can generate different results.
  • The requester has a good reason for making his request. Respect that.
  • Academic project management methodologies offer a starting point, but sticking to them reduces the scope of possibility.

Now let’s us introduce you our values

  • A good working relationship with a client is based on a constructive company-2-company relationship, structured team-2-team cooperation and a fair individual-2-individual collaboration.
  • Remember that you will learn from your initial choices.
  • Share the same goals and support one other.
  • Resolve situations that sap your time and energy.
  • Choose the right tool for the right job.
  • Don’t use all the colours just because you have them on your palette.
  • Make sure you are on the right track.
  • Guarantee a common understanding.
  • Demonstrate agility with the product, the method, the organization.
  • There’s always somebody that will use your product, and somebody that will maintain your software.
  • Listen carefully and respect other people’s constraints.
  • There’s no bad methodology, there’s no best methodology, there’s no point confronting waterfall and agile. Choose whatever solution works best for the situation in-hand.

When you are playing the software development game your secondary goal is to setup to play the next game.
Alistair Cockburn, Agile’s father

For our project management we deal with 2 dimensions

Driven by our enlightened understanding and inspired by the values of objectivity, efficiency, openness and honesty, our project management approach has been broadened to encompass two dimensions.

A cooperation framework for a future proof collaboration

Focusing on controlled planning and on broad and transparent communication, this approach is used to build a relationship with the client during first-time projects, one-shot projects or when handling program management issues. Based on waterfall methodologies, the phases are clearly defined and sequential:

  • Initiation to guarantee a shared understanding of the needs , expectations and perspectives;
  • Planning to reach an agreement on scope and timing, organization and risks;
  • Controlled & Monitored Execution with open communication & fast feedback, with close cooperation during the testing phase.

The aim of this framework is to identify the best way of working together in conjunction with the client. The approach is consequently a circular one, paving the way for the next project by means of an extensive closure phase to assess lessons learned and review the next steps.

Graph_04-EN-2The method focuses on control and communication, which means that numerous deliverables are required:

  • Engagement framework
  • Project Statement Of Work
  • Functional Contract, Solution design & Detailed planning
  • Monitoring reviews
  • Issue tracking with JIRA
  • Product evaluation & acceptance report
  • Project closure record

A fast-delivery framework in a mature relationship

Usually adopted when a mature working relationship has already been established with the client over the course of previous projects, this light and agile method demands a clear commitment in terms of roles and responsibilities. Guided by iterative development and agile methodologies, this approach is based on iterative cycles backed by delivery contracts:

  • Inception to define high-level requirements & engagement;
  • Elaboration using the iteration plan;
  • Execution involving strong collaboration;
  • Transition to review delivery and acceptance;
  • On-going assessment for strategy assurance and scope refinement.

Graph_04-EN-1The method is suitable for product enhancements (change management) or large roll-out projects that involve adding new features to a central environment based on new needs highlighted by a country/division assessment. These iterative cycles can also be run in parallel within the framework of a larger program. That is why the method is based on a light and versatile organization:

  • One project master, responsible for scope, communication and planning;
  • One product owner, usually a client representative or a commission agent, who can make quick & firm decisions, ensure that the functional strategy remains consistent and accept the deliverables;
  • One technical owner who plans and takes action in order to deliver on-time (this is usually a lead developer who is directly involved in the build).

All kinds of additional players may get involved at specific times or for specific reasons. The initial statement of work is put together when the project first kicks off, and then all subsequent communication is handled through our JIRA environment until the project is formally closed and the evaluation reviews are completed.

Our years of rich experience have shown us that these 2 frameworks can cover most situations, as long as the client doesn’t ask us to follow their own policies. Project management is not a science, it is simply good sense driven by experience, basic techniques and positive collaboration.