SergeantSerk
SergeantSerk

Reputation: 140

Tidying up if statements

I made a little program that works out physics calculations using math.

I have couple of if statements that do same thing but to different variables, but it must be them as if a TextBox is empty, the int will be 0.

Here's the example:

if (firstForceTextBox.Text == "")
{
    firstForceInt = 0;
}
else
{
    firstForceInt = Convert.ToInt16(firstForceTextBox.Text);
}

if (secondForceTextBox.Text == "")
{
    secondForceInt = 0;
}
else
{
    secondForceInt = Convert.ToInt16(secondForceTextBox.Text);
}

I want to make sure that both firstForceTextBox.Text == "" and secondForceTextBox.Text == "" do the same job but make sure that one doesn't intervene with other.

Upvotes: 2

Views: 138

Answers (4)

vidstige
vidstige

Reputation: 13085

I would apply a refactoring technique called extract method to obtain someting like so

private UInt16 GetInt16(TextBox textBox)
{
    if (textBox.Text == "")
    {
        return 0;
    }
    else
    {
        return Convert.ToInt16(textBox.Text);
    }

private void Later() 
{
    firstForceInt = GetInt16(firstForceTextBox);
    secondForceInt = GetInt16(secondForceTextBox);
}

Upvotes: 2

NoLifeKing
NoLifeKing

Reputation: 1939

To clarify what I'm doing here.

First I set a default value for the two int stated.

Then I use int.TryParse to ensure that the code doesn't break if you put "banana" into the textbox. If it fails, it will just contain 0, like it should.

int firstForceInt = 0, secondForceInt = 0;
if(!int.TryParse(firstForceTextBox.Text, out firstForceInt))
{
    // Report error to GUI
}
if(!int.TryParse(secondForceTextBox.Text, out secondForceInt))
{
    // Report error to GUI
}

Upvotes: 7

user287107
user287107

Reputation: 9417

you can take my function from here: Elegant TryParse

and extend it:

public class Extensions
{
public static int? TryParse(string this Source)
{
if(string.IsNullOrEmpty(Source)) return null;
if(int.tryparse .... 
}

}

later you can write

firstForceInt = firstForceTextBox.Text.TryParse() ?? 0;

Upvotes: -1

landoncz
landoncz

Reputation: 2017

How about this:

firstForceInt = string.IsNullOrEmpty(firstForceTextBox.Text) ? 0 : Convert.ToInt16(firstForceTextBox.Text);
secondForceInt = string.IsNullOrEmpty(secondForceTextBox.Text) ? 0 : Convert.ToInt16(secondForceTextBox.Text);

Upvotes: 3

Related Questions