DEV Community

Discussion on: [Challenge] 🐝 FizzBuzz without if/else

Collapse
 
guillaume_agile profile image
craft Softwr & Music • Edited

Here's my proposal for a non if/else implementation
Using only Types and Abstractions (Interface) and a bit a Linq (C#)
But the most important part is using full polymorphism and a DDD style with immutable objects (structs)
Made with strict TDD (all tests green), please check my repo

  public class FizzBuzz
    {
        private readonly IDictionary<int, string> rulesSet;
        public FizzBuzz()
        {        
          rulesSet = new Dictionary<int, string>();
            rulesSet.Add(3, "Fizz");
            rulesSet.Add(5, "Buzz");
            rulesSet.Add(7, "Wizz");          
        }

        public string Process(int value)
        {               
            IResult res = new VoidResult();
            foreach (var element in rulesSet.Where(element => value % element.Key == 0))
            {
                res = new TempResult(res.Result + element.Value);
            }
            res = res.Finalize(value.ToString());
            return res.Result;
        } 
     }

    public interface IResult
    {
        string Result { get; }

        IResult Finalize(string v);
    }

    public struct VoidResult : IResult
    {
        public string Result => string.Empty;

        public IResult Finalize(string v)
        {
            return new FinalResult(v);
        }
    }

    public struct TempResult : IResult
    {
        readonly string value;

        public TempResult(string value)
        {
            this.value = value;
        }

        public string Result => value;

        public IResult Finalize(string v)
        {
            return new FinalResult(this.value);
        }
    }

    public struct FinalResult : IResult
    {
        readonly string v;

        public FinalResult(string v)
        {
            this.v = v;
        }

        public string Result => v;

        public IResult Finalize(string v)
        {
            throw new System.NotSupportedException("cannot finalize what is already finalyzed");
        }
    }
Enter fullscreen mode Exit fullscreen mode