Skip to content

proposal: Go 2: Allow multiple check for if operator with assignment #63292

Closed
@pmpavl

Description

@pmpavl

In the language, very often there are nested constructions consisting of the if operator. Because of this, there is a great cyclomatic complexity. Consider a two struct and one of them has a Validate() method:

type Example struct {
    Child *ExampleChild
    // ...
}

type ExampleChild struct {}

func (e ExampleChild) Validate() error {
    // ...
}

let's say, we want to write a validation method for the entire Example structure. Then, in the current syntax of the language, we need to first check that Child != nil, and only then call the validation method for Child:

func (e Example) Validate() error {
    // previous checks

    if e.Child != nil {
        if err := e.Child.Validate(); err != nil {
            // ...
	}
    }

    // another checks
}

Of course, we can check in the first if that Child == nil, but then we will have to terminate the function after executing the part responsible for Child != nil. But let's say there is more than one such pointer field, then there is no way to get rid of the nesting of if. We will have to put validation of fields inside the non-nil checking.

My suggestion is to allow the syntax to write constructions of this type:

func (e Example) Validate() error {
    // previous checks

    if e.Child != nil && err := e.Child.Validate(); err != nil {
        // ...
    }

    // another checks
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions