gossamer icon indicating copy to clipboard operation
gossamer copied to clipboard

refactor: remove unnecessary Else

Open EmilGeorgiev opened this issue 1 year ago • 0 comments

Issue summary

some of the else statements can be removed and simplify the code. For example:

  1. If a variable is set in both branches of an if, it can be replaced with a single if:
var str string
if b {
  str = "Hello"
} else {
  str = "World"
}

can be replaces with:

str :=  "World"
if b {
  str = "Hello"
} 
  1. Another example is if the else is at the end of the method/function it can be avoided:
var Version = func() string {
	if VersionMeta != "stable" {
		return GetFullVersion()
	} else {
		return GetStableVersion()
	}
}()

can be replaces with:

var Version = func() string {
	if VersionMeta != "stable" {
		return GetFullVersion()
	} 
	return GetStableVersion()
}()
  1. When in the unit test expect nil or expect some boolean:
if tt.expectNil {
    assert.Nil(t, got)
} else {
    assert.NotNil(t, got)
}

can be replaces with:

assert.Equal(t, tt.ExpectNil, got == nil)
  1. Some complex if/else if/else ( this is example from the file ./dot/core/service.go):
if errors.Is(err, blocktree.ErrParentNotFound) && block.Header.Number != 0 {
	return err
} else if errors.Is(err, blocktree.ErrBlockExists) || block.Header.Number == 0 {
	// this is fine
} else {
	return err
}

can be replaces with:

if !errors.Is(err, blocktree.ErrBlockExists) && block.Header.Number != 0 {
	return err
}

EmilGeorgiev avatar Jun 09 '24 04:06 EmilGeorgiev