Style Q: if the lock function or around?

Let's say that I have a function that should only be executed when a certain constant is defined. which of the following would be better

Option 1: end all function calls in the if block:

if(defined('FOO_BAR_ENABLED')) {
   foobar();
}

As I understand it, the goal is more clear, but it requires checking the constant every time the function is called.

Option 2: check the constant in the function itself:

function foobar() {
  if(!defined('FOO_BAR_ENABLED')) {
    return;
  }
  //do stuff 
}

This path requires fewer lines of code, and the constant must be checked. However, it’s embarrassing for me to see the calls to this function when it actually does nothing. Thoughts?

+3
source share
6 answers

FoobarIfEnabled(), ?

- , :

  • .
  • .
  • .
  • .... .

, . , , , . , 1. "IfEnabled" - , , . ?

, , ().

, , .

+10

3:

void maybe_foobar() {
   if(defined('FOO_BAR_ENABLED')) really_foobar();
}

void really_foobar() {
    // do stuff
}

, "" "", , , .

- , - " ", FOO_BAR_ENABLED , 2 (, , do_stuff_if_possible, foobar), foobar , -). " -", , 3.

1 , , .

[: 4, , , , :

void if_enabled(string str, function f) {
    if (defined(str + '_ENABLED')) f();
}

:

if_enabled('FOO_BAR', foobar);

, , , , if_enabled.]

+2

if ? if?

, . DRY : . , , - SRP - - .

+1

, foobar ,

#ifdef ENABLE_FOOBAR
#define maybe_foobar(x) foobar(x)
#else
#define maybe_foobar(x)
#endif

, ++ C, foobar .

( language-agnostic. , - , , , , , , ).

+1

2, , , , .

0

, -, foobar(), 2 . , , .

0

Source: https://habr.com/ru/post/1763128/


All Articles