Yes, it is used to catch programming errors by introducing a little type
safety. How many times have you written this in your project:
function showMenu(obj) {
if(obj instanceof MenuItem) {
obj.getNode().style.visibility = "visible";
} else throw new Error("Invalid parameter!");
}
Now you can just do this:
function showMenu(obj) {
MenuItem(obj).getNode().style.visibility = "visible";
}
This convention just makes codifying assertions a little more uniform. You
know for sure that the parameter is of the correct type because (a) if it
isn't it, will be converted to the correct type; and (b) if it cannot be
converted, it will throw an error. This allows you to quickly detect and
correct bugs in your code and allows others (whom use your library) to
detect bugs in their code.
You are right is saying that it will succeed most of the time when
programmer errors are fixed. But do you remove error checking code because
of that? What if new code is added in the future? Keeping these type checks
in the code makes debugging it easier in the future. It also makes it clear
to maintainers what parameters the function requires and enforces that
requirement in a design-by-contract type of way.
I have to admit to a hard time understanding a real-world use case for
this. It seems like any situation where the method would fail would be
programmer error and need to be fixed, and any situation where it would
succeed, it would be unneccessary.
Is there something I'm missing here?
On 7/26/06, Em Te wrote:
I've been experimenting with extending Class.create() to do object casting
as well as its usual object creation. The idea is to use syntax similar to
performing object casts in C++. For example:
int i = (int)3.141;
Tree t = (Tree)obj;
Casting can also be used to do type verification, which Javascript is
loose about.
Tree t = (Tree)human; //throws exception
Tree t = (Tree)pine; //success
I thought about extending the function returned by Class.create() that
performs different actions depending on whether it is called as a function
or as a constructor.
car = new MyCar();
car = MyCar(obj); //may succeed or throw an error
MyCar(obj).startEngine();
[truncated]
_______________________________________________
Rails-spinoffs mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails-spinoffs