<p>One problem that is hard to make not at least somewhat repetitive is if there is code that needs to be executed in a certain order, and the intermediate code is unconditional but first and last code share a condition.</p>
<p>This results in either:</p>
<pre><code>if (foo) {
    bar();
    baz();
    qux();
} else {
    baz();
}
</code></pre>
<p>Or:</p>
<pre><code>if (foo) {
    bar();
}
baz();
if (foo) {
    qux();
}
</code></pre>
<p>In the first case the <em>intermediate</em> code is repeated and the latter case the condition expression and <code>if</code> is repeated. The condition is checked twice so the branching cost <strong>might</strong> be payed twice.</p>
<p>What ways could a language include a DRY method to do this and how could this be optimized in assembly?</p>

<control-flow><conditional>
A conditional block with unconditional intermediate code
CC BY-SA 4.0
2023-07-14T17:48:33.453Z
Assuming the conditon's value doesn't change? Or should value-change also be handled?
Pablo H
CC BY-SA 4.0
2023-07-14T17:49:44.813Z
@PabloH Condition's value doesn't change.
CPlus
CC BY-SA 4.0
2023-07-15T03:18:04.157Z
"*…and how could this be optimized in assembly?*" sounds like a completely separate question
Bergi
CC BY-SA 4.0
2023-07-17T05:52:12.837Z
if foo: bar(); baz(); qux(); else: baz(). Two baz() seem redundant? Maybe from a human perspective. (In that case you could fool the eye by making a function to call bar, baz, qux and call that instead.) From a computation perspective this is already refactored just fine.
Luke Sawczak
CC BY-SA 4.0
2023-07-17T06:08:10.727Z
@LukeSawczak Sure, refactoring this to avoid a second function call might be unnecessary, but what if the code in question is not **just** function calls?
CPlus
CC BY-SA 4.0
2023-07-17T13:08:19.870Z
@user16217248-OnStrike Ah, good question. If baz() is a stand-in for something other than a function call it should of course be refactored to a function in my solution above, or else the repetition would be much worse than storing the evaluation of the condition as others have suggested! Also, I'm definitely on the wrong stack here :)
Luke Sawczak
<p>It is debatable whether you really need a short grammar for everything. Sometimes the logic is just complex enough that you'll need to write it in the complex way.</p>
<p>But in your case, there is a good reason to have a special grammar. That is, sometimes <code>bar()</code> creates an object and <code>qux()</code> uses the object, and it might be in a type that does work in the constructor, in a language like C++, where using <code>new</code> and <code>delete</code> everywhere in short functions doesn't look good, so you are not supposed to use null-like default values.</p>
<p>In this case, I think you could just invent a new grammar, without considering whether it is short.</p>
<p>The basic logic might be:</p>
<pre><code>some_keyword name = if (foo);
// Or: some_keyword name; if(foo) name;
name {bar();}
baz();
name {qux();}
</code></pre>
<p>In the background, of course it is just implemented in the traditional ways. And it doesn't look significantly different. But it could be managed automatically to avoid the possibility of an invalid state.</p>
<p>Or we could change it to make <code>name</code> optional, so you could define something without a name to call its destructor later without referring to it again:</p>
<pre><code>if(foo)
    some_keyword optional_name {bar();}
// Or:
some_keyword optional_name if(foo) {
    bar();
    yield;
}
</code></pre>
<p>In the former case, it is in a situation similar to <code>break</code>, that you may want to allow specifying the scope level it binds into. In the later case, it is supposed to be a coroutine, that doesn't exit the scope of <code>if</code> when it is defined. You may also make it support labels to match labels outside. In either case we are making the scope containing <code>bar()</code> live longer than it appears.</p>
<p>Then we could begin adding syntactic sugar:</p>
<pre><code>try {
    if(foo) {
        bar();
        finally {
            qux();
        }
    }
    baz();
}
</code></pre>
<p>You could also use it to replace the traditional try. With some improvements, it might work better than the traditional try in a constructor, where you undo what you have already done and ignore what you have not when there is an exception.</p>
<p>Note that it has slightly different meaning from your code. It changes the behavior if <code>baz()</code> throws an exception. You should think of what you actually want in concrete examples. It might be not bad to also have destructors marked as ignored on exceptions.</p>
<p>In case you are not using it in a serious programming language, I think I have seen a language, without remembering its name, where <code>then</code> and <code>else</code> are relatively separate from <code>if</code> and just take the result of the last <code>if</code>. (The Shakespeare Programming Language also works like this, but you won't want to use it as an example.) It might be possible to write code like this, which I don't remember:</p>
<pre><code>if(foo)
then bar();
baz();
then qux();
</code></pre>
<p>The down side is it doesn't work well for nested <code>if</code>s. So programmers often write like this:</p>
<pre><code>if(a) then {
    if(b) then
        c;
    if(true);
}
else
    d;
</code></pre>
<p>But I think that could be solved by automatically resetting the <code>if</code> result after <code>then</code> and <code>else</code> blocks, and function calls.</p>
<p>It may not work well if you add more complexity to it, for example stacking more levels of this construct.</p>
<p>And if it is for golfing, you could also just invent an operator for this semantic and don't think too much about the internal logic.</p>

CC BY-SA 4.0
2023-07-14T04:51:31.160Z
2023-07-14T05:35:29.447Z
2023-07-14T05:35:29.447Z
user23013
<h1>Use the language's existing resource-handling mechanism</h1>
<p>Python-style <code>with</code> blocks get you most of the way there. Presumably <code>bar</code> and <code>qux</code> are tied together in some way, so write it as a context manager (or whatever your language has for safely opening and closing resources).</p>
<pre><code>class Resource:
  def __enter__(self):
    bar()
  def __exit__(self, type, value, traceback):
    qux()
</code></pre>
<p>Now we can encapsulate the <code>foo</code> part in a conditional context manager</p>
<pre><code>class IfTrue:
  def __init__(self, manager, condition):
    self.manager = manager if condition else None
  def __enter__(self):
    if self.manager:
      self.manager.__enter__()
  def __exit__(self, type, value, traceback):
    if self.manager:
      self.manager.__exit__(type, value, traceback)
</code></pre>
<p>Then, when you want to run this setup-teardown code,</p>
<pre><code>with IfTrue(Resource(), foo):
  baz()
</code></pre>
<p>This couples the <code>bar</code> and <code>qux</code> parts, which, again, presumably are part of a setup-teardown procedure. The <code>IfTrue</code> context manager is also independent of everything else and can be used with another condition or resource type freely. If you find that this is something your language needs often, <code>IfTrue</code> is a good candidate for standard library inclusion.</p>
<p>You can use whatever tool your language uses for handling resources like files. In Python, that's <code>with</code>. In Ruby, you could just write a method that takes a block (like <code>File.open</code> does). In Java, your resource-allocation object can be <code>AutoCloseable</code> (hence compatible with the try-with-resources statement). In C++, you can use RAII to make the teardown run during your destructor.</p>
<p>Example in C++:</p>
<pre><code>class Resource {
public:
  Resource() {
    bar()
  }
  ~Resource() {
    qux();
  }
};

void example() {
  // Note: std::optional is basically IfTrue already; it
  // runs the deallocation if the thing on the inside exists.
  std::optional&lt;Resource&gt; resource;
  if (foo) {
    resource = Resource();
  }
  baz();
  // resource implicitly goes out of scope and calls qux()...
}
</code></pre>
<p>The point is:</p>
<ul>
<li>Decouple the problem into two parts. We have a setup-teardown, and a condition.</li>
<li>The setup-teardown pattern is something most languages <em>already</em> have, for dealing with file I/O and other resources. Leverage that.</li>
<li>The condition can be added to the resource-management code, making a new resource that's implemented as just &quot;resource plus condition&quot;.</li>
</ul>

CC BY-SA 4.0
2023-07-14T04:42:14.510Z
2023-07-14T04:42:14.510Z
Silvio Mayolo
CC BY-SA 4.0
2023-07-14T19:07:56.207Z
Or try-with-resource in Java
feldentm
CC BY-SA 4.0
2023-07-15T19:07:19.370Z
Instead of building the conditional logic into a separate context manager, it might make more sense to use something like Python's [`contextlib.nullcontext`](https://docs.python.org/3/library/contextlib.html#contextlib.nullcontext): `with Resource() if foo else nullcontext():`. This avoids constructing a `Resource` when it's not needed, which is important for some context managers. It also generalizes easily to choosing between more contexts, and means you don't have to remember the argument order for the `IfTrue` thing.
user2357112
<p>This is giving me goto flashbacks but here goes:</p>
<pre><code>foo_case: if (foo) {
  bar()
}

baz()

continue foo_case {
  qux()
}
</code></pre>
<p>The use of labels and continue allows nesting.</p>

CC BY-SA 4.0
2023-07-15T03:03:47.963Z
2023-07-15T03:03:47.963Z
bob
<p>Separate the testing of a condition from the blocks that use the outcome of the test. This is a form of pattern-matching, for matches that should proceed sequentially, and need not be exhaustive.</p>
<pre><code>given (foo) {

    when (true) {
        bar();
    }

    baz();

    when (true) {
        qux();
    }

}
</code></pre>
<p>Internally this can be lowered to basic blocks that only test the condition once. For example, in SSA (where parameters are equivalent to phi nodes):</p>
<pre><code>start() {
    t = test(foo);
    if (t) true1(); else always(end);
}

true1() {
    bar();
    always(true2);
}

always(return) {
    baz();
    return();
}

true2() {
    qux();
    end();
}

end() {
}
</code></pre>

CC BY-SA 4.0
2023-07-15T07:12:09.817Z
2023-07-15T07:12:09.817Z
Jon Purdy
<blockquote>
<p>What ways could a language include a DRY method to do this and how could this be optimized in assembly?</p>
</blockquote>
<p>One way is to prefix each statement with something that decides whether to execute it or not. For example, in languages with <a href="https://en.wikipedia.org/wiki/Short-circuit_evaluation" rel="nofollow noreferrer">short-circuiting operators</a>, you could write something like:</p>
<pre><code>foo &amp;&amp; bar();
       baz();
foo &amp;&amp; quux();
</code></pre>
<p>If <code>foo</code> is a long expression and/or has side effects, you could first store its result in a temporary variable:</p>
<pre><code>bool f = foo;
f &amp;&amp; bar();
     baz();
f &amp;&amp; quux();
</code></pre>
<p>In assembly languages there is a direct way to optimize this on some CPU architectures. For example, a lot of 32-bit Arm instructions have <a href="https://developer.arm.com/documentation/dui0068/b/ARM-Instruction-Reference/Conditional-execution" rel="nofollow noreferrer">some bits to tell whether to execute that instruction or ignore it</a> based on the state of certain processor flags. On x86 you have the <a href="https://stackoverflow.com/questions/30150274/purpose-of-cmove-instruction-in-x86-assembly">conditional move instruction</a>s. And in almost all CPU architectures, jump instructions can be conditional. As long as <code>bar()</code> and <code>baz()</code> in your example don't modify processor flags, then only a single compare instruction is necessary to evaluate <code>foo</code> to update the processor flags, and that can then be reused to conditionally execute the rest.</p>

CC BY-SA 4.0
2023-07-15T08:02:41.867Z
2023-07-15T08:02:41.867Z
G. Sliepen
CC BY-SA 4.0
2023-07-16T10:50:42.590Z
I was thinking along this line myself. However even assuming short-circuiting, it might be useful to have some way of mandating that foo() only be evaluated once.
Mark Morgan Lloyd
<p>Similar to the suggestion of Python's <code>with</code> syntax, some functional programming is all you need:</p>
<pre><code>withBarQux = \run -&gt; {
    bar();
    run();
    qux();
};
withNothing = \run -&gt; run();

(foo ? withBarQux : withNothing)(baz);
</code></pre>
<p>A programming language can help with this by providing <code>withNothing</code> as a builtin - it is the application operator, or if the pattern is expressed a bit differently, the identity function comes handy as well. Also allowing to pass code blocks to functions without explicit lambda expressions could make the syntax a bit nicer. With Scala's <a href="https://stackoverflow.com/q/19948598/1048572">by-name parameters</a>, this could look like</p>
<pre><code>(foo ? withBarQux : withNothing) {
  baz();
}
</code></pre>
<p>(which is helpful when the <code>baz()</code> code is not already a function that you can pass).</p>

CC BY-SA 4.0
2023-07-15T03:36:19.237Z
2023-07-15T03:36:19.237Z
Bergi
<p>Clearly, inside our hearts (or at least inside mine), what we all want is <em>a table of code</em>, that more explicitly expresses the relationships among parts of code:</p>
<p>(assuming what you want/need is as-if the condition is evaluated only once)</p>
<p><code>if (foo)</code></p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th><code>true</code></th>
<th><code>false</code></th>
</tr>
</thead>
<tbody>
<tr>
<td><code>bar();</code></td>
<td></td>
</tr>
<tr>
<td><code>baz();</code></td>
<td>(*)</td>
</tr>
<tr>
<td><code>qux();</code></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<p>(*) imagine that this row has only 1 cell spanning both columns (i.e., rowspan = 2, but cannot do that with stackexchange's markdown, apparently)</p>
<p>Of course for a <code>switch</code> or a <code>match</code> you just add more columns. :-)</p>

CC BY-SA 4.0
2023-07-14T18:06:46.307Z
2023-07-14T18:08:57.053Z
2023-07-14T18:08:57.053Z
Pablo H
CC BY-SA 4.0
2023-07-14T18:16:36.273Z
Welcome to PLDI! Out of interest, what do you think this sort of "table of code" might look like in practice?
rydwolf
CC BY-SA 4.0
2023-07-14T18:24:41.890Z
@RydwolfPrograms Thanks! Well, options are: horrendous text syntax, IDE support for tables, or programming directly in a spreadsheet... Excel et. al. have "extend cell" to make it span more rows or columns. Or for more precise control, formulas, e.g. "copy contents of relref(0, -1)". Many things you could do with tables... (maintainability unknown...) :-)
Pablo H
CC BY-SA 4.0
2023-12-13T13:13:14.853Z
@RydwolfPrograms By the way, JetBrains' [MPS](https://www.jetbrains.com/mps/) can do tables inside code, for example.
Pablo H
# A conditional block with unconditional intermediate code
Posted by: username_0 on 2023-07-14
One problem that is hard to make not at least somewhat repetitive is if there is code that needs to be executed in a certain order, and the intermediate code is unconditional but first and last code share a condition.
This results in either:
if (foo) {
    bar();
    baz();
    qux();
} else {
    baz();
}

Or:
if (foo) {
    bar();
}
baz();
if (foo) {
    qux();
}

In the first case the intermediate code is repeated and the latter case the condition expression and if is repeated. The condition is checked twice so the branching cost might be payed twice.
What ways could a language include a DRY method to do this and how could this be optimized in assembly?
**Tags:** control-flow conditional
> **Comments:**
> **username_1**: Assuming the conditon's value doesn't change? Or should value-change also be handled?  
> **username_0**: @PabloH Condition's value doesn't change.  
> **username_2**: "*…and how could this be optimized in assembly?*" sounds like a completely separate question  
> **username_3**: if foo: bar(); baz(); qux(); else: baz(). Two baz() seem redundant? Maybe from a human perspective. (In that case you could fool the eye by making a function to call bar, baz, qux and call that instead.) From a computation perspective this is already refactored just fine.  
> **username_0**: @LukeSawczak Sure, refactoring this to avoid a second function call might be unnecessary, but what if the code in question is not **just** function calls?  
> **username_3**: @user16217248-OnStrike Ah, good question. If baz() is a stand-in for something other than a function call it should of course be refactored to a function in my solution above, or else the repetition would be much worse than storing the evaluation of the condition as others have suggested! Also, I'm definitely on the wrong stack here :)  
---
## 7 answers
### Answer by username_4 on 2023-07-14. Score: 11 | Accepted answer
It is debatable whether you really need a short grammar for everything. Sometimes the logic is just complex enough that you'll need to write it in the complex way.
But in your case, there is a good reason to have a special grammar. That is, sometimes bar() creates an object and qux() uses the object, and it might be in a type that does work in the constructor, in a language like C++, where using new and delete everywhere in short functions doesn't look good, so you are not supposed to use null-like default values.
In this case, I think you could just invent a new grammar, without considering whether it is short.
The basic logic might be:
some_keyword name = if (foo);
// Or: some_keyword name; if(foo) name;
name {bar();}
baz();
name {qux();}

In the background, of course it is just implemented in the traditional ways. And it doesn't look significantly different. But it could be managed automatically to avoid the possibility of an invalid state.
Or we could change it to make name optional, so you could define something without a name to call its destructor later without referring to it again:
if(foo)
    some_keyword optional_name {bar();}
// Or:
some_keyword optional_name if(foo) {
    bar();
    yield;
}

In the former case, it is in a situation similar to break, that you may want to allow specifying the scope level it binds into. In the later case, it is supposed to be a coroutine, that doesn't exit the scope of if when it is defined. You may also make it support labels to match labels outside. In either case we are making the scope containing bar() live longer than it appears.
Then we could begin adding syntactic sugar:
try {
    if(foo) {
        bar();
        finally {
            qux();
        }
    }
    baz();
}

You could also use it to replace the traditional try. With some improvements, it might work better than the traditional try in a constructor, where you undo what you have already done and ignore what you have not when there is an exception.
Note that it has slightly different meaning from your code. It changes the behavior if baz() throws an exception. You should think of what you actually want in concrete examples. It might be not bad to also have destructors marked as ignored on exceptions.
In case you are not using it in a serious programming language, I think I have seen a language, without remembering its name, where then and else are relatively separate from if and just take the result of the last if. (The Shakespeare Programming Language also works like this, but you won't want to use it as an example.) It might be possible to write code like this, which I don't remember:
if(foo)
then bar();
baz();
then qux();

The down side is it doesn't work well for nested ifs. So programmers often write like this:
if(a) then {
    if(b) then
        c;
    if(true);
}
else
    d;

But I think that could be solved by automatically resetting the if result after then and else blocks, and function calls.
It may not work well if you add more complexity to it, for example stacking more levels of this construct.
And if it is for golfing, you could also just invent an operator for this semantic and don't think too much about the internal logic.
---
### Answer by username_5 on 2023-07-14. Score: 10
Use the language's existing resource-handling mechanism
Python-style with blocks get you most of the way there. Presumably bar and qux are tied together in some way, so write it as a context manager (or whatever your language has for safely opening and closing resources).
class Resource:
  def __enter__(self):
    bar()
  def __exit__(self, type, value, traceback):
    qux()

Now we can encapsulate the foo part in a conditional context manager
class IfTrue:
  def __init__(self, manager, condition):
    self.manager = manager if condition else None
  def __enter__(self):
    if self.manager:
      self.manager.__enter__()
  def __exit__(self, type, value, traceback):
    if self.manager:
      self.manager.__exit__(type, value, traceback)

Then, when you want to run this setup-teardown code,
with IfTrue(Resource(), foo):
  baz()

This couples the bar and qux parts, which, again, presumably are part of a setup-teardown procedure. The IfTrue context manager is also independent of everything else and can be used with another condition or resource type freely. If you find that this is something your language needs often, IfTrue is a good candidate for standard library inclusion.
You can use whatever tool your language uses for handling resources like files. In Python, that's with. In Ruby, you could just write a method that takes a block (like File.open does). In Java, your resource-allocation object can be AutoCloseable (hence compatible with the try-with-resources statement). In C++, you can use RAII to make the teardown run during your destructor.
Example in C++:
class Resource {
public:
  Resource() {
    bar()
  }
  ~Resource() {
    qux();
  }
};

void example() {
  // Note: std::optional is basically IfTrue already; it
  // runs the deallocation if the thing on the inside exists.
  std::optional resource;
  if (foo) {
    resource = Resource();
  }
  baz();
  // resource implicitly goes out of scope and calls qux()...
}

The point is:

Decouple the problem into two parts. We have a setup-teardown, and a condition.
The setup-teardown pattern is something most languages already have, for dealing with file I/O and other resources. Leverage that.
The condition can be added to the resource-management code, making a new resource that's implemented as just "resource plus condition".
> **Comments:**
> **username_6** (2023-07-14): Or try-with-resource in Java  
> **username_7** (2023-07-15): Instead of building the conditional logic into a separate context manager, it might make more sense to use something like Python's [`contextlib.nullcontext`](https://docs.python.org/3/library/contextlib.html#contextlib.nullcontext): `with Resource() if foo else nullcontext():`. This avoids constructing a `Resource` when it's not needed, which is important for some context managers. It also generalizes easily to choosing between more contexts, and means you don't have to remember the argument order for the `IfTrue` thing.  
---
### Answer by username_1 on 2023-07-14. Score: 7
Clearly, inside our hearts (or at least inside mine), what we all want is *a table of code*, that more explicitly expresses the relationships among parts of code:

(assuming what you want/need is as-if the condition is evaluated only once)

`if (foo)`

| `true` | `false` |
| --- | --- |
| `bar();` |  |
| `baz();` | (\*) |
| `qux();` |  |

(\*) imagine that this row has only 1 cell spanning both columns (i.e., rowspan = 2, but cannot do that with stackexchange's markdown, apparently)

Of course for a `switch` or a `match` you just add more columns. :-)
> **Comments:**
> **username_12** (2023-07-14): Welcome to PLDI! Out of interest, what do you think this sort of "table of code" might look like in practice?  
> **username_1** (2023-07-14): @RydwolfPrograms Thanks! Well, options are: horrendous text syntax, IDE support for tables, or programming directly in a spreadsheet... Excel et. al. have "extend cell" to make it span more rows or columns. Or for more precise control, formulas, e.g. "copy contents of relref(0, -1)". Many things you could do with tables... (maintainability unknown...) :-)  
> **username_1** (2023-12-13): @RydwolfPrograms By the way, JetBrains' [MPS](https://www.jetbrains.com/mps/) can do tables inside code, for example.  
---
### Answer by username_8 on 2023-07-15. Score: 5
This is giving me goto flashbacks but here goes:
foo_case: if (foo) {
  bar()
}

baz()

continue foo_case {
  qux()
}

The use of labels and continue allows nesting.
---
### Answer by username_9 on 2023-07-15. Score: 5
Separate the testing of a condition from the blocks that use the outcome of the test. This is a form of pattern-matching, for matches that should proceed sequentially, and need not be exhaustive.
given (foo) {

    when (true) {
        bar();
    }

    baz();

    when (true) {
        qux();
    }

}

Internally this can be lowered to basic blocks that only test the condition once. For example, in SSA (where parameters are equivalent to phi nodes):
start() {
    t = test(foo);
    if (t) true1(); else always(end);
}

true1() {
    bar();
    always(true2);
}

always(return) {
    baz();
    return();
}

true2() {
    qux();
    end();
}

end() {
}
---
### Answer by username_10 on 2023-07-15. Score: 4
What ways could a language include a DRY method to do this and how could this be optimized in assembly?

One way is to prefix each statement with something that decides whether to execute it or not. For example, in languages with short-circuiting operators, you could write something like:
foo && bar();
       baz();
foo && quux();

If foo is a long expression and/or has side effects, you could first store its result in a temporary variable:
bool f = foo;
f && bar();
     baz();
f && quux();

In assembly languages there is a direct way to optimize this on some CPU architectures. For example, a lot of 32-bit Arm instructions have some bits to tell whether to execute that instruction or ignore it based on the state of certain processor flags. On x86 you have the conditional move instructions. And in almost all CPU architectures, jump instructions can be conditional. As long as bar() and baz() in your example don't modify processor flags, then only a single compare instruction is necessary to evaluate foo to update the processor flags, and that can then be reused to conditionally execute the rest.
> **Comments:**
> **username_11** (2023-07-16): I was thinking along this line myself. However even assuming short-circuiting, it might be useful to have some way of mandating that foo() only be evaluated once.  
---
### Answer by username_2 on 2023-07-15. Score: 4
Similar to the suggestion of Python's with syntax, some functional programming is all you need:
withBarQux = \run -> {
    bar();
    run();
    qux();
};
withNothing = \run -> run();

(foo ? withBarQux : withNothing)(baz);

A programming language can help with this by providing withNothing as a builtin - it is the application operator, or if the pattern is expressed a bit differently, the identity function comes handy as well. Also allowing to pass code blocks to functions without explicit lambda expressions could make the syntax a bit nicer. With Scala's by-name parameters, this could look like
(foo ? withBarQux : withNothing) {
  baz();
}

(which is helpful when the baz() code is not already a function that you can pass).
---
