Magdy Medhat's Blog

Experience Shared in a few words

Observer Design Pattern

Posted by Magdy Medhat on 19/09/2016


Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Encapsulate the core components in a Subject abstraction, and the other dependent components in an Observer hierarchy. Observers register themselves with the Subject as they are created. Whenever the Subject changes, it broadcasts to all registered Observers that it has changed, and each Observer queries the Subject for that subset of the Subject’s state that it is responsible for monitoring



  1. Differentiate between independent functionality and the dependent functionality.
  2. Model the independent functionality with a “subject” abstraction.
  3. Model the dependent functionality with an “observer” hierarchy.
  4. The Subject is coupled only to the Observer base class. //abstraction (i.e interface)
  5. The client configures the number and type of Observers.
  6. Observers register themselves with the Subject.
  7. The Subject broadcasts events to all registered Observers.
  8. The Subject may “push” information at the Observers, or, the Observers may “pull” the information they need from the Subject.



The “View” part of the Model-View-Controller Pattern is implemented by observer pattern.


Posted in Object Oriented Design | Leave a Comment »

MVC Design Pattern

Posted by Magdy Medhat on 05/09/2016

Model — Data only. Get methods, set methods, etc. It is isolated — it knows nothing about the View, nor the Controller.

View — UI only. Dumb or “humble”. Only shows what you tell it to, and never performs any transformation or validation logic — e.g., it always forwards input via an event/callback system. It is isolated – it knows nothing about the Model, nor the Controller.

Controller — Sits between Model and View. Does any data transformation (business logic) that is necessary to get the data from the Model to the View. Does most data validation on input that comes back from the View. It “knows” about both the View and the Model.

The essential ingredient in MVC is the Observer pattern. Take that out and all you have left is IPO (Input-Process-Output). The Observer is what maintains encapsulation and keeps MVC strongly object-oriented. Without the Observer, you need setters and “this object here fiddling inside that object there” – decidedly non-OO.


With this definition it becomes much easier to divvy up work between engineers. If someone is a database engineer, they probably don’t know UI. But they can write the Model to great effect, and hey maybe they can stub out a crappy-and-simple View. Maybe it’s simply a text dump of the data, that’s fine. At least the code-level interface is in place. Then the UI developers can come and write the Controller and View. Then when the UX designers change what they want the UI to look like, you can either change the View or write a new one. Or if you want to use different UI technologies — WinForms on XP, WPF on Vista, or Cocoa on MacOS, then just have different View implementations for each. Things like skinning are then easily isolated to the View pillar.

The other useful pattern to employ here is an Inversion of Control (IoC) container/scope object. None of the classes participating in MVC need to know about the specific implementation of each other, just the interface/contract. This makes it trivial to unit test the Controller with faked out View and Model implementations.

For example, let’s say you have a program that reads data from a database and produces a text report. Something a bit more complex than simple SQL statements. Now, imagine what would happen if your data source was changed. What if the database was completely refactored? How much of your program would you have to change? If you kept your data (model) separate from your business logic (code), the damage would be very limited.

What if you were told that you’d now have to produce not just the report, but an XML file? Again, if your output (view) was separate from your logic and data, generating the XML output should be very straight forward.

What MVC tells you is that your data, logic, and how you present the two to the user should not be tied so tightly together that changing one means changing everything else in your program.

Remember, MVC is just a good idea, and not the law. My criteria is: Does following whatever model help clarify what you’re programming and makes it easier to maintain? If not, I’ll break that particular model — whether OOP or MVC. The whole purpose of a model should be to make your program better, easier to understand, and easier to maintain.

Then again, you shouldn’t break a model just because you’re in a hurry or lazy. Whatever programming you’re doing has to be maintainable. One day, you’ll have to modify the logic, change the way the data is handled, or change the way it is presented.

Posted in Object Oriented Design | Leave a Comment »

Singleton Design Pattern

Posted by Magdy Medhat on 01/09/2016


Ensure a class has only one instance, and provide a global point of access to it. Encapsulated “just-in-time initialization” or “initialization on first use”. Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.


  1. Define a private static attribute in the “single instance” class.
  2. Define a public static accessor function in the class.
  3. Do “lazy initialization” (creation on first use) in the accessor function.
  4. Define all constructors to be protected or private.
  5. Clients may only use the accessor function to manipulate the Singleton.



The answer to the global data question is not, “Make it a Singleton.” The answer is, “Why in the hell are you using global data?”

The Singleton pattern can be extended to support access to an application-specific number of instances

Posted in Object Oriented Design | Leave a Comment »

Object oriented Design and principles

Posted by Magdy Medhat on 19/08/2016


Posted in Object Oriented Design | Leave a Comment »

How to Access a SQL Server Instance from LAN

Posted by Magdy Medhat on 11/12/2015


I came across that frustrating problem, and finally found the solution, if you want to access a SQL Server Instance from a remote machine in your Network, you’d probably need to go through these steps:

  1. Disable Windows Firewall or open the correct TCP port 1433.
  2. From SQL Server Configuration Manager make sure you enabled the TCP/IP Client Protocol.
  3. From SQL Server Management Studio, right click on SQL Server Instance, properties, connection tab. Make sure you make the number of allowed connections set to zero and that you allow remote server connections.
  4. Finally go to local services on your server and find a service called “SQL Server Browser”, right click, properties and make it start automatically.
  5. Restart your server and you are good to go !

Posted in Web Development | Leave a Comment »

Git Quick tutorial

Posted by Magdy Medhat on 18/11/2015

1) Choose online private/public codebase: bitbucket or github.
2) install Git for windows
3) Generate an SSH key pair using: ssh-keygen -t rsa -b 4096 -C “your_email_here”
4) Enter passphrase //password to hash the private key locally.
5) open the directory where ssh keys are stored: ~/.ssh/ and copy the content.
6) go into bitbucket or github account settings and add the public key in the SSH section.
7) open the terminal in your desired project root then use: git init
8) look online for how to setup your .gitignore file correctly based on your project technologies.
9) add current files to git using: “git add .”
10) now to commit current version use: git commit -a -m “your comment here”
11) note that commit does not add new files, only modified ones, you need to add new files manually first.
12) Now to push to the online repository server use: git push ssh://
13) Note that a cloned project remembers where it came from.
14) To bring changes down and merge them in, use: git pull
15) when moving between branches you sometimes need to keep your changes in a safe place, use: git stash
16) to retreive your changes, use: git stash apply

Posted in Web Development | Tagged: , | Leave a Comment »

Composer and Packagist

Posted by Magdy Medhat on 08/10/2015

What is Composer ?!
A tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. It manages the dependency with “packages” or libraries in a per-project basis, installing them in a directory (e.g. vendor) inside your project. Imagine a strong tool like composer installs the packages you need and the packages that these packages depend on and so on, all automatically ! the powerful feature of the composer actually is  the auto-loading, that means you can start using your packages inside your code instantly, leaving everything else to composer. You can download it from here.

What is Packagist ?!
It’s the PHP Package repository , you go there search for what you want and you will get instructions how to use it with composer. you can access it from here.

How it works?!
after installing composer on your machine, steps are easy, for example lets install laravel framework and phpspecs for testing:
1) create a new folder and navigate inside it using cmd.
2) call the composer command: “composer create-project laravel/laravel folderName”  //it will download.
3) call the composer command: “composer require phpspec/phpspec”  //it will download.
4) when porting your project anywhere, you simply take the “composer.json” and “composer.lock”  files and call the command: “composer install”

Note that:
inside the project folder you will see:
– composer.json //look at it as a configuration file.
– composer.lock //this file is useful for development when you lock the versions of your dependencies  in order not to break your project dependency.
– dependency packages are installed at the “vendor” folder.
– inside the “vendor” folder there’s a bin folder for any executable files.

Finally, its important to note that this idea is not new and Composer is strongly inspired by node’s npm and ruby’s bundler.

Posted in php, Web Development | Leave a Comment »

Complexity Analysis and Time Limit

Posted by Magdy Medhat on 22/02/2015

Time complexity of the chosen algorithm will directly affect the time to solve the problem for a particular n.
We always consider worst case condition in the question that means if range of n is from 1 to 1 million, then we will design our algorithm considering n=1 million (worst case).
In programming problems time limit is given in seconds. Now the question is how to map time complexity to seconds ?!
The exact time taken by the problem depends on the speed of server, architecture of server, OS and certainly on the complexity of the algorithm.
For example: SPOJ uses two kinds of servers mentioned in this link Sphere Online Judge (SPOJ)  .
Most of the online judges don’t use latest machines for judging so that minor differences can be judged accurately.

To give a very rough idea consider that every 1 to 100 million instructions will be executed in a second. (That’s a range of 10^6 to 10^8):
max value of n                        time complexity
10^9                                          O(log n)
10^6                                          O(n)
10^5                                          O(n log n)
10^3                                          O(n^2)
10^2                                          O(n^3)

In case time limit is x seconds then the algorithm’s worst case acceptable complexity will be multiplied by a factor of x. of course these approximations are not precise and they vary depending on the specific task. But they are enough to consider running your Algorithm in the required time limit.

This Cheat sheet covers most of the important Algorithms time complexity.

Posted in Problems Solving | Tagged: , | Leave a Comment »

Print all elements modulo (10^9+7)

Posted by Magdy Medhat on 22/02/2015

Well what’s special about (10^9 + 7) or 1000000007 ?
simply it is a prime number. First I will answer why modulo is used then I will come to why prime is used.

1) Why is modulo operation used ?:
Because  it prevents overflow and enables the problem setter to frame his  problem for bigger ranges and hence demand a clever algorithm. And why  it is useful will be clear from the example that follows: Suppose you  are required to find nCr for n and r as high as 10^5. You know  this number is going to be really big and no primitive data type can  contain such a big number. Going for libraries handling big numbers will  mean compromising with the algorithm as the operations like addition,  multiplication no longer remain  O(1) operations. So what to do in these  cases, simply ask for the result modulo some number.

2) Why is prime used ?
It’s because many operations become easier when you do them modulo some prime. To make things clear: How would you calculate [(a/b) mod m] when you know a%m and b%m. Note that this will be required in the example I gave above(finding nCr as nCR = n!/(r!)*((n-r)!)). You cannot do it unless m is a prime number.

I would recommend trying to solve this problem: Robot Movings to understand why modulo some prime is used.

Now  coming to the part on why 1000000007 ? I would say it is a big enough  prime and conventionally it has been used so the use continues. You can  refer to this: What’s significant about the number choice 1000000007? for further explanation.

Posted in Problems Solving | Leave a Comment »

Classes forward Declaration and header files dependency

Posted by Magdy Medhat on 24/02/2014

In some object-oriented languages like C++, it is sometimes necessary to forward-declare classes. This is done in situations when it is necessary to know that the name of the class is a type, but where it is unnecessary to know the structure.

In C++, classes and structs can be forward-declared like this:

class MyClass;
struct MyStruct;

In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about). This is especially useful inside class definitions, e.g. if a class contains a member that is a pointer to another class; to avoid circular references (i.e. that class might also contain a member that is a pointer to this class), we simply forward-declare the classes instead.

Forward declaration of a class is not sufficient if you need to use the actual class type, for example, if you have a member whose type is that class directly (not a pointer), or if you need to use it as a base class, or if you need to use the methods of the class in a method.

theoretically speaking, all the .cpp files include .h header files by simply replacing the include directive by the actual content of the header file, that means the only factor here is the correct order of your includes.

The best practice for a good project dependency management is not having a header file to include another header file. your includes go in the .cpp files (with respect to their order e.g: if a header file requires another header file both should be included in the .cpp according to that dependency!).

by following this practice .. you will never suffer from circular dependency or redundancy in your includes, you won’t need any forward declarations  and you will only worry about how your .cpps are including the correct order if your header files !

Posted in C++ Development | Leave a Comment »