Urbycoz
Urbycoz

Reputation: 7421

Remove repetition from if-else statement

I have written an if...else statement which uses an array myArr and a string myStr as follows:

If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

Upvotes: 1

Views: 1073

Answers (6)

Zaur Nasibov
Zaur Nasibov

Reputation: 22679

You can decompose the statements like this:

If myArr.Length > 0 Then
    If myArr(0) = "-1" Then
       'Do stuff
    Else
       'Do sstuff
    End If
Else
    If myyStr= "xyz" Then
        'Do stuff
    End If
End If

Upvotes: 0

Oswald
Oswald

Reputation: 31685

You might be able to get rid of multiple checks against myArr.Length by using nested If statements, but this makes the code less clear.

A clear approach (i.e. one that can be understood easily) is one that allows you to read a code fragment without having to remember the context in which the code is executed. By nesting If statements, more information must be kept in the readers working memory (or short term memory) to deduce the meaning of he code.

Upvotes: 1

Jon Egerton
Jon Egerton

Reputation: 41589

I don't think you'll be able to get exactly the same flow in a simpler way.

Either you're going to end up doing things different things, or doing duplicate things. eg:

If myArr.Length > 0 Then
   If myArr(0) = "-1" Then
      'Do stuff
   Else
      'Do stuff
   End If
ElseIf myStr= "xyz" Then
  'Do stuff
Else
  'Do Nothing
End If

This will cause mystr="xyz" not to happen whenn myArr(0) <> -1 whereas it may have before.

Upvotes: 2

devprog
devprog

Reputation: 285

If myArr.Length > 0 Then
  If myArr(0) = "-1" Then
    ' Stuff 1
  Else
    ' Stuff 3
  End If
ElseIf myStr = "xyz"
' Stuff 2
End If

... no further else needed

Upvotes: 0

parapura rajkumar
parapura rajkumar

Reputation: 24433

What you need is nested if

If myArr.Length > 0 Then
  'Do stuff for non zero length
    If myArr(0) = "-1" Then
       'Do stuff for -1 and you already have checked for array length
    End If 
End If

Upvotes: 0

filipe
filipe

Reputation: 1691

I guess this would do the trick:

If myArr.Length > 0 Then
   If myArr(0) = "-1" Then
      'Do stuff
   Else
      'Do stuff
   End If
ElseIf myStr= "xyz" Then
  'Do stuff
Else
  'Do Nothing
End If

Upvotes: 0

Related Questions