13 ms·
OrmHate
- debacle 14y agoFor the same reason PHP gets so much hate - both are tools with valid uses, but because they make hard things easier for people, that means that people who have no idea what they're doing can do very bad things. Hating on a tool is ridiculous.
- zzzeek 14y agoThe core of fowler's article is, "what is the alternative to ORMs?" - and the answer is there isn't much other than rolling your own. This is not at all analogous to PHP where there is an abundance of alternatives to it's mediocre design. PHP isn't hated because of its concept - a "web-based scripting language". It's hated because it's done very poorly. Just like a lot of bad ORMs Fowler refers to.
- debacle 14y agoThere is nothing wrong with PHP - it runs multi-billion dollar companies and it is the most ubiquitous language on the web for a reason.
- hzy 14y agoBecause it has near-zero barrier to entry. That doesn't speak highly of PHP as a language, just on how its deployment strategy is designed.
- debacle 14y agoI don't think Facebook or Yahoo chose PHP because it was easy to write.
- Cloven 14y agoyou are incorrect.
- debacle 14y agoYahoo's rationale for choosing PHP: "The short development cycles needed to stay ahead of the competition demand a web-centric scripting language that is easy to maintain and update." http://public.yahoo.com/bfrance/radwin/talks/yahoo-phpcon2002.htm http://public.yahoo.com/bfrance/radwin/talks/yahoo-phpcon200... They didn't choose Python, or Ruby, or Java, because none of those languages are as expressive or shut-up-and-get-out-of-my-way as PHP. Just because a high schooler can write PHP doesn't mean it's a toy not also meant for world class engineers.
- Cloven 14y agoPHP is more expressive than python, ruby, or java. I see.
- varikin 14y agoI think that is exactly why Mark Zuckerburg chose PHP when working on TheFaceBook back in 2003 and 2004. It was easy to write and deploy.
- papsosouid 14y agoJust because PHP doesn't 100% doom you to failure, doesn't mean there is "nothing wrong with it".
- zzzeek 14y agothere's a lot wrong with PHP, here's a good place to start: http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/ http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-de...
- wmil 14y agoIt's success is largely due to it having the correct execution model. The request based execution environment makes iterative development quick and easy. However there are plenty of bad ideas in the language itself.
- brazzy 14y agoFunny you should mention PHP. I suspect that a lot of the ORM hate comes from people forced to develop PHP and witnessing the epidemic of NIH syndrome among its web frameworks, every single one of which seems to come with its own half-assed ORM.
- Cloven 14y agoI would say there's a difference. PHP is bad because it has a wide variety of objectively awful design flaws, its standard library is a conflicted mess, and it's unperformant. Implementing it into a modern architecture is highly correlated with sloppiness and technical debt. ORM is bad because the impedance mismatch between an object and a relational model is very difficult to get right. Frequently, for example, one iterates over collections of objects in the OO paradigm. A naively written ORM, or one without sufficient introspection into the loop intent, can translate that into N select statements, each incurring a network round trip. The end result is that OO programmers have to understand not only their object code, but also the relational model, and finally too the ORM's peculiarities and suboptimalities. So in attempting to solve one problem, most of the time you end up with three. That said, there is a sweet spot in ORMs for simple code (e.g. most web apps, where ActiveRecord and Sequel and the like are fine). But there's no sweet spot for PHP code. Every line written is technical debt.
- krig 14y ago"You have a relational mapping problem. 'I know', you say. 'I'll use an ORM.' You now have two problems." That just about sums up my experience with ORMs. Of course, like all things in the real world, experiences vary. However, I do think that generally, ORMs solve none of the difficult relational mapping problems and adds another layer of abstraction that complicates things like performance tuning to the point of negating any other benefits they may bring.
- brazzy 14y agoHave you actually read TFA? Fowler's point is that yes, ORMs don't solve all of the really hard mapping problems, but save you a lot of boilerplate on the other 80-90%, and the hallmark of a good ORM is that it allows itself to be bypassed with relatively little hassle for those hard problems (like performance tuning). Also from TFA: what do you suggest using instead?
- mgkimsal 14y agoCome on - how hard is it to write "select id, username, email, nickname, date_registered, pass_hash, first_name, last_name, middle_initial, home_phone, mobile_phone, work_phone from user where username=?" and manually do escaping whenever you want user info? You seem to be suggesting that user.findByUsername('joe') is somehow more worthwhile or usable. It's certainly more noble, because an ORM doesn't solve 100% of a set of problems 100% of the time. OBVIOUSLY it's better to never use them, ever. In any circumstance. "select id, username, email, nickname, date_registered, pass_hash, first_name, last_name, middle_initial, home_phone, mobile_phone, work_phone from user where username=?" is really more readable because I always want to know every single piece of data, and read it every time I look at code (and update all my SQL queries every time I make a schema change) all the time. I'm finding that my monitor is often devoid of code - I have too much space on the screen just begging to be filled up with useful boilerplate code so I don't ever forget all the column names in every table.
- krig 14y agoYou pretty much nailed what I was going to say. Yeah, I found it a bit strange that the only alternative to using an ORM that the author could imagine was to roll your own? What's the problem with using SQL directly? To answer the grandparent: I did read TFA, and I don't buy it. His claim that a good ORM makes 90% easier and gets out of the way of the remaining 10% doesn't match my experience with any ORM at least. Perhaps I'm wrong! All I'm saying is that from what I can tell, using an ORM buys you nothing worth buying. edit: Ha, you're being sarcastic. No, I'm serious. Are you saying that using an ORM solves escaping problems? I honestly have never connected those two. That to me is a problem calling for a set of escaping/unescaping functions, not an object-relational mapping. To each their own...
- mattmanser 14y agoI personally haven't heard/seen anyone griping about ORMs for a couple of years now. I thought the debate was over. Much like you rarely see anyone talk about stored procedures these days.
- deleted 14y ago[deleted]
- debacle 14y agoMost of the people I know who gripe about ORMs have either never used one, or tried to apply one in an instance where an ORM is not applicable. ORMs fit a very specific use case - eliminating the tedium and risk associated with writing simple queries, and creating a simple layer of abstraction from the database. If you mention ORMs and someone starts griping about how it made their accounting reports slower, slap the shit out of them.
- GFischer 14y agoPlease do come and have a talk with my (pointy-haired style) boss :) . I take it you think stored procedures are generally good (at least that's what I think). But some people still believe that they'll migrate database architecture or some such. Also, some ORM's aren't fit for the task and give a bad name (Microsoft's Entity Framework v1 was especially horrible) I'm definitely out of touch and I spend way too much time working with Microsoft SQL, but do people treat relational databases as "a crazy aunt" as Fowler says? (I still haven't tried NoSQL)
- mattmanser 14y agoRe: SPs, no, I meant people used to say all your data access should be through SPs, which seemed to turn about 5-7 years ago as the general consensus moved to parametrized queries and freedom from DBAs overseeing your changes. I haven't seen anyone say that in a long time now. I used to use them for complicated TSQL and helper functions, like some crazy recursive tree building stuff, but these days I haven't actually written one now in a couple of years. On a more individual level I'm also now finding myself even shying away from complicated SQL queries. I'm finding these days they're unnecessary 90% of the time. Often it's actually faster and more maintainable to pull out a larger amount of data and then do the more specific calculations in code. Even with good indexes, etc.
- RyanMcGreal 14y ago> There is a lot of truth to these charges, but such charges miss a vital piece of context. The object/relational mapping problem is hard. I suspect that context is precisely what underlies the common critiques of ORMs. Those people who best understand the inherent object-relational impedance mismatch tend to be the very people who conclude that the effort isn't worth it. In my admittedly anecdotal experience, I have found that ORMs are the most useful for the most trivial queries. For anything complicated, I find it easier to drop into SQL and write the query directly than to compose an equivalent object using the ORM - and that becomes increasingly so as the query gets more complicated.
- dasil003 14y agoAnd yet many ORMs such as ActiveRecord let you do this trivially, maintaining as much of it's functionality as you want, such as mapping column types to appropriate pl types. In my experience, even if you had a policy of all queries being written explicitly in SQL by all developers and encapsulating these into your own data access layer, you would still have quite a bit to gain from the well-tested community boilerplate in one of the available ORM packages.
- davesims 14y agoThis. Use ORMs for what they do well, and move into straight SQL when it makes sense.
- debacle 14y ago> Those people who best understand the inherent object-relational impedance mismatch tend to be the very people who conclude that the effort isn't worth it. You're showing a severe bias. > I have found that ORMs are the most useful for the most trivial queries. That's really what ORMs are for. Three joins, max. Any more than that and you really can't trust the ORM. It's a computer, after all, not a DBA.
- RyanMcGreal 14y agoIn other words, ORMs are at their most useful when solving the least challenging problems. To which we must ask: why bother?
- mindcrime 14y agoBecause people are scared of things they don't understand? Or because they had one bad experience, years ago, with some home-grown crappy ORM, and now they assume all ORMs are bad? The reasons are legion... The second of those is what I saw at my last job. The tech-lead / architect guy was vehemently anti-ORM... because a previous group (at the same company) had rolled their own ORM in Jython and embedded it into the Java codebase, and it A. didn't perform well and B. was extremely fragile and hard to modify. Now, you can't explain to him that there are well written, productive, performant ORMs like Hibernate. He just doesn't want to hear it. sigh
- jonstjohn 14y agoOr maybe people expect to interact exclusively through the ORM and when they have to do something more complex, conclude that the ORM is useless. When using an ORM increases the complexity of the code substantially over direct SQL, I'll usually switch to more comprehensible SQL.
- mindcrime 14y agoWell, at least in the case of Hibernate, it's easy enough to drop down to native SQL when you need it (although you obviously risk giving up database independence) and you can still keep the OOP "feel" by defining query post converters and what-not. The points made above about "don't use ORM for reports" aside (a point I strongly agree with, btw), I've found Hibernate makes my life a lot simpler and rarely gets in the way or fails to do what I need it to do. But I do occasionally create a native query to deal with some edge case or whatever.
- einhverfr 14y agoLet's define a good ORM though. A good ORM should be able to handle a database designed for a different application, normalized to 5NF or BCNF, using composite primary keys, composite foreign keys, and other solid db design concepts, and be able to reliably generate queries to bridge the gap, and should do so where sets of objects are required in a way that does not unduly burden the database with small queries that could be consolidated. That's a hard problem. There are some ORMs that come pretty darned close if not there. Many more, in my experience fall well short.
- columbo 14y agodef user = User.findById(25) return user.getLocation().getAddress().getState() What happened during that execution? Was that 1 query or 50? Would it have been better to write a specific sql statement? To me, this describes the biggest challenges with using or not using ORMs. I don't think there is an easy answer.
- moondowner 14y agoAt least in Hibernate, you can set to print the actual queries in console (or text file, depending how your logger is set). http://stackoverflow.com/a/2538954/228692 http://stackoverflow.com/a/2538954/228692 That way, during development you can see which are the actual statements executed. I say during development because after that, in production, you'd be better off filling log files with these stuff :) And I can answer your question (for Hibernate), that will be one query.
- phillmv 14y ago>I don't think there is an easy answer. Uhm, ActiveRecord at least will print the SQL it generated. If you think it's inefficient, you can just… write your own sql that maps out to that query. With Arel/scopes, they're also composable and lazy loaded. What's not to like?
- latch 14y agoSurprised by the pro-ORM comments so far. My hate for ORMs grew proportionally with my usage of NoSQL. It's such a pleasant experience when your domain model fits the data model. Graphs are a good example, but Redis is a better one. When your intention fits a Redis data structure, it's just programming bliss - a few lines of explicit and simple code. The only way I can use a relational database now is with Sequel.
- polyfractal 14y agoI'm confused by your statement. When your data fits the tool that was designed to work with that data...everything is great? Isn't that the point of using the right tool for the right job?
- latch 14y agoWhat's confusing? For years...decades...developers have been taking a one-size-fits-all approach to data storage - relational databases. Now that we are starting to make use of more specialized tools, we're starting to go back and question (or hate) our past approach.
- andrewcooke 14y agoit depends so much on the context. i work with a wide range of different technologies. when i'm doing "enterprise" stuff, i tend to avoid the heavy orm like hibernate and go for things that give me more control (spring's helper classes, say). so you can say that i am "avoiding orm". but then recently i've been writing c code that needs to use a small database and boy, it's tedious working with sql directly. so i'm actually writing an "orm for c". it's all about balance... [the orm for c thing is basically two layers - a simple library that helps make sql queries a little easier to mangle and then a python library that, given some structs and a database, will auto-generate some basic boilerplate via the library. nothing fancy, but it will save a pile of tedious work.]
- mechanical_fish 14y agoFrom the article: I think NoSQL is technology to be taken very seriously… But even so it only works when the fit between the application model and the NoSQL data model is good. Not all problems are technically suitable for a NoSQL database. And of course there are many situations where you're stuck with a relational model anyway. Maybe it's a corporate standard that you can't jump over, maybe you can't persuade your colleagues to accept the risks of an immature technology. In this case you can't avoid the mapping problem.
- antihero 14y agoI've used both Django ORM and SQLAlchemy and they are generally excellent, allowing you to use SQL for anything that's just a bit too complicated for the ORM, but greatly simplifying day to day dynamically generated queries.
- narag 14y agoI don't like the implementation of ORMs as run-time layers. I very much prefer using a tool that generates code. It's orders of magnitude easier to maintain... for me anyway.
- ef4 14y agoI think a lot of the frustration with relational databases in general comes from a misunderstanding. People conflate "relational" with "SQL", because of the historical accident that SQL is the most popular way to query relational data. Then when SQL isn't a good fit for their problem, they think relational is not a good fit for their problem, which is almost certainly not true. The original motivation for relational databases is to have path-independent access to data. This is a really powerful idea. What I think we really need are better APIs around relational data access that embrace real relational semantics, instead of dumping them in favor of an object graph at the first opportunity (which throws away the path-independent access).
- ap22213 14y agoIn some ways, I agree with you. SQL is part of the problem. But, correctly structuring data is generally very hard, time consuming, has diminishing returns, and adds maintenance issues that never go away. I've seen teams spend months up front trying to craft a perfect schema, only to see it demolished when a non-obvious edge case appears. I've also seen teams become over burdened with schema and data maintenance, that it takes up 20-30% of their time. That's not to say that you're not right, but sometimes ORMs are just the more pragmatic answer to get a team through the first 4-5 iterations (or even longer). And, sometimes path-independence is important. But, often, the database just ends up being coupled with the application anyway. At least that's my experience.
- xi 14y agoPeople conflate "relational" with "SQL", because of the historical accident that SQL is the most popular way to query relational data. Then when SQL isn't a good fit for their problem, they think relational is not a good fit for their problem, which is almost certainly not true. For most practical purposes, SQL is the only way to query relational data. In the absence of alternatives, it's natural to conflate the notions of SQL databases and relational databases. I agree that SQL is a mess, but I don't think an approach based on pure relational primitives would make it better; in fact, I think SQL is a mess specifically because of lack of expressiveness in the pure relational primitives. NULL, ORDER BY, LIMIT/OFFSET, opaque keys, windowing functions, transitive closures, etc fit poorly into the relational model. The original motivation for relational databases is to have path-independent access to data. This is a really powerful idea. I agree with both assertions, but in many applications, path-based access makes the total majority of queries, and SQL or relational model provides little means to distinguish them from other equi-joins or arbitrary join conditions. In my opinion, it would be better to start with a navigational path-based database model, and extend it to allow constructing new paths dynamically.
- chris_wot 14y agoI've always wondered what the mathematical basis behind OOP is. I mean, relational databases are grounded in first-order logic and set theory. If there was a mathematical theory that grounds OOP, then I'd love to know because then there may be a way of finding a mathematical basis for ORM. Anyone who wants to provide the answer to this one would be my new best friend :-)
- Ygor 14y agoMaybe this can help: http://reperiendi.wordpress.com/2007/11/03/category-theory-for-the-java-programmer/ http://reperiendi.wordpress.com/2007/11/03/category-theory-f...
- duggan 14y agoThere's some serious miscommunication going on every time this discussion comes up. A lot of people seem to conflate all data abstractions with the term "ORM" (which has a very specific meaning), therefore assuming everyone who thinks ORMs are a bad idea are arguing against all forms of data abstraction. This is not the case. One of the better articles on this: http://seldo.com/weblog/2011/08/11/orm_is_an_antipattern http://seldo.com/weblog/2011/08/11/orm_is_an_antipattern
- compay 14y agoThe single biggest disadvantage of ORM for me is that in exchange for easier programability, they force you to learn a proprietary, arbitrary, ad hoc DSL that is less consistent, more complicated and less powerful than SQL.
- wiradikusuma 14y agoIt depends on what "proprietary" means. In Java, ORM is pretty much standardized with JDO/JPA.
- vegas 14y agoor HQL. which is pretty much exactly what this guy means.
- anuraj 14y agoI for one never touch an ORM if possible. Coding for SQL in code is not that difficult, but sure it leads to SQL lock in. But you don't expect to change your underlying data model and scheme so often, and if you ever do, you most probably need a complete redesign.
- ken 14y ago> In the 90's many of us (yes including me) thought that object databases would solve the problem by eliminating relations on the disk. We all know how that worked out. Maybe I'm too young (or too old) because I don't know what he is suggesting here. I've used an object database on a large commercial project, and it was a dream: everything I like about ORMs, and none of the drawbacks. My impression of OODBs, therefore, is that they were a technical success, but a commercial (and open-source) failure. But I don't think that's what Martin is suggesting. Can someone explain what "we all know" about database history here?
- vegas 14y agoI think it's basically the O part. In theory, one might have a delightful ontology of object oriented code, like Animal->Mammal->Cow , but in reality you often have something much more like CompanyNamePersistentObjectBaseClass->Entity->ExtendedPersistentEntity->CacheFactory->Entity(but in a different package)->NeedToAddAPropertyForJustThisReleaseIPromiseThisClassIsGoingAway->IdAddThisToTheBaseClassButIReallyNeedToRelease->Shape->Triangle->XYCoordinates and then somebody wants to cache these things in hibernate.
- sjwright 14y agoYour comment is screwing up the page layout. (Firefox, Win7)
- soulclap 14y agoI think it's all about getting to know the tool (ORM) you work with. Look at the generated queries and their performance, use eager/lazy loading in the right places and mainly take care of the database operations that run most often. Switching to plain SQL might make sense if you don't need structured/hierarchical objects at this point in your application and a simple array/list/table will do just fine. Don't bother with that if your hand-generated query will most likely end up the same though. Use database-specific bulk imports or plain SQL if you have lots of data to insert and need it fast. I am also often seeing comments about ORMs saying "What's so hard about SELECT..." - nothing's really hard about retrieving data, every decent developer will sooner or later end up with a working complicated SQL that gets them exactly what they wants. But I think the real benefits of ORMs start when you have to save/edit/update/extend relational data again and have to take care of all the inserts, updates, deletes across several tables, maybe including versioning or workflow (drafts or changes waiting for approval) and other additional complexity on top. That's the parts where I am glad to rely on an ORM supporting relationships and which can be extended via hooks or behaviours. (Note that I am mainly talking about 'Admin' pages here and nothing that runs too often.)
- eternalban 14y agoHe comes close but still misses the overall general issue and condition. These are facts: - Relational and/or heap representations can be fairly universally represented e.g. heap on FS aka VM - "impedance mismatch" problem is peripherally about latency and more generally present regardless of heap/store (hey..) image representation medium So in general: Any in-memory store process that is distinct from an in-memory heap process will still face the "impedance mistmatch" unless a) a compiler bridges the semantic gap between the two representation domains b) a mediator provides an interaction means between the two distinct processes A very specific case of this general condition is: [in-memory object language runtime] <--driver--> [FS based relational DB] Fundamentally the condition is that of 'networking' so the question immediately presents itself as to "what is distinct from general networking that is causing the tedium of mapping?". Ad-hoc messages of potentially unseen semantics would certainly cause an "impedance mistmatch" in a networking setup. Think of the nightmare of infrastructure to do the boiler plate, etc. (Look familiar?) So, queries are the raw nerve that is exposed by this type of coupling. What is a query? What is (the meaningful consequences of) a query in context of heap and/or store? A heap typically maintains a 'collected assembly of facts' e.g. a set of related objects (eternalban's comments trail collection object and various other data) all nicely stitched up by a static compiler and/or dynamic runtime. Same set of facts is distributed in a potentially unique manner across an unknown set of store media. A query in store is 'work'. It is also more precisely 'a functional computed in a specific time and space'. (CAP anyone?) So we know the answers to each and every one of these adjacency issues in the simple form. The runtime memory object model process <-> RDBMS is a very common system pattern that unfortunately exposes a whole truck load of these difficult interfacing issues in one lump scary form. It is a lot of 'work'. What is necessary to get around this is entirely against the prevailing trends arguing for "simplicity" as this requires infrastructure level plumbing for code at the same level of care and attention as that given to analogous networks for IP. tldr; ORMs (or any other magic layer) for independent actor system A-B coupling works best when the interaction patterns are bounded and statically known. Any increase in runtime uncertainties will necessitate working partially outside of the framework hand-holding and may even be more tedious. Choose your tools appropriately.
- tomkin 14y agoThroughout history there has always been some hate towards a platform that inherits and simplifies another platform. In truth, it would be more efficient to talk directly to the processor, but that takes a lot of time. And sure, ORM isn't the fastest way to data, but the deficit is well made up in the end result. You can't utilize ORM without an understanding of data. Suggesting that developers are leaving semantics behind is absolutely not true in most cases.
- j45 14y agoMy why is more of a feeling/observation/theory so please feel free to share your thoughts and feelings: Some developers hate, and are almost threatened when something fancy and complex they might do is trivialized, thereby trivializing them. There is no question that something like ORM makes some things easier, and other things harder. It applies equally well to SQL and which flavor of database you end up using, or whether you're using ActiveRecord, etc., or not. I would hope developers who find something that frees to solve user problems instead of technology problems would be a good thing, but maybe it's just me.
- einhverfr 14y agoI think the hate comes from two sides: 1) Relational folks who feel that ORMs don't really enable good relational design, and 2) OO folks who feel that ORM's cause a lot of headache regarding relational to operation data structure conversion. The folks in camp 1 are usually absolutely right. Most ORMs encourage the developer to design the database around the ORM which has to be an antipattern when it comes to relational systems. This isn't always the case. DBIx::Class has done some awesome work on some things like composite primary keys and the like. But generally in most cases it is true. On the OO side I am less convinced of the costs. So my complaints come from the relational side. Yes object to operational data structure mapping is hard to automate, and it's even harder to automate well. So maybe we shouldn't try. Maybe ORM's should be disregarded in favor of ways of designing the data so that abstractions occur at different points. In the LedgerSMB project we decided to use stored procedures to accomplish this abstraction. We don't put "all the logic" in the database, far from it. But database operations go through the stored procedures, and these are often well tuned for performance (or as well tuned as they can be). The stored procedures thus create an API for addressing relational data, and this allows an abstraction layer to be formed which maps these into object methods. We'll probably extend this further in the future to tie object properties to complex database types, but we haven't decided the best way to do this yet. ORMs get a lot of hate because they tackle a very difficult problem and consequently tend to produce results that are unsatisfactory particularly to db folks. They are the product of app designers looking at the db, more often than not, rather than db designers looking at the app.
- sjwright 14y ago> In the LedgerSMB project we decided to use stored procedures to accomplish this abstraction. Why? Stored procedures are nothing more than a bolted-on way to store SQL queries on the database server. Yes, you've create an "API" and an "abstraction" but you've done nothing you couldn't have done in any other language. > The stored procedures thus create an API I consider stored procedures to be little more than a shitty "API builder" thrown in for free with your database. * The programming language generally sucks * Passing in complex data always sucks * Source control is non-existent (or sucks) You've probably had to write an API layer within your code anyway, to deal with the remaining logic requirements, why not store those queries within that layer? Or put them in a further API layer within your own source code?
- bitdiffusion 14y agoAdding to some of the anti-orm sentiment above: I always find that orm's are trying to solve a problem that doesn't really exist. The proportion of time (and therefore cost) spent on a project writing SQL is orders of magnitude less than time spent on things like performance, scalability, user-experience, testing etc. You might have something that only maps data from your results into your language of choice but, again, if small, slightly repetitive tasks like this are affecting your ability to deliver your software, you have bigger problems. Sure - database design is important - but that you have to do that regardless.
- stevenwei 14y agoI really have never understood the ORM hate. I've found them to be immensely useful in 99% of circumstances, and for the remaining 1%, a good ORM will always let you fall back to raw SQL. Aside from providing a simpler syntax for performing basic queries, there are a few features that ORMs provide that have greatly simplified my life: 1. Automatically using prepared statements and validating/escaping query arguments to prevent injection. You have to be quite a bit more careful when you're working with raw SQL. 2. Providing an clean API to construct complex queries. This typically becomes an issue when you have a query where you are filtering and/or sorting by multiple fields which are specified by the user, some of which are conditional. If you're writing raw SQL you end up needing to do a lot of string manipulation which can get fairly messy (and makes the code more difficult to understand). An ORM which provides some sort of query builder syntax that lets you do: if (some condition): query.addWhere(clause) if (some other condition): query.addWhere(other clause) etc. is pretty convenient. 3. Collating repeated result rows from joins Whenever you're working with joins you end up with repeated data in your result set, which you generally end up having to collate before display. For example if I have Recipes <- (many to many) -> Categories and do a query to load the both of them, I might end up with something like this: recipe_id | recipe_name | recipe_ingredients | category_id | category_name -------------------------------------------------------------------------- 1 | Shrimp Pasta | 1 cup tomato sauce | 1 | Pasta 1 | Shrimp Pasta | 1 cup tomato sauce | 2 | Seafood 1 | Shrimp Pasta | 1 cup tomato sauce | 3 | Shrimp 2 | Fruit Cake | 4 cups flour... | 4 | Dessert 2 | Fruit Cake | 4 cups flour... | 5 | Cakes Without an ORM I have to loop through the result set to re-format the data the way I wanted before displaying it. An ORM takes care of that for me and gives me back 2 recipes with their categories accessible via recipe.categories. 4. Simplified manipulation of many-to-many relationships. Following the above example, if I want to add a new Category to a Recipe I can simply do: recipe.categories.add(category) If I want to set the categories to something entirely different, I can do: recipe.categories = [category1, category2, category3, etc] Without the ORM I would have to manually sync up the entries in the join table which is kind of a pain in the ass. Working with join tables in general is rather obnoxious, so I'm quite glad that the ORM takes care of that one for me. 5. Some ORMs give you notifications when an object (or collection of objects) changes. This is pretty important on the client side when you want to make sure the data you're displaying stays up to date, even as it is being manipulated. For example: if I'm viewing a recipe on my iPad and I update that recipe on my desktop. A background thread is running which keeps the two synchronized, and at some point the underlying recipe is updated in the database on my iPad. If I'm working with raw SQL there's basically no way to know when that object is changed (short of polling it periodically, or rolling your own notification system). But my ORM will keep me notified of changes to the object so I can refresh the user interface with the updated recipe after the sync completes. 6. Some ORMs implement a unit of work that allows you to track what changes have been made to an object since it was retrieved from the database. So you can easily see which fields have been modified, and then when you go to save the object back out, it will intelligently only issue the SQL to update the columns which have changed, or won't even touch the database if nothing has actually changed. 7. Some ORMs put their objects into an identity map, so if you query for the same object under multiple different scenarios (e.g different areas of your UI), you always get the same underlying instance back. This means that you don't have multiple copies of what is semantically the same object floating around in different places of your app, and the object is always up to date with the latest changes. Note: my use case is typically client-side database backed software, so features like (5), (6), and (7) save me from having to do a TON of work. If you're doing more web oriented stuff, I can see how those particular features may be less useful to you. Still, I think ORMs are a huge win overall. Of course, none of this absolves you from needing to know what's going on at the database level. You still have to know what SQL your ORM is generating in order to make sure you're using it correctly. But I get really confused when people badmouth ORMs and try to tell me that it's simpler to use raw SQL, cause it never has been for me and my use cases. And the funniest thing is, if I stuck with raw SQL while attempting to solve all of the problems I listed above, I probably would end up with a half-assed version of a full-fledged ORM anyway. (The only use case I can think of where I'd prefer to use raw SQL over an ORM is with report generation type activities: usually those types of queries aren't very dynamic, they can often be too complex to be expressed via the ORM's API, and once you have the data you're just dumping it to display without worrying about interactivity anyway.)
- mjburgess 14y agoThat is really bad ideological myopia there. He refused to consider alternatives (for which I would adovcate functional design or something like sqlalchemy). "Actually I think this is an inevitable consequence of using a relational database - you either have to make your in-memory model more relational, or you complicate your mapping code." No its an inevitable consequence of trying to think with an object-oriented type system to describe a set-based data collection! In other-words the problem is attempting ORM: he's begging the question! I would expect better from Fowler, but it does go to show the futher into an ideology you get (heavily design-patterned OOP in fowler's case) the more you see design and programming problems as problem with OOP rather than anything more fundamental.
- dgreensp 14y agoNot all problems are technically suitable for a NoSQL database. You might as well say "I'm a big fan of JSON, but not all problems are technically suitable for a NoXML data format." There's nothing magical about SQL, as proven by the fact that so few apps actually use its abstractions! The reasons to use SQL today are pragmatic; battle-tested engines, tools, etc. Most developers will never write their own ORM or database, but the ones who are up to it are starting to explore the design space quite profitably.