Uncategorized

TDD Kata | String Calculator

Kata is a Japanese word describing detailed choreographed patterns of movements practiced either solo or in pairs. most commonly known for the presence in the martial arts.
The idea is if you practice something regularly, at some point it will be come natural. (As they call it “Muscle memory” :)).
Even though Test Driven Development has been preached as best practice for years now, there is still resistance in many IT shops to adapt TDD (Test Driven Developer). So the best way to teach your team to start making TDD part of their daily development practice is by running small hands on sessions, KATA.
Yesterday, the architect (a very passionate developer and lead) at my job took the team through one 1hr journey of solving a simple but yet complex enough problem to have the taste of TDD (Red-Green-Re factor) .
You can find the problem definition at Roy’s String Calculator TDD Kata.
 

String Calculator

The following is a TDD Kata- an exercise in coding, refactoring and test-first, that you should apply daily for at least 15 minutes (I do 30).
 

Before you start:

  • Try not to read ahead.
  • Do one task at a time. The trick is to learn to work incrementally.
  • Make sure you only test for correct inputs. there is no need to test for invalid inputs for this kata

    String Calculator

    1. Create a simple String calculator with a method int Add(string numbers)
      1. The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0) for example “” or “1” or “1,2”
      2. Start with the simplest test case of an empty string and move to 1 and two numbers
      3. Remember to solve things as simply as possible so that you force yourself to write tests you did not think about
      4. Remember to refactor after each passing test
    2. Allow the Add method to handle an unknown amount of numbers
    3. Allow the Add method to handle new lines between numbers (instead of commas).
      1. the following input is ok:  “1\n2,3”  (will equal 6)
      2. the following input is NOT ok:  “1,\n” (not need to prove it – just clarifying)
      1. Support different delimiters

      2. to change a delimiter, the beginning of the string will contain a separate line that looks like this:   “//[delimiter]\n[numbers…]” for example “//;\n1;2” should return three where the default delimiter is ‘;’ .
      3. the first line is optional. all existing scenarios should still be supported
    4. Calling Add with a negative number will throw an exception “negatives not allowed” – and the negative that was passed.if there are multiple negatives, show all of them in the exception message

      stop here if you are a beginner. Continue if you can finish the steps so far in less than 30 minutes.


    5. Numbers bigger than 1000 should be ignored, so adding 2 + 1001  = 2
    6. Delimiters can be of any length with the following format:  “//[delimiter]\n” for example: “//[***]\n1***2***3” should return 6
    7. Allow multiple delimiters like this:  “//[delim1][delim2]\n” for example “//[*][%]\n1*2%3” should return 6.
    8. make sure you can also handle multiple delimiters with length longer than one char

    I am sharing my first attempt to develop the String Calculator add functionality using TDD.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;
    namespace TDDFun
    {
    public class StringCalculator
        {
    public double Add(string numbers)
            {
    Double sum = 0;
    if (string.IsNullOrEmpty(numbers))
                {
                    sum = 0;
                }
    else
                {
    const string regex1 = “(\\//)”;
    const string regex2 = “(.*?)”;
    const string regex3 = “(\\n)”;
    const string regex4 = “(.*?\\d)”;
    var delimiters = new List<string>();
    var r = new Regex(regex1 + regex2 + regex3 + regex4, RegexOptions.IgnoreCase | RegexOptions.Singleline);
    Match m = r.Match(numbers);
    if (m.Success)
                    {
    string delimiterCollection = m.Groups[2].ToString();
    int numberStartIndex = m.Groups[3].Index;
    const string re5 = “(\\[.*?\\])”;
    var r2 = new Regex(re5, RegexOptions.IgnoreCase | RegexOptions.Singleline);
    MatchCollection m2 = r2.Matches(delimiterCollection);
    if (m2.Count > 0)
                        {
    foreach (Match x in m2)
                            {
    delimiters.Add(x.ToString().Replace(“[“, “”).Replace(“]“, “”));
                            }
                        }
    else
                        {
    delimiters.Add(delimiterCollection);
                        }
                        numbers = numbers.Remove(0, numberStartIndex + 1);
                    }
    else
                    {
    delimiters.Add(“\n”);
    delimiters.Add(“,”);
                    }
    string[] splittedNumbers = numbers.Split(delimiters.ToArray(), StringSplitOptions.None);
                    ValiateNumbers(splittedNumbers);
    foreach (string s in splittedNumbers)
                    {
    double ss = Double.Parse(s);
                        sum += ss <= 1000 ? ss : 0;
                    }
                }
    return sum;
            }
    private static void ValiateNumbers(IEnumerable<string> numbers)
            {
    double x;
    var negativeNumbers = new List<string>();
    foreach (string s in numbers)
                {
    Validator.IsRequiredField(Double.TryParse(s, out x), “Validation Error”);
    if (Double.Parse(s) < 0)
                    {
    negativeNumbers.Add(s);
                    }
                }
    Validator.IsRequiredField(negativeNumbers.Count <= 0,
    “Negatives not allowed “ + ShowAllNegatives(negativeNumbers));
            }
    private static string ShowAllNegatives(List<string> negativeNumbers)
            {
    var sb = new StringBuilder();
    int counter = 0;
                negativeNumbers.ForEach(k =>
                                            {
    if (counter == 0)
                                                {
                                                    sb.Append(k);
                                                    counter++;
                                                }
    else
                                                {
                                                    sb.Append(“;” + k);
                                                }
                                            });
    return sb.ToString();
            }
        }
    public static class Validator
        {
    public static void IsRequiredField(bool criteria, string message)
            {
    if (!criteria)
                {
    throw new ValidationException(message);
                }
            }
        }
    public class ValidationException : ApplicationException
        {
    public ValidationException(string message) : base(message)
            {
            }
        }
    }
     
     
    using NUnit.Framework;
    namespace TDDFun
    {
        [TestFixture]
    public class StringCalculatorTest
        {
    private StringCalculator calculator;
            [SetUp]
    public void SetUp()
            {
                calculator = new StringCalculator();
            }
            [Test]
    public void Add_DecimalNumbers_ShouldReturnDouble()
            {
    Assert.IsTrue(calculator.Add(“//;\n1.1;1.2″) == 2.3);
            }
            [Test]
    public void Add_EmptyString_ShouldReturnZero()
            {
    Assert.IsTrue(calculator.Add(string.Empty) == 0);
            }
            [Test]
    public void Add_NewLineSeparators_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“1\n2\n34\n5″) == 42);
            }
            [Test]
    public void Add_NewLineSeparatorsCommasCombined_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“1\n2,34,5″) == 42);
            }
            [Test]
    public void Add_NonNumericStringPassed_ShouldThrowException()
            {
    Assert.Throws<ValidationException>(() => calculator.Add(“XT”));
            }
            [Test]
    public void Add_NullString_ShouldReturnZero()
            {
    Assert.IsTrue(calculator.Add(null) == 0);
            }
            [Test]
    public void Add_NumbersGreaterThan1000_ShouldBeIgnored()
            {
    Assert.IsTrue(calculator.Add(“//[***]\n1.1***1000.2″) == 1.1);
            }
            [Test]
    public void Add_OneString_ShouldReturnItself()
            {
    Assert.IsTrue(calculator.Add(“3″) == 3);
            }
            [Test]
    public void Add_SpacesBetweenDelimiters_ShouldBeHandled()
            {
    Assert.IsTrue(calculator.Add(“//[***][kkk]\n1.1   ***  1.2kkk   2″) == 4.3);
            }
            [Test]
    public void Add_SpecialDelimiterWithMultipleNegativeNumber_ShouldThrows()
            {
    var exception = Assert.Throws<ValidationException>(() => calculator.Add(“//[***]\n-1***-2″));
    Assert.AreEqual(exception.Message, “Negatives not allowed -1;-2″);
            }
            [Test]
    public void Add_ThreeString_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“3,33,4″) == 40);
            }
            [Test]
    public void Add_TwoNegativeString_ShouldThrowException()
            {
    var exception = Assert.Throws<ValidationException>(() => calculator.Add(“-1,-2″));
    Assert.AreEqual(exception.Message, “Negatives not allowed -1;-2″);
            }
            [Test]
    public void Add_TwoString_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“3,33″) == 36);
            }
            [Test]
    public void Add_WithDelimiterAndColon_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//;\n1;2″) == 3);
            }
            [Test]
    public void Add_WithMultipleNegativeNumber_ThrowsExceptionShowingAllNegativeNumbers()
            {
    var exception = Assert.Throws<ValidationException>(() => calculator.Add(“//;\n-1;-2″));
    Assert.AreEqual(exception.Message, “Negatives not allowed -1;-2″);
            }
            [Test]
    public void Add_WithNegativeNumber_ThrowsException()
            {
    Assert.Throws<ValidationException>(() => calculator.Add(“//;\n1;-2″));
            }
            [Test]
    public void Add_WithOneSpecialDelimiters_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[***]\n1.1***1.2″) == 2.3);
            }
            [Test]
    public void Add_WithSpecialDelimitersOnlyOneChar_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[*]\n1.1*1.2″) == 2.3);
            }
            [Test]
    public void Add_WithSwithAndAnySpecialDelimiters_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//***\n1.1***1.2″) == 2.3);
            }
            [Test]
    public void Add_WithThreeSpecialDelimiters_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[***][kkk][GGG]\n1.1***1.2kkk2GGG4.7″) == 9.0);
            }
            [Test]
    public void Add_WithTwoSpecialDelimiters_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[***][kkk]\n1.1***1.2kkk2″) == 4.3);
            }
            [Test]
    public void Add_WithTwoSpecialDelimitersOnlyOneChar_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[*][%]\n1*2%3″) == 6);
            }
        }
    }

    One thought on “TDD Kata | String Calculator

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.