简体   繁体   中英

How can I shorten code?

Can I make this code shorter? I don't want to make all combinations from USD,EUR,CHF,GBP to USD,EUR,CHF,GBP for each one because the code is being too long for all conversions.

if (Convert.ToString(comboBoxInputMoney.Text) == "USD")
{
    if (Convert.ToString(comboBoxOutputMoney.Text) == "EUR")
    {
        double USD = double.Parse(textBoxInputMoney.Text);
        USD = USD * 0.74;
        textBoxResultMoney.Text = USD.ToString() + " EUR ";
    }
}

if (Convert.ToString(comboBoxInputMoney.Text) == "USD")
{
    if (Convert.ToString(comboBoxOutputMoney.Text) == "CHF")
    {
        double USD = double.Parse(textBoxInputMoney.Text);
        USD = USD * 0.92;
        textBoxResultMoney.Text = USD.ToString() + " CHF ";
    }
}

You could use a Dictionary to store the input currency and the exchange rate:

var dict = new Dictionary<string, Dictionary<string, decimal>>();
var usDict = new Dictionary<string, decimal>();
usDict.Add("EUR", 0.74m);
usDict.Add("CHF", 0.92m);
dict.Add("USD", usDict); 
// and so on ...

You don't need to create it always, you can reuse it and update the exchange-rates if something has changed. Then the number of input- or output currencies doesn't matter.

This is always the same code:

Dictionary<string, decimal> currencyExchange;
if (dict.TryGetValue(comboBoxInputMoney.Text, out currencyExchange))
{
    decimal rate;
    decimal value;
    if(decimal.TryParse(textBoxInputMoney.Text, out value)
      && currencyExchange.TryGetValue(comboBoxOutputMoney.Text, out rate))
    {
        textBoxResultMoney.Text = string.Format("{0} {1}"
            , value * rate 
            , comboBoxOutputMoney.Text);
    }
}

Your question is only asking that a small number of currencies are able to be converted, so my answer may be more involved than you need, but hopefully it may be of some use.

As some of the commenters have already said, a Dictionary would seem to be the way to go as you don't need huge swathes of currency exchange rates in your application. However, I'd also suggest separating out some of those concerns, so that if you do need to add new currency exchange rates in the future, it's easily do-able, and in one place (the ExchangeRateRepository class).

By using the repository pattern to access your data this also won't tie you in to any particular persistence technique and you can change-over to xml/DB/etc. in the future without needing to make changes to any of the consumers of that repository...and it will enable easy unit-testing.

As Hans said, it would be beneficial also to think in OO terms....instead of string (as I've used below) think about using a Currency object.

// Your calling code would now just be...

double amountToConvert = double.Parse(textBoxInputMoney.Text);
CurrencyConverter converter = new CurrencyConverter(new ExchangeRateRepository());
textBoxResultMoney.Text = converter.Convert(amountToConvert, comboBoxInputMoney.Text, comboBoxOutputMoney.Text);

// ...

public class CurrencyConverter
{
    private IExchangeRateRepository exchangeRateRepository;

    public CurrencyConverter(IExchangeRateRepository repository)
    {
        exchangeRateRepository = repository;
    }

    public string Convert(double amount, string fromCurrency, string toCurrency)
    {
        var fromRates = exchangeRateRepository.Rates.SingleOrDefault(a => a.Key == fromCurrency);

        if (fromRates.Key != null)
        {
            var toRate = fromRates.Value.SingleOrDefault(a => a.Key == toCurrency);

            if (toRate.Key != null)
            {
                return (amount * toRate.Value) + toCurrency;
            }
        }

        return string.Empty;
    }
}

public interface IExchangeRateRepository
{
    Dictionary<string, Dictionary<string, double>> Rates { get; }
}

public class ExchangeRateRepository : IExchangeRateRepository
{
    private Dictionary<string, Dictionary<string, double>> exchangeRatesLookup = new Dictionary
        <string, Dictionary<string, double>>
                                                                                     {
                                                                                         {
                                                                                             "USD",
                                                                                             new Dictionary
                                                                                             <string, double>()
                                                                                                 {
                                                                                                     {"EUR", 0.74},
                                                                                                     {"CHF", 0.92},
                                                                                                     {"GBP", 0.6}
                                                                                                 }
                                                                                         },
                                                                                         {
                                                                                             "EUR",
                                                                                             new Dictionary
                                                                                             <string, double>()
                                                                                                 {
                                                                                                     {"USD", 1.35},
                                                                                                     {"CHF", 1.23},
                                                                                                     {"GBP", 1.1}
                                                                                                 }
                                                                                         },
                                                                                     };

    public Dictionary<string, Dictionary<string, double>> Rates
    {
        get
        {
            return exchangeRatesLookup;
        }
    }
}
double rate;
if (comboBoxInputMoney.Text == "USD")
{
    if (comboBoxOutputMoney.Text == "EUR")
    {
        rate = 0.74
    }
    if (comboBoxOutputMoney.Text == "CHF")
    {
        rate = 0.92
    }

    double result = double.Parse(textBoxInputMoney.Text) * rate;
    textBoxResultMoney.Text = result.ToString() + comboBoxOutputMoney.Text;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM