writing readable clean code

How many times did you worked with a codebase which you did not write?
How many times you was working on a codebase and a new hired developer did not able to work on the same codebase with you?! (and you’ve got that comment “who’s the hell did wrote that code?! and it was you…it’s very annoying situation”)

Writing a nice readable clean code has no manual which you can follow. It’s just best practices and guidelines and here’s some points i’ve faced while my career path which may help.

Functions and procedures:
Function names should be descriptive as you can understand what it’s doing even by reading its name. Function name should not be long and it’s preferred to start by a verb. For example using the following function is a bad practice “check_valid_membership_data_for_user” you may use such name “validate_membership“.

If you’re working with classes do not use the class name within your functions names (function for sure it belong the its class so no need to replicate such info).
For example if you have a “User” class creating a function with the following name is a bad experience “get_user_payments” but the best name for such function is “get_payments” as you’ll user it as follows within your code “$user->get_payments“.

Camel-case or underscored! yeah it’s one of the annoying experiences to have camel-case underscored mixed code. If you’re working within a team you’ve to agree on which type of naming conventions you need to work with. I’ve face such case lately while working with Peter. He suggested using underscores while naming our method and variables. At the first I saw that it’s useless to do so (as I love the came-cased methods). After some point of time I was reading a class which we’ve applied such convention and then compared it with and old version of code. I smiled and said yup you was right Peter(he won the land this time :D).

Naming convention for variables and properties:
Well, who doesn’t use variable in his code, the answer is no one but who is writing non-readable or even understandable variable names, then the answer is everyone. When you ask a developer why you did so he’ll surly say “Man I got stuck with a new release and had a very long backlog how come to care about a useless variable name. That may consume lot of time” (actually I was one of those fools who do so). BTW it’s not useless to care about variable names and yup it deserves to invest a minute to think about a descriptive name. I’ve read some old articles that agreed if you’re working as an individual or a freelance developer it’s useless to care about naming conventions. I can see that it’s wrong. If you look back to see your old code you’ve written 2 months ago you’ll never remember why the hell you’ve wrote such variable name. So it deserves taking a minute to think about it.
Managing dependencies:
One of the most things that annoys me is working with lost of dependencies within a project without having a dependency manager that handles such annoying tasks of updating and getting the chain of dependencies. For example: using bootstrap within your frontend code. If you’ve downloaded bootstrap manually you’ll end up downloading jquery too. And the later boostrap versions cares about the minimum version of bootstrap. And here we go, we’ve to get the proper jquery version. That was a simple example. If you’re working with a complicated dependency that have a long chain of other dependencies this will be very annoying to care about each version. Using dependency managers like bower (in frontend) and composer (for backend) will help you to have free nightmares sleep.

Loops and control structures:
loops, if statements and loops and even more if statements, ugf I cannot read such code, whose the asshole who wrote that shittttttt!. Lots of us faced such problem when reading not well written code. Using loops and control structures is a mixed blessing. And to avoid being an asshole. You have to care not to have lots and lots of nested loops and control flow items within your code. Suppose having such code

			case 1:

This is bad experience to have such code. Having 3 nested indentations is enough to have a readable code. So please do not write that shitty eye-bleeding code that have lots and lots of nested blocks.

The previous notes are not rules that have to be followed when writing code, they’re just best practices i’ve came up with. You build up better rules for better code. Just set your own rules and follow them.


How to build a queuing server

Today i’ll gonna talk about queuing server and how you can you it to optimize processing you big data.
First i would like to start with defining the queuing process itself. queuing is putting jobs or processes in a queue and execute it when its ready for executing (depending upon its position in the queue). You may use for the jobs that takes long time processing (and may even fail).
I’ll explain it more deeply with an example of building a mail queue server.

You may do some processing before sending an email for user. generating statistics, pdfs or any other thing. example for emails that may take a long time processing is the weekly digest mail. And you can’t image how this could be a big load with a big data.

you may have a db table as a datastore for your mail queue. Table fields may be as following: “mail_to”, “mail_content”, “type”, “status”, “failure_info”. whenever you want to send a new mail just insert that table.
you start creating a command (job) that will keep track with the not sent mails (getting rows with status=0). After you get the mail you can start processing this mail (generating statistics, pdfs or whatever). Then try to send the mail. If it’s done set “status” to sent if not set the status to failed and update the “failure_info” attribute.

For the sake of good architecture of your code, you may use the processor design pattern to manage processing for each mail type.

here’s a simple link that can demonstrate the processor pattern http://www.openloop.com/softwareEngineering/patterns/designPattern/dPattern_CommandProcessor.htm

i’ve drew a simple chart that may simplify the whole idea.

queuing server

queuing server

Hope i’ve helped you with this blog. If you have any questions just drop me a comment or ding me if you have my social account or mail.

Thanks 🙂

The missing art of exception handling

First I would like to start by a quote I’ve learnt from Dr.yasser farouk (one of the doctor I’m proud to learned from) ‘as a developer it’s a shame to let the OS throw your code out of CPU because of division by zero or array out of bounds’

He was right about that and it’s also a good behavior and makes It easy for the developer to eliminate bugs. For example: you’re trying to persist a user object in database which has no ’email’ property set(which is required by your class responsible for db operations). This will throw an exception says that ’email’ property should not be null and then you should have an if statement to check if the required properties are not nulls (which is a really big hassle for an object with 20 property for example).

For me as a web developer (who writes in php) exception handling saves me a lot of time spent of dangling if else to check every single case. Using exception handling makes it easy as putting the code which I suspect in a try block such as follows:

try {
$fbdata = $facebook->get($fbToken, $fbId);
} catch (\FacebookApiException $e) {
throw new Exception\AuthenticationFailedException('User exists but Facebook token invalid');

As an architect you should start designing classes to serve your custom exceptions.

As a Symfony2 lover I’ll show you an example how to do it in Symfony by extending the existing exception classes:


namespace Smartizer\EventxBundle\Service\Exception;

class AuthenticationFailedException extends LogicException

as you may notice it’s pretty easy to get started and saves you alot of time spend on checking and dangling if else.

hope you’ve liked my post and start defining your custom exceptions.

Building full stack JS apps

Hi Geeks,

First i’ve a quote which i believe in “Javascript will rule the world!”. Despite being a PHP developer, last months i got stuck loving JS.

Actually last couple of months i was just started using node. As my friend @ma7med_amr was working with me on our graduation project he has used node for managing web based audio/video calls. After that i felt in love with node and also angular. 5 months later i joined eventtus and i knew that they are using mongo as their DB engine. After using mongo i can say that nodeJS, angular and mongo are the best combo for creating full stack js web app.

I can remember also a conversation between me and @shreef about full stack js apps he told me “i’ve looked at lots of github repos and i can say that all those are mess!”. Actually he was right about this. For now, creating a full stack js app is not a good idea. IT’S REALLY A BIG HASSLE to do so. There’s no reliable framework which you can rely on.

here’s i’ll show you in brief how to build up a login/registeration system using node and mongoDB. we’ll do this with some node modules

1- mongoos (for handling db queries).
2- express (for handling http server and routing).
3- ejs (for handling html rendering).
4- connect-flash (for passing flash messages between pages)
5- passport-local (for managing local authentication).

you can find the full project code at https://github.com/AlaaAttya/node-login-registeration

as you may see, lots and lots of packages for just creating a login/registeration system. it’s a new technology that needs more adaption.
it need more and more contribution from the opensource community to create full stacked js framework to make developing such apps more easier and interesting.

Date SQL aggregate functions problem with doctrine and symfony

Hello GEEKs hope you are having a good day,

If you are a symfony developer you may have noticed that you’ll not be able to use sql Date functions (date, year, month, day) with doctrine. You’ll need to write an SQL query to do so and fall in the problem of mapping the results to entity. Actually i hate doing this.

While Googling i’ve found a doctrine extension which does that heavy task smoothly


which you can easily install via composer.json just add ‘”beberlei/DoctrineExtensions”: “dev-master’ to the required dependencies.

to use it you can just you the following snippet

    public function getTodaysUsers($date) {

        $emConfig = $this->getEntityManager()->getConfiguration();
        $emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
        $emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\Query\Mysql\Month');
        $emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\Query\Mysql\Day');

        $qb = $this->createQueryBuilder('e')
                ->where("DAY(e.registeredAt) = :day")
                ->andwhere("MONTH(e.registeredAt) = :month")
                ->andwhere("YEAR(e.registeredAt) = :year");
        $qb->setParameter('year', $date->format('Y'))
       ->setParameter('month',  $date->format('m'))
       ->setParameter('day', $date->format('d'));

        return $qb->getQuery()

It’s an example for finding the today’s registered users. Only you’ll have to place this method to your Entity’s repository and here you are ready to go

Hope you’ve enjoyed,

Thanks 🙂

Hands-On With CE Week’s Hottest Wearable Tech

Template Engines how to start

Hello everyone,

Today i’m gonna show you something which you’ll really love to work with. It’s template engines.
Template engines are libraries which is used to manage large amount of data. Actually creates customized data-structures for the front-end. This picture may clarify the functions of template engines.


When the font-end acquires data, the back-end replies with a row data which need to be formatted in a well organized data-structure and then viewed at the front-end.

It’s the template engine task to do so.

This will show you how the template engine manages data

and there’s the final step, managing the view


There are various template engines like Mustache , Ember js and Knockout js

I prefer to use Knockout. Knock out uses MVVM (Model View View Model).

All you need is to create your view model, add observables to it and apply it.

Observable are used in knockout wherever you want to track properties. Then apply your model view model.
Observables has setters and getters. To set it’s values you need to deal with

ko.observable("Your value goes here");

And the getter is the observable name
for example suppose you need to define an observable for username

function viewModel(){
    this.username = ko.observable("Alaa Attya");//setting username observable value

var vm = new viewModel();

You need to know that each observable tracks a specific data-bind. And data-binds has many types text, value, event,…. you can go and see the documentation.If you wanna create an input text which you wanna track it’s values.

follow this example http://jsfiddle.net/AlaaAttya/PAZ82/1/

That’s the big idea behind the template engines, hope you enjoyed.

Thanks 🙂

Solving PHP5.3 properties access using get_object_vars() method

Hello PHPians 😀

While working on a project i’ve face a bug in php5.3. In PHP4


was returning only public proprties of the object while in php5.3 it’s also returning private properties.
For example if you try to run this code

    class user{
        public $username="alaa";
        private $password="1234";
        function get_user()
	$user_data = new user();

output will be:

  'username' => string 'alaa' (length=4)
  'password' => string '1234' (length=4)

Actually it’s not the end of the story. There’s a class that will got this bug solved. This magical class is called ‘ReflectionObject’ class.

you can use this handy function which takes an object as a parameter and returns and object contains only the public properties.

     * return the public properties only, solving php5.3 bug issue
    function my_get_object_vars($obj) {
        $ref = new ReflectionObject($obj);
        $pros = $ref -> getProperties(ReflectionProperty::IS_PUBLIC);
        $result = array();
        foreach ($pros as $pro) {
            false && $pro = new ReflectionProperty();
            $result[$pro -> getName()] = $pro -> getValue($obj);

        return $result;

now you can modify your class to test the function to be as follows

    class user{
        public $username="alaa";
        private $password="1234";
        function get_user()
     * return the public properties only, solving php5.3 bug issue
    function my_get_object_vars($obj) {
        $ref = new ReflectionObject($obj);
        $pros = $ref -> getProperties(ReflectionProperty::IS_PUBLIC);
        $result = array();
        foreach ($pros as $pro) {
            false && $pro = new ReflectionProperty();
            $result[$pro -> getName()] = $pro -> getValue($obj);

        return $result;

	$user_data = new user();

and auto-magically this will solve your bug 🙂
and here’s the output

  'username' => string 'alaa' (length=4)

Hope you enjoyed, thanks 🙂

2012 in my resolution

I actually i was reading @shreef‘s new blog post Late new year’s resolution and decided to write a blog post like it.

so here’s my 2012’s list and don’t forget your opinions matter specially for me.

1-Started my own freelance work.
2-Being engaged to Codeigniter.
3-Gained more skills in jQuery UI framework.
4-Build new skills for dealing with database.
5-Getting started with Laravel and felt in love with its bundles.
6-Built new social relationships and had the true meaning of inner-peace.
7-Built http://zer0day.info/ for zero day event.
8-won Nokia Smart Asha competition as the best mobile developer.
9-Getting started with Joomla CMS.
10-Gained more skills for building my own REST API.
11-Started using ADO.net & linq for some small projects.
12-Built a mobile web app & 2 asha mobile apps.
13-Got a new big bro. @ahmedhosnycs
14-Built my own gang @ahmedhosnycs , Bojeyy & @RamyBayern 😉

That all i can remember for now 🙂

Joomla how to start with the CMS concept

All of us heard about joomla. So my friends has asked me to write a blog about how to start with Joomla.

Actually joomla is one of the most famous CMSs in the web development world. So here we got the concept of a CMS which is the acronym for Content Management System. CMS is more different from Framework. CMS is a complete system that simplifies the process of changing and editing large contents.
For developers it centralizes the processing and makes their codes more portable. It also enhances re-usability of code.

so let’s talk more about joomla.

Joomla have four main concepts:


-Template is something like a theme for your website.
-Modules is the heart of your website. you can have a login module, registration module…etc. Any Joomla website contains of many modules. Developers can develop any module and you can add it to any joomla website if it’s compatible with your joomla version. It provides code compatibility.

-plugins are some functions which are associated with specific triggers. when an event is fired all function with the same type associated with that plugin are executed.

-Libraries are some codes (or you can say packages) the extends the framework functionality. Libraries are considered the lowest level components specially for developers 😉

-Components are something that is considered a small app.s. To get it, imagine Joomla as a system and components as application running on that system. Components work with the MVC pattern.

Each of the previous will associated with a XML file that describes and identifies it.

In this post it’ll talk only about how to start authoring a Joomla Module.

First of all you must know the structure of a basic module

-The name of your folder must have “mod_” as the prefix of your module name
-a XML file that will hold some meta-data about your module like author name, module name …etc.

it consists of an extension tag which have 3 main attributes

1-method: install
2-version: the version of your Joomla
3-type : module

Then you’ll have some tags that will hold the details like

which is the name of your module
the name of the author (it is supposed to be your name :D)
Your copyright
and many other tags that is so easy to understand.

Then the most important tag is the
which holds any file associated with your module (even the php files)

like that

		<filename module="mod_testmodule">mod_testmodule.php</filename>

-a PHP file that will do all the processing.
The name of this file must also have the prefix “mod_” followed by your module name or it will not be accessible.
This must include that line as the first line before any code is written

defined( '_JEXEC' ) or die;

which means that no one can execute this file through the URL.

-empty index.html file for indexing issues.
-You may have a tmpl folder that will collect the data and generate html code to view the result.

Any basic Joomla module must have at least these requirements.

and here’s a demo module

To install any module package the folder as a .zip file
login as admin. “URL…/administrator/index.php”
Then choose extension tab->new Then browse and add the .zip file
Then you are done !

Hope you enjoyed !

Thanks 🙂