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

@odeke-em

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
}

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