all: simplify nested complexity and if blocks ending with a return statement (#21854)

Changes:

    Simplify nested complexity
    If an if blocks ends with a return statement then remove the else nesting.

Most of the changes has also been reported in golint https://goreportcard.com/report/github.com/ethereum/go-ethereum#golint
This commit is contained in:
Alex Prut 2020-11-25 09:24:50 +01:00 committed by GitHub
parent 29efe1fc7e
commit c92faee66e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 58 additions and 85 deletions

View File

@ -747,13 +747,11 @@ func DefaultConfigDir() string {
appdata := os.Getenv("APPDATA") appdata := os.Getenv("APPDATA")
if appdata != "" { if appdata != "" {
return filepath.Join(appdata, "Signer") return filepath.Join(appdata, "Signer")
} else { }
return filepath.Join(home, "AppData", "Roaming", "Signer") return filepath.Join(home, "AppData", "Roaming", "Signer")
} }
} else {
return filepath.Join(home, ".clef") return filepath.Join(home, ".clef")
} }
}
// As we cannot guess a stable location, return empty and handle later // As we cannot guess a stable location, return empty and handle later
return "" return ""
} }

View File

@ -1695,7 +1695,7 @@ func RegisterEthService(stack *node.Node, cfg *eth.Config) ethapi.Backend {
Fatalf("Failed to register the Ethereum service: %v", err) Fatalf("Failed to register the Ethereum service: %v", err)
} }
return backend.ApiBackend return backend.ApiBackend
} else { }
backend, err := eth.New(stack, cfg) backend, err := eth.New(stack, cfg)
if err != nil { if err != nil {
Fatalf("Failed to register the Ethereum service: %v", err) Fatalf("Failed to register the Ethereum service: %v", err)
@ -1707,7 +1707,6 @@ func RegisterEthService(stack *node.Node, cfg *eth.Config) ethapi.Backend {
} }
} }
return backend.APIBackend return backend.APIBackend
}
} }
// RegisterEthStatsService configures the Ethereum Stats daemon and adds it to // RegisterEthStatsService configures the Ethereum Stats daemon and adds it to

View File

@ -144,7 +144,7 @@ func (b *bridge) OpenWallet(call jsre.Call) (goja.Value, error) {
if val, err = openWallet(goja.Null(), wallet, passwd); err != nil { if val, err = openWallet(goja.Null(), wallet, passwd); err != nil {
if !strings.HasSuffix(err.Error(), scwallet.ErrPINNeeded.Error()) { if !strings.HasSuffix(err.Error(), scwallet.ErrPINNeeded.Error()) {
return nil, err return nil, err
} else { }
// PIN input requested, fetch from the user and call open again // PIN input requested, fetch from the user and call open again
input, err := b.prompter.PromptPassword("Please enter current PIN: ") input, err := b.prompter.PromptPassword("Please enter current PIN: ")
if err != nil { if err != nil {
@ -154,7 +154,6 @@ func (b *bridge) OpenWallet(call jsre.Call) (goja.Value, error) {
return nil, err return nil, err
} }
} }
}
case strings.HasSuffix(err.Error(), scwallet.ErrPINUnblockNeeded.Error()): case strings.HasSuffix(err.Error(), scwallet.ErrPINUnblockNeeded.Error()):
// PIN unblock requested, fetch PUK and new PIN from the user // PIN unblock requested, fetch PUK and new PIN from the user

View File

@ -369,9 +369,8 @@ func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, ma
// in this case it is cheaper to just read the header // in this case it is cheaper to just read the header
if header := hc.GetHeader(hash, number); header != nil { if header := hc.GetHeader(hash, number); header != nil {
return header.ParentHash, number - 1 return header.ParentHash, number - 1
} else {
return common.Hash{}, 0
} }
return common.Hash{}, 0
} }
for ancestor != 0 { for ancestor != 0 {
if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash { if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {

View File

@ -266,9 +266,8 @@ func (g *G1) Add(r, p1, p2 *PointG1) *PointG1 {
if t[1].equal(t[3]) { if t[1].equal(t[3]) {
if t[0].equal(t[2]) { if t[0].equal(t[2]) {
return g.Double(r, p1) return g.Double(r, p1)
} else {
return r.Zero()
} }
return r.Zero()
} }
sub(t[1], t[1], t[3]) sub(t[1], t[1], t[3])
double(t[4], t[1]) double(t[4], t[1])

View File

@ -287,9 +287,8 @@ func (g *G2) Add(r, p1, p2 *PointG2) *PointG2 {
if t[1].equal(t[3]) { if t[1].equal(t[3]) {
if t[0].equal(t[2]) { if t[0].equal(t[2]) {
return g.Double(r, p1) return g.Double(r, p1)
} else {
return r.Zero()
} }
return r.Zero()
} }
g.f.sub(t[1], t[1], t[3]) g.f.sub(t[1], t[1], t[3])
g.f.double(t[4], t[1]) g.f.double(t[4], t[1])

View File

@ -75,9 +75,8 @@ func (b *benchmarkBlockHeaders) init(h *serverHandler, count int) error {
func (b *benchmarkBlockHeaders) request(peer *serverPeer, index int) error { func (b *benchmarkBlockHeaders) request(peer *serverPeer, index int) error {
if b.byHash { if b.byHash {
return peer.requestHeadersByHash(0, b.hashes[index], b.amount, b.skip, b.reverse) return peer.requestHeadersByHash(0, b.hashes[index], b.amount, b.skip, b.reverse)
} else {
return peer.requestHeadersByNumber(0, uint64(b.offset+rand.Int63n(b.randMax)), b.amount, b.skip, b.reverse)
} }
return peer.requestHeadersByNumber(0, uint64(b.offset+rand.Int63n(b.randMax)), b.amount, b.skip, b.reverse)
} }
// benchmarkBodiesOrReceipts implements requestBenchmark // benchmarkBodiesOrReceipts implements requestBenchmark
@ -98,9 +97,8 @@ func (b *benchmarkBodiesOrReceipts) init(h *serverHandler, count int) error {
func (b *benchmarkBodiesOrReceipts) request(peer *serverPeer, index int) error { func (b *benchmarkBodiesOrReceipts) request(peer *serverPeer, index int) error {
if b.receipts { if b.receipts {
return peer.requestReceipts(0, []common.Hash{b.hashes[index]}) return peer.requestReceipts(0, []common.Hash{b.hashes[index]})
} else {
return peer.requestBodies(0, []common.Hash{b.hashes[index]})
} }
return peer.requestBodies(0, []common.Hash{b.hashes[index]})
} }
// benchmarkProofsOrCode implements requestBenchmark // benchmarkProofsOrCode implements requestBenchmark
@ -119,9 +117,8 @@ func (b *benchmarkProofsOrCode) request(peer *serverPeer, index int) error {
rand.Read(key) rand.Read(key)
if b.code { if b.code {
return peer.requestCode(0, []CodeReq{{BHash: b.headHash, AccKey: key}}) return peer.requestCode(0, []CodeReq{{BHash: b.headHash, AccKey: key}})
} else {
return peer.requestProofs(0, []ProofReq{{BHash: b.headHash, Key: key}})
} }
return peer.requestProofs(0, []ProofReq{{BHash: b.headHash, Key: key}})
} }
// benchmarkHelperTrie implements requestBenchmark // benchmarkHelperTrie implements requestBenchmark

View File

@ -588,9 +588,8 @@ func (n *NodeBalance) timeUntil(priority int64) (time.Duration, bool) {
} }
dt = float64(posBalance-newBalance) / timePrice dt = float64(posBalance-newBalance) / timePrice
return time.Duration(dt), true return time.Duration(dt), true
} else {
dt = float64(posBalance) / timePrice
} }
dt = float64(posBalance) / timePrice
} else { } else {
if priority > 0 { if priority > 0 {
return 0, false return 0, false

View File

@ -261,9 +261,8 @@ func (bt *BalanceTracker) storeBalance(id []byte, neg bool, value utils.ExpiredV
func (bt *BalanceTracker) canDropBalance(now mclock.AbsTime, neg bool, b utils.ExpiredValue) bool { func (bt *BalanceTracker) canDropBalance(now mclock.AbsTime, neg bool, b utils.ExpiredValue) bool {
if neg { if neg {
return b.Value(bt.negExp.LogOffset(now)) <= negThreshold return b.Value(bt.negExp.LogOffset(now)) <= negThreshold
} else {
return b.Value(bt.posExp.LogOffset(now)) <= posThreshold
} }
return b.Value(bt.posExp.LogOffset(now)) <= posThreshold
} }
// updateTotalBalance adjusts the total balance after executing given callback. // updateTotalBalance adjusts the total balance after executing given callback.

View File

@ -288,9 +288,8 @@ func activePriority(a interface{}, now mclock.AbsTime) int64 {
} }
if c.bias == 0 { if c.bias == 0 {
return invertPriority(c.nodePriority.Priority(now, c.capacity)) return invertPriority(c.nodePriority.Priority(now, c.capacity))
} else {
return invertPriority(c.nodePriority.EstMinPriority(now+mclock.AbsTime(c.bias), c.capacity, true))
} }
return invertPriority(c.nodePriority.EstMinPriority(now+mclock.AbsTime(c.bias), c.capacity, true))
} }
// activeMaxPriority callback returns estimated maximum priority of ppNodeInfo item in activeQueue // activeMaxPriority callback returns estimated maximum priority of ppNodeInfo item in activeQueue

View File

@ -329,9 +329,8 @@ func (r *ChtRequest) CanSend(peer *serverPeer) bool {
if r.Untrusted { if r.Untrusted {
return peer.headInfo.Number >= r.BlockNum && peer.id == r.PeerId return peer.headInfo.Number >= r.BlockNum && peer.id == r.PeerId
} else {
return peer.headInfo.Number >= r.Config.ChtConfirms && r.ChtNum <= (peer.headInfo.Number-r.Config.ChtConfirms)/r.Config.ChtSize
} }
return peer.headInfo.Number >= r.Config.ChtConfirms && r.ChtNum <= (peer.headInfo.Number-r.Config.ChtConfirms)/r.Config.ChtSize
} }
// Request sends an ODR request to the LES network (implementation of LesOdrRequest) // Request sends an ODR request to the LES network (implementation of LesOdrRequest)

View File

@ -112,9 +112,8 @@ var (
} }
enc, err := rlp.EncodeToBytes(&ne) enc, err := rlp.EncodeToBytes(&ne)
return enc, err return enc, err
} else {
return nil, errors.New("invalid field type")
} }
return nil, errors.New("invalid field type")
}, },
func(enc []byte) (interface{}, error) { func(enc []byte) (interface{}, error) {
var ne nodeHistoryEnc var ne nodeHistoryEnc

View File

@ -119,15 +119,14 @@ func (s *serverPoolTest) start() {
s.clock.Sleep(time.Second * 5) s.clock.Sleep(time.Second * 5)
s.endWait() s.endWait()
return -1 return -1
} else { }
switch idx % 3 { switch idx % 3 {
case 0: case 0:
// pre-neg returns true only if connection is possible // pre-neg returns true only if connection is possible
if canConnect { if canConnect {
return 1 return 1
} else {
return 0
} }
return 0
case 1: case 1:
// pre-neg returns true but connection might still fail // pre-neg returns true but connection might still fail
return 1 return 1
@ -135,17 +134,15 @@ func (s *serverPoolTest) start() {
// pre-neg returns true if connection is possible, otherwise timeout (node unresponsive) // pre-neg returns true if connection is possible, otherwise timeout (node unresponsive)
if canConnect { if canConnect {
return 1 return 1
} else { }
s.beginWait() s.beginWait()
s.clock.Sleep(time.Second * 5) s.clock.Sleep(time.Second * 5)
s.endWait() s.endWait()
return -1 return -1
} }
}
return -1 return -1
} }
} }
}
s.vt = lpc.NewValueTracker(s.db, s.clock, requestList, time.Minute, 1/float64(time.Hour), 1/float64(time.Hour*100), 1/float64(time.Hour*1000)) s.vt = lpc.NewValueTracker(s.db, s.clock, requestList, time.Minute, 1/float64(time.Hour), 1/float64(time.Hour*100), 1/float64(time.Hour*1000))
s.sp = newServerPool(s.db, []byte("serverpool:"), s.vt, s.input, 0, testQuery, s.clock, s.trusted) s.sp = newServerPool(s.db, []byte("serverpool:"), s.vt, s.input, 0, testQuery, s.clock, s.trusted)

View File

@ -219,9 +219,8 @@ func (n *autodisc) String() string {
defer n.mu.Unlock() defer n.mu.Unlock()
if n.found == nil { if n.found == nil {
return n.what return n.what
} else {
return n.found.String()
} }
return n.found.String()
} }
// wait blocks until auto-discovery has been performed. // wait blocks until auto-discovery has been performed.

View File

@ -240,9 +240,8 @@ func uint64FieldEnc(field interface{}) ([]byte, error) {
if u, ok := field.(uint64); ok { if u, ok := field.(uint64); ok {
enc, err := rlp.EncodeToBytes(&u) enc, err := rlp.EncodeToBytes(&u)
return enc, err return enc, err
} else {
return nil, errors.New("invalid field type")
} }
return nil, errors.New("invalid field type")
} }
func uint64FieldDec(enc []byte) (interface{}, error) { func uint64FieldDec(enc []byte) (interface{}, error) {
@ -254,9 +253,8 @@ func uint64FieldDec(enc []byte) (interface{}, error) {
func stringFieldEnc(field interface{}) ([]byte, error) { func stringFieldEnc(field interface{}) ([]byte, error) {
if s, ok := field.(string); ok { if s, ok := field.(string); ok {
return []byte(s), nil return []byte(s), nil
} else {
return nil, errors.New("invalid field type")
} }
return nil, errors.New("invalid field type")
} }
func stringFieldDec(enc []byte) (interface{}, error) { func stringFieldDec(enc []byte) (interface{}, error) {

View File

@ -454,9 +454,8 @@ func (net *Network) getNodeIDs(excludeIDs []enode.ID) []enode.ID {
if len(excludeIDs) > 0 { if len(excludeIDs) > 0 {
// Return the difference of nodeIDs and excludeIDs // Return the difference of nodeIDs and excludeIDs
return filterIDs(nodeIDs, excludeIDs) return filterIDs(nodeIDs, excludeIDs)
} else {
return nodeIDs
} }
return nodeIDs
} }
// GetNodes returns the existing nodes. // GetNodes returns the existing nodes.
@ -472,9 +471,8 @@ func (net *Network) getNodes(excludeIDs []enode.ID) []*Node {
if len(excludeIDs) > 0 { if len(excludeIDs) > 0 {
nodeIDs := net.getNodeIDs(excludeIDs) nodeIDs := net.getNodeIDs(excludeIDs)
return net.getNodesByID(nodeIDs) return net.getNodesByID(nodeIDs)
} else {
return net.Nodes
} }
return net.Nodes
} }
// GetNodesByID returns existing nodes with the given enode.IDs. // GetNodesByID returns existing nodes with the given enode.IDs.
@ -1098,7 +1096,6 @@ func (net *Network) executeNodeEvent(e *Event) error {
func (net *Network) executeConnEvent(e *Event) error { func (net *Network) executeConnEvent(e *Event) error {
if e.Conn.Up { if e.Conn.Up {
return net.Connect(e.Conn.One, e.Conn.Other) return net.Connect(e.Conn.One, e.Conn.Other)
} else {
return net.Disconnect(e.Conn.One, e.Conn.Other)
} }
return net.Disconnect(e.Conn.One, e.Conn.Other)
} }

View File

@ -39,9 +39,8 @@ func (e *testEncoder) EncodeRLP(w io.Writer) error {
} }
if e.err != nil { if e.err != nil {
return e.err return e.err
} else {
w.Write([]byte{0, 1, 0, 1, 0, 1, 0, 1, 0, 1})
} }
w.Write([]byte{0, 1, 0, 1, 0, 1, 0, 1, 0, 1})
return nil return nil
} }

View File

@ -404,9 +404,8 @@ func (c *Client) Notify(ctx context.Context, method string, args ...interface{})
if c.isHTTP { if c.isHTTP {
return c.sendHTTP(ctx, op, msg) return c.sendHTTP(ctx, op, msg)
} else {
return c.send(ctx, op, msg)
} }
return c.send(ctx, op, msg)
} }
// EthSubscribe registers a subscripion under the "eth" namespace. // EthSubscribe registers a subscripion under the "eth" namespace.

View File

@ -267,6 +267,5 @@ func estimateSize(n node) int {
return 1 + len(n) return 1 + len(n)
default: default:
panic(fmt.Sprintf("node type %T", n)) panic(fmt.Sprintf("node type %T", n))
} }
} }