> My extract from this is: use panic() for programming errors and otherwise
> error return values. I've written a simple router that must be configured
> with a kind of regex: router.Register("/<city>/<street>", myHandler) If the
> pattern in the first parameter is wrong, panic() is called. Do you agree
> with this usage of panic?
>
> Another idea to use panic() is parameter checking like it is common in Java
> (
http://code.google.com/p/guava-libraries/wiki/PreconditionsExplained). That
> could reduce the debugging time and lead to more robust code without the
> error handling code in trivial cases. Example:
Don't do things that way, it will hide the possibility of an error,
the idea behind errors as values instead of exceptions is to force the
programmer to think when he is coding the use of that function instead
of simple allowing him to ignore the error handling code.
If you want a version of a function without the error handling, use
the MustXXX idiom, that way the user of your library is aware of a
possible panic (don't forget to document the function to explict
this).
How I would do it:
type Error string
func (e Error) Error() string {
return string(e)
}
const (
EmptyRoute = Err("Routes cannot be empty")
)
// Register the handler, the path cannot be empty.
//
// If the path is empty return EmptyRoute, otherwise return nil
func Register (path string, handler Handler) error {
if path == "" {
return EmptyRoute
}
// do processing
return nil
}
// Does the same thing Register does, but panic if an error happens
func MustRegister(path string, handler Handler) {
err = Register(path, handler)
if err != nil { panic(err) }
}
// User of your library
func main() {
// ...
// no reason to continue the program if can't register the handlers
MustRegister("/route1", handler1)
MustRegister("/route2', handler2)
// ...
// here the handlers can have a path defined by the user
// crazy requiriments...
if err = Register(userSuppliedRoute, handleUserSpecificThing); err {
log.Printf("Unable to load user route %v from database", userSuppliedRoute)
}
}
>
> func Register(path string, handler Handler) {
> if path == "" {
> panic("path must not be empty")
> }
> ...
> }
>
--
André Moraes
http://amoraes.info