开发者

Multiple returns versus Exit for

开发者 https://www.devze.com 2023-01-08 16:22 出处:网络
I have the following VB.NET code (but for each loops are in most languages, thus the language-agnostic tag):

I have the following VB.NET code (but for each loops are in most languages, thus the language-agnostic tag):

  Public Function VerifyServiceName(ByRef sMachineName As String, ByRef sServiceName As String) As Boolean
    Dim asServices As System.ServiceProcess.ServiceController() = System.ServiceProcess.Ser开发者_StackOverflowviceController.GetServices(sMachineName)
    Dim bVerified As Boolean = False
    For Each sService In asServices
      If sService.DisplayName = sServiceName Then bVerified = True
    Next
    Return bVerified
  End Function

If I have X number of services to loop through, and my service name is #3. Is it better to have multiple return statements or an exit for? Or is there a more efficient way of writing this function?

I know that the time difference between looping X times and looping through 3 times could be marginal for what I am doing, but I always have performance on the brain.


I personally believe having one return at the bottom is far more readable and easier to debug than if you have return statements everywhere, as you can never tell when the function is going to exit so you end up putting breakpoints on every return statement instead of just once at the end, for example.

I think it's all down to preference though, as there are valid arguments for both ways.


Found more discussion here about the subject. I guess I am not that proficient at searching.


I would never use a goto as the target of another goto, so if there's some additional processing at the end of the function, use "break / Exit For", otherwise just return early. Otherwise you end up with lines that mean "return" but say "break"... that doesn't help maintainability.

0

精彩评论

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