I have seen a few stories use the programmable magic trope. The most well known I believe is the wiz-biz series, though it's rather old now. The idea is that magic works just like a programming language, you put together words that have meaning and give it power and the spell is compiled and cast immediately, doing whatever you programmed exactly as written. In this case 'power' as a mage usually equates to either having a large number of 'programed' spells you know, or being better at 'programming' a spell on the fly.

However, as everyone who has ever programmed knows, bugs happen. Even a simple Hello World! program will likely have a missing semicolon or misplaced bracket 1/3 of the time someone writes it. It's hard for humans to write anything without at least small mistakes.

The Wiz Biz series addressed this by having a huge disaster in the past due to such mistakes (sort of), and massive effort put into 'testing', as best they could, the spell. Other worlds doing this have always said something about how dangerous mis-writing a spell can be, and yet often the protagonist still manages to code up a spell on the fly with a massive degree of accuracy and no mistakes. In honesty I think all series with this concept have, for all they discussed the potential risk of such magic, failed to represent how absurdly likely and common mistakes would be, and thus how horrible the side effects within the world would be.

Let's say I want to write a world that is more realistic regarding the potential of mistakes. However, I don't want a world where everyone who studies magic ends up accidentally destroying everything around them and then themselves within a year of starting to study it. So how can I minimize the risk of disaster due to programming error, while acknowledging errors exist? I'm looking both for how the magic itself could be designed to lower the potential harm and for how citizens of the world may further lower their risk.

Assume the world has some level of adherence to thermodynamics. The larger the effect of a spell the more magical energy needed; thus preventing entire world from blowing up when someone typo's. However, there are still lots of horrible small scale disasters to be avoided.

I'm okay with some 'bad stuff' happening, but I want it limited in effect if it does. Someone probably won't die from chanting oya instead of oiea in his spell. Negative effects are fine so long as their severity is low enough to not make magic too dangerous to use, or can be identified before the severe harm is done.

At a minimum I'm looking for ways to mitigate the risk for spells written well before they are cast. However, ways to allow someone to write a spell on the fly, or even just modify existing spells on the fly, without lethal risks are good too. In all cases I want to stay realistic to just how common typos or even logical errors are in 'programming'.

PS: to give credit while due this was inspired by How do sorcerers attempt to prevent common people, or other sorcerers, from duplicating their spell scrolls?, though the question has been in the back of my head for a while I never thought of asking it here until now.

  • 11
    $\begingroup$ All I can think of is "magical unit testing." But I have no real answer as to what that looks like. $\endgroup$ – Draco18s Dec 18 '15 at 17:33
  • 8
    $\begingroup$ magical sandbox... $\endgroup$ – user6760 Dec 19 '15 at 4:30
  • 2
    $\begingroup$ Put in mechanics like magic taking up a certain amount of energy to use (like in Eragon), that way if there is something that was programmed wrong the user won't have enough energy for the spell to do any serious damage. $\endgroup$ – womp Dec 21 '15 at 11:56
  • 5
    $\begingroup$ The 40,000 arrows a minute + womp's comment reminded me that there's a book a friend recommended to me about a programmer who gets shifted to a magic universe. The best wizards can summon "a fireball." The protagonist can summon as many as he wants by looping the original spell. for(int i = 0; i < 40000; i++) { fireball(); } Shame I can't remember the title. $\endgroup$ – Draco18s Dec 21 '15 at 15:06
  • 2
    $\begingroup$ "You shall not pass!" - Gandalf messes up a 128bit encryption on the bridge. "Whoops, the bridge collapsed... um, that was intentional, yeah". The Wizprogzardmers simply take credit for all their mistakes, like in the Landover series. $\endgroup$ – Nahshon paz Dec 23 '15 at 8:10

18 Answers 18


Disclaimer: I'm a simulations programmer, so this is kinda-sorta my bread and butter. Sometimes people even call me a wizard when I solve problems.

There's a few major pieces you can focus on. Draco18s mentioned unit testing, which would be a very natural process for weeding out bugs. Take each component and make sure it behaves well in a battery of tests. However, anyone in the software business knows full well that the unit testing is the easy part. Integration is the word that strikes fear into everyone's hearts. This is the step where the assumptions you made during unit testing actually get tested, and we see if the parts are actually what we asked for!

Its easy to make something do what you want. Its hard to make sure you wanted the right thing.

So this is where simulations come in. You need a way to test the behavior of your spell in a low-risk world where, if something goes wrong, you can afford to control it. This might be as simple as having a room which magically emulates what the world outside operates like, only at a vastly decreased level of power.

However, there is a mantra that simulations developers are taught: "All models are wrong, some are useful." As much as I love my bread and butter, a product is never truly "ready" until it's been tested in the field, and that means risking the kind of cataclysmic events.

Fortunately, you are not the only one who cares about preventing these kinds of events. All sorts of three-letter-agencies are interested in the same issue you are: Federal Aviation Administration (FAA), Department of Defense (DoD), Nuclear Regulatory Committee (NRC). All are very interested in the same thing you are: things not going wrong. So we can look at the sorts of things they demand from their spells -- I mean hardware and software devices, and extrapolate.

One of the most important steps to keeping a product under control is the identification of failsafe paths. The software is constantly monitoring itself to make sure the software and hardware is behaving according to expectations. If anything is out of place, a default path makes sure the system remains safe. For example, you might have a very advanced algorithm with all sorts of feedback loops governing a regulatory valve in a nuclear reactor, with the goal of extending the life of the reactor through careful management of temperature. Testing that algorithm is hard. How do you know that it will respond to the particular circumstances it will face in its life? The solution is to have a fail safe. If the temperature (or other variables) get too far off nominal, the advanced algorithm is taken offline and a more predictable, controllable algorithm takes over. This algorithm may not be as capable, but it may be just good enough to shut the system down.

In magic land, this may come in the form of parts of the spell which intentionally cut the magical power of the spell if it detects a problem. Accordingly, "safe" spells would always be identifiable because there would be an intentional "weak spot" which the fail safe can sever or control if need be.

Also key to these structures is the idea of a "safety critical path." This shows up all over in products for the three letter agencies (can I just call them TLAs?). The idea is that not all of the code is actually critical. Some code is optional, other code has fail safes. However, there is always some portion of the software which has no failsafe, just due to the nature of software. This code is tested and audited like crazy. Often they don't use the full capacity of their languages, such as avoiding recursion or allocation of variables.

Want extreme safety? Let's talk about the safety critical layers built into Little Boy, the bomb that detonated over Hiroshima. The actual fuse was set to detonate at 1900ft above ground, using a redundant pair of radar altimeters. However, radar is a complicated system with all sorts of noise issues that could have caused a false positive, so in the interests of safety-critical operation the radar altimeters were not enabled until a barometric altimeter gave them the OK. The barometric altimeter (a thin strip of metal in a glass container that deflected with air pressure) was not precise enough to detonate the bomb, but it was trusted more, so authority was not given to the altimeters until it declared they were low enough. Even then, the crew of the Enola Gay wasn't about to be ground 0 because some thin piece of metal ruptured, so there was a mechanical timer also on board. The barometer was not trusted unless its rupture was detected more than 15 seconds after bomb drop. Would you trust that on its own? Of course not. The final level of safety critical hardware was a pair of arming plugs, one green (safe) and one red (less than safe). They contained physical wires that connected circuits to turn the whole bomb on. Finally we reach the most safety-critical layer: the physical reliability of these plugs was tested tremendously.

The magical equivalent of this would be to make sure dangerous spells are far enough from the caster before they unfold. A fireball may be nothing but a cute little puff of smoke until it gets to a safe enough distance to ignite. Also, individual mages may tune these parameters. A mage with better reaction times may choose to "arm" the fireball at a close distance, while a slower mage may choose to let it fly further before becoming dangerous.

Another key trick we see in software is writing code which has provable limitations. If you can prove that the worst damage doable must be along a safety-critical path you've analyzed. Consider Google's Native Client (NaCl, or simply salt). NaCl is a fascinating plugin architecture which permits running native x86 code in a safe sandbox. Impossible? I thought so too, until I looked into their approach:

  • Dynamic code generation is forbidden outside of Google's own APIs for doing so. Thus, all code may be statically analyzed before it can be run.
  • Privileged instructions are, naturally, forbidden. You have to call Google's API to access things like files. Google installs its "kernel" into your process, and its kernel does the work for you.
  • The indirect JMP instructions are ever so slightly locked down: you are only permitted to jump to places written directly into the code, or to places whose address is a multiple of 32.

Why the last rule? Fascinating really. Consider someone who wants to get around the limits of NaCl by jumping directly into the middle of a Google provided API function. It's really hard to prove that they can't break the sandbox that way. Well, Google wrote their code carefully such that every address that is a multiple of 32 has some sort of HALT or other instruction which immediately terminates. Thus, if you can prove the client code cannot jump to anywhere but multiples of 32, they cannot possibly jump into your code.

This may lead to the development of spell "kernels," which are carefully crafted in this way to limit power and prevent it from running out of control. I could see each school of magic having their own preferred set of kernels to build spells from.

Of course, there's always the non-software approach. Most software is designed to operate at maximum speed with minimal outside interactions. However, what if interaction was built into the spells directly? What if a spell was actually a part of you until both you and the spell decided to go your separate ways. With this, you might be able to maintain a modicum of control as you try to teach the spell to do things you consider to be "good." This approach may be very popular for druids. Instead of starting from some artificial kernel core, they may start by interacting with some seed of life from Gaia herself, teaching it how to become a good spell, a worthy spell, then letting it free into the world.

  • 7
    $\begingroup$ Drat. Halfway through my very similar answer and you posted a better version. Oh well. I was also going to mention make's --dry-run option, but that's more of a comment than an answer. (This comment, actually). +1 $\endgroup$ – Frostfyre Dec 18 '15 at 18:47
  • 1
    $\begingroup$ A world where there is a smooth gradient from hardware to software would be quite interesting! I think the question that may be important here is how much of magic can be defined using information versus how much is defined using physical/magical structure. What makes the study of software so affordable is that you can identify ways to do math to predict the effect of something without actually having to do the whole thing. As a simulations person, what's fascinating are all the things that can't be predicted in this way, and how the hardware peple manage to test it regardless. $\endgroup$ – Cort Ammon Dec 18 '15 at 18:55
  • 2
    $\begingroup$ As a hardware example, civil engineers know how to build scale models of their work, and more importantly, know which variables scaled properly (so could be tested on the scale model) and which ones scale poorly. Without that information, scale models would not be an effective way to test the safety of the final product. $\endgroup$ – Cort Ammon Dec 18 '15 at 18:56
  • 1
    $\begingroup$ or as a better analogy, imagine I'm learning and writing C but for some reason my operating system allows me to write to any memory location (like how the magic language lets me run any command). How long until I confuse my pointers and write over my boot-sector :). That's what I mean about lack of hardware and software distinction. This makes unit testing potentially scary... $\endgroup$ – dsollen Dec 18 '15 at 22:16
  • 2
    $\begingroup$ +1 for kernels. Want to wizard? Cool. You can try it on your own but you'll probably die. Or get someone to teach you the WIZ kernel, always use that, and the worst that will happen is you spawn a talking paperclip that gives you patronising advice on what you did wrong. $\endgroup$ – Joe Bloggs Jul 13 '17 at 9:45

Let's just visit the first lesson of Magic 101 at the Wizard's University.

Finally the professor entered the room. Before he turned to the audience, he muttered "abra". Now this was to expected; it was a strange tic shared by all wizards that they every now and then muttered, without evident reason, "abra"; indeed it was such a common occurrence that "abra" had become a synonym to "wizard".

Now the professor turned to the audience: "Good morning, dear wizard candidates. I'm your professor of magic spelling, and today you'll learn the most important spell of all."

The candidates got excited: The first lesson of the first course, and they already would learn the most important of all spells! What would it be? The tension became almost unbearable.

The professor continued: "You're certainly eager to learn that spell, but you should know that I'm going to keep an important part back until the end. I know the magic students; after all, I've been one myself, and I've got a host of experience in teaching. Abra I know, you'll be eager not only to try it, but to try variations of it. But small variations of spells can easily be very dangerous. Abra You may have heard about the large flood five hundred years ago. What is less well known is that it was the fault of a single wizard. He was experimenting with a spell to turn stone to meat, and thought he might be able to make better meat by changing the spell a bit; abra well, it turned out that instead the change made the spell incredibly more powerful, turning the wall of a nearby mountain lake to meat. The meat could not hold the water pressure, and the flood was released. The wizard turned the meat back to stone, but he couldn't stop the flood he started. Abra"

The audience got impatient. They were not here to learn about the dangers of magic, they were here to learn how to apply it!

Fortunately the professor now came back to the spell: "OK, so after the word of warning, I'm going to tell you the main part of the spell. It's actually quite short: "ab". That's the active part of the spell.

One of the students asked: "What do you mean with active part?"

The professor answered: "That's what I was coming to anyway. Abra A spell consists of three parts: An opening, an active part, and a closing. This is very important, because anything you say between the opening and the closing part is part of the active part of the spell. Abra So if you happen to say something in between that's not part of the spell you want to cast, that means you've got a different spell; quite possibly one you'll regret to have cast. This even includes a repetition of the opening part. Therefore you have to be very careful what you say when casting a spell."

"So whenever I say something wrong, I'm immediately doomed?" the student asked.

"Oh no, fortunately not; that would be terrible." replied the professor. "No, as long as you didn't utter the closing formula, the spell will not go into effect, and therefore you can still correct your error."

"But how would I correct that mistake?"

"That's a good question. There is a spell word for this, that cancels everything between the opening of the spell and that spell word. Abra That is, after uttering that word, you can start over as if you had just uttered the opening. Abra And if you continue with the closing, it means you've completely cancelled whatever spell you were starting to cast. Therefore this spell is known as the spell of cancelling. Abra Indeed, that is the most important spells of all. I already told it to you: It's "ab".

So that was the most important spell the professor was talking about. The students were somewhat disappointed. On the other hand, that safety was valued that much showed that it would be a powerful art they were learning.

The professor continued: "Abra Now as you know the active part of the most important spell, it's time to teach you the other parts. One part is the closing. The closing is the part that finally releases the magic. Be always sure that you don't utter it before your spell is complete. Abra The closing of a spell is "ra". So whenever you started a spell, even if unintentionally, you just have to say "abra" and the spell is cancelled and finished, so you can continue to speak normally as long as you don't utter a starting formula. Abra"

Again, the same student put his hand up. It had to be a very intelligent and attentive student. His question was: "You said, a starting formula. Does that mean there are several?"

"Indeed." the professor replied. "Abra Actually, for a long time we thought there were just one, but fifty years ago the great mage Hudus found a second opening. It's a very useful one, and the one I'll teach you today. Abra But we don't know if there are others we haven't yet found. For this reason, it is a good idea to cancel a possibly ongoing spell you are not even aware you're casting. Abra You may have wondered why wizards constantly say "abra". Well, that's the reason. We protect ourselves against unintentional spells. Abra Also, it's a good idea to prefix each of your spells with "abra", to prevent it to become part of an ongoing spell you were not aware of abra. You better also get into the habit of saying "abra" from time to time, so you don't get caught by surprise."

"Ah, " the student replied, "but if you can utter a spell by accident so easily, then why do non-wizards do it all the time? After all, they don't know how to avoid it!"

"Abra Well, a spell only works if you own a magic staff. It doesn't matter if you have it with you, but you have to own it. Abra All of you will be given a magic staff soon; until then, you should get into the habit of saying abra frequently. From now on, I want you to start every sentence you say here with "abra"."

"And …"

"Start wit "abra"!"

"Abra And what's so special about the newer opening that you said it's so useful?"

"Well, if you cast a spell with that opening, it doesn't actually happen. But you immediately know what would have happened if you had cast the same spell with the standard opening. Therefore it allows you to safely test spells. And to safely learn them, I want to add."

"Ok, so …"

"Start with "abra"!"

"Abra so you say we won't be able to actually do magic?"

"Abra Well, not until you learn the standard opening formula. Which you will as soon as you've passed the first exams and proved that you can indeed be trusted to cast your spells responsibly. Abra For now, you'll only learn the newer opening, known as the dry run opening. It's "kad". Abra And remember, you should always cancel a possible ongoing spell first. OK, you" — he pointed to another student — "please tell me, what would be the correct way to dry-run cast just the cancelling spell?"

The student thought for a few seconds and then said: "Abra kad abra."

"Exactly" the professor said. "Abra."

  • 15
    $\begingroup$ You submit this as an article for the blog :) I saw the punchline coming in advance but it was still good. $\endgroup$ – Tim B Dec 21 '15 at 13:19
  • $\begingroup$ dido both parts that Tim said :) $\endgroup$ – dsollen Dec 21 '15 at 14:39
  • $\begingroup$ @TimB: How would I post it on the blog? (I just created an account on Medium, but I wouldn't know what to do next.) $\endgroup$ – celtschk Dec 21 '15 at 20:44
  • 1
    $\begingroup$ @SouthpawHare: No, there is no "literal" here. Think of kad like entering (dryrun-) command mode, ab as deleting the command typed so far, and ra as executing it. So if e.g. oops is the fireball spell, and eek is the flying spell, then ab ra kad oops ab eek ra will be equivalent to ab ra kad eek ra, i.e. dryrun the flying spell. ab ra kad oops ab ra will do nothing, as the oops is cancelled. Also note that with the previous ra you left spell casting mode, so the new kad is not part of the previous spell (cancelled or not), but has the effect of starting a new one. $\endgroup$ – celtschk Nov 19 '17 at 14:50
  • 1
    $\begingroup$ @SouthpawHare: No. Let me spell it out in detail (no pun intended). There are several modes. Normally you are in "talking mode" where nothing you say has any significance except for opening formulas. The opening formula has the effect of switching into the corresponding magic mode; for "kad" it is the dryrun magic mode. Everything following is then interpreted as magic spell, which is triggered upon the closing formula. Directly after the "kab" the spell built so far is empty. The ab goes back to the state directly after the opening formula, thus cancelling anything spoken afterwards. $\endgroup$ – celtschk Nov 22 '17 at 22:31

Make "nothing happens" reality's error message. Even in a magic world, 99.9% of all events that happen aren't magic. A cow eats grass, water flows downhill, and the sun keeps shining, and a wizard didn't cause any of it. Magical events are the exception, not the norm, so let those small spell-coding errors do exactly what most real coding errors do and cause the whole thing to just fail and do nothing. No explosion, no curses, the wizard says words, and the sun shines and the birds sing and an orc crushes his head with a club. More experienced wizards might have less chance of these harmless "compile time errors" and a greater chance of more interesting "run time errors", as they get better at making sure their spells work enough to always do...something... Actually "run time" takes on a whole new meaning with spell program errors..."

  • 6
    $\begingroup$ "It's a run-time error!" - "What do we do, Mr Wizard?" - "Fly, you fools!" $\endgroup$ – Joe Bloggs Dec 21 '15 at 10:52
  • 3
    $\begingroup$ But what about the errors like where you misplace a decimal point and the fireball ends up consuming a whole town instead of lighting a candle like you intended... $\endgroup$ – colmde Dec 21 '15 at 11:43
  • 3
    $\begingroup$ had to upvote just for the "run time" errors comment at the end :) $\endgroup$ – dsollen Dec 21 '15 at 14:41
  • 1
    $\begingroup$ @colmde that's not a run time error, that's a mistake in judgement. The spell did exactly what the wizard told it to do. Spells have to obey the wizard, so wizards would have to learn to be very deliberate. $\endgroup$ – AndyD273 Dec 23 '15 at 12:34

As a programmer, the single most common result of typographic error in programming is that nothing happens. Syntax errors, misspelled identifiers, etc make the source code incomprehensible to the compiler or interpreter, and as a result the program doesn't run.

That would be the fate of most mis-cast spells as well; a "fizzle", nothing of much consequence happening other than the caster stands there looking rather foolish.

The potential magnitude of other types of errors depends on the scope and scale of the error and that of the code containing the error. All other things being equal, the "closer to the metal" your code is, the bigger the potential for catastrophic error because there's less in the way to prevent it. In the opposite way, the more your code tries to do, the more it can mess up.

So, a spell trying to do something very specific and detailed, like changing someone's physical appearance or imbuing them with innate power, has to be damn perfect, because you're changing the entire person's makeup at the cellular level. Make the same mistake to every cell of that person and they could very well dissolve in a puddle of gibs. Other types of spells, especially those applied to nonliving matter, might be simpler and more error-tolerant because the end result isn't a matter of life or death.

To avoid this fate, you can either limit the amount of fine-grained control that is possible with magic, inventing some other means to affect the desired change (a long-lived magical "aura" that surrounds the person to grant an ability or alter their appearance), or you can make the "engine" that makes magic work in this universe somewhat intelligent, giving it a role analogous to a managed runtime in the computer world. That would allow the magical energies to identify the user's intent behind the specifics of their spell and, at the very least, fizzle the spell to prevent unintended consequences, or at best, say "I know what you meant" and act as if the caster's incantation were perfect. The potential for error, perhaps comical, perhaps horrifying, still exists, when the semi-sentient magical energy says "Oh, I know what you really meant" and does something very different from the caster's intent.

The Potterverse does a little of all of this. There seems to be an inherent limit to the "resolution" with which wizards can modify the world around them using spells; they can influence reality and make small changes to it, but not totally remake it (though potions, which take much more care and time in crafting than a simple incantation, do allow for more fine-grained effects, with serious potential for disaster if brewed incorrectly). Further, there is some level of sentience embodied in the wand the wizard uses, and an inherent requirement that the wand understand what the wizard intends, and that it wants (or at least allows) them to do it. If the wand doesn't understand what the wizard wants to do, usually nothing happens, but from time to time there are spectacular misfires (especially in the movies). Further, the wand chooses the wizard; anyone with magical power can channel that power through almost anything, but a wand works best for a wizard that the wand accepts as its master, and in the books, wands resist spells cast through them by wizards other than their owner.

  • $\begingroup$ Uh, no. Syntax errors while, common, are quickly patched away by virtue of compiler/interpreter finding them in the early stages of their work with just static analysis and clearly identifying them. And THEN you spend most of the time with logic errors and it is those that cause most devastating real-life consequences, like blown up spacecrafts or security compromised Internet-wide. $\endgroup$ – Oleg V. Volkov Dec 22 '15 at 16:11
  • 2
    $\begingroup$ Your point about how intelligent the interpreter/compiler is could be made an answer in itself. If the airy spirit or daemon that hears a spell had a human-like level of ability to take into account context and interpret the intent of spell-code, you could end up with a very "safe" universe where magicians could make dozens of mispronunciation errors and still expect a spell to work. On the other hand, if the hidden powers of the universe were less intelligent and benign... "It looks like you're throwing a fireball. Would you like help?" $\endgroup$ – user867 Dec 24 '15 at 3:25
  • $\begingroup$ @OlegV.Volkov - And if you're casting a spell that you intend to work first try, "compiler errors" preventing the spell even beginning to do its thing will cause the spell to fizzle. Doesn't matter whether the "environment" catches the error as you cast or once you finish; if there's an error the program (spell) doesn't function. These typos are more common than actual logic errors, and if you have to explicitly "compile" to find them they take more time (which is why IDEs now have "check-as-you-go" functionality). $\endgroup$ – KeithS Jan 13 '16 at 21:02

Most modern techniques for improving code quality won't work with magic.

Unit testing does not prevent errors from happening; it only prevents errors happening in production. With magic there is no test environment that could burst into flames without anybody caring too much.

Carefully designing provably correct code also has limitations. You can make nuclear weapons that don't go off the first time someone looks at them funny, and you can give students spells that teach the concepts without doing anything dangerous, but the ability to write machine code that bypasses all that still exists. A typical student would never be allowed to do that on a computer that controls nuclear weapons, but with magic there is only one environment.

To prevent anything too disastrous from happening will require active defense - a group of highly experienced wizards who can install protective spells and deal with any less predictable incidents that come up.

Much of this could be automated - for example a spell that detects and disrupts anything using too much magical energy within city limits. Magical barriers set up on property boundaries could let careless wizards eliminate themselves without causing too much trouble for anyone else.

With these defenses the city is kept safe, but there is still plenty of scope for causing trouble. An infinite looping spell that summons a live frog twice a second uses an almost undetectable amount of magical energy, so may go unnoticed until you have several thousand of them to deal with.

Since defending against all magic takes a significant effort, there would be little if any protection between cities. Something that detects planet-melting levels off energy is probably worthwhile, but generally the first time you cast a spell outside the bubble you are on your own and have hopefully learned to be careful.


My answer would be to have them run as Macros, with your Wand, Amulet, or other magical construction being the activation sequence. All magic must then be "preloaded" and "run" through these items.

You could make it so they have to use their magic tomes to write them across - magic tomes which "check and debug" the spells you write or edit in them, as well as include a quick explanation of their function and effects.

It could even be that this is just the way things are done and whilst Maging on the fly is possible, it's dangerous, prohibited and frowned upon. And of course, nobody expects the spanish magic inquisition

Include things like Power Budgets (hat-tip @AndyD273) and you're on to a winner!


So I really like user3573647 answer in regard to syntax errors just causing the spell to not do anything.
But colmde does have a good point of what if it an error in scale, not syntax.
(The wizard uses the word for mile instead of the word for inch when creating a fireball)

So I have a few ideas:

  1. Magic has to be written down first, in a scroll or book. The paper doesn't have to be special, but can have special symbols to tell the universe that it's magic and to pay attention.
    Once the spell is written, then the wizard would read from it and invoke the spell.
    The downside is that a wizard might not always have a way to write stuff down.
    The way to get around that is to be able to take a written spell and bind it to an object as a macro.
    So if a wizard wants to be able to light his pipe by shooting a 1 inch flame from his finger for 1 second, he could write it up, bind it to his ring with a macro phrase, and then invoke the macro with that phrase any time he wants to light his pipe.
  2. If magic is seen as the programming language for the universe, then why not provide a debug window. The wizard begins speaking the spell, and words written in flame appear before him with the spell. Then if he sees an error he can nullify it and start over. The words might only be visible to the caster, or maybe only to wizards.
  3. Include a power budget inside of the spell. Say a 1 inch fireball requires 10 magical units to create. So the wizard gives the spell a 10 unit power budget, and then misplaces a decimal point. The spell tries to run, doesn't have enough power, and fails. You could still mess it up, but you'd have to be careless to mess it up really really badly.
  • $\begingroup$ For point 3, the spell might still run with the power, but show an error. A good wizard gives his spells an end message to see if they had enough power. $\endgroup$ – Mathmagician Jun 28 '17 at 8:35
  • $\begingroup$ @MatthewLang Maybe, though it seems like it would have a power overflow failure. Like, it needs 100, only gets 10, and so fizzles out. Then the wizard needs to quickly go over the spell to see where they messed up, which is where a debug error message might come in handy. Seems like an opportunity for comedic relief. Wiz starts to cast, the target is looking worried, the fireball begins to form, and then implodes. Wiz looks confused, says something like "Wait, did I carry the 4?" and then the target kicks them in a sensitive area and runs away. $\endgroup$ – AndyD273 Jun 28 '17 at 17:57

I'm approaching this from the perspective of someone who regularly deals with the fallout of mistakes in programming.

From what I see, there are certain types of errors that would apply equally to a magical world where programming spells results in magical effects:

  • Input validation. If I want to cast a spell to turn a pumpkin into a coach, for example, that spell should contain validation that the input (a pumpkin) is in fact valid (i.e. not a squash, melon, gourd, or other vegetable). It would be possible to bypass this validation, and hence convert other inputs into something, but I'm guessing that the process would be unreliable - if you put in a cucumber, for example, you probably get a sort of soggy limousine, whereas a cherry would result in a tiny little coach which rots if you look at it funny. Effectively, the process keeps going, but without the correct input, doesn't produce the expected output.

    In this case, the solution might be to allow these mistakes to happen, or to require a well defined input for all spells. If the input isn't defined properly, it just doesn't work - it's a strongly typed language.

  • Unexpected interactions. Most programming nowadays involves bolting together pre-existing parts to do something new. These libraries tend to be fairly well behaved, but sometimes they do have some unexpected side effects. Therefore, if I take a module from Spellcraft which handles "fireballs", and a module from Hex-u-like which handles staff-interactions, I might expect to be able to combine them to have a staff that fires fireballs when I point it and say "bang". If the fireball module also knows that keyword, though, I might get a staff which fires a tiny fireball which immediately explodes, with a correspondingly smaller effect than a big fireball which has had a chance to expand to usable size.

    This one is essentially user error. In real world systems, the effect just happens, but tends to be noticed quickly, unless it's a very specific edge case.

  • Authorization errors. Forgetting to check whether a given user has permission to do something is really common. Taking my staff from above, if I forget to program in a check that it's me holding it, I might find that anyone can use it against me. More subtly, I might make a magic portal for my local town, allowing selected dignitaries to visit a regional city quickly. I might have a list of known undesirables who are prevented from using the portal, but base it on a characteristic that can be changed, such as hair colour. In that case, it's a logical error that results in undesirable results.

    Again, this is basically user error. The mistake will probably happen, and it's really difficult to prevent automatically, since it's down to a logical flaw.

  • Infinite loops. I might set up a well on a barren hilltop to help the locals with their water supply. I might well set it to fill any bucket that is present at a given depth in the well, which seems reasonable enough, until someone drops a bucket, which lands upside down in the well. The spell tries to fill it, the water comes out, and starts building up. The spell keeps trying to fill it, eventually resulting in a build up of ground water, and flooding of the local area.

    This could be addressed with a kind of power reservoir which a magic user can draw on. Given the power of a single user, they might be able to run a drinking well pretty much indefinitely, based on 10 buckets of water per day, but anything above that starts eating into their reserves of power. For larger spells, such as magically assisted warfare, it might be that large numbers of magic users are needed.

In any case, there is a good chance that things can still go wrong, but that the most common errors are prevented. Clearly, it's not desirable for a junior magic user to be able to blow up the world, but put enough of them together, with a suitable spell (input: world, output: fragments of world, process: turn input into output with maximum boom), and you get a big bang.


Depending on the setting, you could have a central authority similar to the Psi-Corps in Babylon 5, where all magic users, whatever the level, must be registered members, and then, not permitted to practice magic until they reach a certain level of competency which includes training in QA processses that Cort Ammon describes in his answer. Perhaps each spell they have in the repertoire must be put through testing and be accredited before they are allowed to cast it outside lab conditions.

Or it could be a bit like having a driving license.

This could be more difficult in a medieval setting where the flow of information isn't as easy, but certainly possible in a more modern setting... Unless you included in the setting that high-level "Psi-Cops" equivalent could detect a "disturbance in the force" whenever a spell was cast.

  • $\begingroup$ Just thinking that comparing the organisation to the "Psi-Corps" makes it sound sort of evil, but it could also be no different to how doctors, etc. have to operate today... $\endgroup$ – colmde Dec 21 '15 at 15:06

The smart move is to consult with Joe.

You will need to be careful in your phrasing and be prepared to pay his hefty consulting fees, but the money will be well-spent.

Hey, if magic exists, why not Joe's superpower?

  • 1
    $\begingroup$ "Make use of magic that gives reliable information to check your spells work as intended" is actually a pretty good answer to this question. $\endgroup$ – user867 Dec 24 '15 at 3:27

Several of the other answers takes the approach that programming language means high level programing language. I'm going to take another approach and be inspired by assembler. This has the advantage that there does not have to be any syntax errors, any combination will do SOMETHING.

So to make this safe.

  • Let magic work by weakening the veil to the astral plane (or something like that) in precise patterns directed by the spell words.
  • Let each spell word take effect as soon as it is uttered.
  • Make any sensible spell start by a stage where a pattern is etched on the veil to the astral plain, at which point it is obviously visible what the spell will do (This is the key point). Only after that is the veil pierced to add power to the spell. This enables a mage (and possibly everyone else) to see exactly what a spell will do before adding power, and if a mistake is made before piercing the vail the mage need only abort the spell.

This framework can be extended by adding further stages. For example

  1. Draw pattern for spell effect including targeting
  2. Pierce veil to add power
  3. Add spell words to extend the duration
  4. Add protective details to the spell to defend it from meddling

So to summarize, if a mage is forming the spell in a way that makes it's effects visible before adding power placing all the complexity of the worlds assembly programming up front and then make the activation a single command then mistakes can be reduced by letting mages know before finishing casting if it will work.


Powerful programs need powerful resources. To run weather simulation or to crack powerful cipher you need supercomputer.

If magic program needs to consume lots of mana to produce big results then a newbie cannot cause disaster - he does not have resources. And you can test new spell by adding available mana during each start. Or maybe even cut off mana source in the middle of execution.


If, in your world, magic behaves as programming, I believe the analogy could be extended to broader subjects regarding computer science. After all, computer science is coherent and works pretty well, if you're constructing magic around one of its concepts, taking the analogy further has a good chance of giving you a pretty coherent result.

First of all, I disagree with some of the answers suggesting that a "badly written" spell just shouldn't do anything, or "raise an error". True, that happens a lot when programming, but those would just be uncoherent babbling that have nothing even close to do with magic. Saying random words or getting the "syntax" wrong will indeed not do anything, but one could build a spell that is well formatted (it "compiles") but doesn't do what the wizard intended. Think of DELETEing a production database when you only wanted to DELETE a single entry. Pretty bad, right ? You forgot the WHERE statement giving your condition, but your request is still well-formed and gets executed by the server. Well, a wizard could boil every single ocean on the planet, because he forgot to specify a condition on the spell. It happens.

To limit and regulate what a spell can do, one could think of power limitations. It makes sense for a wizard to be more or less powerful, just as it makes sense for a computer to have more or less processing power. That would mean you can only cast spells that fall into a level of power consumption you can manage : massive destruction with a single spell will most likely demand a huge amount of power, so unless you're a superpowerful wizard, there's no way you can cause significant damage. And if you are, well, with great power comes great responsibility, and you should be more careful. You're probably much more experienced too, which further reduces the risk. Trying to cast a spell when you don't have enough power to do so will just result in a miserable failure, and you also might exhaust yourself... Try running modern games in Ultra mode on your old laptop and see what happens !

In addition to this concept of "power requirements", the authority/ies ruling your world might be well aware of the issue, and it would seem pretty senseless not to regulate power usage. Maybe a wizard could need specific qualifications to use certain types of spells, or spells that require a given amount of power to be cast properly. Think of permissions : if you don't have permission to delete a file, then you won't be able to do it. Here, you might not be able to prevent a rogue wizard from trying a spell he is not authorized to cast, but since it's against the law, you can prosecute him. It also seems fairly realistic in this kind of magical world to be able to detect if a spell fulfills given requirements before allowing its casting (like a pre-commit hook), and filter spells that don't. The wizard would then know that his spell has been blocked, and no damage is done.


In conjunction with other techniques others have mentioned you could use a virtual universe (VU) to test all your spells before you release them on to the real universe, in the same way that a programmer might use a virtual machine to get used to working in an unfamiliar operating system.

I'm not sure if you should be extra confident in a wizard with a VU which has been totally messed up because they do plenty of experimentation, or worried that they might do the same to you!


Syntax errors produce a puff of harmless smoke

If you say a spell wrong, nothing happens. In real world programming, changing a character somewhere usually ends up producing a syntax error, or at worst will change a string or number to something different.

Spells would be much the same. If you mispronounce a word, you probably will cast a dud. If you're unlucky, the scale of your spell might be different, but you likely won't summon a chicken instead of shooting a fireball.

There could be a way to interpret the smoke patterns which vary based on the mistake.

Simple spells are less error prone

Hello world basically always works as intended, assuming it compiles correctly. Simple spells don't usually have issues and are easy to cast.

Most errors are simply not catastrophic

Most real world software isn't life-or-death. Often, the worst-case scenario is crashing the program or opening a security vulnerability. Yes, you can definitely do some serious damage, but most of the time, software bugs don't kill people. As long as spells aren't messing with life-and-death type stuff like healing, transformation, and summoning, you don't need to worry much.

Large-scale spells like rain dances would be frowned upon or banned because of the possibility of minor errors doing severe damage.

Spell safety

This world would likely have spell safety practices, much like gun safety. It would be bad practice to point spells at anyone and wands (or whatever channeling implement) would be treated like deadly weapons. While spells are not generally harmful, there is a real possibility of unintended effects doing harmful things. Perhaps you might intend to spawn a brick, but you mess up and the brick is launched forward at a high velocity after being spawned.


Because of the risks involved, healers should probably go through intensive schooling to ensure that they do not make deadly mistakes. They will rely exclusively on known spells rather than creating new ones. They would almost definitely need to have a license, much like doctors and nurses do in the real world.


I really like celtschk's "abrakadabra" answer, but I think we can handle this in a much easier way: Spells are not programs, they are invocations of programs.

Yes, it's programming all the way, but what you are interacting with, is not the compiler, it's the shell. It's that part of the magic system that is designed for interaction, and which has the relevant safeguards implemented.

I don't know how you use your computer, but I for one am working on the command line a lot. I'm typing stuff like make, git status, vim foo.c faster that you can grab your mouse. All of these are simple commands that are hard to get wrong.

And, for the most part, I'm only invoking one simple command at a time. So, if I mess up, I'm usually in a state where I can recover quickly and easily.

I also know the commands that may get dangerous to invoke wrong. Like rm. I never say rm on the command line without taking a short pause to check whether that's really what I intend to be doing. It's basically CONSTANT VIGILANCE! to put it in Prof. Moody's words...

Still, there is stuff that those commands can do, but which they have been taught to error out on because that just can't be right. If you invoke rm with the path / (Don't try this!), it'll hopefully just throw an error. At least that's what the man-page says, I'm not going to put that to the test...

Mistakes can, and do happen, though. Anyone who does serious work on the command line has lost data due to mistakes. It's inevitable. But for the most part, I can happily hack away without committing serious blunders for months on end.

So, the crucial part of programmable language magic is, to program spells that are easy to use in a safe manner and which take extra care not to explode the planet.


As mentioned above, if I forget to close a bracket or add a semi colon, the program just won't work... This should be a common error for spells on the fly as its common to typo when typing at speed.

Like coding, if the spell is done incorrectly, the results should be incorrect to a similar nature. The spell to turn a pumpkin into a coach could have a missed step that turns the Pumpkin into something relatable... from a Pumpkin with wheels or a coach without wheels or a metallic pumpkin or a pumpkin like organic coach... One to the other needs precise steps. If a step is missed, it should have a logical reason to provide the desired outcome... and given where it is an expert spell crafter could see what step was missed and have a laugh. This would play into a spell-debug where the spell crafter may be show to practice each step of his spell and whatch each change from pumpkin to coach as he authorizes each step to happen.

Finally, I also have to give a shout out to Spell crafting in the Gargoyles series. Series creator Greg Weisman explained that it was easier to get magic to work if you had specific qualifiers for the spell. This is seen in the origin story where the spell that turned the Gargoyles to stone for a thousand years required the castle to rise above the clouds... its not an impossible feat, but it certainly would require effort to break, but it can be broken (as we see, moving it onto a skyscraper is enough to cause it to become broken). But it also works as garbage in, garbage out as well. In a later episode, a spell is cast over television that will turn "All who see and hear this" to turn to stone. Both of these can follow logic elements that are common in code.

Case one:

while(castle.height !> clouds.height){ gargoyles.stone(); }

Case two:

if(this.see() && this.here()){ person.stone(); } else{ //do nothing }

In case two, we do see this come into play as the Gargoyles find that their blind friend is unaffected by the spell because he's not able to see the television, thus he always goes to the else condition. Similarly, the Gargoyles don't get zapped because they hit mute, thus negating the condtition of hearing it, but are capable of viewing the footage.


A spell needs a program and an infusion of willpower to work. A sorcerer has to learn how to idly kinda wish for something to happen, and to do that reliably. It's possible to debug most spells by putting in a teeny amount of willpower and observing the results. A misbehaving fireball spell produces a few sparks when it goes wrong when the sorcerer is using debugging levels of willpower.

Naturally, there's the possibility for a disaster to happen, should a sorcerer use a spell that incorporates willpower enhancement. That's a somewhat discouraged magic pattern. There's also the problem when the sorcerer gets surprised or panicky.

People who try to use spells without the training usually manage to mess up with significant levels of willpower, not having learned to use just a tiny bit. This at least keeps the numbers down.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.