czwartek, 24 września 2009

Stay away from these rocks we'd be a walking disaster

Some time ago my friend wrote a post about open - close principle - Open – Close principle / Object – Orientated Design in PHP. I hate to say that but there is something fundamentally wrong about the example in this post. I thought about it for a while and here are my thoughts on it.

Open - close principle doesn't encourage particular design - e.g. it doesn't say that it should be achieved through inheritance. Unfortunately, when you're into OOP, sometimes classes and inheritance and all that stuff cover the real solution. Imho, in example provided Image content type should not be hard-coded in particular classes. For me, content type is just a resource. For example, if you want to implement different language versions, you do it using resources, not through inheritance. You don't implement abstract Caption class and then EnglishCaption, FrenchCaption or PolishCaption. The same goes with content type of an image.
If you create base classes and mark methods as virtual (or you don't mark them as virtual because they are virtual by default like in Java), the point of doing it is to implement different behavior in particular classes. If you do it just to return different string and you don't implement any different logic, then maybe there is something wrong with the design.

Ok, that's the most important problem with the given example, but there also some more:
  • abstract class is called AnImage, ImageBase or sth similar would be far better
  • in every SendFileHeader in every derived class you are forced to write header("some type"), GetContentType as an abstract method and implementing SendFileHeader in abstract class as header(GetContentType()) would allow avoiding logic duplication
  • and there is that SendToBrowserFunction that was better before the refactoring than after the refactoring, I'll describe it in more details below

Before the refactoring SendToBrowser looked like this:
public function SendToBrowser()
{
$strFileExtention = $this->GetFileExtention();
switch ( $strFileExtention )
{
case ‘gif’ :
header("Content-type: image/gif");
break;
case ‘jpg’ :
header("Content-type: image/jpg");
break;
}
$strFileContent = file_get_contents($this->fPath);
echo $strFileContent;
die();
}

and after the refactoring it looks like this:
public function SendToBrowser()
{
$this->SendFileHeader();
$strFileContent = file_get_contents($this->fPath);
echo $strFileContent;
die();
}

Before and after refactoring it has this nasty echo and even worse die. Yep, there is also that header function, but I guess changing these methods would be scheduled for further refactoring, because the author writes:
Our first implementation of Image class did not follow one other object orientated design principle. The Single Responsibility Principle.

Ok, let's get back to that switch that didn't follow open - close principle. Am I wrong or the switch logic looks for me like:
header("Content-type: image/" . $this->GetFileExtention());

What is more, the author states:
Why this class breaks the open-closed rule? If we need to send PNG image, we would need to change behaviour of SendToBrowser method and add new case to our switch statement.

Well, if we got rid of switch statement, the above code would also work for PNG. And if we came up to the conclusion that it doesn't work for some particular extension, I still think it should be implemented as a resource (some config file), not using inheritance.
Furthermore, GetFileExtension should be moved to File class, not completely removed.

I would also like to share some general thoughts. Imho, interfaces provide much better decoupling than abstract classes, especially in languages where you can inherit only one base class. Creating abstract class is more risky than creating interface. Also, too many abstract methods in abstract class lead to derived classes that have empty implementation of these methods. Creating interfaces is easier and more flexible.
Interfaces are also essential to loose coupling and technology that has been a real buzzword for some time now - dependency injection.

Eventually, I want to say that this post is not criticism of the author of the Image example. I'm quite sure that he understands open - close principle really well, but he just chose a wrong example. Or maybe I'm totally wrong and the cure is worse than evil? If so Hit me! Come on, hit me!

niedziela, 6 września 2009

Programming - It's hard

I've just finished Martin Fowler's Refactoring: Improving the Design of Existing Code.
Great book with even better examples. That's the best one:
double getSpeed() {
switch (_type) {
case EUROPEAN:
return getBaseSpeed();
case AFRICAN:
return getBaseSpeed() - getLoadFactor() * _numberOfCoconuts;
case NORWEGIAN_BLUE:
return (_isNailed) ? 0 : getBaseSpeed(_voltage);
}
throw new RuntimeException ("Should be unreachable");
}

Imho, this book shows the most important thing about code that I have learnt during three years of working as a full-time programmer - quality of code DOES matter.
Heck, it matters a lot.
For me, the real revolution started after reading Ron Jeffries' Extreme Programming Adventures in C# or some time around it. I don't clearly remember if I was first into XP techniques and then read that book or whether I became a fiend of it after reading the book.
Clean, object oriented, readable code is my definition of pretty code.
When I read something like...
Use short names (like i, x) for variables with a short, local scope or ubiquitous names. Use medium length for member names. Use longer names only for global scope (like distant or OS interfaces). Generally: the tighter the scope, the shorter the name. Long, descriptive names may help the first time reader but hinder him every time thereafter.

... I just cannot understand how variable name "x" can do anything good. I really don't like variable names like i, x, var1, result11. They clearly show that someone wasn't thinking about the purpose of a variable. Imho, when you create a loop, call a variable index if it's index or at least idx. If you do that and begin to think about every variable name, you will improve your code. If you can't find appropriate name, maybe you should substitute it with a method call or change the way of thinking about solving a given problem.
The excerpt I quoted is from Seven Pillars of Pretty Code by Christopher Seiwald. I can't fight the feeling that the author tries to find a complicated solution instead of naming things appropriately and extracting functions. When I look at jam.c example, I can find many adjectives describing that code, but adjective pretty just can't come up to my mind.
The article by Christopher Seiwald is more than ten years old and it's not my aim to criticize the author. Maybe this article shows the way people were thinking about source code 10 or 15 years ago. I just wanted to show another view on code structure and other conventions that people follow.
In my opinion, source code should show programmer's intention. And here is another great example by Eric Lippert C# Round up.

Ok, but let's get back to refactoring. Martin Fowler says that before you start to refactor, you should have good unit tests. I cannot disagree with him, but I often find writing good unit tests really hard. Most systems I'm working with have architecture that makes unit testing a real pain. What is more, I often look at source code, and I see that it is properly designed and I can understand the author. The real reason is that unit testing is very very very hard and requires lots of experience. Here's a nice example - unit tests for Microsoft Enterprise Library (link).
Data — 56 tests will fail if you do not have Oracle installed. If you do happen to have oracle installed, you’ll need to manually open the Data\Tests\TestConfigurationContext.cs file and change your oracle connection settings.
Logging — EmailSinkFixture.LogMessageToEmail will fail, since you do not have access to our internal mail server. You can fix this by changing Logging\Tests\EnterpriseLibrary.LoggingDistributor.config on line 22 to reference different smtpServers and to and from addresses.
Security.ActiveDirectory — Tests will fail because you cannot access our Active Directory server. There are instructions about how to set up ADAM in Security.ActiveDirectory.Configuration.ADAM Setup. You’ll also need to change line 53 in Security.ActiveDirectory.Tests.TestConfigurationContext to reflect your ADAM setup.
EnterpriseLibrary — It is normal for several of the tests to occasionally fail. There are a few unit tests that are timing-dependent, especially in Caching and Configuration. These tests are testing whether or not something happens during a particular time interval, and sometimes the system delays the actions too long and those tests fail. If you rerun the test, it should work the next time. Additionally, our tests write to the event log, which occasionally fills up. If you begin to see a number of tests failing, check that your application event log is not full.

That's a nice suite of unit tests. Some DO fail, some don't. Run them if you like it...
Ok, it sounds like I'm making fun of Microsoft guys, but the point is that I also can't write good unit tests. The biggest problem I have is isolation of datasources, such as database of some kind or directory service.
Maybe using some kind of IoC would solve the problem, but it would require redefining the project design just because I want to write unit tests.
Currently, I'm refactoring without unit tests. I don't have confidence that I don't introduce new bugs or break existing functionalities. Sad but true. I cannot isolate directory service to some interface (without big changes in design) and I also don't have time to create and maintain domain controllers just for the sake of running unit tests on build server.
I hoped that I could find some unit test examples on Directory Programming .NET (especially here: http://directoryprogramming.net/files/3/csharp/entry24.aspx) but there are no interesting examples. Maybe because it's an example of CRUD and it would require integration tests, not unit tests.

When I started programming I thought it was simple. When I started working as a programmer and met real-life applications, it became clear that I didn't know anything about programming. Then there was some time when I thought that I learnt a lot and I really knew a lot about writing code and design, not about every possible technology, but I thought that technologies are similar.
Today, I feel that I have so much to learn and I see so many things that I should improve. I feel a bit overwhelmed, but, first of all, I feel excited and eager to learn all that stuff. Maybe "Programming - It's hard" should be changed to something as kitschy as "Programming - A quest for perfect code" ;)

Tomorrow I'm going on a two-week vacation. It's been a while since I last had a vacation and it could be hard not to think about programming at all (what bad could possibly happen?). Especially, when I'll be reading Pragmatic Programmer, The: From Journeyman to Master (talking about kitschy titles...) ;)

czwartek, 3 września 2009

Don't add uninitialised data or check if it is not in md_rand...

Recently I blogged about static code analysis. I am learning more about it and when I have some more experience with nDepend I'll share some knowledge on this blog.
More than a year ago there was THAT story about random number generator in debian. Well, it was pretty funny and pretty serious. For me mostly funny ;)



And this is the famous revision: diff.
In comments the developer claims that Purify made him do it ;) I'm not saying that this is the effect of code analysis, it's just a funny story. Still...
The funniest part for me is that this bug existed for about two years before it was spotted.

For your consideration ;)

piątek, 21 sierpnia 2009

PHP MVC vs. C# ASP.NET or the cure is worse than the evil

I started programming using C++.
Then I was writing stuff in C, C++, Pascal, Java, C#.
When I wanted to get my first job I figured out that most students work as PHP programmers, so I borrowed a book about PHP, wrote a sample application and a month later I was a PHP programmer.
I must say that in the beginning I hated every single bit of PHP. I've never written an app that I din't have to compile in order to run it. These crazy PHP constructs such as $$. Wow, they're really crazy.
What is more, I have never written a web application before. I always wrote some console / desktop stuff.
However, after about 3 months of coding on a daily basis I was pretty comfortable with almost everything I was doing. Maybe not with PHP itself, to be honest - I have never become comfortable with this language, but whole MVC pattern and its connection with web interface is so intuitive and natural that it really became my world. I still think that navigation on web pages is far better than navigation in desktop applications. When everything is identified by URL and I can open every link in another tab, I feel comfortable with interface. When I have lots of buttons and no tabs to open, I feel crippled with interface.
When I see a link like /article/show/123 or /article/edit/123 and I have Article controller and methods like show or edit, I can just sit and write code I need. I just love that HTTP protocol is stateless. I love the fact that anyone who clicks the link, be it a real user or google crawler, sees (almost) the same content.
PHP also has great template frameworks, such as Smarty. It's very intuitive and readable. The most important this is that THAT guys ;) don't have problems working with it and can easily can change the markup without affecting application logic.
Even though PHP frameworks like Cake and basically all MVC frameworks are very intuitive (in fact we were using our own MVC framework), language that drives them is really crappy. I've seen lots of PHP code, even very good PHP, and I've never seen good object-oriented patterns. Yes, there were lots of classes, but concepts such as inheritance, static objects, interfaces or abstract classes are not a part of this world. Classes in php are quite important but they are not strongly related to each other. When I think of real OO classes, I think about inheritance, interfaces that they implement, I see that some of them are more specialized, while others represent some general ideas. PHP OO in my opinion is poor man's OO. The real power in php are its associative arrays.
If I ranted about PHP flaws in its implementation of OO and wouldn't say that I was a strong advocate of not using most of its features in PHP5, I would be very unfair with people developing this language. I was always a strong opponent of using private / public keywords. The main reason was that every time someone messed up with it, we got white page of death on production server. I consider private / public modifiers to be important while compiling the code, but they become completely unimportant during runtime. Even if you declare field to be private, you can still access it using reflection of some kind. In php, when you don't declare types of method arguments, concepts such as interfaces also don't mean anything. PHP function takes basically anything and then tries to execute some methods on it. You don't have to declare interface to be able to execute some particular method on a given object. Well, you just try to execute it.
I worked with php programmers who actually used to think about types of objects they passed to functions. All interface / abstract stuff WAS implemented in the logic but not in terms of keywords. It was convention over configuration, and it worked pretty well.
Unfortunately, when someone didn't want to keep the convention, we just couldn't force them to keep it. And hell yeah, I wanted all people using my code to pass only some particular interfaces as arguments. I was unable to do that.
To sum up, I think that PHP is crappy, but it has great MVC frameworks, nice templating systems and if you want, you can write really good code in it.

On the other hand, there are C# and ASP.NET. I must say that I just love C# 3.0. It has so many useful features, great attributes, lambda expressions, generics. Some things could be better in C# 4.0, but even now it is my language of choice. C# lets you write clean and descriptive code that you would not be able to write in PHP.
However, here comes ASP.NET. I'm not talking about ASP.NET MVC - I have no experience with it, I'm talking particularly about classic ASP.NET. Well, ASP.NET is such a poor abstraction that I still cannot understand how someone came up with this idea. The whole concept of WebForms is really far from what web is really about. How could they come up with a lifecycle like that: page lifecycle (click to see the picture). Honestly, how could anyone make such an unintuitive life cycle and say that it is easier for web programming because it's like WinForms programming?
Most ASP.NET developers think that ViewState and Session are perfectly good places for keeping variables responsible for page navigation. Yeah, it's so great when you click on a page and URL doesn't change. It's so easy to share content with other users. Crawlers also love it! And what is really cool, sometimes you have to debug your application to see what are your current arguments and then you may find out that e.g. you forgot to clear Session in some onclick event.
And the whole gridview thing. That's a neat idea. Take everything from any datasource you have (e.g. 10 million records from a database) and do all things like filtering, sorting, paging, etc. yourself! Furthermore, keep all data in ViewState.
Seriously, how could anyone come up with that?
Everybody knows that webpage is like a real desktop application and all actions should be seen as events, e.g. click. Everyone agrees? Great.
Templating engine? We will show how hard could that be. Even tags are messed up: inline tags.
Crossbrowser issues? Only in asp.net. Yeah, there are lots of controls that work in IE, but don't work in FireFox.
Someday, I will come back to asp.net issue. In this post I just wanted to show how crappy it is. In my opinion, when you write web apps in php, ruby or python, you feel that you're writing for the web. When you use ASP.NET, you're writing these stupid webforms.
To sum up, C# - great, ASP.NET - yuck.

And here comes the final conclusion.
If I had to write a web application that goes public (not some intranet application) I would choose...


... PHP + MVC. I'm really sure that the result would be far better using that technology.

If I had to choose a job and I could choose between using these two technologies I would choose...


... C# + ASP.NET. It's better paid and you have chances that you'll be writing some underlying layer in C# and you don't have to deal with ASP.NET.

I must check this ASP.NET MVC stuff. I hope it will solve all issues of classic ASP.NET.
Remember kids, choose the right tools for the job and keep in mind that all that glitters is not gold ;)
Q.E.D., Bitches!

środa, 19 sierpnia 2009

Prisoner of ice

All software companies talk about quality of their products. Quality is such a buzzword - sometimes I think that it doesn't mean anything at all.
However, quality means a lot to developers. Many developers that I know really care about products that they create, often against their managers and their companies. I understand when managers decide that they cannot spend more on some particular product, but I cannot understand a situation when a company makes developers work on some unimportant documents instead of making them focus on their work and implement the real thing.
I often encounter a situation when best developers in the team are assigned to create some specs in the early stages of development (often they have to analyze problems that they don't fully understand before the implementation), and people who are responsible for the actual implementation are unexperienced folks that have to learn how to solve problems during the project.
During the development everybody is in such a hurry that all tools and practices that are necesarry to create quality product are abandoned. This means no unit tests, no code reviews, etc. The project just flows. Because people who are developing it don't have any experience, they cannot solve even simple problems, they make obvious mistakes, copy code and everything becomes an awful mess. The project runs behind the schedule and, what is more important, it doesn't ensure any quality at all. After struggling with deployment, the product goes public and bugtracker is filled with bugs.
Unfortunately, because the budget was exceed, all funds are cut and people working on the project don't think about ways to heal it, but they start reading the specs, trying to persuade the client that the project meets specification requirements.
In this stage we can hear a bunch of silly questions, such as:
Do we have to log errors?
Do we have to support firefox?
Do we have to show error messages to users?
Do we have to validate input?

Well, the specs don't say anything about it. What's the conclusion? The project is just perfect. The only problem is that it just doesn't work.
After wasting lots of time on trying to vainly persuade the customer that it's not a bug, but it's a feature - the company faces the fact that they have to solve these problems. Unfortunately, as I've said before, they don't have any funds left. What is more, they discover that time spent on fixing the product generates loss, but if the developer does nothing or does not report his time on this particular product, no loss is generated. Now, the biggest issue is reporting the time spent on fixing the product. On paper it is better to sit and do nothing than to fix the damn thing.
It's like putting handcuffs on developers' hands. You just can't do anything. You know how to fix it, you have the idea, you know what you need, but you can't do it because, magically, the moment you report your time on the project, you start generating loss.
And the so story goes...

In my opinion, these problems are encountered in companies that are focused only on making money and they forget that they are making software. In the end, developers have to think about the budget and all that stuff around cost management, not about making great software. As the result, software is crappy and the income is far smaller than it was initially expected.
I have no experience running any company and maybe I am totally wrong, but I can tell bad software when I see one. And when I see developers that are prisoners of their projects, managers and procedures, I wish all project managers would be like Ron Jeffries or Joel Spoolsky. I wish developers could create applications that delight customers, create code that speak for them, have specifications consisting of test cases and work with the best programming teams in the world ;).

niedziela, 16 sierpnia 2009

Some nice quotes


  • Never pay more than 20 bucks for a computer game - Guybrush Threepwood

  • Yes, there were some customers reporting problems with their phones, but it seems that most iPhones repaired themselves after plugging them to iTunes - guy at the cell phone store, when I asked him if iPhones break often. I wonder if the same thing goes with Mac's Xserves...

  • While all those other languages (Lisp and Smalltalk being particularly noteworthy offenders) tried to pretend that operating systems don't exist, and that lists (for Lisp) or objects (for Smalltalk) are the be-all, end-all of getting shit done, Perl did exactly the opposite. Larry said: Unix and string processing are the be-all, end-all of getting shit done. - Steve Yegge http://steve.yegge.googlepages.com/tour-de-babel

sobota, 15 sierpnia 2009

Nobobody wants to be THAT guy

Yesterday Jeff Atwood quoted some excerpts from Michael Braude's post Why I’ll Never Be A ‘Web Guy’ on his blog.
Of course it led to some flame wars about the question whether being a web programmer means to be a bad programmer or stupid programmer or anything else.
I must say that I completely disagree with Michael Braude's post. Especially with the hypothesis that web programmers are worse than desktop programmers. I cannot see the line that is between web and desktop programmers. Are there any big apps that don't connect with webservices or don't get any resources from the web?
Well, maybe I misunderstood Michael's post because in one of his comments he says:
I don't consider server-side programming "web programming" because SOA encompasses all mediums. Once you get into writing web services and DAL's you've left the world of aggravation.

So what the hell is he talking about? About creating simple html pages? Writing some javascripts?
In a company where I worked previously there was position called HTML programmer. We were making some jokes about it, because we, backend developers - "the real programmers" - didn't consider html to be a programming language. Due to popularity of XHTML we said the position name should be changed to XHTML programmer, however one of the HTML programmers left the job before the renaming took place and was claimed to be first ex-HTML programmer ;)
I must say that I really liked this distinction. I never had to deal with CSS or divs or anything. I just prepared some basic html (mostly including table layouts ;)) and then the template went to HTML guy and he prepared some decent looking webpage.
I always thought that HTML / javascript guys were not real programmers. They often didn't know how to program but they were never responsible for application logic. I never wanted to be a HTML guy and I never was. However, I would never say that they are better or worse than backend programmers. The reason why they wrote HTML was because they liked it, they chose this job, not because they weren't smart enough - they just had different skills.
I know good and bad html programmers. I think that writing good html and css requires lots of skill and I appreciate their work.
I don't consider c# / php guys smarter than html guys. On the other hand, I do think that being frontend developer is far less demanding that being backend developer. But that's just my opinion. If I say that being windows administrator is far easier than being unix administrator, I am not saying that windows administrators are dumber that unix guys. And if I needed windows administrator I would hire one. I would not hire unix administrator for this position because I think that his previous job was more challenging.
The problem with Michael Braude's post is that he somehow says that html programmers are inferior to backend developers. I am also considering their JOB inferior but I don't consider THEM inferior. Still, that's only my personal view on job market and it also reflects my ambitions and aims in my career as a developer.
The last remark is that people who use easier tools aren't dumber than people using the tools that are harder to maintain. What is more, maybe they choose better technologies and more powerful toys and in this way they are far smarter than people who think are intelligent enough to reinvent the wheel from scratch.