0

My question is which method below of defining variables is a cleaner way to code and why?

Option 1:

 file_one=/path/to/file1
 file_two=/path/to/file2

if condition
   cd(file_one)
else
   cd(file_two)

Option 2:

if condition
   file=/path/to/file1
   cd(file)
else
   file=/path/to/file2
   cd(file)
  • 1
    Do you have a short script in mind with this program, which can be adapted easily when the paths change? If not, I would question any hardcoded paths in the program. – Doc Brown Mar 31 '17 at 13:29
  • yes, just a short python script. Forget that they are paths, I'm more concern about the style of defining one or more variables. – Dawn555 Mar 31 '17 at 13:47
5

I'd say it's more a question of what your business logic dictates.

But if you're asking for this specific case, I'd say both are wrong! In the first example you set a value that you might not need. In second example, you duplicate the code unnecessary.

I'd rather write it like:

if condition
    Method(file1)
else
    Method(file2)

Method(file)
    cd(/path/to/file)

Keep it short, up to the point, readable and above all simple. Don't be afraid to write an extra method if it makes the code more readable. That's the principle of Clean Code style by Uncle Bob.

1

(1) you have a lot of duplication in both examples, and duplication is the enemy of maintainable code. The first consideration must be removing it.

(2) a lot of people have an aversion to the use of the alternation operator (?:), but frankly in situations like this, it's use can make code a lot clearer. Therefore, as long as condition is something relatively simple, of suggest this as an alternative:

cd ("/path/to" + (condition ? "file1" : "file2"))

For a task like this, i think brevity is highly beneficial.

Now, of the logic is any more complex than this, I'd suggest factoring out choice of the file path to a separate function, but at this level of complexity (and as long as it only occurs in one place) I think doing it online like this is fine.

0

I would prefer option 2, assuming file_one and file_two will be used nowhere else, because it keeps your scope tighter. Variables are declared in the scope where they are used and thus are not noise in some other place where they serve no purpose.

Declaring variables in a broader scope will have the reader search for the places where they are used and for what they mean. From the other end, at the point where they are used, one is missing information about type and value, again one has to go hunting to find the declaration before one can fully understand the cd call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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