Some Javascript Questions

Global Variables:
The var keyword is used to declare a local variable or object, while omitting the var keyword creates a global variable.

Types in Javascript:
JavaScript is a loosely-typed language (some call this weakly typed); this means that no type declarations are required when variables are created. Strings and numbers can be intermixed with no worries. JavaScript is smart, so it easily determines what the type should be. The types supported in JavaScript are: Number, String, Boolean, Function, Object, Null, and Undefined.

What does “this” refer to in Javascript?
In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack.

Every line of JavaScript code is run in an “execution context.” The JavaScript runtime environment maintains a stack of these contexts, and the top execution context on this stack is the one that’s actively running.

There are three types of executable code: Global code, function code, and eval code. Roughly speaking, global code is code at the top level of your program that’s not inside any functions, function code is code that’s inside the body of a function, and eval code is global code evaluated by a call to eval.

The object that this refers to is redetermined every time control enters a new execution context and remains fixed until control shifts to a different context. The value of this is dependent upon two things: The type of code being executed (i.e., global, function, or eval) and the caller of that code.

That’s it! You can figure out what object this refers to by following a few simple rules:

– By default, this refers to the global object.
– When a function is called as a property on a parent object, this refers to the parent object inside that function.
– When a function is called with the new operator, this refers to the newly created object inside that function.
– When a function is called using call or apply, this refers to the first argument passed to call or apply. If the first argument is null or not an object, this refers to the global object.

Why to use call and apply instead of calling a function directly ?
You use call or apply when you want to pass a different this value to the function. In essence, this means that you want to execute a function as if it were a method of a particular object. The only difference between the two is that call expects parameters separated by commas, while apply expects parameters in an array.

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

Must Know Algorithms

As per Cracking the Coding Interview:

Data Structures
Linked Lists
Binary Trees
Hash Tables

Breadth First Search
Depth First Search
Binary Search
Merge Sort
Quick Sort
Tree Insert/Find/etc

Bit Manipulation
Singleton Design Pattern
Factory Design Pattern
Memory (Stack vs Heap)
Big-O Time

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.

Software Architect Interview Questions

What do you understand from the word Architecture? What is meant by software Architecture?

What kind of Software Architecture have you designed till now? Can you explain with the help of commands and patterns?

Which kind of design patterns have you used while building software architecture?

Explain pattern? What is design pattern and factory pattern? Where can these be used?

What is the use of builder pattern? Why it is so important in Software Architecture?

What is shallow copy and deep copy in prototype pattern? Describe: singleton and command pattern?

Numerate the advantages and disadvantages of composition and inheritance in Software Architecture?

When do you use abstract class and what are the conditions to use interfaces?

Explain the difference between object oriented, interface oriented and aspect oriented design and programming?

In which case do you use interface oriented and aspect oriented designs?

Difference between Object Oriented Programming and Component Oriented Programming

Finding if a string occurs in another string

1) strpos
2) strstr

If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead of strstr.

For case insensitive queries, use stripos and stristr

strstr: Returns part of haystack string starting from and including the first occurrence of needle to the end of haystack. Has option in new version of PHP to return part of string before needle also. Returns false if not found.

strpos: Find the numeric position of the first occurrence of needle in the haystack string.
Returns false if not found.

Different types of errors in PHP

There are three basic types of runtime errors in PHP:

1. Notices: These are small, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although the default behavior can be changed.

2. Warnings: Warnings are more severe errors like attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.

3. Fatal errors: These are critical errors – for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.

Can be changed by
a) php statement error_reporting — Sets which PHP errors are reported
b) php.ini : error_reporting = E_ALL