Skip to main content
added syntax-highlighting
Source Link
Deduplicator
  • 9.1k
  • 5
  • 33
  • 52

This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
  • Is there a name for this kind of logic?
  • Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
  • Is there a name for this kind of logic?
  • Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
  • Is there a name for this kind of logic?
  • Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

Question Protected by gnat
edited tags
Link
gnat
  • 20.9k
  • 29
  • 115
  • 295
Post Made Community Wiki by outis
Tweeted twitter.com/#!/StackProgrammer/status/141839663425011713
Source Link
Benjol
  • 3.7k
  • 5
  • 35
  • 41

Elegant ways to handle if(if else) else

This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
  • Is there a name for this kind of logic?
  • Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...