ChainSafe / gossamer

🕸️ Go Implementation of the Polkadot Host
https://chainsafe.github.io/gossamer
GNU Lesser General Public License v3.0
427 stars 110 forks source link

refactor: remove unnecessary Else #4020

Open EmilGeorgiev opened 3 weeks ago

EmilGeorgiev commented 3 weeks ago

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"
    } 
  2. 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()
    }()
  3. 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)
  4. 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
    }