JuliaLang/julia — pull request #1594 by toivoh (2012-11-22 10:13:31+00:00)
Title: RFC: @expect macro

I've found the `@assert` macro very useful for writing assertions in a compact and readable way. The same kind of format would be useful also when the condition to be checked is not really an assertion.

I therefore propose an analogous `@expect` macro, to e.g. check for fulfillment of preconditions to a function call. If an `@expect` fails, it is the caller of the function that is to blame,
as opposed to an assertion failure, where there is a bug in the function itself.

Compare e.g. the somewhat readable code

function split_fdef(fdef::Expr)
@expect (fdef.head == :function) || (fdef.head == :(=))
@expect length(fdef.args) == 2
signature, body = fdef.args
@expect is_expr(signature, :call)
@expect length(signature.args) >= 1
(signature, body)
end

to the much bulkier version without `@expect`:

function split_fdef(fdef::Expr)
if !(fdef.head == :function || fdef.head == :(=))
error("need fdef.head == :function or :(=)")
end
if !(length(fdef.args) == 2)
error("length(fdef.args) != 2")
end
signature, body = fdef.args
if !is_expr(signature, :call)
error("signature.head != :call")
end
if !(length(signature.args) >= 1)
error("length(signature.args) == 0")
end
(signature, body)
end

The latter takes longer time both to write and to read.

Do people think this is a good idea? Thoughts?