|
Re: Code Generation: The Real Lesson of Rails
|
Posted: Mar 21, 2006 11:21 AM
|
|
> Bill writes: > > >>> When I want to write something a certain way, because > it is a good design, but it still requires a lot of > repetive coding ...<<< > > Hmmmm, isn't good design supposed to avoid repetitive > coding? :-) > Yes, but sometimes you can't get there by abstracting via OO mechanisms, at least not without sacrificing other good things such as static type checking, readability, and speed of development. It is hard for me to figure out how to describe it, but there are situations in which you are repeatedly doing the same class of thing, but for which you couldn't make a class.
An example from our web apps is our controllers. We do have a superclass Controller , but each subclass has different parameters coming in from the request. So it would be hard in a superclass to parse the parameters once into instance variables that can be used, because every different controller would need different instance variables. So we find ourselves typing this kind of repetitive code:
String firstName = request.getParameter("first"); String lastName = request.getParameter("last");
Different controllers have different parameters, so we can't really factor this code out anywhere. What Rails does is look at the parameters at runtime when the request comes in, and creates instance variables with the property names. What we do is list the parameters in our DSL, and generate code that grabs then and puts them into instance variables. Then when we need to use the first name in our controller subclass, we just say firstName . It has already been declared and filled with a value from the request.
> Semantics aside, how about this example: > > for(Field field : fieldsToTabulate) > tableRow.set(field, user.get(field)); >
> instead of > > tableRow.setField("first_name", user.getFirstName()) > tableRow.setField("last_name", user.getLastName()) > ...(shake and repeat 10 times)... >
> The first has less code, but it can be also more flexible: > it is easy to modify display by just manipulating the > 'fieldsToTabulate' collection. > > Ultimately, I would like to have both: generated attribute > accessors for business logic that requires them AND the > ways to manipulate attributes in bulk.
We haven't needed the latter, so if we need it we can add it. But we try very hard to not add any code until we have a need for it.
|
|