the blog for developers

Be careful with magical code

Let’s talk about programming magic. It seems hip to use the most powerful language or framework and power often goes hand in hand with magic. Many kinds of magic are available, especially in languages which are renown for their magic, like Ruby. But there is a lot of magic even in Java:

  • Class loading
  • Garbage collection
  • Terracotta (which is still a wonderful solution to the coherence problem)
  • Remote procedure (RMI) or webservice calls
  • AOP
  • ORMs and in particular Hibernate

I’ve been a long fan of ORMs – especially Hibernate – but I’m no longer, so I wrote “Orms are a thing of the past”. Particulary because of their magic. The same goes with AOP. I’ve biten by Spring AOP, but it could be any AOP, with the more powerful like AspectJ being more dangerous. Some methods changed, Eclipse wasn’t clever enough, pointcuts didn’t find the right methods anymore and the system was broken in production.

Leaky abstractions manifest themselves often because of magic. Early Java examples of magic which can go wrong are garbage collection (GC) and RMI. Garbage collection works like a charm, up until it doesn’t work anymore or a full GC run stops your application for several minutes. RMI, another early one, breaks in ways you do not anticipate:

calc.add(2,4)

Reading this code, one would assume very little can go wrong. But if it’s a RMI call it can throw some nasty exceptions at you. As I’ve commented in my post “ORMs are a thing of the past”:

But association managment with ORMs has the same problem as RMI: It seems to be transparent, but it is not (lazy exceptions and remote exceptions).

What is programming magic? Is it Vodoo? Arthur C.Clarkes third law says:

Any sufficiently advanced technology is indistinguishable from magic.

which makes magic something you do not understand. Any sufficiently advanced programming language or framework. As a sidenote, programming magic is bordering and related to cargo cult programming.

Why is magic even used?

Magic is good. It helps developers safe time, work with higher abstractions, write less code, read less code, have more aesthetically pleasing code and it makes you feel powerful. And it seldom does bite the one who wrote the code. Problems often arise in maintanance, with developer turnover and new developers needing to understand the code. Magic most often bites operations, and because developers and operations often do not talk, it seems like a SEP.
As I’m working more in operations in the last years, I have been biten by Java code. I have no experience with Rails ops – someone can fill me in? – but assume it is the same in Rails and PHP as it is in Java operations.

Why does magic bite you?

Because

Magic is non-linear

Repeat: Magic is non-linear. It works for a wide range, then suddenly breaks.

  • High Load under special circumstances
  • Many, many more queries than you thought of
  • Locking in unpleasent ways
  • Exceptions you didn’t think of

And because you do not understand the magic it’s hard to know the breaking point. Assume

customer.getAddresses()

which differs a lot when it’s proxied with an ORM, compared to a local method call. Perhaps it produces n+1 queries, it might be lazy, might take a lot of time under load or might have non-linear and unknown caching behaviour.

What you can do

You can and should use magic, but need to balance with maintanence and operations:

  1. Know where it’s happening
  2. Confine it to defined points
  3. Really understand what’s going on

“Confine” today is a very strong concept to me, and most of the code I write or review confines magic to clearly understood place. I’ve also learned to write a small anti-corruption layer around all external frameworks, but this is better explained in another post. Taking the Hibernate example – and I will get flamed for this – you might use:

dao.getAddresses(customer)

instead of

customer.getAddresses()

With a simple implementation this looks like:

class HibernateCustomerDao extends CustomerDao {
  def getAdresses(c:Customer) = c.getAdresses
}

Why is this better? A developer knows it’s non-linear when he sees dao.getAddresses(customer) compared to customer.getAddresses(). And sooner or later you will need to optimize performance or change caching. Easy to swap with JDBCTemplate for performance reasons, to add caching etc.

Other kinds of magic?

There some more kinds of magic you need to beware of. All the time there is new magic coiming up. Is Project Lombock magic? Probably not. Is type inference in Scala magic? I’m not sure yet, there is some discussion. Are implicits in Scala magic? I’m pretty sure they qualify. Beware of magic. Use it to your advantage, know it, confine it and really understand what’s going on.

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

About the author: Stephan Schmidt has more than 15 years of internet technology experience and 10 years experience in agile. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own.

53 Tweets 8 Comments

Leave a reply.

Comments

TrungH

There never is magic, only complexity. Computers are deterministic.

@TrungH: Sorry to disagree.

a.) read the definition of magic again
b.) with non-deterministic input, output is non-deterministic either. Same goes for runtime behaviour
c.) non-linear behaviour is most often determenistic

Stefan Schubert

Thanks for posting this. As magic is making thinks intransparent the best way to counter that seems to make transparent transparent itself. I will take that with me.

After all I am very curious to someday read something about big in-memory web applications from you. With enough local memory the magic required to do an architecture like that seems much smaller. You should become a fan of that. Though you might not deem it applicable yet for your purpose :-)

Stefan Schubert

Sorry … a lot spelling mistakes: I am talking about making transparent :-)

I agree with your post.

I try to reduce ‘magic’ in my own projects and only use it when it’s a real benefit.

I used to utilize ‘magic’ just for less important, ‘nice-to-have’ features. But it made it much more difficult to find out the cause when it broke.

@Stefan: SnipSnap, the wiki I’ve co-authored some years ago, was memory only with write-behind, something which now becomes trendy with #NoSQL.

Redis is in-memory only. Looking at some memory graphs in operations if fear mem-only apps – seeing the JVM heap grow and grow +g+

But mem-only is the future I assume. I think about a post.

Sure we must take care with “magic code” and that’s why i dug inside my favorite ORM to see how i works and learned how i should really use it, i’s been fine since then. Don’t remember now but i think Jamie Zawinski or Brad Fitzpatrick said “don’t trust your abstractions” in “Coders at Work”.

@Michael: I need to reed “Coders at Work” too, it’s on my list for quite some time.

“[..] inside my favorite ORM to see how i works and learned how i should really use it, i’s been fine since then.”

100% ack. One needs to learn how the ORM works if you want to use it. Many developers don’t do that.

Jonathan

IMO, things like AOP and Project Lombok were an attempt to make up for missing Java language features (traits/mixins, closures, properties, delegates, tuples), and weren’t necessarily created for the sole purpose of performing magic. Still, as you say, it is important to know what’s going on inside the black box.

Tyro

When I first read about AspectJ, I was a huge fan but after using it on a project and spending days and weeks fighting obscure bugs I finally gave up, deeply disillusioned. Same thing with Hibernate which got swapped out for iBATIS until I tried Groovy/Grails and gave Hibernate a second chance only to find a whole new category of problems, some of which are still not resolved. They’re minor time savers when they work but when they fail, they fail hard. You could argue that I and my team failed by not understanding all of the intricacies but this is the actual problem, illusory simplicity which hides deep complexity.

On all new code I much prefer iBATIS, JDBCTemplate or even JDBC directly. The small costs to write the queries more than pays for itself by reduced complexity and easier debugging.

I think magic might be the primary reason for why programming is so difficult. Designing an algorithm is not too difficult. It requires an analitically oriented mind. But facing some magical error is a nightmare. Then the programmer has two options:

1. Diving deep into the underlying framework to understand what happens beneath.
2. Trying lots of different paths to make the code work.

Both options are very unproductive and usually frustrating. Worse, the programmer cannot make a good estimate on how long it will take to overcome the problem. It may take one week or just 5 minutes.

Nick Wiedenbrueck

Great post. Totally agree with you.

It’s kind of a love/hate thing. Hibernate proxies, AOP, Scala implicits, Groovy MOP, … – it’s all so great when it works, it’s not so bad when it fails and you understand it, but it’s a mess when it fails and you don’t understand it.

You’ve got to be more like Merlin than Harry Potter to get it right.

@Nick: Thx, exactly (Merlin).

Everything is magic. But sometimes you know the spell. If you mix them, strange things can happen.

privateer

Of course specifications, frameworks, api’s etc. have to become more complex (eg. magical) over the course of time… that’s just a logical consequence of “software-evolution”, isn’t it?

IMHO the problem is that the people using them (developer’s but especially projectmanagers) did NOT change over time!

Let’s assume at 1990 (technologies and user-expectaions) it took one developer to get “enough” experience with every technology/practice/technique/methodology about 2-3 years.

In the year 2010 with probably 10 times more stuff to master and way higher user-expectaions this timeframe is now probably at 6-9 years!

Long story short:
IMHO its not the frameworks that get out of hand but we, the developers, have to find a way to catch up!
Maybe the industry needs to change it’s mindset that 2-3 junior-dev’s, 1 dev, 1 senior-dev and 1 PM could handle any project…

Or we just need more developers without a social-life and learning all the stuff at weekends. :)

[...] Am I too stupid for @Autowired? – Peter Veentjer talks about his objections with Spring’s automagic functionality. I tend to agree that @Autowired et.al. is fairy dust in your code. And magic should be avoided when programming. [...]

Leave a Reply

What people wrote somewhere else:

Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

Totally agree – RT @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

RT @codemonkeyism: “Be careful with magical code” http://bit.ly/b89k0z

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

I’ve been wanting 2 blog about this, Stephan saved me the trouble: “Be careful with magical code” http://bit.ly/b89k0z (via @codemonkeyism)

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

RT: @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

RT @codemonkeyism Code Monkeyism: Be careful with magical code http://bit.ly/b89k0z

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

Be careful with magical code! http://bit.ly/9qYymQ

This comment was originally posted on Twitter

【Hacker News】Be careful with magical code: http://bit.ly/aQHcZW

This comment was originally posted on Twitter

Beware! Beware your magical code! http://bit.ly/bacTtZ

This comment was originally posted on Twitter

Be careful with magical code http://bit.ly/aYfaiK

This comment was originally posted on Twitter

【Hacker News】Be careful with magical code: http://bit.ly/aQHcZW

This comment was originally posted on Twitter

【Hacker News】Be careful with magical code: http://bit.ly/aQHcZW

This comment was originally posted on Twitter

【Hacker News】Be careful with magical code: http://bit.ly/aQHcZW

This comment was originally posted on Twitter

【Hacker News】Be careful with magical code: http://bit.ly/aQHcZW

This comment was originally posted on Twitter

【Hacker News】Be careful with magical code: http://bit.ly/aQHcZW

This comment was originally posted on Twitter

【Hacker News】Be careful with magical code: http://bit.ly/aQHcZW

This comment was originally posted on Twitter

Be careful with magical code: http://bit.ly/b8pwGQ Comments: http://bit.ly/d7t8eC

This comment was originally posted on Twitter

I always try to take care of that – RT @codemonkeyism Just blogged: “Be careful with magical code” http://bit.ly/b89k0z

This comment was originally posted on Twitter

http://is.gd/7uYJR Be careful with magical code < Magic is non-linear. It works for a wide range, then suddenly breaks.

This comment was originally posted on Twitter

http://codemonkeyism.com/beware-magical-code/

This comment was originally posted on Twitter

RT @codemonkeyism: Just blogged: “Be careful with magical code” http://bit.ly/b89k0z – Please RT :-)

This comment was originally posted on Twitter

RT @mhaller1979: http://codemonkeyism.com/beware-magical-code/

This comment was originally posted on Twitter

DZone Direct Link To Article – Be careful with magical code http://bit.ly/bY1Dwv

This comment was originally posted on Twitter

Be careful with magical code http://bit.ly/bY1Dwv #java

This comment was originally posted on Twitter

Be careful with magical code – http://su.pr/2BGh0y

This comment was originally posted on Twitter

RT @codemonkeyism “Be careful with magical code”
http://bit.ly/b89k0z (that’s why programming is so difficult)

This comment was originally posted on Twitter

Currently Browsing: http://is.gd/7xgAe

This comment was originally posted on Twitter

Be careful with magical code! http://codemonkeyism.com/beware-magical-code

This comment was originally posted on Twitter

Be careful with magical code http://ow.ly/16tKl4

This comment was originally posted on Twitter

Top 5 entrance sources for my last post http://bit.ly/b89k0z , HackerNews: 674, Dzone 655, Direct 606, Feedburner 552, Google.com 265

This comment was originally posted on Twitter

I had to think quite a while to agree: “Be careful with magical code” http://bit.ly/b89k0z (via @codemonkeyism)

This comment was originally posted on Twitter

What do you think? What about MDD in this context? – Be careful with magical code http://bit.ly/dAQouf

This comment was originally posted on Twitter

RT@ JohanDenHaan Be careful with magical code http://bit.ly/dAQouf

This comment was originally posted on Twitter

Interesting article about magical code http://bit.ly/dbroJn #code #scala #java #external #frameworks

This comment was originally posted on Twitter

Be careful with magical code. Good read! http://tinyurl.com/yhvns85

This comment was originally posted on Twitter

Java Annotations and Magic Code http://bit.ly/9ludfq http://bit.ly/bNpwcj

This comment was originally posted on Twitter

Java Annotations Have Become Pixie Dust: http://bit.ly/a7o3jV …but, Be careful with magical code: http://bit.ly/djMsgD #java

This comment was originally posted on Twitter

Code Monkeyism: Be careful with magical code http://ff.im/-fq4Bd

This comment was originally posted on Twitter

This is a must read for Java developers in love with frameworks *cough*Spring*cough* “Be careful with magical code” http://bit.ly/aQpD2a

This comment was originally posted on Twitter

Be careful with magical code, by @codemonkeyism http://codemonkeyism.com/beware-magical-code/

This comment was originally posted on Twitter

RT @laogao: Be careful with magical code, by @codemonkeyism http://codemonkeyism.com/beware-magical-code/

This comment was originally posted on Twitter

Bei DS einen interessanten Artikel gelesen http://bit.ly/7WpQ7R und noch interessanteren Autor entdeckt: @codemonkeyism http://bit.ly/dt651Z

This comment was originally posted on Twitter

RT @LeMondefr_Sport: Coupe de France : Quevilly fait chuter Rennes http://tinyurl.com/yzad6fq

This comment was originally posted on Twitter

foursquareの方が良いよなぁ…遊びがあるもん。マピオンならランニング情報と連動とかしてくれないと。 『iPhoneからTwitterで「○○なう」――今いる場所をつぶやける「なうまぴおん」』 http://tinyurl.com/yfha3hq

This comment was originally posted on Twitter

RT @codemonkeyism Code Monkeyism: Be careful with magical code http://bit.ly/b89k0z

This comment was originally posted on Twitter

@codemonkeyism Quoting this blog post “I’ve been a long fan of ORMs – especially Hibernate – but I’m no longer” http://is.gd/8OOSU :D

This comment was originally posted on Twitter

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?