开发者

Remove repetition from if-else statement

开发者 https://www.devze.com 2023-03-09 19:35 出处:网络
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

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.


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.


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.


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


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号