Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Delayed error checking #101

Closed
wirekang opened this issue Apr 21, 2022 · 4 comments
Closed

Delayed error checking #101

wirekang opened this issue Apr 21, 2022 · 4 comments

Comments

@wirekang
Copy link
Contributor

wirekang commented Apr 21, 2022

I use this function personally. With this, you can save dozens of lines with if err != nil. Execute all simple logics (doSimpleThing) first, and check the error later. The error will be the first occured error or nil.

func Delay[T any](target *error) func(v T, err error) T {
	a := func(v T, err error) T {
		if *target == nil && err != nil {
			*target = err
		}
		return v
	}
	return a
}

Example:

func doSimpleThing1() (int, error){...}
func doSimpleThing2() (string, error){...}

var err error

dInt := Delay[int](&err)
dString := Delay[string](&err)

_ = complexStruct{
    id: dInt(doSimpleThing1()),
    name: dString(doSimpleThing2()),
    email: dString(doSimpleThing2()),
    ...
}

// check error later
if err != nil {
    panic(err)
}

I think this function is appropriate for this package if there's a good name for it. Do you have a good idea?

@samber
Copy link
Owner

samber commented Apr 22, 2022

You use case is interesting.

I wonder if it could be replaced by Must+Try:

err, ok := lo.TryWithErrorValue(func() error {
    complexStruct{
        id: Must(doSimpleThing1()),
        name: Must(doSimpleThing2()),
        email: Must(doSimpleThing2()),
        ...
    }

    return nil
})

WDYT?

@wirekang
Copy link
Contributor Author

wirekang commented Apr 22, 2022

@samber
https://gist.github.com/wirekang/372054026f5f7db887d55485b8ee4ca2

I wrote 3 different way to make Person from ctx. I think Delay(temp name) way is also a decent way, although it's similar with Try way.

@samber
Copy link
Owner

samber commented Apr 22, 2022

Using this Delay function implies a side effect. I'm not a fan of such a pattern. In the library, we try to stay close to functional programming philosophy.

On the other side, Try+Must will halt the function and immediately return the error.

I don't want to block this contrib, but I wonder if we could make it easier to use.

@wirekang
Copy link
Contributor Author

I totally agree with you, and I think there are no way to make the function easier to use due to limitation of Go.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants