1

I have a set of codes in my function with a lot of if-else loops but each doing a diffrent one

like

if(ddlname.SelectedIndex = 0)
{
//do this
}
else
{
//do this
}

if (txtprice.Text ="")
{
//do tis
}
else
{
//do this
}

my whole program looks clumsy and unnecessarily long because of this one. I have some 20 dropdownlists and ten textboxes. Is there way to make this as simple as 1 or 2 for loops ?

Karthik Ratnam
  • 3,032
  • 2
  • 20
  • 25

1 Answers1

2

I am currently reading Clean Code by Robert C. Martin. According to his book, you should refactor your method into several smaller methods, doing exactly one thing. You should for example extract every do this into its own method.

As to your question, I don't think there is any way of achieving the same logic using for loops, unless you do the same for every call.

foreach (ctl in page.ctls)
{
  TextBox tempTextBox = ctl as TextBox;
  if (tempTextBox != null)
  {
    doTheSameForEveryTextBox(tempTextBox)
  }

  DropDownList tempDropDownList as DropDownList; // not sure if this is the right Type...
  if (tempDropDownList != null)
  {
    doTheSameForEveryTextBox(tempDropDownList)
  }
}

void doTheSameForEveryTextBox(TextBox tempTextBox)
{
  if (tempTextBox.Text == "")
  {
    //TODO: implement your code here
  }
}

void doTheSameForEveryDropDownList(DropDownList tempDropDownList)
{
  if (tempDropDownList.SelectedIndex == 0)
  {
    //TODO: implement your code here
  }
}
froeschli
  • 2,692
  • 2
  • 28
  • 55
  • foreach (ctl in page.ctls) - Can i do something like this ? – Karthik Ratnam Dec 07 '10 at 18:32
  • You could. But you would have to check the type of the ctl. A TextBox has no SelectedIndex, likewise a DropDownList won't have a Text property. – froeschli Dec 07 '10 at 18:34
  • One more, is Clean Code book is specially for c#. If it is so useful, I should get one too :] – Karthik Ratnam Dec 07 '10 at 18:36
  • That's what I am trying to convey. If I can write a for loop for textbox and another one for drop down lists and implement your code like ...................foreach (textbox in page.ctls){ if (textbox.text ="") and so on for drop down list in my idea. Is that possible in c#? – Karthik Ratnam Dec 07 '10 at 18:37
  • I edited my answer. This should get you going in the right direction. The as operator tries to cast the object. If that fails null is referenced. – froeschli Dec 07 '10 at 18:49
  • I ommitted an answer to your question about Clean Code. It is NOT C# specific. The code examples are Java actually, but the principles can be applied to all OO languages including but not limited to C#. I recommend reading this book. Other users have other opinions: http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read – froeschli Dec 07 '10 at 19:06