5 ms·
> "Because I don't have a lot of time to plan out the full requirements of my objects, it has been a great boost to productivity to just toss in an additional f
by asaph 9y ago
> "Because I don't have a lot of time to plan out the full requirements of my objects, it has been a great boost to productivity to just toss in an additional few attributes on unsuspecting objects, or quickly sort through a list of objects based on criteria that would require awkward reflection code in Java or C++."
In Java, sorting objects based on arbitrary criteria doesn't require reflection. Just pass in a Comparator to one of the JDK-supplied sort methods. It's not awkward. I'm not a C++ programmer but I suspect it's similar.
- pjmlp 9y agoWith C++ you can even do it over template parameters.
- throwaway080383 9y agoYep, in C++ you can pass in a lambda to create the comparator inline: std::sort( myvec.begin(), myvec.end(), [](obj& A, obj& b) { return A.attr < B.attr; } );
- brianwawok 9y agoThat is disgusting as a non-C++ programmer
- mhh__ 9y agoeh, it's not Haskell (or even D for that matter) but C++ has come a long way in the last few years.
- electricslpnsld 9y agoIf you use std::begin and std::end instead of the member functions this will even work with old-school C-style arrays.
- emmelaich 9y agoYes, and you can even use the range syntax instead of begin/end. Here's a file with a few different ways https://gist.github.com/anonymous/78b4f257e60d55537b36e2e4f3c6de9d https://gist.github.com/anonymous/78b4f257e60d55537b36e2e4f3...
- emmelaich 9y ago.. and Herb Sutter recommends those free functions over the member functions for this reason -- genericity.
- nrdvana 9y agoWhat I'm talking about is arbitrary attributes that might not exist on the base class, resulting in something like: std::sort( myvec.begin(), myvec.end(), [](obj& A, obj& b) { int A_attr1= dynamic_cast<Thing1*>(&A)? dynamic_cast<Thing1*>(&A)->attr1 : dynamic_cast<Thing2*>(&A)? dynamic_cast<Thing2*>(&A)->attr1 : -1; int B_attr1= dynamic_cast<Thing1*>(&B)? dynamic_cast<Thing1*>(&B)->attr1 : dynamic_cast<Thing2*>(&B)? dynamic_cast<Thing2*>(&B)->attr1 : -1; return A_attr1 < B_attr1; } ); and then compare that to @list= sort { ($a->{attr1} // -1) <=> ($b->{attr1} // -1) } @list;
- nrdvana 9y agoYou need reflection if the type of object you're comparing doesn't have that attribute, and only half the subclasses do. You then have to inspect the actual class to see if the attribute exists before you can access it, and the code to do that is so ugly it would take less time to go edit the base class and constructors to give them all the attribute. This is the hassle that perl is avoiding, in the same way that JavaScript would avoid it. Every object is just a collection of attributes and you can access them by name. It's not as efficient as structs or interfaces, but it's very convenient for prototyping.