morrisonlevi/Ardent

Binding to specific class (aka type template)

Mikulas opened this issue · 2 comments

Hi, this is a feature request / question rather than a bug. Straight to the point:

Does the current implementation allow for an equivalent of Vector<Student>, which would only allow insertion of Student instances (or descendants)?

While it would be a nice and useful feature, I can see how it would complicate both the nomenclature and api if there were implemented as Vector and TypedVector or whatever (and analogies for other templates). Another way would be somewhat like setType() on the current classes, but that feels like it wouldn't properly communicate it's implications once used in code.

I suppose I can always extend the current implementation and override the insert (or equivalent) method with type checking, but it would basically create a class that would have to be copied project to project every time.

Any thoughts on this?

PS: It would be so great for this collection if php actually supported type templates.

Mikulas,

Thanks for opening an issue for this. Let me share a few reasons why I decided not to add type-specific information:

  1. In PHP there is (currently) no way to do any kind of optimization by knowing what type of items the collection holds; in fact, adding type checking would only slow you down.
  2. PHP is a dynamic language; using strict typing in the collections goes against that spirit and culture.
  3. Storing the types doesn't help the toolchain (such as an IDE) in any way I can think of.
  4. The only benefit I could think of is that it guarantees that all objects in the collection are of the same type; this can be enforced by testing your code which you should be doing anyway.
  5. As you mentioned, it does add some complexity to both the APIs and implementation to support it.

In the end I decided it was not worth it. However, the groundwork is laid in such a way that you could easily decorate the implementations to restrict input if you would like to; there is even a TypeException provided by the library that you could throw.

This decision isn't final; feel free to try to persuade me otherwise if you think there are more benefits.

Right, I can see your point. I guess the only benefit is really just testing against TypeException being thrown rather than iterating over the map and checking instances. You got me on the spirit of php point anyway, it's true it does really make sense the way you've implemented it.
Alright, thanks for the explanation :)