Language Comparision


var colors = “green”;

$colors = “green”;


var colors ;
colors = [‘white’,’black’,’brown’];


var colors = Array(‘white’,’black’,’brown’);


var hotel = {
name: ‘Super8’,
rooms: 40,
booked: 25

checkAvailability = function(){
return this.rooms – this.booked;


var hotelName =;
var roomsFree = hotel.checkAvailability();

What are magic methods, magic quotes, short tags in php?

Magic Methods:

PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions. The magic functions available in PHP are: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __autoload().

Why are they called Magic Methods?
The definition of a magic function is provided by the programmer – meaning you, as the programmer, will actually write the definition. This is important to remember – PHP does not provide the definitions of the magic functions – the programmer must actually write the code that defines what the magic function will do. But, magic functions will never directly be called by the programmer – actually, PHP will call the function ‘behind the scenes’. This is why they are called ‘magic’ functions – because they are never directly called, and they allow the programmer to do some pretty powerful things.

PHP: What are magic methods?

Magic Quotes:
Magic Quotes is a process that automagically escapes incoming data to the PHP script. It’s preferred to code with magic quotes off and to instead escape the data at runtime, as needed.

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Short Tags:
< ?= Hello World ? >
Output is displayed directly to the browser.

– PHP also allows for short open tags which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive
– Can have problems with portability if the server does not allow short tags
– Can interfere with XML documents.

Ajax and XMLHttpRequest

Ajax – an acronym for Asynchronous JavaScript and XML)[1] is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications. With Ajax, Web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not required; JSON is often used instead (see AJAJ), and the requests do not need to be asynchronous.

Technologies involved:
HTML (or XHTML) and CSS for presentation
The Document Object Model (DOM) for dynamic display of and interaction with data
XML for the interchange of data, and XSLT for its manipulation
The XMLHttpRequest object for asynchronous communication
JavaScript to bring these technologies together

XMLHttpRequest (XHR) is an API available to web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests to a web server and load the server response data back into the script. All browsers supports XMLHttpRequest.

typical use:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("demo").innerHTML = xhttp.responseText;
};"GET", "filename", true);

With Jquery :

$('#main-menu a').click(function(event) {
   $.ajax(this.href, {
      success: function(data) {
         $('#main').html($(data).find('#main *'));
         $('#notification-bar').text('The page has been successfully loaded');
      error: function() {
         $('#notification-bar').text('An error occurred');

Sorting Algorithms

1) Merge Sort

– O(n log n) comparison based sorting algorithm (best case, worst case, avg case)
– Produces a stable sort (implementation preserves the input order of equal elements in the sorted output)
– Top Down Implementation and Bottom Up Implementation
– Is more efficient at handling slow-to-access sequential media. Merge sort is often the best choice for sorting a linked list
– Uses more memory (2n locations)
– Can be parallelized

2) Quick Sort
– Avg O(n log n) , Worst Case O(n ^ 2)
– Is comparison based sorting
– In place partioning algorithm and hence uses O(log n) additional space
– Can be parallelized (like mergesort)
– Depending on implementation may or may not be a stable sort
– Low memory required
– Useful in cases where data is in RAM, not useful in cases where data lives on disk (In that case use merge sort)
– usually faster than mergesort
– The worst-case running time for quicksort is O(n2), which is unacceptable for large data sets and can be deliberately triggered given enough knowledge of the implementation, creating a security risk

QuickSort is more popular than Merge Sort because it:

Is in-place (MergeSort requires tons of extra memory).
Has a small hidden constant

3) Heap Sort

– Heapsort is part of the selection sort family. Is a comparison based sorting algo.
– it has the advantage of a more favorable worst-case O(n log n) runtime
– Heapsort is an in-place algorithm, but it is not a stable sort
– Quicksort is typically faster than Heapsort, but the worst-case running time for quicksort is O(n2), which is unacceptable for large data sets and can be deliberately triggered given enough knowledge of the implementation, creating a security risk
– Merge sort requires ?(n) auxiliary space, but heapsort requires only a constant amount.

Merge sort has several advantages over heapsort:
Merge sort on arrays has considerably better data cache performance, often outperforming heapsort on modern desktop computers because merge sort frequently accesses contiguous memory locations (good locality of reference); heapsort references are spread throughout the heap.
Heapsort is not a stable sort; merge sort is stable.
Merge sort parallelizes well and can achieve close to linear speedup with a trivial implementation; heapsort is not an obvious candidate for a parallel algorithm.
4) Intro Sort

Design Patterns

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. A design pattern isn’t a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations.

There are three basic kinds of design patterns:

  • creational
  • structural
  • behavioral

Creational patterns provide instantiation mechanisms, making it easier to create objects in a way that suits the situation.

Structural patterns generally deal with relationships between entities, making it easier for these entities to work together.

Behavioral patterns are used in communications between entities and make it easier and more flexible for these entities to communicate.

References :
====================== CREATIONAL =========================
(Single Factory Builds Prototypes)

Singleton Pattern (Creational) :
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”.

Example: The office of the President of the United States is a Singleton.
Example: Logger Class, Configuration Class

Factory Pattern (Creational) :
– (Similar to Abstract Factory Pattern)
– One of the most used patterns in programming
– Define an interface for creating an object, but let subclasses decide which class to instantiate (usually with the help of a type parameter). Factory Method lets a class defer instantiation to subclasses.Defining a “virtual” constructor.
– creates objects without exposing the instantiation logic to the client. and refers to the newly created object through a common interface

For example a graphical application works with shapes. In our implementation the drawing framework is the client and the shapes are the products. All the shapes are derived from an abstract shape class (or interface). The Shape class defines the draw and move operations which must be implemented by the concrete shapes. Let’s assume a command is selected from the menu to create a new Circle. The framework receives the shape type as a string parameter, it asks the factory to create a new shape sending the parameter received from menu. The factory creates a new circle and returns it to the framework, casted to an abstract shape. Then the framework uses the object as casted to the abstract class without being aware of the concrete object type.

Example: Injection molding presses demonstrate this pattern. Manufacturers of plastic toys process plastic molding powder, and inject the plastic into molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the mold.

Builder Design Pattern (Creational) :
Separate the construction of a complex object from its representation so that the same construction process can create different representations.Parse a complex representation, create one of several targets. It is a mechanism for building complex objects that is independent from the ones that make up the object.

The “director” invokes “builder” services as it interprets the external format. The “builder” creates part of the complex object each time it is called and maintains all intermediate state. When the product is finished, the client retrieves the result from the “builder”.

Example: This pattern is used by fast food restaurants to construct children’s meals. Children’s meals typically consist of a main item, a side item, a drink, and a toy (e.g., a hamburger, fries, Coke, and toy dinosaur). Note that there can be variation in the content of the children’s meal, but the construction process is the same. Whether a customer orders a hamburger, cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a main item, side item, and toy.

The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. That?s why it is important to be able to make the difference between the situations when one or the other is used. In the case of the Abstract Factory, the client uses the factory?s methods to create its own objects. In the Builder?s case, the Builder class is instructed on how to create the object and then it is asked for it, but the way that the class is put together is up to the Builder class, this detail making the difference between the two patterns.

Prototype Pattern:
Prototype pattern refers to creating duplicate object while keeping performance in mind. This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, a object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as as and when needed thus reducing database calls.
=========================== STRUCTURAL ==============================
(Adapt Face for Decoration Bridge Proxy)

Adapter Design Pattern (Structural) :
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Wrap an existing class with a new interface.
Impedance match an old component to a new system

Example: Adapter for electronic devices

Facade Design Pattern (Structural):
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
Wrap a complicated subsystem with a simpler interface.

Example: Consumers encounter a Facade when ordering from a catalog. The consumer calls one number and speaks with a customer service representative. The customer service representative acts as a Facade, providing an interface to the order fulfillment department, the billing department, and the shipping department.

Decorator Design Pattern (Structural)

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Add behavior or state to individual objects at run-time. Note that this pattern allows responsibilities to be added to an object, not methods to an object’s interface.

Example: Attaching a standard disclaimer signature to an email. (signature is the decorator)

Example: assault gun is a deadly weapon on it’s own. But you can apply certain “decorations” to make it more accurate, silent and devastating.

Bridge Design Pattern:
Decouple an abstraction from its implementation so that the two can vary independently

Example of Blog and Themes

Example of TV Remote, and TV implementors like Sony, Philips, etc.

Proxy Pattern:
is very similar to the Adapter pattern. However, the main difference between bot is that the adapter will expose a different interface to allow interoperability. The Proxy exposes the same interface, but gets in the way to save processing time or memory. Typically, you’ll want to use a proxy when communication with a third party is an expensive operation, perhaps over a network. The proxy would allow you to hold your data until you are ready to commit, and can limit the amount of times that the communication is called.

================================ BEHAVIORAL =================================
(Observe the Iterator Visit, Strategize, and act as Mediator to create Memories)

Observer Design Pattern (Behavioral):
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Define an object that is the “keeper” of the data model and/or business logic (the Subject). Delegate all “view” functionality to decoupled and distinct Observer objects. Observers register themselves with the Subject as they are created. Whenever the Subject changes, it broadcasts to all registered Observers that it has changed.

1) The observer pattern is used in the model view controller (MVC) architectural pattern. In MVC the this pattern is used to decouple the model from the view. View represents the Observer and the model is the Observable object.
2) News Publishing:
3) In Yahoo, whenever state of user changes, all concerned properties are notified and action taken accordingly.

Iterator Design Pattern (Behavioral) :
A collection is just a grouping of some objects. They can have the same type or they can be all cast to a base type like object. A collection can be a list, an array, a tree and the examples can continue. But what is more important is that a collection should provide a way to access its elements without exposing its internal structure. We should have a mechanism to traverse in the same way a list or an array. It doesn’t matter how they are internally represented.

The idea of the iterator pattern is to take the responsibility of accessing and passing trough the objects of the collection and put it in the iterator object. The iterator object will maintain the state of the iteration, keeping track of the current item and having a way of identifying what elements are next to be iterated.

“An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover, you might want to traverse the list in different ways, depending on what you need to accomplish. But you probably don’t want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you’ll require. You might also need to have more than one traversal pending on the same list.” And, providing a uniform interface for traversing many types of aggregate objects (i.e. polymorphic iteration) might be valuable.

The Iterator pattern lets you do all this. The key idea is to take the responsibility for access and traversal out of the aggregate object and put it into an Iterator object that defines a standard traversal protocol.

1) Book Collection: (uses “nested class”)

Visitor Design Pattern (Behavioral) :
Represents an operation to be performed on a set of objects in a collection. Visitor lets you define a new operation without changing the classes of the elements on which it operates.

1) taxi example, where the customer calls orders a taxi, which arrives at his door. Once the person sits in, the visiting taxi is in control of the transport for that person.

2) Shopping in the supermarket is another common example, where the shopping cart is your set of elements. When you get to the checkout, the cashier acts as a visitor, taking the disparate set of elements (your shopping), some with prices and others that need to be weighed, in order to provide you with a total.

3) Postage Visitor applied to elements in a shopping cart:

Main Class will implement a accept() method. example Book class will implement accept() method which will accept a visitor. PostageVisitor class will implement a visit method which will do the calculation.

public void accept(Visitor vistor) {

Strategy Design Pattern:
The Strategy pattern provides a way to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. A good use of the Strategy pattern would be saving files in different formats, running various sorting algorithms, or file compression

Memento Design Pattern:
Memento pattern which is used in undo frameworks to bring an object back to a previous state

An airport control tower is an excellent example of the mediator pattern. The tower looks after who can take off and land – all communications are done from the airplane to control tower, rather than having plane-to-plane communication. This idea of a central controller is one of the key aspects to the mediator pattern.

Summary of Good REST Api Design

Summary of points about good RESTful API design from below talk:

Definition: Representational state transfer (REST) or RESTful Web services are one way of providing interoperability between computer systems on the Internet. REST-compliant Web services allow requesting systems to access and manipulate textual representations of Web resources using a uniform and predefined set of stateless operations

1) 2 base urls
a) for collection (/dogs)
b) for a single element (/dogs/bo)
3) nouns are good, verbs are bad
4) Assocations GET /owners/bob/dogs
5) Complex Associations – Sweep under the carpet (behind the question mark)
6) pagination (offset, limit or start, count)
7) searching ( global: /search?q=fluffy+dog , scoped: /owners/bob/dogs/search?q=fluffy+dog)
8) versioning (as far to the left as possible)
9) give me exactly what i need

  • a) /people:(id,first_name,last_name)
  • b) ?fields=id,first_name,last_name

10) output format

  • a) /venue.json
  • b) ?output=json

11) Standardize Error Formats
12) Make dog to bark (/dog?event=bark)