Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
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 Oct 16 '11 at 4:01
3  
@Job: That's a clause, not a statement. –  Ben Voigt Oct 16 '11 at 4:02
1  
You mean like in Verilog? –  dan04 Oct 16 '11 at 17:50
1  
Needs more description... very broad question. –  WernerCD Oct 16 '11 at 23:22
2  
The question is being discussed here on meta. –  Anna Lear Oct 17 '11 at 12:26
show 7 more comments

21 Answers 21

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.

share|improve this answer
add comment

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.

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

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

    while (!value)
{
}

//Execute code
share|improve this answer
add comment

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.

share|improve this answer
show 3 more comments

If you consider Drools a language, then yes.

An example:

rule "Rule 08 - Debit"
when
    AccountingPeriod( $start : start, $end : end )
    $cashflow : AllocatedCashflow( $account : account, $date : date <= $end, $amount : amount, type==TypedCashflow.DEBIT )
    not AccountingPeriod( start < $start)
then 
    $account.setBalance($account.getBalance()-$amount);
    retract($cashflow);
end
share|improve this answer
add comment

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.

share|improve this answer
show 1 more comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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
    evaluateOutputA()

when input2 changes
    evaluateOutputA()

evaluateOutputA()
    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
    launchNukes()

...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
    launchNukes()

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!)

Conclusion

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
show 1 more comment

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.

http://en.wikipedia.org/wiki/Database_trigger

share|improve this answer
add comment

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.

share|improve this answer
2  
Lisp's when is more like an if, not the observer pattern inadvertently described by the OP. –  Slomojo Oct 17 '11 at 3:23
add comment

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
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).

share|improve this answer
add comment

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

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

E.g.

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.

share|improve this answer
add comment

Does this (COMEFROM statement described on Wikipedia) count?

Summary:

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.

share|improve this answer
6  
I see where you're coming from. –  Pubby Oct 16 '11 at 4:05
6  
-1 for a link with no summary; linkrot can happen. –  Hugo Oct 16 '11 at 4:06
5  
@Ben - Regardless, your answer would be much better if you bothered to write a little more than 3 words. –  BlackJack Oct 16 '11 at 6:37
3  
@BenVoigt: in that case you could have just pasted the entire link instead of hiding it behind "this". –  Marjan Venema Oct 16 '11 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. –  Marjan Venema Oct 16 '11 at 16:20
show 2 more comments

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; }
}
share|improve this answer
3  
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 Oct 16 '11 at 13:36
1  
Smells like a switch statement to me. (With brass knobs on it, but then again it is Perl…) –  Donal Fellows Oct 16 '11 at 18:05
show 1 more comment

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;
btnOK.registerClickHandler(
    new ClickHandler {
        public void handleClick(Event e) {
            f.handleOKClick(e);
        }
    });

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

var btnOK = $('btnOK');
btnOK.click(handleOKClick);
share|improve this answer
add comment

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

share|improve this answer
show 1 more comment

Something like event handling?

instead of func() handles event

you say when event do func

Or, maybe a callback on a particular varible?

share|improve this answer
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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