Wednesday, December 24, 2008

singleton discussions

Why I Hate Singletons

Singletons are not evil

Why Singletons are Evil

Thursday, December 18, 2008

OOP Principles

Below principles are extracted from the excellent PHP book: PHP In Action.

A class should be open to extend, closed to modification. A refactoring technique is also regarded in this principle: Replace conditional with polymorphism.

In real world: when a new requirement comes up, what a programmer usually do is, open the source code, find the related part, put if (condition) {//do the new requirement}

a class that tries to do everything will have to change frequently because
some responsibility it has needs to be updated. A class should have only one reason to change.

In real world: any other template engines except smarty can allow developers put business logic into it?

GoF tell us: program to an interface, not an implementation.


Friday, December 12, 2008

read list

I list some books which i am reading and about to read.

1. PHP Objects, Patterns, Practices
2. PoEA
3. High Performance Mysql 2nd edition (i read the 1st one and feel good. Wonder the difference in 2nd edition)
4. Symbian S60 Programming a tutorial guide
5. Symbian Effective C++
6. Common Design Patterns for Symbian

Monday, December 8, 2008

Good and Bad PHP Code

Today I read a blog about good and bad php code.

When I asked this question to myself, what is good php code, I surprisingly find out that my brain is blank! However, when I try to ask in the other way, what is bad php code, I can give tons of examples. Below is some of them.

0. Variable is not initiated.
1. Not using isset to check if a variable is initiated.
2. Not checking data type
3. Global variables everywhere
4. Static methods everywhere
5. Long functions (function should be short & simple enough that you even think unit test is not required)
6. Long parameters
7. Duplicate codes
8. Low efficient coding style
9. huge class
10. No memory management concept in mind (Yes, even PHP we need to think of that!)
11. Implement large project without MVC architecture.
12. Put business logic in presentation logic(Especially for smarty users)
13. Like to use too many if, else, switch to control the logic
14. Without security concept in mind (sql injection, string filter)
15. poor DB modelling and SQL statements, e.g. using too many Mysql Fucntions which could be done in PHP, using IN in sql Query (Although this is not PHP code)

Friday, November 21, 2008

Some thoughts about reading Patterns of Enterprise Application Architecture

First of all, it is a good book. There is no doubt for that. Its author name, Martin Fowler, is a guarantee in quality.

However, I think it might be better if we read it from its Part 2: The Patterns. And then refer back to Part 1: The Narratives. The reason is simple, if you don't have any knowledge of those patterns, reading part 1 doesn't help you a lot and would not offer you any valuable information. If we start from Part 2 and get a solid knowledge of the patterns and their implementation, we can easily link them with our practice. And it may be just like, ah ha, that is it! And then if we turn back to part 1, we can get our knowledge solid.

It is just my personal thought about reading this book.

Refactoring:Introduce parameter object

This is refactoring is to reduce the long parameter list. Long parameter list make it hard to understand and maintain. It bring down the code's readability either. Introduce a parameter object is a natural solution to this problem. Parameter object contains numbers of get methods to get the parameter value used in other methods.

However, compared with other program languages, PHP contains the most powerful and flexible array functionality. PHP developers are temped to use array to group all necessary parameters. The good side of using array lies in simplicity. However, the downside is obvious as well. You can't guarantee array's integrity, and you need to check if a parameter is contained in an array everywhere in functions that accept this array as parameter.

Wednesday, November 19, 2008

Refactoring:Compose Method

Today I applied this refactoring to extreme. Let's learn some theory about it after lots of practice. Below are all quoted from Refactoring to Patterns.

"You can't rapidly understand a method's logic.

Transform the logic into a small number of intention-revealing steps at the same level of detail. "

"A Composed Method is a small, simple method that you can understand in seconds. Do you write a lot of Composed Methods? I like to think I do, but I often find that I don't, at first. So I have to go back and refactor to this pattern. When my code has many Composed Methods, it tends to be easy to use, read, and extend."

For people who worry about performance issue, the book also clarify:

"Once you finish this refactoring, you will likely have numerous small, private methods that are called by your Composed Method. Some may consider such small methods to be a performance problem. They are only a performance problem when a profiler says they are. I rarely find that my worst performance problems relate to Composed Methods; they almost always relate to other coding problems."

Benefits and Liabilities
+ Efficiently communicates what a method does and how it does what it does.
+ Simplifies a method by breaking it up into well-named chunks of behavior at the same level of detail.
– Can lead to an overabundance of small methods.
– Can make debugging difficult because logic is spread out across many small methods.

I think this is a technique we need to use in most of refactorings. Because a typical procedure program/code is usually hard to understand especially when the procedure is horribly long and contains lots of conditional logic.

Sunday, November 16, 2008

Refactor Conditional Logic

In the book Refactoring to Patterns:
"Martin Fowler writes, "One of the most common areas of complexity in a program lies in complex conditional logic". We often find such logic in algorithms because they tend to grow, becoming more sophisticated over time. "

Conditional logic contain two kinds of statement: if...else... and

The book Refactoring presents us below refactoring techniques:

Replace Type Code with Class
Replace Type Code with Subclasses
Replace Type Code with State/Strategy

Decompose Conditional
Consolidate Conditional Expression
Consolidate Duplicate Conditional Fragments
Remove Control Flag
Replace Nested Conditional with Guard Clauses
Replace Conditional with Polymorphism
Introduce Null Object
Introduce Assertion

The book Refactoring to Patterns also demonstrate below conditional logic related refactorings:

Replace Conditional Logic with Strategy
Replace Conditional Dispatcher with Command
Move Accumulation to Visitor
Move Embellishment to Decorator
Replace State-Altering Conditionals with State
Introduce Null Object

As conditional logic is a common issue that increase a program's complexity and reduce its readability, examine these refactoring techniques become instructive.

Thursday, November 13, 2008

Refactoring: Replace Conditional Dispatcher with Command

Quote from the book Refactoring to Patterns:

Conditional logic is used to dispatch requests and execute actions.

Create a Command for each action. Store the Commands in a collection and replace the conditional logic with code to fetch and execute Commands.

The main idea is to create a command for each action, and then create a sort of command lookup class to lookup the request and delegate to the command.

This can work very well if you can easily decide what command should be taken from the request. Actually, in PHP web development, command pattern might be the most common pattern.

However, things become a little hard if you cannot easily find out the corresponding command to the request. In this situation, I would think of chain of command. Let each command decide if it should process the request by itself. If it should, it will process it and stop, otherwise, the request will be passed to the next command and so on.

PHP In Action VS PHP Objects Patterns and Practice (2)

Both of these books heavily refer to some typical software development books: Design Patterns (Gang of Four), Refactoring (Martin Fowler), patterns of enterprise architecture (Martin Fowler), etc. Basically, these two books are trying to introduce concepts like design pattern, architecture, refactoring, which are common to java developers, to PHP. So, if you find these two books helpful, it is natural that the next step should be those reference books.

Both books introduce some common design patterns which may be used frequently in PHP development, for example, Factory, Singleton, Strategy, Observer, Composite, Command, Decorator.

However, I think both of them missed another important pattern: Delegate.

There are some other design patterns, which, based on my experience, are not often used in PHP development, are introduced in the two books. PHP In Action shows us Adapter, and the other book explain Interpreter.

Monday, November 10, 2008

PHP In Action VS PHP Objects Patterns and Practice (1)

First of all, both of them are very good books. They are the only books I've seen that focus on software development methodology instead of PHP language features. Even an experienced PHP developer should take some time to read through them (or at least one of them).

Both of these books are organised in three parts: 1. PHP Class, Objects, OOP design; 2. Design Patterns 3. Testing and other practice such as version control, refactoring.

For people who have any experience of C++ or Java, the first part of the books may be safely skipped. However, pure PHP programmers, especially those still using PHP 4, better read through the first part.

Second part of these two books are most valuable to PHP developers and worth careful reading. Each book introduces some design patterns. Some of these patterns are introduced in both books. The others could only be found in either one of them. PHP In Action uses one chapter to explain six design patterns, the other book spends 5 chapters in presenting 10 design patterns. Personally, I think the second books presents design patterns in more details.

Both books have chapters about database patterns, unit test. PHP In Action also introduces some concepts of refactoring while the other book uses a whole chapter to show us enterprise patterns and it also introduces other PHP development practice such as CVS, Pear, etc.

As I said, both of these two books are good and worth your reading. However, if I have to pick up one winner from them, i will choose PHP Objects Patterns and Practice. Compared with its competitor, it digs deeper and explain more details.

Wednesday, October 22, 2008

More about Singleton and static

Below is from ''

Singleton also gives a reference/pointer to the class instance. You can then pass this reference as a parameter for some other function for example. If you were using static classes, the other function would have to use the class statically too and if you ever needed to change the behavior, you would need to rewrite parts of that function too instead of just having the first one pass a different class as the parameter.

There's also an another side to the reference thing. If you use the reference in your class and decide that you won't need a singleton anymore, but a normal class, you will just need to change the behavior of the class itself and perhaps replace the line which gets an instance of it to constructing a new one or such. If you were using a static class, you would have to rewrite a lot of the code to use the new reference to the class instead of the static class name. A singleton class should also work almost out of the box as a normal class too. If you had a static class and wanted to convert it to a normal one, you would have to rewrite many parts of it.

You can't extend static classes, but singletons you can. Except it doesn't work very well in PHP due to some issues with static method inheritance, but it's not the only language in the world and it can be done but slightly hackily.

So if we think about it with all this, why would you use static classes at all?
They have their uses too - For example for library code they can be nice, such as the static System.Math class in C#.

Tuesday, October 21, 2008

scattered thought

Haven't updated my blog for a while. The company restructured PHP team, again. Now i'm in the team in charge of the project of the company's future core system. I found I entered a crazy world. I experienced this case several times: this this feature, must be done by the end of today! The team had to work night to 11 pm or even 12 pm. This is a project with 3 releases per week!

Experienced developers can imagine that this project must be messy, and actually, yes it is. Now i know why the project's initiator resigned two weeks ago. However, this is life.

Still reading the book refactoring, and after that, i plan to read professional refactoring to patterns.

Tuesday, October 7, 2008

php refactoring

I decide to spend more time in refactoring. I plan to read two books thoroughly: one is "Refactoring: improving the design of existing code", and the other one is "Refactoring to patterns".

I believe refactoring can be applied to PHP applications more than others. Due to PHP language's drastic evolution from a simple script which can be embedded in HTML, to a full OOP features contained programming language, we can apply refactoring technique to tons of legacy PHP applications.

A pity is there are few refactoring topics regarding to PHP. One of them is a chapter in book "PHP In Action". However, based on my opinion, that chapter only touches the super surface of refactoring. There are serveral articles or tutorials as well, i think. But none of them dig more in this area.

Saturday, October 4, 2008

singleton, static, defensive programming

below quoted from PHP 5 CMS Framkwork Development.
"The singleton appears repeatedly, especially for the handler objects described later. In theory, handlers could be implemented as class methods, but in PHP5 a class is not itself a first class object and it is more effective to use singleton objects. Other objects are naturally singletons, such as the session object, since PHP5 handles only a single request at a time.

They(signleton classes) arise naturally in designing systems where a range of related services is needed. Sometimes, this is done by creating a class that consists only of static methods. But that is both inefficient, and inflexible. Dealing with an instance of a class is generally more efficient than dealing with static methods, and in many cases a singleton object will know quite a lot of potentially complex information. Since a class of this kind is a manager or handler, there should never be a need for more than a single instance of the class, hence the name singleton. "

Friday when i was looking into the codes of our system, i found piece of codes like below:

public function f($keyword, $country)
if ($keyword === 'a') {
$keyarray = $config[$country]['a'];
} elseif ($keyword == 'b') {
$keyarray = $config[$country]['b'];

foreach($keyarray as $key) {

What is the problem of the above code? First, $keyarray is not initialised! if $keyword is neither 'a' nor 'b', the program will still try to run the next codes and throw a notice: Undefined variable and a warning 'Warning: Invalid argument supplied for foreach()'.

In the above case, at lease we should put one more 'else{$keyarray = array()}' at the end to ensure $keyarray is initialised. It is better to check with isset to make sure $config is set up correctly. However, since many php programmers don't do this in practice.

My friend who was working in GE told me that none of PHP programmers are professionals, or all PHP programmers are amateur because PHP is designed for amateur to develop simple database driven website quickly. However, since PHP plays increasingly important role in web app development, enterprises tends to employ PHP developers for their web applications. As usual, they define the criteria like 3-5 years experiences, etc, etc. They never thought that PHP programmers with 3,5 years experiences means they don't have any formal, scientific software development methodology. Probably they know more detail of PHP language. They know more functions in PHP manual. But they don't have OOP in mind. They don't have design patterns in mind. They don't have refactoring in mind.

Friday, October 3, 2008

Experienced programmer != Good programmer

The title formula especially applies to PHP grogrammer. Why? Because PHP's feature determines that an experienced PHP programmer is very likely to be a programmer with very bad programming style & habit. This is fine. But the terrible thing is, he doesn't realise that and is still thinking he is good, experienced. The more terrible thing is, the company heads also trust him, believe he is good because he is very experienced. That makes things hard for those truly good programmers.

Monday, September 29, 2008

Team restructured again

Our PHP teams get restructured again, combining 3 teams as 2 teams. It seems hard for the company to keep excellent software engineers. When i started working for this company, we had 15-16 PHP developers, divided into 3 teams. Now, we just have 11 left. The most unbelievable thing is, I have been working for this company only 1 year (actually, less than 1 year until 22 Oct, 08), and I'm the one who have served for the company 2nd longest among PHP developers!

This is not a good sign. I'm quite worrying about the company's future. Although now we are still a big company in Sydney, although the company is trying hard to build corporate culture, there must be something wrong.

Saturday, September 20, 2008

Accidently delete files on linux

Today I accidently delete some files of my project on linux. I wasn't panic because i think there must be some way to recover these files, such like what i did on Windows. I open my browser, google is my default home page. I typed 'recover deleted files on linux' and search. There are some solutions, however, they are all complicated! I thought maybe it is my keyword is not right, no matter all, i'm not a native english speaker. So i tried to search Chinese instead, the result disappointed me as well. It seems there is no easy way to recover deleted files on linux.

Then i became a little panic, what i have to do is to recreate those files again. I believe that is faster than i implement those complicated solutions.

Friday, September 19, 2008

A colleague resigned

Today i got a news that one of my colleagues decided to resign. I feel shocked by that. He interviewed me when i was trying to enter this company. Although later i'm not in his team, i feel grateful to him. He is leading a very important project for this company's future. He succeeded, and now decided to move on. That is quite a normal thing, but i still feel a little sad. I wish him the best in future.

My team leader will be back next Monday from US Zend conference. He will bring back a lot of funny stories & technical resources. I feel excited about that.

I'm gonna have a busy weekend for my new project.

Tuesday, September 16, 2008

What a day!!!

Today, one of my team member was asked to leave. Although he resigned two weeks ago, his last day in our company should be 24 Sep, 2008.

The main reason is probably yesterday's fight with another team member. And that fight did bring very uncomfortable air in the team.

I really don't know what to say. I feel a little bad, upset. I wish him best in future.

Now i have to work harder to keep my project on track. What a day today...

Friday, September 12, 2008

mid-autumn/mooncake festival

14 Sep, 08 is Chinese mid-autumn festival, or mooncake festival. At that day the moon will look round. In Chinese 'round' means 'all being together', 'complete', 'perfect'. So that day should be a day for all family members being together. As to mooncake, there are several stories, which even I don't know too much details for.

As usual, i will spend that day on my own. I always since i came to Australia. I will give a call to my parents in China and tell them i miss them.

I think I need to read some books about design patterns, software architecture. I still have a lot to learn.

Monday, September 8, 2008

Google Chrome

I like Google Chrome a lot, and actually i am using it as my default browser. However, it cannot access hotmail. When i try to access hotmail through Google Chrome, I get the information like 'upgrade your browser'. Another problem is sometime when i try to join some groups in facebook, it seems i can't do that in Google Chrome. At these cases, i have to open my Firefox or IE again.

However, generally, I like Google Chrome. I think it is simple, clean, elegant and fast. I read the comic interpretation of key engineering decisions at I like their ideas.

I don't know if Google has any plan to integrate their online office applications( with Chrome so that one day people just need to open Chrome and start working.

Saturday, September 6, 2008

Notes of reading PHP In Action

I start to read a book PHP In Action. I think this is a great book for PHP developers. Below quoted from the book really impressed me.

Page 38,
"The traditional alternative is typically to emphasize up-front design. The idea is
that you need to plan well ahead and design everything in a relatively detailed manner before you start to code. And if you’re good at doing the design, the resemblance between what you do and what the customer needs will be sufficient to get you through to the first release without major problems. But along the way, you will probably have yielded to the temptation to make some changes that weren’t planned, but make the software more palatable to the users. The fact is that user requirements
change, and this tends to corrupt pretty designs. As programming guru Martin Fowler
puts it: "Over time the code will be modified, and the integrity of the system, its structure according to that design, slowly fades. The code slowly sinks from engineering to hacking.""

Also page 38,
"The way that agile methodologies such as Extreme Programming (XP) attempt to solve this problem is by doing less up-front design, making sure it is always possible to
make design changes, and constantly improving the structure of the code using a set
of systematic procedures known as refactoring."

I think it points out the problems existing in many companies. At the beginning, the whole team is very ambitious and positive that they believe they can produce an elegant, robust and efficient system/application. They do excellent job at design. However, most of the applications end up as a buggy, ugly and unreasonable monster. The problem is, requirement keeps changing and new features keeps being added. You can't foresee all the requirements at design phase. This particularly applies to web application development.

Friday, September 5, 2008

Some thoughts about PHP

Since PHP 5 has contained most of the features of OOP (and the latest PHP 5.3 even supports namespace), people are keen on PHP OOP, framework, architecture, design pattern, etc. It is great to see PHP is evolving so fast and it is easy to understand that PHP users expect one day PHP can somehow compete with JAVA & .NET at enterprise market.

However, people seem to forget that PHP is hot and popular not because of its 'enterprise' level features, but the features like easy to use, easy to learn, flexible, simple, and fast for web development. Without these, PHP could never be as popular as today. It is quite natural that since PHP is used by more and developers and companies and getting more attention than before, it needs to turn to something not just a 'toy' programming language.

People are talking about PHP is becoming increasely similar with JAVA. But I think it is more and more like C++, which keeps all features of a procedure language while allows you to program in OO style as well.

It doesn't mean procedure programming is bad. Actually, many excellent software are developed in this way. If an application is robust, scalable, secure, efficient and less bugs mostly depends on the developers, the code quality, not those things like framework, OOP, etc.

Probably many PHP developers are coming from PHP 4. When they migrate to PHP 5, it looks like they are doing OOP, but actually they think in procedure way. These developers features with long, long, ugly codes in one function. Even a framework is chosed and design is done very well, the chance that you may still producing a buggy and hard to maintain application.