4

Guava Preconditions allow to check method parameters in Java easily.

public void doUsefulThings(Something s, int x, int position) {
    checkNotNull(s);
    checkArgument(x >= 0, "Argument was %s but expected nonnegative", x);
    checkElementIndex(position, someList.size());
    // ...
}

These check methods raise exceptions if the conditions are not met.

Go has no exceptions but indicates errors with return values. So I wonder how an idiomatic Go version of the above code would look like.

deamon
  • 89,107
  • 111
  • 320
  • 448

2 Answers2

2

It depends on context.

If doUsefulThings is a public function exported from a package, return an error. You can have exported package level error variables that you can return, and the caller can check if the returned error is equal to one of the documented ways to screw up.

If it's not exported, and it would be a programmer error to call it incorrectly, I think it's reasonable to panic(errors.New("bla bla bla")). Although the function would panic once you dereferenced that pointer, anyway.

For this: checkArgument(x >= 0, "Argument was %s but expected nonnegative", x) you can pass in uint.

Matt K
  • 13,370
  • 2
  • 32
  • 51
  • Panicing would be even okay in an exported function or method, especially if it is documented and possibly named MustXYZ see e.g. regexp.MustCompile (http://golang.org/pkg/regexp/#MustCompile) – Volker Oct 07 '12 at 22:44
-1

I'm not sure using assertions to check basic properties of the parameters is in the philosophy of the language.

In case of a parameter which really could have an invalid value without bug (for example you don't find it in database), you would return an error :

func doUsefulThings(s *Something) error {
      // return an error if your algorithm detect an invalid value

Asserting that s isn't nil would only add verbosity. There is no point in verifying you weren't provided nil.

Adding a return parameter, especially error forces all users to check this error. Don't write code in your function to defend against trivial bugs in the caller code. The caller should simply test it's not nil, if that's possible depending of the rest of the code, before calling your function.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758