Skip to content

style: privval/FilePVLastSignState.CheckHRS can use early returns and refactor by reverse conditional for more idiomatic Go code to reduce nesting #2154

Closed

Description

@odeke-em

If we examine this code

cometbft/privval/file.go

Lines 100 to 131 in f4d73cd

func (lss *FilePVLastSignState) CheckHRS(height int64, round int32, step int8) (bool, error) {
if lss.Height > height {
return false, fmt.Errorf("height regression. Got %v, last height %v", height, lss.Height)
}
if lss.Height == height {
if lss.Round > round {
return false, fmt.Errorf("round regression at height %v. Got %v, last round %v", height, round, lss.Round)
}
if lss.Round == round {
if lss.Step > step {
return false, fmt.Errorf(
"step regression at height %v round %v. Got %v, last step %v",
height,
round,
step,
lss.Step,
)
} else if lss.Step == step {
if lss.SignBytes != nil {
if lss.Signature == nil {
panic("pv: Signature is nil but SignBytes is not!")
}
return true, nil
}
return false, errors.New("no SignBytes found")
}
}
}
return false, nil
}
there is a bunch of unnecessary nesting which can be made much neater by

func (lss *FilePVLastSignState) CheckHRS(height int64, round int32, step int8) (bool, error) {
	if lss.Height > height {
		return false, fmt.Errorf("height regression. Got %v, last height %v", height, lss.Height)
	}

	if lss.Height != height {
		return false, nil
	}

	if lss.Round > round {
		return false, fmt.Errorf("round regression at height %v. Got %v, last round %v", height, round, lss.Round)
	}

	if lss.Round != round {
		return false, nil
	}

	if lss.Step > step {
		return false, fmt.Errorf(
			"step regression at height %v round %v. Got %v, last step %v",
			height,
			round,
			step,
			lss.Step,
		)
	}

	if lss.Step != step {
		return false, nil
	}

	if lss.SignBytes == nil {
		return false, errors.New("no SignBytes found")
	}
	if lss.Signature == nil {
		panic("pv: Signature is nil but SignBytes is not!")
	}
	return true, nil
}

Activity

  1. added 2 commits that reference this issue on Jan 28, 2024
    6e2264c
    3b4b1c3
  2. added a commit that references this issue on Jan 29, 2024
    aad77ed
  3. added a commit that references this issue on Jan 29, 2024
    5ef38ad
  4. added a commit that references this issue on Jan 29, 2024
    ceff662
  5. added this to the 2024-Q1 milestone on Feb 1, 2024
  6. moved this from Todo to Done in CometBFTon Mar 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions