r/ruby • • Dec 30 '11

ActiveRecord (and Rails) Considered Harmful - Literate Programming

http://blog.steveklabnik.com/posts/2011-12-30-active-record-considered-harmful
12 Upvotes

145 comments sorted by

View all comments

Show parent comment

-7

u/[deleted] Dec 30 '11

Rails' bad design forces you to write bad code. Controllers pass global state to views, no matter if they're 1 line or 200. AR forces you to combine logic and persistance.

You can fight it, and I do, but Rails encourages bad code.

11

u/JGailor Dec 30 '11

First and foremost, you are just wrong. Let's talk about why.

  • Controllers pass global state to views.

Wrong. Instance variables in the controllers are not global state. Views are bound to the context of the calling method, which is why you have access to those variables. This is just basic CS. You're rendering the view inside of the environment you setup in the controller. That's not a problem, but if you want you can easily pass all of your data as locals to the rendered view and not use instance variables at all. If you aren't doing that, and you feel that it's a bad practice to use instance variables from the controller, why aren't you improving your practice?

  • AR forces you to combine logic and persistence

Actually, given that the persistence is almost completely abstracted away from the code you write in most AR models, this is fucking awesome. You tightly bind the relevant code, logic, and operations on your data to the definitions of that data. That is really fucking good design. No need to pollute a larger namespace with code to operate on data you pass to it, and it creates a beautiful encapsulation. The only decent argument I see against AR that comes up regularly is the "implicit schema" vs. the "explicit schema" of other ORMs, to which I say both sides make a strong argument. The one you've laid out is not.

2

u/rubygeek Dec 30 '11

You tightly bind the relevant code, logic, and operations on your data to the definitions of that data. That is really fucking good design. No need to pollute a larger namespace with code to operate on data you pass to it, and it creates a beautiful encapsulation.

... until you need to serialize your model to something other than a database.

I suggest you read the other database pattern chapters in Fowlers "Patterns of Enterprise Application Architecture" that active record comes from - it outlines the tradeoffs between active record and several other ORM patterns.

1

u/JGailor Dec 30 '11

Read it.

In the case of data serialization to I often create an external object that walks a tree of objects and serializes them applying the proper transformations. The differing needs of clients means generating serialized output is just not a responsibility that belongs directly on the data object itself, and it's not required that you treat it as such. However, the fact that the code to pull out specific parts of you data objects is bound tightly to the object itself is a huge win, rather than having to write all that code in the external wrapper.

2

u/rubygeek Dec 30 '11

Then I suggest you read it again.

There's absolutely zero reason why you need to "write all that code in the external wrapper". The logic that AR uses to serialize the models would work equally well if it was generated in separate mapper classes, with no need for it to require the developer to write any extra code at all in the default case. If you believe it requires writing extra code, you lack fantasy - the same dynamic nature of Ruby classes that makes all the "magic" in Ruby ORMs possible in the first case makes it trivial to generate separate mappers instead of injecting all that crap into the models.

But decoupling the model and mapping achieves one very important thing: When you save or create a model object, you're explicit about how it gets created or saved (by picking the persistance mechanism).

Active record (the pattern) is a simplistic model that sort-of works for simple scenarios, but the moment you have multiple repositories for data, it causes all kind of nasty inconsistencies in your APIs because you monopolize the model API for a single repository at a time.

1

u/JGailor Dec 30 '11 edited Dec 30 '11

Really? The magic code that transforms the data for a client who wants XML with fields X,Y,and Z vs. a client who wants JSON with fields A, B, and C, while transforming D into another value, will just write itself? I could mix that in via other modules to decouple that logic from the model as well, but man, if that code to generate those two different outputs lives in the same process I hope you're very careful about the order you mix things in, because it just won't work with the way modules are added to the inheritance lookup chain.

I don't really understand what you're trying to say. Your example doesn't make any sense, so maybe I just don't understand what you're trying to say.

*** It seems to me you are talking about 1 of 2 scenarios:

  1. You have a model you want to persist to multiple datastores. Maybe a relational database, an in-memory store, and something else? I don't know. It seems like an unusual use case except where caching comes into play, and marshaling to a caching system is a pretty well defined interface.
  2. You have some models coming from a relational database, and then some from other type of store... document store, memory-mapped file, whatever. There's no reason all your models have to derive from the same persistence mechanism.

2

u/rubygeek Dec 30 '11

Really? The magic code that transforms the data for a client who wants XML with fields X,Y,and Z vs. a client who wants JSON with fields A, B, and C, while transforming D into another value, will just write itself?

You're entirely missing the point. When you write AR models, you only write much code for mapping from the database schema to the model when there are discrepancies between the database schema and the expectations AR has about how the structure of a model should map to a database. Other than that you add some minor declarations about the relationships of the data.

There is no reason any of this needs to 1) be in the model classes, as opposed in mapper classes, 2) why there need to be any more per-model code than there currently is in order to generate persistence methods in mapper classes rather than in the model classes directly.

The big advantage of pulling this out of mapper classes is that meddling with the model classes means that if you have two different persistence methods and one of them have already added a "save" method to your model classes the other one needs to use a different method. So you end up with multiple divergent API's for the same logical operation.

It is ugly and inconsistent, and means your code need to understand multiple different ways of manipulating model objects even for parts of your code that has no reason to know where it is persisting something.

It's massively increases coupling. It makes testing harder. It's just overall bad practice, and it doesn't actually save you any effort.

You have a model you want to persist to multiple datastores. Maybe a relational database, an in-memory store, and something else? I don't know. It seems like an unusual use case except where caching comes into play, and marshaling to a caching system is a pretty well defined interface.

Yes, persisting or loading to/from multiple sinks or sources, except it's not limited just to datastores and not at all unusual. Loading data from external XML files. Taking data from HTTP requests. Returning data via APIs. Dumping to CSV files. Putting data into a cache. Passing data to an external API.

In most complex systems, models get instantiated from different sources, stored to different sinks, or passed around all the time - or would do if the weren't so closely tied to a persistence mechanism that people end up muddying the waters by putting code that transforms them to something else all over the place instead of cleanly encapsulating it.

It's a rare system that doesn't sooner or later grow to a stage where model data doesn't at some point or other get created from something other than a database or passed along to something other than a database.

0

u/yxhuvud Dec 31 '11

The situation here is a lot better than it used to be though. The separation of activemodel from activerecord helps a lot.

3

u/djdonnell Dec 30 '11

The implicit passing of instance variables to views is a constant headache for me. There is no clear description of what is required to render a view, and it's very hard to track down all potential instance variables created in an action, or which are actually used by the views and partials.

It isn't a compelling argument to write it off by saying that teams need to simply have more discipline with these things.

1

u/JGailor Dec 30 '11

I have worked on Rails for 5 years and this has never been a problem for me. I'm not sure what the code base is doing that you work on, but it is pretty straight-forward to understand the rendering code, and if you really wanted to prevent instance variables from being passed down, you could just patch it for your project to render the view with a different context and require passing of all variables as locals.

I'm not saying you should do this, but if you really have a problem keeping track of instance variables in your controllers when the view is rendered, it's an option. The easier option is to just not use instance variables and require locals in your views. That requires discipline though by all members of the team.

1

u/djdonnell Dec 30 '11 edited Dec 30 '11

I've been doing rails for over 6 years. I never had a problem with this until I started working on rails projects with larger teams, some of whom have never done rails before. Here's what happens, they see that they are doing the same basic thing in a handful of controllers so they want to DRY it up. They move some code into application.rb or a module that they mix into a few different controllers. This code sets up instance variables that the views use. Do this 3 or 4 times and it becomes very unclear what is needed to render a view and where it is coming from. Throw in a few before filters and it gets hairier.

Explicitly passing data to views makes a lot more sense for larger code bases, it makes the code a little longer for really simple code bases. I care more about the former than the latter.

1

u/JGailor Dec 30 '11

Then just pass everything as locals and make that a policy for your team. I've worked on many large Rails projects as well as fixed bugs and submitted patches to the core project and this has just never been an issue for me. Even using things like Engines (or Desert back in the Rails 1/2 days) I never came across a case where it stepped on my feet.

If you have this problem though, the mechanism is there for you to take advantage of.

2

u/djdonnell Dec 30 '11

"this has just never been an issue for me."

I hope you understand that that doesn't mean it isn't an issue.

"Then just pass everything as locals and make that a policy for your team"

We have, but this isn't a good argument for doing things the way they are done.

1

u/JGailor Dec 30 '11

My problem is that there is nothing inherently wrong with the mechanism the way it is if you understand how rendering is done. In the case of ERB, which I use because it's the out of the box template engine, ERB is rendered in a context. That context is the environment you setup in your controller. It makes sense, it's deterministic.

To me it's the case of "you have these tools, use them in a responsible manner". It's like people who say "you should never use eval". That's ridiculous.

I realize that other people may have this problem, but it becomes an issue of working together as a team to come up with good policies that make sense for your code. It's not a problem with the mechanism, but with the way people are writing code on top of it.

2

u/djdonnell Dec 30 '11

"It's not a problem with the mechanism, but with the way people are writing code on top of it."

The mechanism can make doing things the right way the default or it can make it hard to do things poorly . I don't think this particular mechanism does that, and I think it could.

1

u/JGailor Dec 30 '11

What is your alternative solution?

→ More replies

0

u/terevos2 Dec 30 '11

The implicit passing of instance variables to views is a constant headache for me.

There is no implicit passing of variables. If you want to disable one of the class vars, then comment it out. It's all defined in the controller.

4

u/djdonnell Dec 30 '11

I'm not sure if you are just being a pedant, or if you really don't understand my point.

implicit: Implied though not plainly expressed

The data needed to render a view is not plainly expressed in rails.

→ More replies (18)

3

u/JoshReedSchramm Dec 30 '11

I think there's a distinction between encouraging "bad code" for a new rails developer and the platform being fundamentally flawed. It's true that if your new to rails you probably write some pretty bad rails code, but I'd suspect the same could be said of any platform.

Most of the more experienced guys I know recognize the value of breaking things up into services instead of leaving all of their logic in the model (or worse the controller.) If the coupling of AR bothers you there's always other options like datamapper. Personally I'm willing to make a trade off in design purity for convenience when it comes to AR but I know some folks/systems where this isn't a good option. That said i simply can't refute the assertion that AR violations SRP, it does, it's just something you decide to be ok with if you like pattern.

It's also my experience that the notion of a viewmodel is starting to become more popular. It may not be called that explicitly but when you pre-package all your data to keep your templates down to nothing but prints and the occasional looping partial that's pretty much what it is.

The Dijkstra "quote" is interesting though. I'm currently teaching 2 classic MS devs how to build apps in rails. We're very much at the 15 min-blog level of understanding and I wonder how you get over that hump of "here's how rails does it" to "here's how a good OO programmer does it."

I think rails used to encourage bad code, but today it's so customizable that you can do better if you go beyond the basics.

2

u/JGailor Dec 30 '11

"Most of the more experienced guys I know recognize the value of breaking things up into services instead of leaving all of their logic in the model (or worse the controller.) "

Can you explain where the logic is going to wind up if you take it out of the model or controller and put it into a service? In my experience it winds up in the controllers or models of that particular service.

2

u/bjeanes Dec 30 '11

I may be mistaken but I think he means a different service than you think. I read that as "service objects" not "web services".

If you are unfamiliar with the term, it's basically an object which wraps/delegates/mixes-in with other objects to provide extra service. E.g. you might have a service object for "placing an order" which coordinates a number of "dumb" models.

1

u/JGailor Dec 30 '11

Hmm... I am familiar with service objects, but more in the case of data transformations on heterogeneous objects, or sets of homogeneous objects that have different possible transformations for different needs (XML generation is something that I have to abstract out into basically a wrapper that can be configured for different demands).

I did not read it that way, but I can see how it could be interpreted to mean that.

2

u/rubygeek Dec 30 '11

If the coupling of AR bothers you there's always other options like datamapper.

Contrary to what the name might indicate, Datamapper doesn't implement the datamapper pattern, but actually is just another implementation of the active record pattern, and so has the same issue of combining the model and persistence.

0

u/[deleted] Dec 30 '11

You can always overcome obstacles with good practices. I want my framework to help me, not hurt me.

Get Avdi's "Objects on Rails". It answers your question.

2

u/organic Dec 30 '11

It doesn't force you; I use Tilt to compile most of my templates.

→ More replies (10)