Project

General

Profile

Actions

Feature #12625

open

TypeError.assert, ArgumentError.assert

Added by eike.rb (Eike Dierks) over 7 years ago. Updated over 7 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:76553]

Description

I am well aware that ruby is not typed (and so for a good reason)

But sometimes it makes sense to check the types (or values) of arguments upfront.
(It actually helps to narrow down your arguments to the known)

I'd like to suggest an extension to all the Error types.
(I should obviously come up with a gem first, but you get me)

I frequently write (in the prologue)
raise TypeError.new(...) unless SomeClass === arg

I suggest to extend TypeError so that I could write instead:
TypeError.assert(msg)(SomeClass, arg)
and i'd expect that to raise the exception in the calling frame (which can be done via the binding?)

We might want to do the same for ArgumentError:
ArgumentError.assert(msg){|arg| arg.nil?}
ArgumentError.assert('too low'){|arg| arg<0}

But obviously, this api is just a first shot.

I'm with you: we can't check args at compile time.
But checking args at runtime
should be done via well known verses.

added bonus:
we might want to make that a domain language.
We could attach the argument checking rules to the method.

This might help in generating automated testing rules.


No one wants types.
but annotating types helps a lot.

It helps in documenting the code.
It helps in making the code more foolproof.

def foo(arg)
    TypeError.assert(String, arg) # should raise in the foo frame if arg is not of type String
    ...
end
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0