Fresh Blurbs

To Use or Not To Use "Select * From"

Pizza_milkshake, a PHP/MySQL celebrity from the IRC (where lots of LAMP dudes reside) has posted an article about this subject. This view seems to be growing in popularity since I noticed it referred to several times during my today\'s visit @ MySQL on Freenode.

Even though it has some valid points, I do not necessarily agree to this oppinion and I definitely do not agree to the assertive tone of the paper. Being spoiled with ORM tools à la Hibernate, I kinda smell that there is more to this discussion than what is covered in the mentioned paper.

Among other things, there are two things that matter in software engineering style: resulting performance and productivity. Yes, you always want your code to be the fastest, most efficient, yadda, yadda, yadda, but you also want your program to be flexible, easy to maintain and you do want to write it as fast as possible and get to more important things in this life :-)

Anyway, to achieve all these good stuff, shorter the code - the better, less code duplication - even better. I am not just whining about the length of explicitely enumerated list of fields. That\'s a lesser problem. Bigger problem is that you will be using these field names somewhere later. So something is used in several places. See the threat? You change in one place, forget to change in another - oops! On the other side, you could have used a star in one, pretty critical, place and there you go - one less place to worry about.

In addition, remembering that PHP is a dynamic language, one place may be all you need. If you can think it through well, you can write your data objects so that they have the same properties as whatever the table has in the DB and then other objects dynamically find-out about these properties via some mechanism à la Java Reflection (but for PHP) and you end-up with a situation that for a significant number of your objects, the only place you need to define field names - is in the database. Need to add one more field, or remove? Do it in the database and never worry about possible code incosistency.

How is that? Would you use * if it delivered so much productivity/maintainability boost? You should.

I am not saying that all objects should be mapped to a DB like that and completely loaded each time (pizza_milkshake had a valid point that sometimes you do not want to populate recordset with all fields from a table) but there are times when you do want and when it helps. So, it is as much wrong to declare * as evil, as to have a habbit of using it all the time :)

cheers.

comments powered by Disqus