<p>As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on <a href="http://en.wikipedia.org/wiki/Active_record_pattern" rel="noreferrer">Active Record</a>.</p>

<p>Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains <strong><em>why</em></strong> it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?)</p>

<p>Hopefully this won't turn into a holy war about design patterns -- all I want to know is ****specifically**** what's wrong with Active Record.</p>

<p>If it doesn't scale well, why not?</p>

<p>What other problems does it have?</p>

[{'answer_id': 7908, 'author': 'Tim Sullivan', 'author_id': 722, 'author_profile': 'https://Stackoverflow.com/users/722', 'pm_score': 2, 'selected': False, 'text': '<p>The main thing that I\'ve seen with regards to complaints about Active Record is that when you create a model around a table, and you select several instances of the model, you\'re basically doing a "select * from ...". This is fine for editing a record or displaying a record, but if you want to, say, display a list of the cities for all the contacts in your database, you could do "select City from ..." and only get the cities. Doing this with Active Record would require that you\'re selecting all the columns, but only using City.</p>\n\n<p>Of course, varying implementations will handle this differently. Nevertheless, it\'s one issue.</p>\n\n<p>Now, you can get around this by creating a new model for the specific thing you\'re trying to do, but some people would argue that it\'s more effort than the benefit.</p>\n\n<p>Me, I dig Active Record. :-)</p>\n\n<p>HTH</p>\n'}, {'answer_id': 7939, 'author': 'BlaM', 'author_id': 999, 'author_profile': 'https://Stackoverflow.com/users/999', 'pm_score': 0, 'selected': False, 'text': '<p>The problem that I see with Active Records is, that it\'s always just about <strong>one</strong> table. That\'s okay, as long as you really work with just that one table, but when you work with data in most cases you\'ll have some kind of join somewhere.</p>\n\n<p>Yes, <strong>join</strong> usually is worse than <strong>no join at all</strong> when it comes to performance, but <strong>join</strong> <em>usually</em> is better than <strong>"fake" join</strong> by first reading the whole table A and then using the gained information to read and filter table B.</p>\n'}, {'answer_id': 8141, 'author': 'Lars Mæhlum', 'author_id': 960, 'author_profile': 'https://Stackoverflow.com/users/960', 'pm_score': 1, 'selected': False, 'text': '<p>I love the way SubSonic does the one column only thing.<br>\nEither </p>\n\n<pre><code>DataBaseTable.GetList(DataBaseTable.Columns.ColumnYouWant)\n</code></pre>\n\n<p>, or:</p>\n\n<pre><code>Query q = DataBaseTable.CreateQuery()\n               .WHERE(DataBaseTable.Columns.ColumnToFilterOn,value);\nq.SelectList = DataBaseTable.Columns.ColumnYouWant;\nq.Load();\n</code></pre>\n\n<p>But Linq is still king when it comes to lazy loading.</p>\n'}, {'answer_id': 8215, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 8, 'selected': True, 'text': '<p>There\'s <a href="http://en.wikipedia.org/wiki/Active_record_pattern" rel="noreferrer">ActiveRecord the Design Pattern</a> and <a href="http://api.rubyonrails.com/classes/ActiveRecord/Base.html" rel="noreferrer">ActiveRecord the Rails ORM Library</a>, and there\'s also a ton of knock-offs for .NET, and other languages.</p>\n\n<p>These are all different things. They mostly follow that design pattern, but extend and modify it in many different ways, so before anyone says "ActiveRecord Sucks" it needs to be qualified by saying "which ActiveRecord, there\'s heaps?"</p>\n\n<p>I\'m only familiar with Rails\' ActiveRecord, I\'ll try address all the complaints which have been raised in context of using it.</p>\n\n<blockquote>\n  <p>@BlaM</p>\n  \n  <p>The problem that I see with Active Records is, that it\'s always just about one table</p>\n</blockquote>\n\n<p>Code:</p>\n\n<pre><code>class Person\n    belongs_to :company\nend\npeople = Person.find(:all, :include =&gt; :company )\n</code></pre>\n\n<p>This generates SQL with <code>LEFT JOIN companies on companies.id = person.company_id</code>, and automatically generates associated Company objects so you can do <code>people.first.company</code> and it doesn\'t need to hit the database because the data is already present.</p>\n\n<blockquote>\n  <p>@pix0r</p>\n  \n  <p>The inherent problem with Active Record is that database queries are automatically generated and executed to populate objects and modify database records</p>\n</blockquote>\n\n<p>Code:</p>\n\n<pre><code>person = Person.find_by_sql("giant complicated sql query")\n</code></pre>\n\n<p>This is discouraged as it\'s ugly, but for the cases where you just plain and simply need to write raw SQL, it\'s easily done.</p>\n\n<blockquote>\n  <p>@Tim Sullivan</p>\n  \n  <p>...and you select several instances of the model, you\'re basically doing a "select * from ..."</p>\n</blockquote>\n\n<p>Code:</p>\n\n<pre><code>people = Person.find(:all, :select=&gt;\'name, id\')\n</code></pre>\n\n<p>This will only select the name and ID columns from the database, all the other \'attributes\' in the mapped objects will just be nil, unless you manually reload that object, and so on.</p>\n'}, {'answer_id': 8233, 'author': 'Johannes', 'author_id': 925, 'author_profile': 'https://Stackoverflow.com/users/925', 'pm_score': 1, 'selected': False, 'text': '<p>@BlaM:\nSometimes I justed implemented an active record for a result of a join. Doesn\'t always have to be the relation Table &lt;--> Active Record. Why not "Result of a Join statement" &lt;--> Active Record ?</p>\n'}, {'answer_id': 12293, 'author': 'engtech', 'author_id': 175, 'author_profile': 'https://Stackoverflow.com/users/175', 'pm_score': 0, 'selected': False, 'text': '<p>The problem with ActiveRecord is that the queries it automatically generates for you can cause performance problems.</p>\n\n<p>You end up doing some unintuitive tricks to optimize the queries that leave you wondering if it would have been more time effective to write the query by hand in the first place.</p>\n'}, {'answer_id': 28758, 'author': 'Sam McAfee', 'author_id': 577, 'author_profile': 'https://Stackoverflow.com/users/577', 'pm_score': 6, 'selected': False, 'text': '<p>I have always found that ActiveRecord is good for quick CRUD-based applications where the Model is relatively flat (as in, not a lot of class hierarchies). However, for applications with complex OO hierarchies, a <a href="http://martinfowler.com/eaaCatalog/dataMapper.html" rel="noreferrer">DataMapper</a> is probably a better solution. While ActiveRecord assumes a 1:1 ratio between your tables and your data objects, that kind of relationship gets unwieldy with more complex domains. In his <a href="http://martinfowler.com/eaaCatalog/" rel="noreferrer">book on patterns</a>, Martin Fowler points out that ActiveRecord tends to break down under conditions where your Model is fairly complex, and suggests a <a href="http://martinfowler.com/eaaCatalog/dataMapper.html" rel="noreferrer">DataMapper</a> as the alternative.</p>\n\n<p>I have found this to be true in practice. In cases, where you have a lot inheritance in your domain, it is harder to map inheritance to your RDBMS than it is to map associations or composition.</p>\n\n<p>The way I do it is to have "domain" objects that are accessed by your controllers via these DataMapper (or "service layer") classes. These do not directly mirror the database, but act as your OO representation for some real-world object. Say you have a User class in your domain, and need to have references to, or collections of other objects, already loaded when you retrieve that User object. The data may be coming from many different tables, and an ActiveRecord pattern can make it really hard.</p>\n\n<p>Instead of loading the User object directly and accessing data using an ActiveRecord style API, your controller code retrieves a User object by calling the API of the UserMapper.getUser() method, for instance. It is that mapper that is responsible for loading any associated objects from their respective tables and returning the completed User "domain" object to the caller.</p>\n\n<p>Essentially, you are just adding another layer of abstraction to make the code more managable. Whether your DataMapper classes contain raw custom SQL, or calls to a data abstraction layer API, or even access an ActiveRecord pattern themselves, doesn\'t really matter to the controller code that is receiving a nice, populated User object.</p>\n\n<p>Anyway, that\'s how I do it.</p>\n'}, {'answer_id': 28804, 'author': 'Kevin Pang', 'author_id': 1574, 'author_profile': 'https://Stackoverflow.com/users/1574', 'pm_score': 2, 'selected': False, 'text': '<p>Although all the other comments regarding SQL optimization are certainly valid, my main complaint with the active record pattern is that it usually leads to <a href="http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch" rel="nofollow noreferrer">impedance mismatch</a>.  I like keeping my domain clean and properly encapsulated, which the active record pattern usually destroys all hope of doing.</p>\n'}, {'answer_id': 28891, 'author': 'John Topley', 'author_id': 1450, 'author_profile': 'https://Stackoverflow.com/users/1450', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <p>The question is about the Active\n  Record design pattern. Not an orm\n  Tool.</p>\n</blockquote>\n\n<p>The original question is tagged with rails and refers to Twitter which is built in Ruby on Rails. The ActiveRecord framework within Rails is an implementation of Fowler's Active Record design pattern.</p>\n"}, {'answer_id': 117795, 'author': 'MattMcKnight', 'author_id': 8136, 'author_profile': 'https://Stackoverflow.com/users/8136', 'pm_score': 4, 'selected': False, 'text': '<p>I think there is a likely a very different set of reasons between why people are "hating" on ActiveRecord and what is "wrong" with it.</p>\n\n<p>On the hating issue, there is a lot of venom towards anything Rails related. As far as what is wrong with it, it is likely that it is like all technology and there are situations where it is a good choice and situations where there are better choices. The situation where you don\'t get to take advantage of most of the features of Rails ActiveRecord, in my experience, is where the database is badly structured. If you are accessing data without primary keys, with things that violate first normal form, where there are lots of stored procedures required to access the data, you are better off using something that is more of just a SQL wrapper.  If your database is relatively well structured, ActiveRecord lets you take advantage of that.</p>\n\n<p>To add to the theme of replying to commenters who say things are hard in ActiveRecord with a code snippet rejoinder</p>\n\n<blockquote>\n  <p>@Sam McAfee Say you have a User class in your domain, and need to have references to, or collections of other objects, already loaded when you retrieve that User object. The data may be coming from many different tables, and an ActiveRecord pattern can make it really hard.</p>\n</blockquote>\n\n<pre><code>user = User.find(id, :include =&gt; ["posts", "comments"])\nfirst_post = user.posts.first\nfirst_comment = user.comments.first\n</code></pre>\n\n<p>By using the include option, ActiveRecord lets you override the default lazy-loading behavior.</p>\n'}, {'answer_id': 1153656, 'author': 'Alexander Trauzzi', 'author_id': 128991, 'author_profile': 'https://Stackoverflow.com/users/128991', 'pm_score': 0, 'selected': False, 'text': "<p>Try doing a many to many polymorphic relationship.  Not so easy.  Especially when you aren't using STI.</p>\n"}, {'answer_id': 1807560, 'author': 'Frunsi', 'author_id': 206247, 'author_profile': 'https://Stackoverflow.com/users/206247', 'pm_score': 3, 'selected': False, 'text': '<p>My long and late answer, not even complete, but a good explanation WHY I hate this pattern, opinions and even some emotions:</p>\n\n<p>1) short version: Active Record creates a "<strong>thin layer</strong>" of "<strong>strong binding</strong>" between the database and the application code. Which solves no logical, no whatever-problems, no problems at all. IMHO it does not provide ANY VALUE, except some <strong>syntactic sugar</strong> for the programmer (which may then use an "object syntax" to access some data, that exists in a relational database). The effort to create some comfort for the programmers should (IMHO...) better be invested in low level database access tools, e.g. some variations of simple, easy, plain <code>hash_map get_record( string id_value, string table_name, string id_column_name="id" )</code> and similar methods (of course, the concepts and elegance greatly varies with the language used).</p>\n\n<p>2) long version: In any database-driven projects where I had the "conceptual control" of things, I avoided AR, and it was good. I usually build a <strong>layered architecture</strong> (you sooner or later do divide your software in layers, at least in medium- to large-sized projects):</p>\n\n<p>A1) the database itself, tables, relations, even some logic if the DBMS allows it (MySQL is also grown-up now)</p>\n\n<p>A2) very often, there is more than a data store: file system (blobs in database are not always a good decision...), legacy systems (imagine yourself "how" they will be accessed, many varieties possible.. but thats not the point...)</p>\n\n<p>B) database access layer (at this level, tool methods, helpers to easily access the data in the database are very welcome, but AR does not provide any value here, except some syntactic sugar)</p>\n\n<p>C) application objects layer: "application objects" sometimes are simple rows of a table in the database, but most times they are <strong>compound</strong> objects anyway, and have some higher logic attached, so investing time in AR objects at this level is just plainly useless, a waste of precious coders time, because the "real value", the "higher logic" of those objects needs to be implemented on top of the AR objects, anyway - with and without AR! And, for example, why would you want to have an abstraction of "Log entry objects"? App logic code writes them, but should that have the ability to update or delete them? sounds silly, and <code>App::Log("I am a log message")</code> is some magnitudes easier to use than <code>le=new LogEntry(); le.time=now(); le.text="I am a log message"; le.Insert();</code>. And for example: using a "Log entry object" in the log view in your application will work for 100, 1000 or even 10000 log lines, but sooner or later you will have to optimize - and I bet in most cases, you will just use that small beautiful SQL SELECT statement in your app logic (which totally breaks the AR idea..), instead of wrapping that small statement in rigid fixed AR idea frames with lots of code wrapping and hiding it. The time you wasted with writing and/or building AR code could have been invested in a much more clever interface for reading lists of log-entries (many, many ways, the sky is the limit). Coders should <strong>dare to invent new abstractions</strong> to realize their application logic that fit the intended application, and <strong>not stupidly re-implement silly patterns</strong>, that sound good on first sight!</p>\n\n<p>D) the application logic - implements the logic of interacting objects and creating, deleting and listing(!) of application logic objects (NO, those tasks should rarely be anchored in the application logic objects itself: does the sheet of paper on your desk tell you the names and locations of all other sheets in your office? forget "static" methods for listing objects, thats silly, a bad compromise created to make the human way of thinking fit into [some-not-all-AR-framework-like-]AR thinking)</p>\n\n<p>E) the user interface - well, what I will write in the following lines is very, very, very subjective, but in my experience, projects that built on AR often neglected the UI part of an application - time was wasted on creation obscure abstractions. In the end such applications wasted a lot of coders time and feel like applications from coders for coders, tech-inclined inside and outside. The coders feel good (hard work finally done, everything finished and correct, according to the concept on paper...), and the customers "just have to learn that it needs to be like that", because thats "professional".. ok, sorry, I digress ;-)</p>\n\n<p>Well, admittedly, this all is subjective, but its my experience (Ruby on Rails excluded, it may be different, and I have zero practical experience with that approach).</p>\n\n<p>In paid projects, I often heard the demand to start with creating some "active record" objects as a building block for the higher level application logic. In my experience, this <strong>conspicuously often</strong> was some kind of excuse for that the customer (a software dev company in most cases) did not have a good concept, a big view, an overview of what the product should finally be. Those customers think in rigid frames ("in the project ten years ago it worked well.."), they may flesh out entities, they may define entities relations, they may break down data relations and define basic application logic, but then they stop and hand it over to you, and think thats all you need... they often lack a complete concept of application logic, user interface, usability and so on and so on... they lack the big view and they lack love for the details, and they want you to follow that AR way of things, because.. well, why, it worked in that project years ago, it keeps people busy and silent? I don\'t know. But the "details" separate the men from the boys, or .. how was the original advertisement slogan ? ;-)</p>\n\n<p>After many years (ten years of active development experience), whenever a customer mentions an "active record pattern", my alarm bell rings. I learned to try to get them <strong>back to that essential conceptional phase</strong>, let them think twice, try them to show their conceptional weaknesses or just avoid them at all if they are undiscerning (in the end, you know, a customer that does not yet know what it wants, maybe even thinks it knows but doesn\'t, or tries to externalize concept work to ME for free, costs me many precious hours, days, weeks and months of my time, live is too short ... ).</p>\n\n<p>So, finally: THIS ALL is why I hate that silly "active record pattern", and I do and will avoid it whenever possible.</p>\n\n<p><strong>EDIT</strong>: I would even call this a No-Pattern. It does not solve any problem (patterns are not meant to create syntactic sugar). It creates many problems: the root of all its problems (mentioned in many answers here..) is, that <strong>it just hides</strong> the good old well-developed and powerful SQL behind an interface that is by the patterns definition extremely limited.</p>\n\n<p>This pattern replaces flexibility with syntactic sugar!</p>\n\n<p>Think about it, which problem does AR solve for you?</p>\n'}, {'answer_id': 6327670, 'author': 'Alex Burtsev', 'author_id': 235715, 'author_profile': 'https://Stackoverflow.com/users/235715', 'pm_score': 1, 'selected': False, 'text': "<p>I'm going to talk about Active Record as a design pattern, I haven't seen ROR.</p>\n\n<p>Some developers hate Active Record, because they read smart books about writing clean and neat code, and these books states that active record violates single resposobility principle, violates DDD rule that domain object should be persistant ignorant, and many other rules from these kind of books.</p>\n\n<p>The second thing domain objects in Active Record tend to be 1-to-1 with database, that may be considered a limitation in some kind of systems (n-tier mostly).</p>\n\n<p>Thats just abstract things, i haven't seen ruby on rails actual implementation of this pattern.</p>\n"}, {'answer_id': 7188181, 'author': 'Juanjo', 'author_id': 911722, 'author_profile': 'https://Stackoverflow.com/users/911722', 'pm_score': 3, 'selected': False, 'text': '<p>Some messages are getting me confused.\nSome answers are going to "ORM" vs "SQL" or something like that.</p>\n\n<p>The fact is that AR is just a simplification programming pattern where you take advantage of your domain objects to write there database access code.</p>\n\n<p>These objects usually have business attributes (properties of the bean) and some behaviour (methods that usually work on these properties).</p>\n\n<p>The AR just says "add some methods to these domain objects" to database related tasks.</p>\n\n<p>And I have to say, from my opinion and experience, that I do not like the pattern.</p>\n\n<p>At first sight it can sound pretty good. Some modern Java tools like Spring Roo uses this pattern.</p>\n\n<p>For me, the real problem is just with OOP concern. AR pattern forces you in some way to add a dependency from your object to infraestructure objects. These infraestructure objects let the domain object to query the database through the methods suggested by AR.</p>\n\n<p>I have always said that two layers are key to the success of a project. The service layer (where the bussiness logic resides or can be exported through some kind of remoting technology, as Web Services, for example) and the domain layer. In my opinion, if we add some dependencies (not really needed) to the domain layer objects for resolving the AR pattern, our domain objects will be harder to share with other layers or (rare) external applications.</p>\n\n<p>Spring Roo implementation of AR is interesting, because it does not rely on the object itself, but in some AspectJ files. But if later you do not want to work with Roo and have to refactor the project, the AR methods will be implemented directly in your domain objects.</p>\n\n<p>Another point of view. Imagine we do not use a Relational Database to store our objects. Imagine the application stores our domain objects in a NoSQL Database or just in XML files, for example. Would we implement the methods that do these tasks in our domain objects? I do not think so (for example, in the case of XM, we would add XML related dependencies to our domain objects...Truly sad I think). Why then do we have to implement the relational DB methods in the domain objects, as the Ar pattern says?</p>\n\n<p>To sum up, the AR pattern can sound simpler and good for small and simple applications. But, when we have complex and large apps, I think the classical layered architecture is a better approach.</p>\n'}]
['https://Stackoverflow.com/questions/7864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/751/']