Reputation: 3570
I'm coding a page that requires a unique hash in the URL to load. My code, for reference sake, looks something like this:
<?php
if (!isset($_GET['hash'])) {
mysql_close();
header("Location: error.php");
exit();
}
?>
My question is: if that if
statement will redirect when it fails, should I (and more importantly, why should I) continue my code like so:
else {
// More Code
}
As opposed to just:
// More Code
Is it just a case of good coding practice, or are there reasons behind it? Are there situations where continuing without an else
gives different results to coding within one (other than the obvious else if {}
clauses between them both?
I've written my code in PHP
, but as far as I can comprehend, this would apply to a lot more languages too.
Upvotes: 0
Views: 64
Reputation: 51
You should avoid as possible to user exit(); , break(); and other function like goto that make your program jumping instruction.
Why ? Programmers are used to read codes with if, else if, else ... it's more intuitive and structurated. If the way to read the code is not common, the reader have to think where to continue reading after an exit(); , break() or goto ..
Upvotes: 0
Reputation: 17831
I don't think you should do it. If you continue this in the code that comes afterwards, everything will already be indented 1 level more than it has to be.
The readability of the code will be compromised if you keep doing this, adding else statements and indenting the code further and further, leading to arrow code.
I like to create things like you did, too, because it keeps the code flat, and easier to read. There is even a pattern that describes what you are doing: Guard Clauses / Statements
.
They may lead to complex situations, when you have many strange returns, ifs, loops, and whatnot. But in most cases, they make everything easier, cleaner and better to read.
Upvotes: 3
Reputation: 496
Having an else statement is only a good coding practice. It won't change anything in what your code is doing, since you end your "if" with an "exit".
Upvotes: 0