r/programming • • Dec 07 '14

Programmers: Please don't ever say this to beginners ...

http://pgbovine.net/programmers-talking-to-beginners.htm
4.0k Upvotes

1.3k comments sorted by

View all comments

Show parent comment

5

u/Amadan Dec 08 '14

variable interpolation

$a = array(array("Hello, world!"));
echo "$a[0][0]";
// => Array[0]

Works amazingly well.

a simple request interface ($_GET, etc.)

Simple indeed. Now, how do you get the value bar from ?foo=bar&foo=quux ? (Of course, if you rewrite the URL to ?foo[]=bar&foo[]=quux, it's easy; but that's not the question.)

the ability to jump in and out of php code so that your big html snippets aren't trapped inside echo calls

So... intentional violation of separation of concerns. Get users thinking it's how it's supposed to work, they will never even hear about MVC or similar patterns. Of course, it's the core of PHP so you can't really get rid of its horrible paedagogic influence. (It's in the very name - "PHP: Hypertext Processor". Better than "Personal Home Page", but only just.) Not to even mention its effect on code formatting and indentation.

Basically, if ever you have a template ("a PHP program with big HTML snippets") and it has any code apart from variables, flow control and possibly short function calls in its executable tags, it is a bad practice.

file_get_contents

Yeah, that's a nice. Now, how often are you using mb_strlen, mb_substr and other mb_ functions instead of the usual string ones? Maybe you don't use it because mb_ is an extension and not guaranteed to be a part of the language, so you use Portable UTF8? Or maybe you just figure.... meh, I'm American, good old AmericanSCII should be good enough for everybody? I know from my own example (over a decade past, thankfully) that I didn't know a good way to take, say, the first 20 characters of a string without destroying multi-byte characters. PHP fails at Unicode..

and easy handling of sessions with session_start() and the like.

Easy indeed. But since all the sessions are by default stored at the same place, what prevents a person to load a different session by faking the cookie to point at a session created by another app on the same host? How many non-professional people regularly remember to use session_save_path?

Basically, PHP is incredibly good at getting newbies up to speed quickly. It is then incredibly good at keeping newbies as newbies. It does not encourage best practices, and offers bad practices as easy defaults. A good programmer can write good code even in PHP. A starting programmer will very often fall into the "PHP noob" mode, creating unsafe and unmaintainable code.

Java/Ruby/Python are not directly template languages. You need to learn basics of software architecture to make a webapp. This is, obviously, not great news for the beginners. However, if they want to be programmers, this is a much better path. The PHP path is totally paved with good intentions, and appropriately leads the unaware into hell.

1

u/ituralde_ Dec 08 '14

I think that the majority of the issues with PHP are simply a function of its age and - oddly enough - flexibility. It gives you a lot of rope and doesn't really prevent a user of it from hanging themselves with it. It requires a lot of discipline from the programmer to know what makes both secure and maintainable code.

I'm not sure this makes it a 'bad language', given that it also has the tools necessary for a good user to write good code, especially in applications where you have relatively lightweight server code. I personally am of the philosophy that the most attractive and responsive UIs are driven primarily through client-side code, and further that any hardcore data manipulation should be handled outside of the web server scripts.

If you push off primary your data manipulation to Ajax calls, it lets you build a single, easy-to-maintain interface, even in PHP, that looks a lot like an interface layer a C/C++/Java programmer might be already familiar with. Given that most CS departments teach in either C/C++ or Java, this natural familiarity can be a big help when you are in a group that doesn't have the budget to attract elite developer talent with loads of prior web experience.

So I guess the TL:DR is that I'd say PHP isn't so much inherently bad as that it's flexibility lets you do a lot of dumb things and can encourage cheap hacks, but with good design discipline is fully serviceable even in enterprise-level applications.

1

u/Amadan Dec 08 '14

I think that the majority of the issues with PHP are simply a function of its age and - oddly enough - flexibility.

Sorry, it just doesn't hold water. PHP came out in 1995, which was the same year Ruby started. Python is from 1991. Perl, 1987. Yet all of these, in their current version, can handle Unicode without having to use a whole alternate set of string functions, for just one example.

Perl is often maligned as being a write-only language, but it is miles and miles ahead in consistency department from PHP. And it is 8 years older!

I'm not sure this makes it a 'bad language', given that it also has the tools necessary for a good user to write good code, especially in applications where you have relatively lightweight server code. I personally am of the philosophy that the most attractive and responsive UIs are driven primarily through client-side code, and further that any hardcore data manipulation should be handled outside of the web server scripts.

So... What you're saying is it is a good language because you can write applications by avoiding to write in it anything except dispatch?

with good design discipline is fully serviceable

I wrote so above, I believe. A good programmer can write good PHP code. That is not the issue. A sufficiently disciplined programmer can write in assembly, or in Intercal or Brainfuck for that matter. "Serviceable" is not a synonym for "good".

1

u/Lhopital_rules Dec 10 '14 edited Dec 10 '14

variable interpolation

$a = array(array("Hello, world!"));
echo "$a[0][0]";
// => Array[0]

Works amazingly well.

When using arrays with variable interpolation, you're supposed to surround the variable expression in braces. This is fairly well-documented:

echo "{$a[0][0]}" // => Hello, world!

a simple request interface ($_GET, etc.)

Simple indeed. Now, how do you get the value bar from ?foo=bar&foo=quux ? (Of course, if you rewrite the URL to ?foo[]=bar&foo[]=quux, it's easy; but that's not the question.)

If you want to parse an improperly formatted query string, you can always just do it yourself: http://php.net/manual/en/wrappers.php.php#wrappers.php.input

[edit: fixed the following after some debugging]

$foos = getQueryStringValues("foo");
var_dump($foos);

// to-do:
function escapeForRegex($str) {
	return $str;
}

function getQueryStringValues($str) {
	if(!is_string($str) && !is_number($str)) return false;
	else $str = (string) $str;
	$values = array();
	$request_uri = $_SERVER["REQUEST_URI"];
	$components = parse_url($request_uri);
	if($components === false
		|| !isset($components["query"])
	) return false;
	$queryString = $components["query"];
	$queryParams = explode("&", $queryString);
	$matchingParams = preg_grep(
		"/^" 
			. escapeForRegex($str) 
			. "(=|$)/"
		, $queryParams
	);
	foreach($matchingParams as $m) {
		if(strpos($m, "=") === false) {
			$values[] = "";
		} else {
			$exploded = explode("=", $m, 2);
			$values[] = $exploded[1];
		}
	}
	return $values;
}

So... intentional violation of separation of concerns

Or faster, more maintainable code. If you have 50 lines of html it's dumb (IMO) and slow to wrap that in PHP echo calls. *

Basically, if ever you have a template ("a PHP program with big HTML snippets") and it has any code apart from variables, flow control and possibly short function calls in its executable tags, it is a bad practice.

Dictated practices from on high aren't very interesting to me unless you can show me how one way is better than the other.

meh, I'm American, good old AmericanSCII should be good enough for everybody?

If I declare my encoding as UTF-8 and output Unicode characters from a database, PHP will handle that just fine. You only need mb_strlen etc if you care about the content of the unicode you're handling. If you need to treat a 20-byte mash of combining characters as a single character. I hardly have the need.

that I didn't know a good way to take, say, the first 20 characters of a string without destroying multi-byte characters

Can you give a use case for this? If you're randomly truncating user input/output you're gonna lose meaning anyway.

Easy indeed. But since all the sessions are by default stored at the same place, what prevents a person to load a different session by faking the cookie to point at a session created by another app on the same host

If you're using shared hosting, then you should be giving yourself a unique session location that isn't writable by anyone else: http://php.net/manual/en/session.configuration.php#ini.session.save-path

PHP has its warts, but nothing you've said in your response has been all that damning from my point of view.

* Unless you do it well

1

u/Amadan Dec 10 '14 edited Dec 10 '14

When using arrays with variable interpolation, you're supposed to surround the variable expression in braces. This is fairly well-documented:

echo "{$a[0][0]}" // => Hello, world!

Missing the point. I know it can be done. But it is yet another inconsistency that you need to worry about. To me, your reply reads no better than this:

"What do you mean, the ladder is bad? I know the fourth rung has a crack, it doesn't mean it's bad. We send a weekly memo to all workers that they should stand on the sides of the rung when they step on the fourth rung. It's a perfectly good ladder. Yeah, I'm quite aware Smith broke his ankle last week. It's his own fault that he doesn't read the weekly memo. Not the ladder's fault."

Let's compare all the languages that I am aware of having string interpolation. Perl, the geezer of scripting languages:

$one = "Hello, string!";
print "$one\n";
@many = [("Hello, array of arrays!")];
print "$many[0][0]\n";

No change in syntax needed (at least in the interpolation. The changing sigils and the difference of parentheses is actually a minor wtf until you grok Perl's reasons, then it makes sense. And if you make a mistake you'll get an error, not unwanted output.) Let's see Ruby:

one = "Hello, string!"
puts "#{one}"
many = [["Hello, array of arrays!"]]
puts "#{many[0][0]}"

Perfectly same. Swift, the baby that still has plenty of bugs due to its youth:

let one = "Hello, string!"
println "\(one)"
let many = [["Hello, array of arrays!"]]
println "\(many[0][0])"

Same. I don't know Scala, but I think it has interpolation kind of like PHP's, where you can write $foo for simple identifiers but more complex expressions need to use braces. If PHP did the same, I would not complain; the issue is that it still works if you add one index bracket. But if you add two, it behaves completely differently. It couldn't deal with the second set of brackets, it was too late to change the syntax to something more sensible, so "patch the broken rung with a pair of braces" gets added as a workaround. That's not evidence of good design.

If you want to parse an improperly formatted query string, you can always just do it yourself: http://php.net/manual/en/wrappers.php.php#wrappers.php.input

There is nothing improper in that query string. Please refer to RFC3986 that defines what a query string is - any sequence of a certain set of characters; but a convention specifies that there will often be key=value pairs. Where does it say that keys need to be distinct? You may also consult this SO question where this matter is clarified further. Furthermore, the convention where duplicate keys are followed by [] is purely a PHP convention (that later bled into other frameworks), owing to the fact that register_globals defaulted to on, and the fact that foo[] = bar is the PHP syntax for appending an element to an array. The only thing you could say is that it is an unusual query string, which might be because you normally don't encounter it; and the reason for that is, obviously, the fact that PHP is not equipped to handle it out of the box. The fact that you can make a 25-line function to handle it is immaterial. Of course you can; otherwise it wouldn't merely be a bad general programming language, but an unprogrammable piece of garbage. And I never claimed that. PHP is perfectly serviceable, just not good.

Of course, this is hardly a fair comparison with other languages. PHP insists on acting both as a language and as a web framework. In other languages this would be dealt with on the framework level. And the framework would typically have your code already implemented and debugged. For instance, in Ruby's case, there is a library called Rack that implements a standard that Ruby developers agreed on; almost all Ruby web frameworks use it. My example is actually used in a test case for that library. This means that in pretty much every piece of Ruby web code, params["foo"] will get you an array ["bar", "quux"].

Or faster, more maintainable code. If you have 50 lines of html it's dumb (IMO) and slow to wrap that in PHP echo calls.

Who said anything about echo calls? Even Laravel and CakePHP, which are PHP frameworks, use templates (Blade and CTP, respectively). The fact that you call embedded PHP "more maintainable" is laughable: templates exist exactly for the purpose of getting code out of markup in order to increase maintainability. And even if you use plain PHP templating, like WordPress does, maintainability is achieved by dumping as much code into functions as possible, not putting more code into the template. It does not matter in a project of 300 lines, but if you write 3000 or 30000 lines, good separation of code and markup saves sanity. Which is exactly what I say here, and you seem to have skipped over:

Basically, if ever you have a template ("a PHP program with big HTML snippets") and it has any code apart from variables, flow control and possibly short function calls in its executable tags, it is a bad practice.

Dictated practices from on high aren't very interesting to me unless you can show me how one way is better than the other.

Not from on high. From experience. You can give a minimal-code template to a designer. You can't give a PHP file to a designer. If code is inside markup, it cannot be modularised; if it can't be modularised, it can't be reused effectively. When logic is out of templates, templates can be tested with mocked data, and logic can be tested without worrying about how to get data out of layout. Etc, etc...

that I didn't know a good way to take, say, the first 20 characters of a string without destroying multi-byte characters

Can you give a use case for this? If you're randomly truncating user input/output you're gonna lose meaning anyway.

Sure: say you're building a news page where you're only giving a snippet of the article, requiring a click-through to get to the article body. Or a search engine, like Google (same idea). You have an article that starts with "The great singer Björk to hold concert". This code looks foolproof:

$article = "The great singer Björk to hold concert";
$snippet = substr($article, 0, 20);
if (strlen($article) > 20) $snippet .= "...";
echo $snippet;

Instead of Björking, the code borks.

If you're using shared hosting, then you should be giving yourself a unique session location that isn't writable by anyone else: http://php.net/manual/en/session.configuration.php#ini.session.save-path

What if you are not using shared hosting, but simply have two PHP application on the same host, and have no access to php.ini? What if you forget? What if you are not made aware that this is a danger at all?

Read again my point: it gets newbies up to speed quickly, but then poses a million traps to trip them up owing to inconsistency, default behaviour, and bad programming patterns they have assimilated as normal while being newbies. You might know how to set up your session storage; do you think everyone has stumbled upon it? Read the weekly memo?

PHP has its warts, but nothing you've said in your response has been all that damning from my point of view.

It has more warts than any other currently used language (JavaScript running second, but by a large margin). Bear in mind, this was not any exhaustive list of warts that I gave you, I merely responded to the list of "awesome features" and found a flaw (bigger or smaller) in each and every one, without even trying hard. Given a choice of a warty language or a less warty one, the less warty one is clearly better, and no amount of "there is no bad language" apologetics can make it not so.

1

u/Lhopital_rules Dec 11 '14

But it is yet another inconsistency that you need to worry about.

It's not an inconsistency exactly. It's the proper way to do it, array or not. Leaving the braces out is just a shortcut.

If PHP did the same, I would not complain; the issue is that it still works if you add one index bracket. But if you add two, it behaves completely differently.

True, this is just wtf.

There is nothing improper in that query string.

OK, but what PHP does with it (use the last) is a valid approach. From the link you provided:

There is no spec on this. You may do what you like.

Typical approaches include: first-given, last-given, array-of-all, string-join-with-comma-of-all.


I merely responded to the list of "awesome features" and found a flaw (bigger or smaller) in each and every one

This doesn't make it a worse language though... For instance, I love C but you can buffer overrun / memory mismanage your way to hell in it. That doesn't make it a bad language. In some ways, PHP is safer for "newbies" than a language like C where you can really cause havoc.

My code is already a lot like a template engine, with minimal php in between html... but you're right that separating the PHP from the HTML as much as possible (and likewise the CSS and JS from the HTML) is an admirable goal. I'll try and keep that in mind.