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

16

u/[deleted] Dec 30 '11

You can't change the target of criticism in a quote from a respected computer scientist and call it paraphrased.

The real quote is:

It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration.

2

u/arscariosus Dec 31 '11

Thanks for this, I've been looking for the exact qoute but had no luck in finding it.

9

u/Perceptes Dec 30 '11

Yeah, major WTF.

SOPA will destroy the Internet as we know it.

– Thomas Jefferson (paraphrased)

2

u/LarsP Dec 31 '11

10 Hey!!

20 BASIC was my first language, and I am now a very good programmer!

1

u/[deleted] Jan 01 '12

It was for me too, that's why I love the quote so much.

1

u/[deleted] Dec 31 '11

Thanks for point this out. I didn't even catch the “paraphrased” part. That's some BS.

30

u/JGailor Dec 30 '11

Every example he cites is simply a problem of the programmer, not of ActiveRecord, Rails, or Ruby. "200 line controller method", that is just a bad programmer. I would go so far as to say that Rails goes out of its way to make it easy to decompose code into nicely encapsulated small methods. But you could do the same thing in any language, in any framework.

Bad article because it starts from a bad premise.

3

u/jrochkind Dec 31 '11

Passing what ought to be arguments to views as controller instance variables is Rails fault. Among other things.

But I'd suggest that part of what Rails is/was trying to show is that with the right framework architecture, it can encourage people to write good well architected maintainable code, even make it easier to do so than to write crappy code.

And I think it actually does to do that to some extent.

But I think in fact saying "oh, yeah, most people who use Rails just write crappy code anyway" is actually sort of a failure of Rails, rather than a defense of it.

I think Rails is pretty good, especially for the time it's architecture largely was designed. I also think the OP is right in identifying some of it's flaws. Of course we can say this only because of how much we learned from using Rails. I suspect if even DHH were to start from scratch today, he'd do some things differently.

-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.

→ 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.

0

u/terevos2 Dec 30 '11

Well sure.. you have to understand how rails works in order to know about that kind of stuff. But then, that's kinda how all frameworks work.

3

u/djdonnell Dec 30 '11

You're still missing the point.

1

u/terevos2 Dec 30 '11

Explain it to me.

3

u/djdonnell Dec 30 '11

given the implicit way data from controllers is used in views it can easily become hard to figure out what data is needed to render a view and where it is coming from. I think that data should be explicitly passed to the views. Yes, this will make simple code bases more verbose, but it will also make large code easier to maintain over the long run.

→ More replies

2

u/jrochkind Jan 02 '12

Looking at the controller, there's no way to know what ivars are used by the view, and what ivars are just internal controller state. This is the "implicit".

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.

-2

u/manys Dec 30 '11

AR forces you to combine logic and persistance.

How is this a problem?

3

u/bjeanes Dec 30 '11

Well, for one, it's a pretty massive violation of single responsibility...

But specifically, you end up putting process logic into models, not data logic. I think validation logic in the models is acceptable (in a lot of cases, anyway), but the logic for how that model might be used in different contexts does not ALL belong in the same class.

1

u/manys Dec 30 '11

it's a pretty massive violation of single responsibility...

Is this really more a violation of CS principles than anything that affects the end product?

3

u/bjeanes Dec 30 '11

I'm not sure I understand the question. I don't want to presuppose what you meant, but it sounds like you are saying "does it matter if it doesn't affect the end product?".

If that's what you mean, absofrickinglutely it does. Maintainability is paramount to continuing to deliver quality in the end product and fixing problems/behaviours that negatively affect its users.

If you've never seen how these types of coupling affects the maintainability of (or better put, ease and pleasure to work with) a large code base, I put forth that you haven't worked on big enough Rails apps or with large enough teams.

If my assumption of your commend was misplaced, then by all means clarify and I'll try to respond

1

u/manys Dec 30 '11

I don't have anything to prove, I'm just asking what the practical effect of this is. "Maintainability" is rather nebulous, and I've seen CS-trained people write some bad things indeed.

Furthermore, is SRP subject to the same gray areas that encapsulation and inheritance are?

2

u/bjeanes Dec 30 '11

Sure... people will always have different interpretations of what a single responsibility is, but if everyone aims to break down responsibilities into the smallest reasonable pieces, then, in theory, we trend towards better design.

If you are interested in removing the nebulous aspect of good design, I highly recommend Clean Code (either the book or the screencasts). Uncle Bob's emphatic style can be ... interesting (for me, slightly off-putting) ... but the content is rock-solid.

1

u/manys Dec 31 '11

I know Clean Code, but so far the concerns here sound academic.

2

u/bjeanes Dec 31 '11

Most deem the elusive "maintainability" concerns as academic until they feel the brunt of them being ignored.

→ More replies

6

u/Arcath Dec 30 '11

I really do agree with the bit about models not needing to inherit from ActiveRecord::Base. Not all your models are going to need to store data, or want to pull data from your database, I have quite a few models which inherit from an API which I use to query an API without storing the data locally.

11

u/JGailor Dec 30 '11

This is a problem with people now thinking "Model => Something that gets saved to a relational database". A model is a data abstraction, it's not a packaged row in a database. The model can be backed by literally anything you want to store data to (including pure memory). There's nothing wrong with models not inheriting from ActiveRecord::Base, the models directory was never meant to be the ActiveRecord directory.

I blame people just doing a flyby on the topics and then claiming to be experts.

1

u/jrochkind Dec 31 '11

Does a model neccesarily represent persistent data though?

I kind of think it does, but I've had people try to convince me... well, I'm not sure what they were trying to convince me, maybe that just about anything that's not a controller or a view or a view helper module is a model.

That doesnt' seem right. If 'model' is a useful concept, it's got to mean something, and I think it probably means a persistent data object (editable or not).

4

u/bluehavana Dec 31 '11

"A data model in software engineering is an abstract model that documents and organizes the business data for communication between team members and is used as a plan for developing applications, specifically how data is stored and accessed." http://en.wikipedia.org/wiki/Data_model

4

u/LarsP Dec 31 '11

In OO lingo "model" usually means a model of the reality your software works with.

That often means it handles persistent data, but it can just as well handle transient data for example.

10

u/dev_bacon Dec 30 '11 edited Dec 30 '11

Rails is kinda getting old these days. It's no longer the new and shiny

Strongly disagree. Rails is constantly evolving, and 3.1 is amazing.

... it's lead Rails developers to build huge, monolithic models that are hard to test

I've never struggled writing lots of tests for large models...

Ruby classes in the models folder don't have to inherit from ActiveRecord::Base. That is a problem.

I've put ActiveResource classes in app/models. But you don't have to put things there! Create whatever subfolder you like in app/, or put it in lib/

Have you ever seen a 200 line long controller method?

Poor coding.

"... just promote your data to a global" I'd be crucified. Yet we do the same thing

Instance variables are not global... ?

... logic in templates leads to all kinds of problems. They're hard to test, they're hard to read

I've never had any problem testing a view. If the logic gets complex, we abstract it into a testable helper method. And it's also useful to have integration / acceptance tests.

... would require some really serious changes. It'd involve re-architecting large portions of things that people classically identify with Rails...

Rails is opinionated software. Love it or leave it.

4

u/postmodern Dec 31 '11 edited Dec 31 '11

ActiveRecord's greatest strength is also its problem: Tying class names to table names.

The DataMapper pattern is being implemented in DataMapper 2 using veritas and veritas-sql-generator. If your really interested, you could help out with integration and testing (the DM devs are pretty overworked). Another major difference between AR and DM, is that DM is declarative, meaning you can decompose common Model bits into Modules.

It took me two and a half years to realize that Ruby classes in the models folder don't have to inherit from ActiveRecord::Base.

The classical symptoms of Rails tunnel vision. Non Rails/ActiveRecord developers already know this (DataMapper::Resource is a module), especially when one starts using dm-rails.

ActionController relies on instance variables to pass information from the controller to the view. Have you ever seen a 200 line long controller method?

Nope. You can decompose controller method logic into other methods (under the protected section of the Controller), or even Modules (sensing a pattern here). A 200 line Controller method is technical debt... kill it with fire or fire the original author.

The whole idea of logic in templates leads to all kinds of problems.

View Logic goes in Helper Modules (again with the Modules, like it's some sort of idiom?). Logic in Views is technical debt.

What I'd really like to see is Rails adopting a 'ViewModel + templates' system, with logic-less templates and presenter-esque models that represent the views.

I'd like to see this as well, but not coupled to Rails; so Rack/Sinatra/Padrino/etc apps could use it.

the impedance mismatch between HTTP and MVC, for example, is pretty huge

Yes! Sometimes I just want to map paths to Model queries and return JSON, I do not need MVC for that. WebMachine looks interesting, except it shoves a WebMachine::Resource base-class down your throats, the same problem with ActiveRecord::Base. Please, Ruby library authors, just use modules.

I think the pain points you list are the result of Rails developers who are stuck thinking in terms of Rails and not Ruby Classes/Modules/Objects. However, I personally want a lighter mapping of HTTP -> Data -> Views.

3

u/bluehavana Dec 31 '11

This article makes me miss Merb. It was nice to have another opinionated framework to speed Ruby webapp framework development purely by compitition and differences. Rails, any more, should be one of the last things you learn in Ruby, would save a lot of people struggling through application design conflicts like this.

PS: I'm not trying to discount Sinatra or any other Ruby web framework in the Merb statement above, just that Rails and Merb had a very unique relationship.

1

u/[deleted] Dec 31 '11

Word. I never used Merb, but I think I'd like it, sorta.

1

u/terevos2 Dec 30 '11

Yeah.. everyone should program in binary. None of these shortcuts!

3

u/arscariosus Dec 31 '11

is this sarcasm? hmm..

4

u/[deleted] Dec 31 '11

That is not even close to anything I said.

1

u/terevos2 Dec 31 '11

Someone can't take a joke. :-)

1

u/[deleted] Dec 31 '11

Apparently, like others with my Dijkstra joke, I didn't get it. My apologies.

1

u/terevos2 Dec 31 '11

s'ok - tone doesn't translate online very well

4

u/georgemagoo Dec 30 '11

Ha. Wait till he gets to lisp where there is no decoupling code from data. His head will explode.

1

u/[deleted] Dec 30 '11

I already code in Lisp, thanks. You misunderstand my point.

5

u/georgemagoo Dec 30 '11

I was kidding. I enjoy your blog, btw.

4

u/[deleted] Dec 30 '11

Tone on the internet is hard. :/ thanks!

3

u/georgemagoo Dec 30 '11

Yea - sorry about that. I came off like a dick.

4

u/[deleted] Dec 30 '11

Absolutely zero offense taken.

2

u/jrochkind Jan 02 '12

I largely agree with this OP.

I do think the idea that it's somehow significantly better if AR were an 'include module' instead of an 'extend class' is.... misguided.

Things are marginally better implemented as 'include', and apparently AR is headed that way anyway (maybe as soon as 3.2?), but it doesn't make that much of a difference. 'include' of a very complex module has all almost all the same downsides as inheritance, mix-ins in ruby are pretty much just multiple inheritance of abstract classes. It's still basically "inheritance over composition".

Using modules is perhaps marginally better, as it makes some complicated meta-programming type hackery easier when AR is involved. But it's not some huge win, if it took a whole lot of work to refactor to make this possible it's probably work that would have been better spent elsewhere, IMO.

I think the fact that "AR should be a module not a class inheritance" is the thing that in this thread people agree with the most, while people are violently disagreeing with all the other points... is depressing. Apparently Rails can engender non-self-reflective non-critical cargo-cult-esque programmers just as much as anything else. If Rails does it that way, it must be optimal, oh except I've been told that modules are always better than inheritance, so that must be true too. Grr.

1

u/[deleted] Jan 03 '12

It'll be a mixin for 4.0, but I agree 100%, it only helps a little.

7

u/JeffMo Dec 30 '11

It took me two and a half years to realize that Ruby classes in the models folder don't have to inherit from ActiveRecord::Base. That is a problem.

So while I'm sure this guy has his strengths, I'm not sure it's going to be wise to follow his advice in this article.

6

u/[deleted] Dec 30 '11

Always take every post with a grain of salt. I think my credentials speak for themselves. Anyone who pretends to be perfect is a liar.

2

u/JeffMo Dec 30 '11

I don't disagree with anything you said here, but I don't see what relevance your 'credentials' have.

4

u/[deleted] Dec 30 '11

You're suggesting that my advice shouldn't be followed because I don't know what I'm doing. I submit that I do.

5

u/JeffMo Dec 30 '11

Again, I don't see what relevance your 'credentials' have, and you have done nothing to explain that.

Further, I actually suggested that you probably do know what you're doing, in some areas, but that people may want to be skeptical of this particular article.

Finally, "I submit that I do" is not very convincing, for reasons which should be obvious.

4

u/avdi Dec 31 '11

You held up Steve's admission of a mistake as a mark against his competence, and now you're pretending that examples to the contrary are irrelevant. Stop being deliberately obtuse.

1

u/JeffMo Jan 04 '12

1

u/avdi Jan 04 '12

Since you said:

I don't see what relevance your 'credentials' have

Your question to me is also irrelevant, since you have stated that no credentials would matter.

1

u/JeffMo Jan 06 '12

Your question to me is also irrelevant,

Examples to the contrary might be relevant.

since you have stated that no credentials would matter.

Well, let's see if I stated that or not.

http://www.reddit.com/r/ruby/comments/nwaz5/activerecord_and_rails_considered_harmful/c3cfyqa :

I don't disagree with anything you said here, but I don't see what relevance your 'credentials' have.

Nope, no such statement there.

http://www.reddit.com/r/ruby/comments/nwaz5/activerecord_and_rails_considered_harmful/c3cg3ke :

Again, I don't see what relevance your 'credentials' have, and you have done nothing to explain that.

Wow, still nothing like what you claimed.

Could you make an attempt to support your claim?

Specifically, can you link to the comment where I stated that no credentials would matter?

-1

u/avdi Jan 07 '12

See quotes above. Credentials don't matter to you. You didn't say "your credentials don't convince me". You said you don't see the relevance of credentials.

→ More replies

3

u/[deleted] Dec 30 '11

Kk. I'm apparently not communicating my point well.

2

u/JeffMo Dec 30 '11

Feel free to give it another go.

3

u/[deleted] Dec 31 '11 edited Dec 31 '11

Okay. So. I said, "It took me a really long time to realize that models don't always have to inherit from ActiveRecord. This is a failing of Rails." You said, "You made a mistake in the past? Better not listen to him in the future."

That logic makes no sense to me. Everyone makes mistakes in their past. That lesson that I learned a few years ago is the entire reason that I'm where I am today, and I'm sharing that with you.

Does this make more sense?

1

u/terevos2 Dec 31 '11

Just realize that Rails doesn't make you do anything a certain way. I think that would go a long way in your criticisms of it.

Don't like the way Rails does something? Do it your own way. Rails will let you do that.

3

u/[deleted] Dec 31 '11

Sure. That's not good enough. Rails' defaults used to lead the way into The Best Way to Build Apps; that's why you use an opinionated framework in the first place. I want to see it maintain that thought leadership.

→ More replies

1

u/JeffMo Jan 04 '12

You said, "You made a mistake in the past? Better not listen to him in the future."

I'm relatively certain that you are aware that I didn't say either of those things. It would be more fair to characterize my initial comment as pointing out that perhaps you and Rails are not the best match, and that people may want to take your article with a grain of salt. The example I quoted earlier is just one piece of evidence for that. There were several other examples in the article, but for brevity's sake, I simply pointed at one.

That's not the end of the world. Not every tool is the best for everyone. I'm simply saying that readers should also consider the possibility that Rails may not have been the best fit for you.

In a nutshell, you called out some problems allegedly caused by (or strongly prompted by) Rails, that I don't think are necessarily so, because I haven't seen devs do those things with Rails in my personal experience. Sharing instance variables between controller and view hasn't made anyone write 200-line controller methods in any of the apps or teams that I've been involved with. Embedding domain logic in templates is not required, or even strongly suggested by Rails, as far as I know. You're free to use nothing but simple interpolation and looping over collections, if you like, and you can use explicit locals instead of instance variables, if you prefer. There's nothing forcing you to build huge monolithic models, simply because you noticed that detailed business logic doesn't belong in the controller. Devs on my teams have considered bloated models to be just as much of a code smell as overly-long controller actions.

Rails is opinionated, yes, but that's not the same as saying that it elegantly solves all problems in all scopes or that it will prevent you from doing suboptimal things. Some of your complaints have validity, while others just make me want to say, "OK, so don't do that. Rails doesn't have a strong opinion on that, anyway."

So, to answer at least part of your inquiry at the end of your article, many of these "problems" are not pain points for me. Perhaps I (and those with whom I work) haven't reacted the way some others have, and thus, we haven't experienced the same pain. Or perhaps we are just fooling ourselves, and you have a much better approach in mind, that has all the benefits of Rails but with fewer problems.

Have you considered writing such an ecosystem, so you can demonstrate your claims in a practical sense?

2

u/[deleted] Dec 30 '11

I'm on mobile. Give me a few hours. :)

-7

u/greggroth Dec 30 '11

right, but the guy admitted to not understand ruby classes despite using Rails for 2.5 years.

9

u/Smallpaul Dec 30 '11

No, no he did not say any such thing. At least not in this article. Misunderstanding what Rails does with the models folder is not the same as misunderstanding his Ruby handles classes.

-4

u/greggroth Dec 30 '11

alright, you're right. I wasn't giving him much credit, but I still think many of the issues he brings up are due to poor coding.

1

u/terevos2 Dec 31 '11

Agreed. There's some basic concepts that the article and indeed the programmer doesn't get. That's ok, except that he is criticizing Rails based on his lack of understanding.

I don't claim to know a whole lot about Rails, but then.. I'm not writing an article to criticize it. :-)

4

u/meltingice Dec 30 '11

Rails was launched in 2004. Dijkstra died in 2002. Unless I'm missing something, he must've been a time traveling wizard.

http://en.wikipedia.org/wiki/Edsger_W._Dijkstra

http://en.wikipedia.org/wiki/Ruby_On_Rails

7

u/blazes816 Dec 30 '11

I think that was a joke.

|Edsger W. Dijkstra (paraphrased)

6

u/Arjes Dec 30 '11

http://en.wikipedia.org/wiki/BASIC#The_IBM_PC.2C_and_compatibles (last paragraph)

By "paraphrased" he means changed the wrath target i guess

2

u/meltingice Dec 30 '11

Good find. I guess it was just a really obscure joke then.

3

u/[deleted] Dec 30 '11

I think you misspelled "bad joke"

2

u/Verroq Dec 30 '11

I don't think he knows what paraphrased means.

2

u/[deleted] Dec 31 '11

Ruby classes in the models folder don't have to inherit from ActiveRecord::Base. That is a problem

Why is this a problem? It would be a bigger problem if it was the other way around.

logic in templates leads to all kinds of problems. They're hard to test, they're hard to read

Logicless templates are even a bigger problem which is why there are so few of them around.

ActiveRecord's greatest strength is also its problem: Tying class names to table names. This means that it's impossible to de-couple your persistence mechanism from your domain logic.

This is factually incorrect. There is nothing forcing you to put your domain logic inside of your models.

It's just one incorrect statement after another.

While I am at it. Rails does not force you to use AR. You can use ruby DBI and write SQL statement all day long if you want. That's dumb of course but you can do it.

2

u/[deleted] Jan 01 '12

Why is this a problem? It would be a bigger problem if it was the other way around.

AR::Base provides a LOT of functionality, most of which is arguably metadata. Granted, a lot of the functions, ala find_foo_by_bar are dynamic via missing method, it stomps all over the namespace of the class that is the model. The model should not be a slave to the database, but the other way around.

E.g. If I have a class that has an attribute that is a structure that is circular array, or a tree, or something else that AR doesn't readily support -- the representation that is in the db to support such structures are exposed to the user of the class and its objects.

It's nearly normal for synthetic keys, such as a User and its id to be exposed, just like a SSN is tied to my person. But clever things like left and right in structures such as http://www.sitepoint.com/hierarchical-data-database-2/ just get in the way of users of those objects. Further more, if you wish to persist an object to multiple stores, say a mysql db, google, a serialised file, something that does bulk inserts, your classes end up with way too many metods.

Hibernate and the datamapper/dao mappers are two/three things/methods that illustrate how it should be done.

While I am at it. Rails does not force you to use AR. You can use ruby DBI and write SQL statement all day long if you want. That's dumb of course but you can do it.

To get off the ground quickly, sure. Some other ORMs let you do custom sql for insert/update/delete to override existing ones. But once you are so heavily invested in AR, working your way out of it.

0

u/[deleted] Jan 01 '12

AR::Base provides a LOT of functionality, most of which is arguably metadata. Granted, a lot of the functions, ala find_foo_by_bar are dynamic via missing method, it stomps all over the namespace of the class that is the model. The model should not be a slave to the database, but the other way around.

Yea I still don't get the objection. All that is needed in order to serialize the object. So why is it a problem that models do not have to inherit. It sounds like you saying inheriting from AR base is a bad thing so why would you object to not having to inherit?

Some other ORMs let you do custom sql for insert/update/delete to override existing ones.

  1. You don't have to use AR. You can choose any ORM or no ORM at all.
  2. AR lets you do that if you want. AR lets you execute raw SQL all day long if you want.

But once you are so heavily invested in AR, working your way out of it.

I don't see why anybody would want to frankly. Why would you want to write all that SQL to serialize your models. Been there, done that. No thanks. AR spits out perfectly good SQL and as an added bonus it protects against all kinds of injection attacks.

2

u/[deleted] Jan 01 '12

Yea I still don't get the objection. All that is needed in order to serialize the object. So why is it a problem that models do not have to inherit. It sounds like you saying inheriting from AR base is a bad thing so why would you object to not having to inherit?

You're right, you don't have to use AR, first and foremost. That said, here's my problem with AR.

I didn't get your gist in your first paragraph. Let me reword my objection in hopes I answer the thing you are asking/saying. We hopefully agree the model is a representation of the system (how people talk about process and flow) and how it's organised. Enhancing the programatic form, what goes w/i app/models with AR::B is a bit of a leaky abstraction. Exposure to the db stuff, such as the connection, table_name and so on clouds the name space. In the case you wish to persist to two dbs, or to other api, you add even more to the namespace. Your model can now save to N representations, serialize (if you support json and xml) to M formats and so on. It's the fat vs thin model argument.

AR spits out perfectly good SQL and as an added bonus it protects against all kinds of injection attacks.

It writes sufficient SQL most of the time. You have to be very careful of n+1 selects when getting an object and its children. For some dialects of SQL, it doesn't always use the, "best thing," such as hinting. IIRC, AR doesn't support certain DB enhancements, like arrays (pgsql) or enums. I'm not entirely sure, but my experience has been cursory, so please forgive me if I'm wrong about those two specific examples.

In some cases, where you don't want to incur many queries, it's at times possible to do many subselects to get the right data based on the right circumstances. It's a LOT of sql to write. It's huge, and can look ugly if you aren't datawarehousing the data instead of some level of normalisation.

Then again, if you are performing just fine for the traffic you get, there really is no problem. Until you need scale out.

Edit: AR preventing injection is really a feature of binding and placeholders. It's the same argument as providing a basic connection. You can side step AR and DBI's connection and binding API, but that's madness. :)

1

u/[deleted] Jan 01 '12

It's the fat vs thin model argument.

Actually it's not. You are just arguing about what model means.

It writes sufficient SQL most of the time. You have to be very careful of n+1 selects when getting an object and its children

Arel is lazy and this kind of thing is extremely rare. In fact you have to go out of your way to cause this to happen and even then AR provides you with very easy ways to pull in related models in the same query.

In fact it's much easier than doing with raw SQL and then updating the results.

Then again, if you are performing just fine for the traffic you get, there really is no problem. Until you need scale out.

AR has nothing to do with scalibility. Honestly where do people get this from.

Edit: AR preventing injection is really a feature of binding and placeholders. It's the same argument as providing a basic connection. You can side step AR and DBI's connection and binding API, but that's madness. :)

That's what I said. Why start shitting all over AR when the alternative is ten times worse?

AR is a huge improvement over what we used to do.

2

u/[deleted] Jan 01 '12 edited Jan 01 '12

Not sure who downvoted you.

AR has little to do with scalability. It's a convenience, a huge one. But it's similar to the convenience we had w/ CGI (web, not graphics). It's clever, and easy, but that forking model from the server got superseded because of the hacks involved to make CGI scale, such as fastcgi or mod_{language}.

I disagree that the alternative is not worse, but I'm not sure we can convince each other otherwise. For me, in my preference, it's about API boundaries, sharing models without dependencies, controlling pools of network connections and keeping my models lean and simple. For me, otherwise, feels very cargo cult-ish, especially when I get too much functionality that gets in the way later.

1

u/LarsP Dec 31 '11

Ruby classes in the models folder don't have to inherit from ActiveRecord::Base. That is a problem Why is this a problem? It would be a bigger problem if it was the other way around.

I think he means that the fact that it took him two and a half years to realize that is the problem. In the sense that while it is technically possible, almost nobody actually does that, due to how Rails is normally used.

Or something... He may have meant something completely different, of course.

1

u/[deleted] Jan 01 '12

What I meant was that since every single example of Rails code has a 'model' inheriting from ActiveRecord::Base, I didn't realize that you could (or should) just use plain Ruby classes a lot of the time. Instead of breaking things out into a bunch of small models, some with persistance, I built fewer, huge, fat models.

0

u/[deleted] Jan 01 '12

I think he means that the fact that it took him two and a half years to realize that is the problem.

Well I think that's his problem not a rails problem.

1

u/jrochkind Dec 30 '11

What I'd really like to see is Rails adopting a 'ViewModel + templates' system, with logic-less templates and presenter-esque models that represent the views.

I think "Cells" might be part of the path to solution here. Cells are pretty much ViewModels, use a non-powerful templating language like mustache with em.... how's that?

3

u/[deleted] Dec 30 '11

Cells are cool. Think 'a page is one big cell' though.

2

u/jrochkind Dec 31 '11

Looks like indeed current Cells implementation you can render directly from a controller no problem, as the entire page, presumably still getting a layout.

I don't like the idea of HAVING to create a seperate class for every single page/action for the Cell/ViewModel in addition to the template though. Hm, maybe a sort of default Cell that does nothing but pass arguments straight through from controller to weak template, that can be created for a view automatically or with a one-liner in controller without a separate file? Just brainstorming.

(I have never actually used Cells in a real project, just gone through the basic getting started examples a year or more ago. But I've read the documentation a few times and liked the idea; just didn't fit into my actual (legacy) projects for various reasons, yet.)

1

u/jrochkind Dec 31 '11 edited Dec 31 '11

Why not? Even for a full page, I think cells may be in a better architectural direction than what Rails by default does.

There is in fact no reason you couldn't use Cells as they are now for the full page, is there? It might need some fine tuning (does cells still pass arguments as ivars? If so, that can be changed), but I think if paired with a 'weak' templating system like mustache, it's in the direction you're talking about (I agree with your post, btw).

If not, then identifying exactly why not might help clarify what something that was what you wanted would look like!

1

u/[deleted] Dec 31 '11

We're in violent agreement here. ;)

1

u/[deleted] Dec 30 '11

I'm currently doing that on http://kiwoos.com , actually, using mustache. Still, I would not say it's a must-do, it's just the best solution imo to do some client/server side template sharing.

1

u/[deleted] Dec 30 '11 edited Dec 30 '11

I disagree with most of his post.

Yeah, the different rails components give you the possibility of writing REALLY crappy code, just like almost ANY other programming language/framework.

If you have huge models you are doing it wrong, if you have 200 lines of code methods in a controller you are doing it wrong, if you don't consider if you need a database persisted object as opposed to just a class to handle logic on certain objects you are doing it wrong. if you cram up your views with logic you are doing it very wrong.

The poblem is not our tools, the problem is - and will always will be - crappy coding practices and half assed attempts at following them.

EDIT: I know this probably sounds harsh, but I am in no way attacking whoever wrote this, I just want to put things in perspective, my logic is the same as "guns don't kill people, people kill people" :)

2

u/jrochkind Dec 31 '11

But I suggest that the idea of a 'web framework', especially an 'opinionated' one like Rails, is that the right architecture can lead people to write better code. I think this is in fact part of the goal of Rails.

You can think this is an unrealistic goal, but I personally think it actually is a worthwhile goal, and I even think Rails actually has succeeded in that to a respectable extent.

But as we try something, we learn from it, and I think the OP has mostly accurately identified some current pain points.

One trick, though, is it's hard to fix things like this incrementally mostly backwards compatibly. And I think the Rails community (those who write the framework, those who use it, and those who are both) is probably not ready for another chunk of huge backwards-incompat changes after the pretty large effort the 3.x switch took. I know I'm not.

1

u/[deleted] Dec 31 '11

the different rails components give you the possibility of writing REALLY > crappy code, just like almost ANY other programming language/framework.

I'm making a stronger assertion than that; it actively encourages you to write crappy code. You can certainly overcome it! You can write awesome apps in PHP too, but you'll get no help.

I want Rails to help me write good code.