Is there a language or language feature that can handle "when" cases? That is, whenever some condition becomes true, in any scope or context, that extra code could be specified to execute?

Note that this is different from a simple if, which must be in a particular scope and explicitly written. This when clause would almost be like an if that applied to every case in the execution of the program after it.

  • 1
    Sql Server: select case table1.col1 when 1 then 'Y' else 'N' end as col1_yn from .... Also: msdn.microsoft.com/en-us/library/dd233249.aspx Basically I would do a search for "when" using Google code search.
    – Job
    Commented Oct 16, 2011 at 4:01
  • 5
    @Job: That's a clause, not a statement.
    – Ben Voigt
    Commented Oct 16, 2011 at 4:02
  • 2
    You mean like in Verilog?
    – dan04
    Commented Oct 16, 2011 at 17:50
  • 2
    Needs more description... very broad question.
    – WernerCD
    Commented Oct 16, 2011 at 23:22
  • 2
    The question is being discussed here on meta.
    – Adam Lear
    Commented Oct 17, 2011 at 12:26

24 Answers 24


Your question is not clear but the Observer pattern seems to be the thing you are looking for http://en.wikipedia.org/wiki/Observer_pattern

  • 1
    Yes, what I asked seems like a native implementation for it. I'd also like to point to an interesting paper on reactive programming posted bellow, "deprecating the observer pattern" (no link, CTRL+F it). A when statement would, in theory, run a block of code whenever, during the execution of the program, a condition is met - regardless of how this is implemented - and would ease the work of at least me who will instead have to implement the observer pattern by myself.
    – WindScar
    Commented Oct 19, 2011 at 21:13

Syntax wise, quite a few languages have a when keyword, but I am unaware of any language that uses it the way you describe.

The 'when X occurs, do Y' pattern is kind of the core of aspect-oriented programming: instead of defining a linear flow, you hook handlers into certain conditions (a.k.a. 'subscribing' to an 'event'). This kind of programming is popular in GUI applications, where the core routine of the program is an event dispatcher.

Some languages have extensive syntax features to provide such mechanisms through language constructs; an example would be C# with its delegates and events:

// 'when btnOK is clicked, run HandleOKClick'
btnOK.Clicked += this.HandleOKClick;

Other languages use OOP constructs (Observer pattern, event listeners, etc.; an example in Java (my Java is a bit rusty, so feel free to edit):

Foobar f = this;
    new ClickHandler {
        public void handleClick(Event e) {

Yet another approach is using plain old callbacks. Example in javascript:

var btnOK = $('btnOK');

Nobody has yet mentioned INTERCAL's COMEFROM :

COMEFROM was initially seen in lists of joke assembly language instructions (as 'CMFRM'). It was elaborated upon in a Datamation article by R. Lawrence Clark in 1973, written in response to Edsger Dijkstra's letter Go To Statement Considered Harmful. COMEFROM was eventually implemented in the C-INTERCAL variant of the esoteric programming language INTERCAL along with the even more obscure 'computed COMEFROM'. There were also Fortran proposals for 'assigned COME FROM' and a 'DONT' keyword (to complement the existing 'DO' loop).

On 1 April 2004, Richie Hindle published an implementation of both GOTO and COMEFROM for the Python programming language. Despite being released on April Fools' Day and not being intended for serious use, the syntax is valid and the implementation fully works.

  • 7
    ... and you had to spoil it! :-)
    – Stephen C
    Commented Oct 16, 2011 at 10:59
  • 2
    O rly?
    – Ben Voigt
    Commented Oct 16, 2011 at 14:44
  • 2
    @BenVoigt: Your answer, at the time of posting, did not contain "Intercal" or "COMEFROM".
    – DeadMG
    Commented Oct 16, 2011 at 15:01
  • 2
    @DeadMG: My answer contained "en.wikipedia.org/wiki/COMEFROM" from the very first version.
    – Ben Voigt
    Commented Oct 16, 2011 at 15:04
  • 2
    @BenVoigt: That doesn't count.
    – DeadMG
    Commented Oct 16, 2011 at 18:53

The Tcl language has traces on variables which allow arbitrary code to be executed whenever a variable is set (or read or deletion, but that's less important here). That arbitrary code can easily include evaluating an expression and executing some code if it holds. The main constraint is that while you can do this for local variables, it's not generally very useful because they tend to have very short lifespans, so such things are usually restricted to global and namespace variables. (Tcl doesn't have closures.)

But if you're doing this, you should be careful. While you don't officially have problems with reentrancy (the trace is disabled for the duration of the execution of the body) it's still a great way to write vastly unclear code and cause much confusion. It's also a truly terrible idea to use it with a loop variable (other than for debugging) as the performance hit can be quite significant.

An example (based on code from the linked manual page above) illustrates.

set foo 1
set bar 2
proc doMult args {
    global foo bar foobar
    set foobar [expr {$foo * $bar}]
trace add variable foo write doMult
trace add variable bar write doMult

From that point onwards, any time that either $foo or $bar becomes a new integer, $foobar becomes the product of the two. Automatically.

Tcl also allows setting up code to be run on other kinds of triggers, such as execution of commands, deletion of commands, timers, data becoming available on sockets, etc. With the Tk library added, this is expanded to include a whole large set of GUI events as well. It's true to say that Tcl is actually a very strongly event-oriented language (even if you can easily write code that never uses any of those features, too).


Something like event handling?

instead of func() handles event

you say when event do func

Or, maybe a callback on a particular varible?

  • Definitely sounds like an event.
    – Ton Plomp
    Commented Dec 8, 2011 at 21:47

Yes, there is such a keyword in Perl, as a statement modifier :

say 'Well done!'        when 'A';

It's also part of the switch statement :

given ($foo) {
    when (/^abc/) { $abc = 1; }
    when (/^def/) { $def = 1; }
    when (/^xyz/) { $xyz = 1; }
    default { $nothing = 1; }
  • 5
    I don't know Perl, but this 'when' looks more like an 'if' to me... I think the question means the 'when <event> <action>' type of 'when'.
    – ShdNx
    Commented Oct 16, 2011 at 13:36
  • 1
    Smells like a switch statement to me. (With brass knobs on it, but then again it is Perl…) Commented Oct 16, 2011 at 18:05
  • Actually, this is a case in a switch statement. Just like in Ada.
    – mouviciel
    Commented Oct 17, 2011 at 12:43

Does this (COMEFROM statement described on Wikipedia) count?


COMEFROM is roughly the opposite of GOTO in that it can take the execution state from any arbitrary point in code to a COMEFROM statement. The point in code where the state transfer happens is usually given as a parameter to COMEFROM. Whether the transfer happens before or after the instruction at the specified transfer point depends on the language used. Depending on the language used, multiple COMEFROMs referencing the same departure point may be invalid, be non-deterministic, be executed in some sort of defined priority, or even induce parallel or otherwise concurrent execution as seen in Threaded Intercal.

  • 6
    I see where you're coming from.
    – Pubby
    Commented Oct 16, 2011 at 4:05
  • 6
    -1 for a link with no summary; linkrot can happen.
    – Hugo
    Commented Oct 16, 2011 at 4:06
  • 5
    @Ben - Regardless, your answer would be much better if you bothered to write a little more than 3 words.
    – BlackJack
    Commented Oct 16, 2011 at 6:37
  • 3
    @BenVoigt: in that case you could have just pasted the entire link instead of hiding it behind "this". Commented Oct 16, 2011 at 8:30
  • 1
    @BenVoigt: My point was that had you pasted the entire link instead of hiding it behind "this", the words to search for would be immediately visible in the text of your answer, instead of only when you hover over the link... Plus I happen to agree with BlackJack and Hugo that an answer that is mainly a link should at least give a short summary of what can be found there. It helps ensure that StackExchange can stand on its own two feet, even if the link does rot. Commented Oct 16, 2011 at 16:20

Are you looking for a language with a synchronous or an asynchronous when statement?

Sounds like an event (/subscription/callback) pattern to me.


conditionOwner.Condition += listener.WhenCondition

Whenever the condition owner notifies that the condition has taken place, the listener will do WhenCondition().

You could use a binding pattern with a converter that checks the state of several input variables (on change) and calculates the condition, then have an input property of listener binded to the output and act when that input is changed.

As of languages, .NET for example (i.e. C#) has built in synchronous subscriptions (events) and its Reactive Extensions (RX) adds asynchronous subscriptions.


The description sound like a database trigger which is designed to await a certain scenario and then execute.

From Wikipedia:

A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. The trigger is mostly used for keeping the integrity of the information on the database. For example, when a new record (representing a new worker) is added to the employees table, new records should be created also in the tables of the taxes, vacations, and salaries.



What you're talking about is less syntax than structure. You could really only have a when statement like that in a system that executes a finite amount of logic, then executes the when statements, then loops around and executes the logic again, continuing in an infinite loop.

For instance Windows programming is typically "event based". Subscribing to a button's Click event essentially means "do this when clicked". However, what's going on under the hood is a message processing loop. Windows sends a message to the application when the user clicks the button, and the message processing loop in the application runs the appropriate event handler.

If you use events in, for instance, C#, you can do this without a message loop, but the limitation is that you have to declare the event ahead of time, so you can't write an artibrary when statement that watches for any kind of state. You have to wait for a specific event.

To get this behavior in a Von Neumann Architecture you have to run some kind of infinite loop that checks for all the conditions every time through the loop running the appropriate code if appropriate. Internally you just get a big list of if/then or switch statements. Most desktop application and web programmers would vomit if they saw such a construct so it's really only palatable if you wrap it in some kind of syntactic sugar like the Windows event model (even though that's what's going on under the hood).

On the other hand, if you look at the field of embedded firmware development, real-time executives, or industrial controllers, this model of programming is very common. For instance, if you have a real-time program, you may want to express:

outputA = input1 && input2

The code is straightforward to understand (because it's declarative). However, to make it work you have to execute it in a tight loop. You re-evaluate outputA every time through the loop. A lot of desktop or web programmers wouldn't like this because it's inefficient. To them, the only time you should re-evaluate outputA is when input1 or input2 changes. They would rather see something more like you're describing:

when input1 changes

when input2 changes

    outputA = input1 && input2

Now if this is what you want (and personally I don't prefer this idea), and your goal is efficiency, then you still have to ask yourself what the processor is doing under the hood. Obviously there's still some kind of loop running that compares the input states to the previous input states every time, and executes the appropriate code whenever one changes. So really it's less efficient and it's harder to read and harder to maintain.

On the other hand, if the work that you have to do when input1 changes is significant, then your when clause might make sense. In PLCs this type of instruction is called a "rising edge detection". It saves the state of input1 on the last time through the loop, compares it to the value this time, and executes the logic if the last state was false and this state is true.

If you don't have a Von Neumann Architecture, then the game changes. For instance if you're programming an FPGA in VHDL, then when you write:

outputA = input1 && input2

(... or whatever the appropriate VHDL syntax would be) then the FPGA actually gets wired up such that input1 and input2 are wired to the input of an AND gate, and the output of the AND gate is wired to outputA. So, not only is the code easy to understand, it's also executed in parallel with all the other logic, and it's efficient.

When you're talking about an industrial controller like a PLC or PAC, programmed in one of the five IEC-61131-3 languages, the typical case is this kind of arrangement:

  1. Read inputs and store in memory
  2. Execute main program
  3. Write outputs from memory to actual outputs
  4. Go to step 1

This is built into the architecture of the system, so it's expected that you'll just write:

outputA = input1 && input2

... and it will be executed in a continuous loop.

There are also interrupt routines in these machines. These are more like hardware level support for the when operator that you're talking about. The hardware interrupt is a means of executing some code on an external event. For instance, when a network card says that it has data waiting, the processor normally has to read that data immediately or you'll run out of buffer space. However, for the amount of times you need to hook a real hardware interrupt, I doubt including a language keyword for it is worthwhile. You'd be limited to CPU input pins, and it looks like you want to test internal program state.

So, in a traditional language (without a tight loop that runs infinitely) you have to ask the question, "when does the evaluation code run"?

If you write:

when A do

...and assuming A is an arbitrary boolean expression, how do you know when to re-evaluate that expression? A naive implementation would mean you have to re-evaluate it after every single memory write. You might think that you can narrow it down, but consider this:

when systemTime > actionTime do

Notice that systemTime is always changing (every time you read it, you'll get a different number). This means that the conditional part of all of your when clauses have to be re-evaluated continuously. That's almost impossible (and just consider for a second what happens if your conditional expression has side effects!)


You can only have a when statement (like you're describing) in an architecture based around an infinite loop that runs the main program, then executes the when statements if the conditions went from false to true on this loop. While this architecture is common in embedded and industrial devices, it's not common in general purpose programming languages.


The AspectJ language has a Join-Point Model, which is one solution for handling exactly this kind of situation.

A Join-Point in AspectJ is a dynamic event in a Java program that occurs when the program is executing. Example join-points are: (1) A method is called; (2) A method is executed; (3) A constructor is called; (4) A constructor is executed; (5) A field is set; or (6) A field is accessed.

You can then create sets of these join-points, called pointcuts. Pointcuts can then be joined, complemented, and intersected in the usual set theory way. Other point cuts can be conditioned on the values/types of variables (e.g., "only when x is positive", "only when the value being set is a subclass of this type") and based on the state of the program ("when this method is called, but only when this other method is on the stack of this thread [meaning that that method indirectly called it]").

Once you have all of these pointcuts describe events in the program, you can then use AspectJ to advise these events. You can choose to do something before the event happens (before advice), after the event happens (after advice), or instead of the event happening (around advice).

Around advice is particularly helpful for adding caching to your programs: When some method is executed, look up in a table to see if the same computation has already been performed and, if so, use the cached version. With AspectJ, it's so lightweight and expressive you can do such caching experiments on hundreds of different points in your code in order to find if and where caching adds values.

Many people outside of aspect-oriented programming believe AOP is mostly about "logging." You can use AspectJ to handle logging, and it does it quite well ("record in this log file when all public methods in this package are called, and what their results/error results were"). But there is so much more to AspectJ, including a clever trick to simulate dynamic scope called the Worm Hole Pattern [see slide 23 and following].

Outside of AOP, you are also talking about event-based programming, which includes [as others have noted] the Observer Pattern. The difference between the solutions is: (1) how the condition is detected; (2) where the condition is expressed; and (3) how the-code-to-execute is bound to the event.


How to use Notify/Wait would seem to be close to this:

We've mentioned that the Java wait/notify mechanism is essentially a way to communicate between threads. In a nutshell, the idea is as follows:

  • one or more threads sits waiting for a signal;
  • another thread comes along and notifies the waiting threads (i.e. "wakes it/them up" with the signal).

Depending on the context there are some structures that can be close to this but you really have to clarify your question.

There is also a "when" statement in XSLT:

The element is used to determine one course of action based on a series of tests. Each test is done inside an element. If a test succeeds, the body of the element is executed. If no tests fail then a element can be used to specify a default action:

The XSLT "when" is a conditional statement, more like a switch than an if. However, the context of what was meant by a "when" in the initial question wasn't really well clarified.

I use XSLTs quite often in the Sitecore CMS where I work for presenting content so it can be used in a GUI environment in some cases.

  • The XSLT when sounds more like an if, even though it is not the procedural type if you would find in programming languages. (I view XSLT more as a specific data processing language more than a common programming language - I don't see you building a desktop GUI using XSLT) Commented Oct 16, 2011 at 17:12

What you are asking for is called Reactive Programming.

It is a paradigm of programming where the variables are aware of the expression they've been assigned and whenever a component of the expression changes, the variable reacts by re-evaluating the expression, possibly triggering other similar re-evaluatoins down the chain of dependencies.

Usually this reactive behavior is achieved through clever use of observer pattern, where a reactive value registers itself as a listener to a set of events that trigger the re-evaluation of the value.

To the best of my knowledge, there does not exist a programming language that would entirely embrace reactive programming in it's core, but there are plenty of libraries in many languages offering benefits of reactive programming in one way or another.

Most of the data binding frameworks can be considered implementations of reactive programming.

There is a nice paper on called "Deprecating the observer pattern", that will probably explain much better than I ever could, what the reactive programming is all about and what would an implementation of it offer over and above already existing techniques.

  • One of the best answers for my question. Great paper.
    – WindScar
    Commented Oct 19, 2011 at 20:56
  • 1
    Feel free to mark it as "accepted" (wink, wink, nod, nod) Commented Oct 20, 2011 at 10:30
  • I was about to post this, but happily you beat me to it and wrote a much better answer than I would have. Reactive programming is awesome (and a great way to build UIs in functional languages), but a little esoteric. Commented Dec 8, 2011 at 22:47
  • 1
    @RolandTepp Shameless self-promotion, eh? I admire that about you. +1
    – Neil
    Commented Sep 20, 2018 at 6:23

Lisp (and its many dialetcs, including Scheme) has it:

(when (> 2 1) 'do-something)

evaluates to do-something and:

(when nil 'other-thing)

evaluates to nil or its equivalent.

  • 2
    Lisp's when is more like an if, not the observer pattern inadvertently described by the OP.
    – ocodo
    Commented Oct 17, 2011 at 3:23

I know such a kind of statement only for error handling. For example, BASIC's ON ERROR ... or SQL*PLUS's WHENEVER SQLERROR ...

For arbitraty conditions, it would require either an extremely clever compiler or a rather expensive kind of brute force (check after every statement) to catch the exact moment when the conditions becomes true.


It is a feature of dataflow languages such as hardware description languages (Verilog and VHDL).

Other than that, I can think of Ada and its exception handling mechanism: An exception handler is triggered when some exception is raised.


It sounds like you're looking for condition variables, things that allow threads to sleep until some predicate becomes true.

Boost implements them for C++, the Apache Portable Runtime implements them for C. In Common Lisp you'd use bordeaux-thread's make-condition-variable.

  • Can you name the part of the boost library responsable for implementing this?
    – WindScar
    Commented Oct 19, 2011 at 21:18

If you consider Drools a language, then yes.

An example:

rule "Rule 08 - Debit"
    AccountingPeriod( $start : start, $end : end )
    $cashflow : AllocatedCashflow( $account : account, $date : date <= $end, $amount : amount, type==TypedCashflow.DEBIT )
    not AccountingPeriod( start < $start)

Perl 6 can handle signals in a direct fashion using tap:

signal(SIGINT).tap: {
    note "Took { now - INIT now } seconds.";

for 0, 1, *+* ... * {
    sleep 0.5;

whereas Powershell can handle it using a run loop with a try/finally block:

$Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
        Write-Host $n
        $n ++
        Start-Sleep -m 500
    $End_Time = (Get-date).second
    $Time_Diff = $End_Time - $Start_Time
    Write-Host "Total time in seconds"$Time_Diff

as can Expect using trap:

package require Expect

proc sigint_handler {} {
    puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
    set ::looping false

trap sigint_handler SIGINT

set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
    puts [incr n]
    after 500



It has been a LONG time since I looked at these, so I could well be mistaken.

As I recall, PL/I and BASIC both had "ON" statements. In PL/I, the concept was "ON DO ". In BASIC, it was "ON ", where statement was usually a GOSUB. In both languages, whenever the specified condition became true, the associated statements were executed.

You wouldn't want to do this today. The compiler basically has to do a bunch of work, to figure out where/when the condition could become true, so it can generate a test at that point. Once you are in the associated handler, you don't really know where you came from, so you have to figure out what happened to get you there, and you probably don't want to go back to where you came from.


You might have a look at the OPS5 language. Its programs are written as a set of conditions. When a condition is met, the corresponding action is performed. The actions can modify state, which can cause other conditions to be met. While it doesn't use the when keyword, it work essentially by performing actions "when" a condition is met. From here:

An OPS5 program consists of a declaration section where basic data constructs are defined followed by a production section where rules for manipulation of the data.

OPS5 programs execute by matching working memory elements with rules in production memory and firing (executing) the most dominant rule which is matched. The Match-Select-Execute cycle continues until the program halts explicitly or until no rules can be matched to the working memory.

I had to write a simple text adventure in this language when I was at University in the early 90s. It was interesting, but I'm not sure how useful it would be for most desktop or mobile tasks. It might make sense in a backend environment, though.


Haskell has one. But it's not a special construct, just another function http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Monad.html#v:when


In most OOP languages it would be possible to spawn an extra thread, have this as the context:

    while (!value)

//Execute code

Well, you could write a bunch of parallel threads, each of which polls for its respective condition. I suppose that would be a rather low-performing application, but it's possible.

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