views:

48

answers:

3

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.ServiceController.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.

+1  A: 

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.

w69rdy
I didn't know if there was a standard way of handling the statement.
Jim
A: 

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.

Ben Voigt
+1  A: 

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

Jim