TryElseExpression DIP
Basile B. via Digitalmars-d
digitalmars-d at puremagic.com
Mon Sep 5 14:58:41 PDT 2016
On Monday, 5 September 2016 at 20:04:43 UTC, pineapple wrote:
> On Monday, 5 September 2016 at 19:12:02 UTC, Jacob Carlborg
> wrote:
> [...]
>> On 2016-09-05 20:57, pineapple wrote:
> Which is easier to read and to write? Which is more
> maintainable? Which is less prone to programmer errors? This?
>
> [...]
> This?
>
> try{
> do_a_thing();
> }else{
> depends_on_success_of_thing();
> }
>
> Or this?
>
> bool success = false;
> try{
> do_a_thing();
> success = true;
> }finally{
> if(success){
> depends_on_success_of_thing();
> }
> }
There's probably also a FP approach:
function TryElse(
alias TryStatements,
alias ElseStatements)(){}
function TryCatchElseFinally(
alias TryStatements,
alias ElseStatements,
alias CatchStatements,
alias ElseStatements,
E : Exception = Exception)(){}
etc.
You pass delegate literals:
°°°°°°°°°°°°°°°°°°°°°
void TryElse(alias TryStatements, alias ElseStatements)()
{
bool doElses = true;
try TryStatements();
catch(Throwable){}
ElseStatements();
}
void main()
{
int i;
import std.conv: to;
TryElse!(
{i = to!int("0.42");},
{i = -1;}
);
}
°°°°°°°°°°°°°°°°°°°°°
With optional sugar to name each statements group:
°°°°°°°°°°°°°°°°°°°°°
template Statements(alias T)
{
alias Statements = T;
}
alias Try = Statements;
alias Else = Statements;
void main()
{
TryElse!(
Try!({}),
Else!({})
);
}
°°°°°°°°°°°°°°°°°°°°°
More information about the Digitalmars-d
mailing list