Showing posts with label standards. Show all posts
Showing posts with label standards. Show all posts

Saturday, April 10, 2010

The Apple of sin

I realize that I am biased against Apple as I'm not a fanboi of them and do not buy their products, but this time the situation is really ridicolous. As you may have read in one of the dozens of posts about the issue, Apple has decided that if you want to use the iPhone 4.0 SDK, you cannot choose the language to write your applications in (yes, also the linked posts are biased.)
3.3.1 … Applications must be originally written in Objective-C, C, C++, or JavaScript as executed by the iPhone OS WebKit engine, and only code written in C, C++, and Objective-C may compile and directly link against the Documented APIs (e.g., Applications that link to Documented APIs through an intermediary translation or compatibility layer or tool are prohibited).
It simply does not make sense. Well, it makes sense from their business perspective, but not from the users and developers point of view. Users get less choice for apps, while developers are forced to use a particular environment which they may not be familiar with. Someone said that this is a move to prevent compilation of Flash applications into C (like Facebook has done with HipHop for PHP), a possible solution to get them running on the iPad.
Perception of software development is often confused from many people, so let's extend the metaphor to other fields, showing what would happen if this prohibition would be applied there:
  • you're not allowed to edit images that will be displayed by Apple products with Photoshop (ops, Adobe). You shall use the iPencil instead and scan your drawings in a iJpeg, which is like a normal Jpeg but costs a dollar a piece.
  • you're not allowed to write your PDF files displayed on Apple products with OpenOffice.org and export them in this format. You must use iWork (this one really exists.)
  • you're not allowed to play musical instruments to produce songs that will be stored on the iPod or similar products. You must use GarageBand instead.
And of course, you're not allowed to write your own source code the way you want it, and then compile (ops, this is real.) But my source code is my own business: if I want to write it in Brainfuck, I'll definitely write it in Brainfuck. It's Turing-complete, so Steve where's the problem?
Of course I will continue not buying anything from Apple.

Tuesday, December 22, 2009

Asking the community: a standard for @return array

It would have certainly happened to you to define a phpDocumentor annotation on a function or a method:
<?php
/**
 * @param string $a   name your parameter better than this one
 * @return boolean
 */
function doSomething($a)
{
    // code... 
}
These annotations are parsed by phpDocumentor to automatically produce Api documentation in various formats, such as html and pdf.
It is also true that you can specify a class name as a data type:
<?php
/**
 * @return Zend_Form_Element
 */
function doSomething()
{
    // code... 
}
Since this is a widely employed standard for php frameworks, I decided to rely on @return annotations as the mean to define domain model relationships in my project NakedPhp. This is not different from the relationships phpDocumentor infers to generate links between html documents: for instance the Zend_Form_Element return type definition would be printed as a link to its actual Api documentation html page, to allow fast navigation.
But what happens when you want to specify that a methods return an array or a collection of elements?
<?php
/**
 * @return array
 */
function doSomething()
{
    // code... 
}
Not very clear, as the question that arises is "What is the type of array elements?"
Note that Php is a dynamic language and arrays can be heterogenous, but very often they contain elements of the same type for the sake of consistency; consider for example an array of Zend_Form_Element instances: even if they are different elements they share a common superclass whose methods you can call without fear.
Note also that Php lacks a real collection class or interface, and even if a generic one is provided by a framework, the annotation would not be much clear.
/**
 * @return Doctrine\Common\Collections\Collection
 */
or:
/**
 * @return ArrayObject
 */
At least in the former case you know that there are homogeneous elements in the returned collection, but the situation is the same.
Since arrays and collections are used as dumb containers, the first thing you will do on an array is to iterate on it, and then you will need to know what is the class of the contained elements to find out which methods to call, or which methods accept this kind of elements.
Of course you can do something like this:
/**
 * @return array   of @see Zend_Form_Element
 */
But this is not a standard, and different developers would use different annotations:
/**
 * @return array   this contains Zend_Form_Element instances
 */
/**
 * @return array   of Zend_Form_Element 
 */
These annotations would be parsed by phpDocumentor, but the class name would be mangled in a string and not manageable anymore. It's like scraping a blog versus using a feed.
PHPLint documentation says it recognizes annotations like array[K]E, as in this example:
/**
 * @return array[string]Zend_Form_Element 
 */
They also say that phpDocumentor already support it, but there is no trace of that in its own documentation:
The datatype should be a valid PHP type (int, string, bool, etc), a class name for the type of object returned, or simply "mixed".
The original Naked Objects implementation is written in Java and takes advantage of generics (not available in Php):
/**
 * @return List<FormElement>
 */
When javadoc or Naked Objects parse annotations, they know instantly the collection elements type, thanks to a reasonable standard that imitates the language syntax: I would be glad to do the same in Php, but there is no syntax to refer to.
I turn thus to the community, which comprehends millions of talented developers. My question is: how would you specify @return annotations for containers of elements in a way to include the elements type? I hope to grasp a de facto standard, which I can then require to follow in NakedPhp applications.

Tuesday, November 03, 2009

Anti-patterns

If you work with object-oriented programming languages, you most certainly have come in contact with design patterns, reusable solutions to common problems which are composed by a set of roles that your objects and classes fulfill.
Nothing prevents a programmer from implementing a coupled and ineffective solution, maybe without even knowing it, and just like with the more famous design patterns recognizing what he has built only at completion. These counterproductive solutions can be identified as standard bad practices: they are called anti-patterns. Moreover, while design patterns usually are focused on design and coding, anti-patterns can be observed in many different fields of software engineering such as the organization and management levels.

Let's see an example focused on software design. Suppose you have a small application which a narrow set of features and you are in a rush to implement new ones. In the worst case, these features will be hacked in without respect for the design of the application, whose architecture is not even formally defined or cannot scale while the size increases. What you obtain is a large system composed of highly coupled parts you cannot change, with duplication in business logic spreaded troughout the classes and in which different components break after a change in unrelated ones. This is called a Big ball of mud.
The requirements for an anti-pattern to exist are simple: a repeated behavior that may appear beneficial in the short-term, but causes pain in the long run while a standard good solution exists. In the case of an object-oriented Big ball of mud, the solution is unit testing and dependency injection.
We are most interested in object-oriented and general programming anti-patterns, and they are the subject of this post. Here are listed the most important and (in)famous, and maybe you have already heard their names. You can consult the wikipedia category for more examples. I guess you will recognize also why most of these anti-patterns are considered bad practices.
Object-oriented anti-patterns:
  • Anemic Domain Model: use of a domain model layer where business logic is not incorporated with data, for instance a big group of entities without any method different from a getter or setter.
  • God object: an object from a class that have many responsibilities instead of a single one.
  • Sequential coupling: an object requires the client to call its methods in a particular order.
  • Circular dependency: mutual dependencies between classes, object or packages. A circular dependency makes two or more code entities inseparable, increasing coupling and killing reusability of both. Mutual dependencies should be break with interfaces, like in the Observer pattern.
  • Object orgy: free access to object properties by collaborators, also by setters and getters overusage. Encapsulation should be preferred to prevent changes in a component to affect the other ones.
Design and programming anti-patterns
  • Interface bloat: an interface that has grown so much and has to do so many things that it is too difficult to implement, resulting in only the first and official implementation being available. Small and focused interfaces should be preferred.
  • Magic pushbutton: inserting domain logic in the user interface only. The name derives from writing code in the generated event-handling routines of buttons. This practice should be replaced with delegation to the domain layer.
  • Action at a distance: unexpected interaction between different components. Global state and singletons are typically an example of this anti-pattern, which reveals its Api problems during unit testing.
There are even more anti-patterns than design patterns: it's easy to do something wrong. As I said, I listed the most famous anti-patterns related with design and implementation, but management and methodological anti-patterns have been recognized as well throughout the years (one for all: Silver Bullet).
I think learning from errors is fundamental in every profession, and I considered lucky who can learn from others' mistakes. If we learn what are the wrong choices, we feel confident to apply the best practices of this industry as we can see why they are valid.

Sorry for the late post but it's my ISP fault. Feel free to add anti-patterns that you perceive as diffused in the comments.

Tuesday, September 15, 2009

SOLID part 6 (bonus): how much solid Standard Php Library is?

This is a bonus part for the SOLID principles series. You can check it out to view the articles which explain all the principles or subscribe to the feed to be informed of new posts.

How that we have talked a lot about the five SOLID principles, it's time to apply them to a real project and see the good design ideas they introduce and what trade-offs are accepted in everyday coding. Since I have mainly a php audience, I have chosen the unique object-oriented library that the php core features natively: the Standard Php Library (SPL).

The Iterator interface and its implementations were the first Spl components to be included in php. This interface is very cohesive and it does not assume much about the source where items are coming from: for instance, in every implementation there's no need to write a method that counts the elements, since it is segregated in a Countable standard interface.
Iterator is extended by RecursiveIterator and OuterIterator, which manages respectively an iterator which items have children and a iterator who decorates another. These components adds only one or two methods to the parent interface and are also very cohesive: they are the hook for opening Spl to extensions.
The responsibilities of these classes are evenly distributed: the basic Iterator implementations have proven to be very useful (such as DirectoryIterator which produces the list of files contained in a folder), while other functionalities are kept in their own OuterIterator implementation, like LimitIterator and CachingIterator.
The primary use of Iterator (and of its parent interface Traversable) is in the foreach construct, where it can be passed as it were an array. The standard implementations can be swapped without problems in a foreach, and this means that Liskov Substitution Principle is more or less respected. What comes to mind is that different Iterators will return a different type of items, but php is a dynamic language and this precisation does not strictly affect the application of principle as long as the methods retain the same meaning and intent. To solve it completely the interface should use generics like in Java: Iterator.

Spl provides object-oriented way to access filesystem (SplFileInfo and similar ones), which is not a point of interest in this discussion since these classes are a wrapper to the basic functions such as opendir() and filesize(). The same goes for Exception and its tree of subclasses. The Serializable interface is also a good hook for extension of behavior, but we are not going to overanalyze the library.

What indeed raise attention is the SplObserver and SplSubject interfaces, which suggest a standard way to implement the observer pattern. These components are not useful in my opinion, and a comparison with static typed languages will show the difference.
In a static language like Java, when a parameter is passed to a method which have a determinate signature, only the contract defined by this signature could be used in the body of the method. This is the definition of SplObserver:
public function update(SplSubject $subject);
where SplSubject contains the methods attach(), detach() and notify(). Since the contract is defined from SplSubject interface, if php were a static language we could only call these three methods, which are totally unuseful to get the state of the subject (which can be thinked as some getXXX() methods to call on the subject); only the fact that php is a dynamic language, and does not complain if you call methods which can be unexistent,allows such a method call. Moreover, these interfaces force the developer to adopt a pull-style of Observer pattern even where a push-style would be simpler.
In sum, a design pattern, like the Observer one, is a common solution to a problem and should be implemented every time with different flavours, requiring different classes. SplObserver and SplSubject fail to satisfy the Dependency Inversion Principle since they won't decouple their implementors, that needs to know a large abstraction they leave out.

With the release of php 5.3, it has become clear that the goal of Spl is to provide fast components, implemented in C for particular purposes, and not a well designed object-oriented library. SplQueue is an example of this, along with its companion SplStack:
class SplQueue extends SplDoublyLinkedList implements Iterator, ArrayAccess, Countable { ...
SplDoublyLinkedList is a classic data structure, a general purpose list that is subclassed by SplQueue and SplStack. Since it implements Iterator and other Spl interfaces, their children inherits these features, but in my opinion it's not a good idea.
A queue can be accessed only one element at time; a stack has the same limitations, which are voluntarily imposed to incapsulate the internal data structure and limit the operations that can be done on it by a client class: I would rather have a SplQueue as an interface and not a concrete implementation, with just the enqueue() and dequeue() methods; SplStack as another interface with pop() and push(). SplDoublyLinkedList would be a generic implementation, which satisfies both interfaces.
Why I would prefer this design? Because it places functionalities in two compact interfaces; otherwise Interface Segregation Principle is not applied and no interfaces are even defined. SplQueue can't be a child of a SplDoublyLinkedList as it would be a violation of Liskov Substition Principle: a implementation of a queue can use a double linked list internally, but not inherit methods from it or it is not a queue anymore.
A benefit of a Queue interface would be real decoupling and its consequences: for instance, a mock of Queue can be used in testing to make sure only enqueue() and dequeue() are used, while mocking a SplQueue as it is will expose also all the other Iterator methods as empty ones, leading to strange results (and tying my high level modules to details instead of to a queue abstraction, infringing Dependency Inversion Principle).

I would say that Spl is a good product for the goals which it had been thinked for: a reliable and fast object-oriented layer, which can overload common constructs like count() and foreach; it has been a very successful feature of php. But its design could be vastly improved, also with application of SOLID principles.

The image at the top is an upside down library.
Did you like this series? Leave a comment or subscribe to the feed to stay in touch.

Thursday, September 03, 2009

Coding standards and religion wars

A common tip in the "guidelines for good code" posts is to adopt a coding standard and stick to it. What is a coding standard and why you should adopt one now? Don't be worried about which one.

A coding standard gives a coherent look&feel to your code, promoting predictability. For a software system, predictability is almost always a good feature since a developer cannot hold a picture of all the code in his head, and has to guess what other unit of the systems will do in some situations as they collaborate with the one under development.
This applies on a behavior level, but also on a more physical Api discovering; while the description of the correct behavior resides in specification, tests and mocks, the appearance of the code and the classes and methods it expose is generated by a coding standard. If the names of methods (and their capitalization) are analogue and have the same structure, it becomes easy for a developer to program against it.

Code reading and analysis
Every coding standard forces an organization in the code to make it readable. Indentation, tabs vs spaces, control structures organization are all techniques which maintains order in a codebase, but there is a free choice
As an example, let's talk about the Java methods bracing in contrast with the php one. Java prescribes the developer has to put the opening brace { on the same row of the method signature definition; php coding conventions instead tell the developer to place it on the subsequent row, at the same level of indentation of the signature:
void doSomethingJava() {
// ...
}
public function doSomethingPhp()
{
// ...
}
There is no functional difference in the two cases; compilers and interpreters ignore whitespace, indentation and line breaking. All these rules serve no functional purpose.
The problem they address is style: a book can be beautiful and well-written, but if it's printed in an unreadable font, in pages of different sizes kept together by nylon threads, it will be very difficult to read without exhausting your nerves. The importance of a coding standard does not derive from which one you choose but from the constance in sticking to it, particularly in large or open source projects where many different people patches and rewrites code at the same time.

Subjective rules
Meaningful variable names is a subjective rule, since it cannot be cheked to a great extent from a static analysis tool. However, it is applied to improve the readability of the code, again. The convention on capitalization (CamelCase for instance) is a real coding standard, but the identifier names is more a matter of programming style, as long as you do not call variables $a1 and $a2.

If you are not organizing your source files, adopt a coding standard now. In the php world, Pear coding standard is the most famous one: I use Zend Framework one which is nearly identical to it. However, every project has conventions: if you want to be considered serious, follow a standard.

Thursday, July 23, 2009

Php 5.3 without screwing up apt-get

Php 5.3 is stable and if you want to experience improved performance and lessened memory usage, and also play with nice tools like Doctrine 2 that are built for this version, you have to install on your box. But a .deb is better than 'make install': it does not sends binaries and configuration files all over your system, without a mean to trace where they end up.

Php 5.3 is a new minor version of Php, so it does not break the strict compatibility of your application. Though, it deprecates some old features and practices and it could cause problems, so you shoud cautious about using it in a production environment. That's what staging exists for.
However, if you choose to install it, your better choice is to use a .deb package that could be easily removed when the distributors catch up and provide a php5 package: 'make install' command issued after compiling will spread files all over the filesystem, without let know you what is being overwritten and created. A .deb will also help upgrading with its simple removal procedure.
This example is based on Ubuntu Jaunty (9.04), but probably will work on other versions and Debian-derivated distros.

Step 0: downloading the source
To build a package, the C source code is needed. A tarball for the release is provided from the php team:
wget http://www.php.net/get/php-5.3.0.tar.bz2/from/a/mirror
tar xvjf php-5.3.0.tar.bz2
cd php-5.3.0
Now we have source files at hand.

Step 1: compiling
Compiling is the fragile and longest part, as the compile time can be very long, especially if you use many bundled extensions and your machine is performing other tasks at the same time.
First, the build configuration has to be created.
./configure --disable-short-tags --with-zlib --enable-bcmath --enable-exif --enable-ftp --with-gd --with-jpeg-dir --with-png-dir --enable-mbstring --with-pdo-mysql --with-sqlite --enable-sqlite-utf8 --enable-zip --with-pear
"with" and "enable" commands are listed using --configure --help and will tell you what bundled extensions are available in this release. The more extension you pull in the compilation, the more time it will take, but you do not want not be surprised with undefined function: mysql_connect. With this configuration, it is not included because PDO is used instead.
The ./configure command will fail often, and it probably means that you lack some source files or libraries needed for the extension to compile and to be linked to. They are normally not installed in the average system, so is something is needed you will probably run commands such as:
sudo apt-get install libjpeg
sudo apt-get install libbz2
depending on the extension choosed. To find the name of the library, see the Requirements section on php.net/manual for the extension in question.
When ./configure does not fail anymore, we can start the compilation:
make
This will take time, so you should consider running when you're not at the pc.

Step 2: building a package
When the compiling is finished, a .deb has to be built from the produced binaries. checkinstall is the command line tool that will do the job for us. Of course if you do not have it, sudo apt-get install checkinstall.
sudo checkinstall -D --install=no --fstrans=no --maintainer=piccoloprincipeazzurro@gmail.com --reset-uids=yes --nodoc --pkgname=php5 --pkgversion=5.3 --pkgrelease=200907011400 --arch=x86
We are telling checkinstall to create a Debian package (-D), to not install it for now, do not use a fake filesystem since this is not necessary, to not include the documentation since we aren't going to distribute this package but only to use it at home.
To be useful, checkinstall must be run as root, so we use sudo.
After this command, checkinstall asks you to confirm the options and by pressing Enter your (probably if you're still reading this simple guide) first deb is created.

Note: use php with apache
If you included the directive --with-apxs, to build a mod_php instance, checkinstall (but also make install) will tell you that almost one LoadModule directive has to exist. This happens because the installation process reads /etc/apache2/httpd.conf, that is not used in Ubuntu, so let's fake it. Add the following line:
LoadModule php5_module /usr/lib/apache2/modules/libphp5.so
to /etc/apache2/httpd.conf; create it if it not exists. You will need sudo to write such a file.
After generating the package, you could clean this file and leave it empty as Ubuntu uses the /etc/apache2/mods-enabled/ folder to maintain the LoadModule directives.

Step 3: avoid conflicts
The compilation process has not touched your system yet, but probably there is an old installation of php hanging around that will get in the way. Let's remove all package and extensions: if you need a particular extension you should have included it in Step 1; if you need a PECL or PEAR package you will grab it later, in the new installation.
This will remove any package whose name contains php:
sudo apt-get remove --purge `dpkg -l | grep php | awk '{print $2}';`
You could also delete /usr/share/php, the PEAR folder. A new pear will be installed if you enable it in Step 1 and old files will point the old php binary and it will be a mess. Take them out:
sudo rm /usr/bin/php
sudo rm /usr/bin/pear
sudo rm /usr/share/php
If you have any PEAR packages, the folder was not removed by apt because it was not empty.

Step 4: install your brand new, fine-tuned package
Assuming that your package is named php5_5.3.0-200907181600_i386.deb, install it:
sudo dpkg -i php5_5.3.0-200907181600_i386.deb
You will find it in the source folder.
If you're using php from the command line you have finished. You have the possibility to run pear on php 5.3 and install what you want.
If you use php with apache, you need to set up the loading of mod_php. Put in /etc/apache2/mods-available two files named php5.conf

AddType application/x-httpd-php .php .phtml .php3
AddType application/x-httpd-php-source .phps
and php5.load:
LoadModule php5_module /usr/lib/apache2/modules/libphp5.so
The content could slightly differ, and the files may already be present (from your previous installation).
Then Apache could use php compiled by you:
sudo a2enmod php5
sudo /etc/init.d/apache2 restart
Enabled the module, and restarted the webserver. Have fun with your shiny new php!

Featured post

A map metaphor for architectural diagrams

It is a (two-dimension) representation of a pipe. The map is not the territory , but in software engineering terms they are models of it....

Popular posts