1

I'm working a large piece of code and for brevity sake find myself setting variables inside of if statements, example, if ( $subscriber = $this->subscriber->addSubscriber($request->all()) ) . Expanded example below.

It works great and probably is good indicator to use ternary statement. However, before I create a problem for myself that will result in late nights of refactoring.
I feel I need to ask if this problematic or bad practice? Should declare before use i.e. traditional approach? Sorry if this is basic question, but cannot find anything on the here or PHP forums.

    public function postSubscriber(Request $request)
    {
        if ( $subscriber = $this->subscriber->addSubscriber($request->all()) ) {
            return response()->json($subscriber, 200);
        }

        return response()->json("Oops! something went wrong with your subscription.", 500);
    }
3
  • 2
    Your code is just fine ™ Commented May 27, 2016 at 19:14
  • 1
    A ternary would probably make the code less readable; there's nothing wrong with if statements, even for short methods like this Commented May 27, 2016 at 19:19
  • 1
    Whether or not the more concise code is more readable is very subjective. To me, the main advantage to breaking code into more steps is that it can make debugging a little neater by allowing you to set breakpoints more precisely. Also assignment in an if condition triggers a warning in some IDEs (Netbeans does that iirc), which you can turn off, but then won't warn you if you do it accidentally later. Commented May 27, 2016 at 19:52

1 Answer 1

2

No, as I see it, it isn't likely it will cause problems that will require refactoring. Re: whether traditional approach is more readable, that part of your question is entirely subjective and is best answered with 'what is most readable to you?'

Sign up to request clarification or add additional context in comments.

1 Comment

thanks , I always hesitant to ask these types of basic questions but all to often bites me in the behind when I don't

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.