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

dry-er arg type checking #340

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

0xor1
Copy link

@0xor1 0xor1 commented Jul 22, 2021

these changes are around unifying argument count and type validation errors:

many functions are of the format:

func foo(args ...Object) (Object, error) {
    if len(args) != 2 {
        return nil, ErrWrongNumArguments
    }

    a1, ok := args[0].(*Int)
    if !ok {
        return nil, ErrInvalidArgumentCount{
            Name: "first",
            Expected: "int",
            Found: args[0].TypeName(),
        }
    }

    a2, ok := args[1].(*String)
    if !ok {
        return nil, ErrInvalidArgumentCount{
            Name: "second",
            Expected: "string",
            Found: args[1].TypeName(),
        }
    }

    // now do some business logic with a1 and a2 knowing what types they are:
}

here I am proposing following a different pattern:

var foo = CheckStrictArgs(func(args ...Object) (Object, error) {
    a1 := args[0].(*Int)
    a2 := args[1].(*String)

    // now do something with a1 and a2 knowing what types they are:
}, IntTN, StringTN)

CheckStrictArgs is one of several functions that allow for a range of flexible argument type checking. The general idea is the call to them takes the function and the type names of the arguments and it will do the argument count and type checking for you, returning the same error values as previously, only the argument number error has more info.

My apologies for wasting time if this isn't in the scope of the project. I was only intending on adding in a http client module to the standard library but I couldn't help but find the manual error checking of the args ...Object very repatitve boilerplate code and not DRY.

@0xor1 0xor1 marked this pull request as draft July 22, 2021 18:06
@0xor1 0xor1 marked this pull request as ready for review July 23, 2021 08:48
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

Successfully merging this pull request may close these issues.

None yet

1 participant