Magic is often used to describe confusing code. Often we cannot explain how something works so magic seems like an apt description.
The problem with magic is that it’s an entirely subjective term which can be used as a very annoying stick to hit useful abstractions.
A while ago I wrote something along the lines of this in Scala.
val transformedCollection = collection map transformer
For those not familiar with the
map construct, this will run the
transformer function on each item in the
collection, returning a new collection of transformed items.
Another nameless programmer chastised me
"I like to be pragmatic"
(Who exactly doesn’t like to be pragmatic?)
"This is magic, why not just write a for-loop, it’s clearer"
Apart from the pragmatic comment it’s actually a reasonable thing to say, if you don’t understand how something works then it’s magical!
Understand the magic
Just because something seems magical doesn’t mean it’s wrong. The problem with the term is it’s often lazily used when someone doesn’t understand an abstraction, or worse - doesn’t want to understand.
So what is magic?
For me I get the feeling of dark arts surrounding me when there is a lack of explicitness. Generally stuff changing “underneath” me based on some kind of state of the system. It often feels like the code is working by accident rather than deliberately.
Anti-patterns like global imports and setter-based DI makes the system feel magical in a very ugly way.
Choose your spells
From time to time all of us look at some code and throw our hands up in the air when we don’t initially understand something. Rather than unsheathing our anti-magic sticks make an attempt to understand it first.
There’s nothing more annoying than someone describing your code as magic when you feel you put some effort into a useful abstraction. So try to be considerate when faced with unfamiliar constructs.
That being said it is important for programmers to share their knowledge when introducing something new. Be sure to explain your sleight of hand at code review and use abstractions tastefully and keep intent clear at all times.
Don't lazily conflate the unfamiliar with magic. It's short-sighted and annoying.