How can I avoid repeating code in a conditional?

I quite frequently find myself writing an if clause along the lines of:

if (cond A) { // typically if mysql has returned a valid and non-zero result
    do Z to define cond B; // typically extract variables from the mysql result
    if (cond B) {
        do X;
    } else (
        do Y;
} else {
    do Y;

As you see, I end up repeating the ‘do Y’ code. I can’t use ‘if (cond A && cond B)’ because I cannot evaluate ‘cond B’ until I know I have met ‘cond A’.

I feel sure there must be a way to avoid this repetition.

In most languages if statements are evaluated left to right. If left side fails then the right side will never be ran, which will prevent unnecessary evaluations or calls.

if($condA && $condB = zDefineB()) {
} else {

You can actually force both conditions to be evaluated by using a single & or | instead of using a double. I’ve never once found a reason to do this, but it could be useful if you need to use $condB later on… but it would probably be better to just put that on the left side instead.

Thank you, Mawburn.
That looks fairly straight-forward in pseudo code. I will just need work out a tidy way to lay it out with real code, because sometimes the ‘zDefineB()’ could run to several lines.

You can refactor your code following the best practices mentioned by Martin Fowler or this book(which is more PHP specific):

Take a look at the section: Replace Conditionals with Polymorphism and Replace Nested Conditionals with Guard Clauses, they may provide good hints to your problem.

Thanks, Hall_of_Famer.
I’ll look into that. I fear, however, that the book may be aimed at OOP, whereas I am stuck on procedural code. I have tried repeatedly to get to grips with OOP but never made it.

This is also a good video about this topic too.


1 Like

This is also a good video.


If you are stuck at procedural code, then you need to do big refactoring to convert it into OOP. Procedural programming is for amateurs, it is good and only good for absolute newbies to learn programming, since not everyone grasps OOP at their first few days learning how to code. OOP, on the other hand, is the professional standard, a programming technique that everyone should follow. If your code is procedural, you shouldnt worry about writing elegant code at first since there’s no way to achieve this. Instead, rewrite your script in OOP, and only since then we can even talk about how to write better and more elegant code. The bottom-line is, never write procedural code, its amateurish and its a pain for advanced coders to read.

In my case, it’s not so much amateurish as ingrained. I cut my teeth on BASIC GOTOs many years ago. It’s taken great effort to get into OOP-think. JAVA helped a lot with that, but it sure wasn’t easy

This is actually a really interesting topic on its own. There’s lots of discussion in academia about how to teach programming. There is a school of thought (I’m yet to decide whether I agree entirely yet) that says objects should be taught from day 1. This paper makes quite a strong case: in practice it’s a lot more difficult. A key part is the difference between calling a function and a method as you need a very basic understanding of polymorphism (that you call a methond on an object.

If the result of asking a question is simply to have scorn poured one one’s head it is not very encouraging. It is harder to learn new stuff when over seventy.

1 Like

Well I think I should refine my statement to languages that support OO. If your project uses a procedural language, such as C or BASIC, writing OO code may not necessarily be a good practice. Though theoretically possible to write OO in procedural languages, the fact that they lack native object and OO support makes things difficult. In this case, writing in OO can be inefficient, which kills the purpose.

But I think this is a PHP forum so all topics are PHP related. As PHP is now a language that almost fully supports OO, my statement above was perfectly valid. This is not a subforum for C or BASIC, we are not writing in a procedural language. In a language that supports OO enough well, there’s no reason not to write in OO and instead go with the old and bad ways. Perhaps it can be a controversial topic with PHP 3 or PHP 4, whose object models are somewhat primitive and inconvenient to use. Since version 5, PHP’s object model has matured and should be used by every aspiring PHP developers.

Of course, the difficulty of OO thinking can prove to be a problem for newbies, which is understandable and acceptable. But once a developer gets a hang of the basic programming concept, it will be a good time to switch into OO, if he hasnt already done so. Sticking with procedural mindset can be severely detrimental for a programmer’s career, the longer you are stuck with procedural code, the harder it is to make the transition to OO, as evidenced in your own experience. This is why I recommend newbies to try switching into OO as soon as they can, once they are comfortable at writing functions and arrays it will be about time to make the transition.

You make an interesting point. I actually think that Objects should be taught from day 1, in universities/colleges that you can safely assume your students are capable programmers, or will be capable programmers. If they all major in Computer Science, and aspire to work for companies like Microsoft and Facebook, it is a good way to go. But this indeed makes the learning process more difficult, as not everyone possess the talent to write quality code. There will be some people who just cannot click when it comes to programming and its concept, some may be web designers who are more like artists in nature. They do not care about elegant code or reusable code, they just want to learn something quick and be done with it. Teaching OO to those who do not have a programmer’s mindset at the first day of their coding lesson may be infeasible.

So I guess, eventually, it all comes down to the audience, whom you are supposed to teach, and what expectations you have on them. Do you think they will eventually become capable coders who will find programming jobs in this industry? Or do you think they are just hobbyists who only learn coding for fun or for minor purposes? The answer to this question dictates whether teaching students OO at their first day at school is necessary, or not.

If the result of asking a question is simply to refuse and reject the valid answers you receive, it sure is not very encouraging. It is hard to learn anything when you aint willing to learn.

I also have to disagree with this. Procedural code can be for professionals, who have to program in a procedural language. It is a method, a way to do programming and has its advantages and disadvantages. Trying to program procedurally in a OOP language is simply a mistake, but only because you aren’t taking advantage of the built in OOP features, which are supposed to help your coding be loosely coupled, modular and testable.

@ramasaig - learning OOP isn’t all that hard. Putting the abstract concepts to work properly is a bit more difficult, but once you work with it some, it will go “click”. Try your best and when you have some issues, that is what we can help with and maybe even learn some more ourselves. :blush:


Yeah I understand, you make a point. I already refined it in a later post that procedural programming is bad and amateurish when you use it in a language like PHP, which supports OO almost fully and has enough features built upon it. For pure procedural languages, you dont have a choice, and its better to adhere to the practices widely used and accepted in that programming language, than to force yourself to write OO. Still, most modern programming languages are either OO in nature, or at least moderately support OO. For this reason, my statement is still valid, in most cases.

It is kinda like your company is at a location 20 miles away from home. In general, you have a choice between walking(procedural) or driving a car(OO). If you dont know how to drive a car, you should learn how to drive and get a driver’s license, so you can drive a car in recent future(learning how to write OO code). If you really have no choice, as there is no driveway between your company and your home, maybe its a mountainous landscape, you may have to end up walking(sticking to procedural programming as you are stuck with a procedural language). But the fact that your destination is 20 miles away means that you have to walk several hours.

Thank you, Scott. That’s way more constructive than some of the other replies. At no point (Hall_of_Famer) did I say I didn’t want to learn, I am always keen to embrace the new (in this case of course, new to me, not new as in new-minted).

I have been programming in procedural PHP for over fifteen years, and in that time have become quite fluent, though not of course perfect.

I know OOP isn’t all that hard. I know it has advantages (and no doubt disadvantages). No one needs to sell it to me. I have several times set out to learn it, but I’m always overtaken by the ‘real’ world - people who want their web sites updated NOW. Very inconvenient of them, of course. One of the problems of being a small operator in a remote place.

I think this discussion has gone way beyond the question I originally asked, so I’m signing off here. But I will listen if anyone has a constructive suggestion about how I jump out of the procedural box without terminally disrupting my workflow.

I really think you should stop making this argument. For a start, you constantly use the term amateur in a condescending way, but the fact is that not every one who uses this forum is a professional… many are using PHP for their own projects or perhaps to add some features to their business’ website, and there is nothing wrong with that. For them, your insistence that they rewrite all their code to be OO is impractical and unhelpful.

@ramasaig If you’re interested in taking some of your code and converting it to OOP as an exercise, there are members here who’ll be more than happy to help, discuss, and offer suggestions. But, regardless of whether you’re writing procedural or OO, your questions are welcome here at the forums and you’ll find people willing to help.



A single | or & is a bitwise operator, using one in place of || or && will have unexpected results.


LOL! I thought that sounded a bit fishy when I read it. :smile:


If both operands for the &, | and ^ operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be converted to integers and the result will be an integer.

Too many gotcha’s in PHP. This is just +1 to the reasons why I don’t use it.

PHP has its faults but & and | are bitwise operators in C, C++ and Java as well.

1 Like