For my first CodeReview, I would like to present my FizzBuzz solution in C#. My design has all of the rule logic about when to display what in separate classes through an interface. This design should be able to handle the common follow-up changes (ie. mod 7 instead of mod 3, bazz, etc.) for this problem by simply adding another rule to the game. Below is the problem statement.
And as I am not a professional developer, I am especially interested in additional feedback on style, formatting, and adherence to SOLID principles, as well as limitations of this design.
Problem: Write a short program that prints each number from 1 to 100 on a new line. For each multiple of 3, print "Fizz" instead of the number. For each multiple of 5, print "Buzz" instead of the number. For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
Solution:
class Program
{
static void Main(string[] args)
{
var rules = new List<IRule>
{
new FizzMod3Rule(),
new BuzzMod5Rule(),
new BazzMod7Rule()
};
new FizzBuzzGame(rules).Play();
Console.ReadKey();
}
}
public class FizzBuzzGame
{
private List<IRule> _rules;
public FizzBuzzGame(List<IRule> rules)
{
_rules = rules ?? new List<IRule>();
}
public void Play(int numberOfRounds = 100)
{
for (var i = 1; i <= numberOfRounds; i++)
{
var output = string.Empty;
foreach (var rule in _rules) { output += rule.Run(i); }
if (output == string.Empty) { output += new EmptyRule().Run(i); }
Console.WriteLine(output);
}
}
}
public interface IRule
{
string Run(double number);
}
public class FizzMod3Rule : IRule
{
public string Run(double number)
{
return (number % 3) == 0 ? "Fizz" : string.Empty;
}
}
public class BuzzMod5Rule : IRule
{
public string Run(double number)
{
return (number % 5) == 0 ? "Buzz" : string.Empty;
}
}
public class BazzMod7Rule : IRule
{
public string Run(double number)
{
return (number % 7) == 0 ? "Bazz" : string.Empty;
}
}
public class EmptyRule : IRule
{
public string Run(double number)
{
return number.ToString();
}
}
Output:
1
2
Fizz
4
Buzz
Fizz
Bazz
8
Fizz
Buzz
11
Fizz
13
Bazz
FizzBuzz
16
17
Fizz
19
Buzz
FizzBazz
...
EmptyRule
class just to append a number to an empty string is an overkill. You should simply dooutput = i.toString()
\$\endgroup\$