jeudi 1 septembre 2016

Best way to structure this app?

Suppose a person works a number of hours. Said person can then bill these hours worked, however he can have any of the following three choices as far as how to bill:

1) Hourly - the number of hours worked * hourly rate

2) Dual - (for simplicity sake) first rate + second rate

3) Flat - just an amount, regardless of the hours worked

Here's the code that I came up with, but I just can't help but think that there's a much more elegant way to do this. In the code below I have a class per rate type, one base class for a rate, a person, and a calculator that does the math. Suggestions?

using System;

public class Program
{
    public static void Main()
    {
        Person p = new Person();
        p.HoursWorked = 2;
        p.Rate = new Hourly(10);
        //p.Rate = new Dual(10, 1);
        //p.Rate = new Flat(10);
        Console.WriteLine(Calculator.Calculate(p));
    }
}



public class Person
{
    public RateStyle Rate { get; set; }
    public int HoursWorked { get; set; }
}

public abstract class RateStyle 
{
}

public class Dual : RateStyle
{
    public int First { get; private set; }
    public int Second { get; private set; }

    public Dual(int a, int b)
    {
        First = a;
        Second = b;
    }
}

public class Hourly : RateStyle
{
    public int Rate { get; private set; }
    public Hourly(int r)
    {
        Rate = r;
    }
}

public class Flat : RateStyle
{
    public int Rate { get; private set; }
    public Flat(int r)
    {
        Rate = r;
    }
}

public static class Calculator
{
    public static int Calculate(Person p)
    {
        if (p.Rate is Hourly)
        {
            return p.HoursWorked * ((Hourly)p.Rate).Rate;
        }
        if (p.Rate is Dual)
        {
            return ((Dual)p.Rate).First + ((Dual)p.Rate).Second;
        }

        return ((Flat)p.Rate).Rate;
    }
}

Aucun commentaire:

Enregistrer un commentaire