Is it a bad style to declare a variable within a condition?

Advertisements

I have an if condition in which I send a database query with a string to see if at least one entry already exists. If a value exists, another method should be called with the resultset of the query.

$title = 'hello_world';
if( $array = $this->DbResolver->resolve(Str::of($title)->slug('_')->toString()) ) {
  $title = $this->anotherMethodInMyClass($array, $title));
} 

return $title;

I could also simply define the array in advance as an empty array. But I thought this would save a line of code. Would be grateful for your opinion and experience. Thanks a lot!

>Solution :

I will keep this factual and will not drift away to the realm of opinions.

You can further reduce the number of lines, like:

$title = ($array = $this->DbResolver->resolve(Str::of($title)->slug('_')->toString())) ? $this->anotherMethodInMyClass($array, $title)) : 'hello_world';

Where we convert the if into a ternary which results in the proper result if array is truey and to your default otherwise, assigning the result to $title.

But, as we can see, this is a complex line and people may find it less readable than in the case when the code is more explicit, like:

$title = 'hello_world';
$array = $this->DbResolver->resolve(Str::of($title)->slug('_')->toString());
if( $array ) {
  $title = $this->anotherMethodInMyClass($array, $title));
} else {

return $title;

So it’s up to you and your team to decide how explicit you like the code to be and if everyone is okay with less lines, then you may choose the first approach. Otherwise, if people prefer to make it more explicit and to separate value assignment from if or ternary conditions, then the latter suits you more.

So, you will ultimately decide upon subjective matters, but it’s important to lay the foundations of this question upon objective, factual basis and to understand why explicit codes tend to be more readable rather than compact code with reduced lines.

To illustrate it further, here you can see explicit and minified code (in JS, but I think it’s good example nevertheless): https://www.imperva.com/learn/performance/minification/

Which code is more understandable for you: the minified code or the explicit code?

The answer is likely the latter. So, in general people tend to like more explicit and readable code, but code is often minified when it’s released to environments where humans will no longer read it and where their size matters.

Leave a ReplyCancel reply