Features of Object Oriented Programming

Encapsulation:
Encapsulation is a mechanism by which you restrict the access to some of the object’s components, as well as binding the data and methods operating on the data. Encapsulation is a way to obtain ‘information hiding’.

Abstraction:
Abstraction is the process of moving from a specific idea to a more general one. For example take your mouse. “Silver Logitech MX518” is a concrete, specific item, and “mouse” is an abstraction of that.

Inheritance:

Polymorphism:
Displaying multiple behavior. Achieved via virtual functions, operator overloading, function overloading, etc

Virtual Function: Without “virtual” you get “early binding”. Which implementation of the method is used gets decided at compile time based on the type of the pointer that you call through. With “virtual” you get “late binding”.

Virtual Constructor:

Stack vs Heap

The Stack

What is the stack? It’s a special region of your computer’s memory that stores temporary variables created by each function (including the main() function). The stack is a “LIFO” (last in, first out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is “pushed” onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.

The advantage of using the stack to store variables, is that memory is managed for you. You don’t have to allocate memory by hand, or free it once you don’t need it any more. What’s more, because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.

A key to understanding the stack is the notion that when a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature. This is related to a concept we saw earlier known as variable scope, or local vs global variables. A common bug in C programming is attempting to access a variable that was created on the stack inside some function, from a place in your program outside of that function (i.e. after that function has exited).

Another feature of the stack to keep in mind, is that there is a limit (varies with OS) on the size of variables that can be stored on the stack. This is not the case for variables allocated on the heap.

To summarize the stack:

  • the stack grows and shrinks as functions push and pop local variables
  • there is no need to manage the memory yourself, variables are allocated and freed automatically
  • the stack has size limits
  • stack variables only exist while the function that created them, is running

The Heap

The heap is a region of your computer’s memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc() or calloc(), which are built-in C functions. Once you have allocated memory on the heap, you are responsible for using free() to deallocate that memory once you don’t need it any more. If you fail to do this, your program will have what is known as a memory leak. That is, memory on the heap will still be set aside (and won’t be available to other processes). As we will see in the debugging section, there is a tool called valgrind that can help you detect memory leaks.

Unlike the stack, the heap does not have size restrictions on variable size (apart from the obvious physical limitations of your computer). Heap memory is slightly slower to be read from and written to, because one has to use pointers to access memory on the heap. We will talk about pointers shortly.

Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.

Stack vs Heap Pros and Cons

Stack

  • very fast access
  • don’t have to explicitly de-allocate variables
  • space is managed efficiently by CPU, memory will not become fragmented
  • local variables only
  • limit on stack size (OS-dependent)
  • variables cannot be resized

Heap

  • variables can be accessed globally
  • no limit on memory size
  • (relatively) slower access
  • no guaranteed efficient use of space, memory may become fragmented over time as blocks of memory are allocated, then freed
  • you must manage memory (you’re in charge of allocating and freeing variables)
  • variables can be resized using realloc()

In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap.

https://www.gribblelab.org/CBootCamp/7_Memory_Stack_vs_Heap.html

Functional vs Procedural vs Object Oriented Programming

In a purely procedural style, data tends to be highly decoupled from the functions that operate on it. Procedural is a type of imperative programming style. An imperative language uses a sequence of statements to determine how to reach a certain goal. These statements are said to change the state of the program as each one is executed in turn.

In an object oriented style, data tends to carry with it a collection of functions.

Functional programming (often abbreviated FP) is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects. A function is called ‘pure’ if all its inputs are declared as inputs – none of them are hidden – and likewise all its outputs are declared as outputs. Functional programming is about writing pure functions, about removing hidden inputs and outputs as far as we can, so that as much of our code as possible just describes a relationship between inputs and outputs. Let’s not hide what a piece of code needs, nor what results it will yield. If a piece of code needs something to run correctly, let it say so. If it does something useful, let it declare it as an output. When we do this, our code will be clearer. Complexity will come to the surface, where we can break it down and deal with it.

Explain FLUX

Flux is an architectural pattern that enforces unidirectional data flow.

MVC vs Flux:
MVC did not scale well for Facebook’s huge codebase. The main problem for them was the bidirectional communication, where one change can loop back and have cascading effects across the codebase (making things very complicated to debug and understand).

How does Flux solve this? By forcing an unidirectional flow of data between a system’s components.
In general the flow inside the MVC pattern is not well defined. A lot of the bigger implementations do it very differently (e.g. Cocoa MVC vs. Ruby on Rails MVC).
Flux on the other hand is all about controlling the flow inside the app?—?and making it as simple to understand as possible.

Action –> Dispatcher –> Store –> View

Facebook found that two-way data bindings led to cascading updates, where changing one object led to another object changing, which could also trigger more updates. As applications grew, these cascading updates made it very difficult to predict what would change as the result of one user interaction. When updates can only change data within a single round, the system as a whole becomes more predictable.

https://medium.com/@grover.vinayak0611/what-is-flux-architecture-why-facebook-used-it-and-the-comparison-with-mvc-architecture-49c01ed5d2e1

http://blog.andrewray.me/flux-for-stupid-people/

Object Oriented Programming vs Procedural

Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP)

Procedure Oriented Programming
In POP, program is divided into small parts called functions.
In POP,Importance is not given to data but to functions as well as sequence of actions to be done.
POP follows Top Down approach.
POP does not have any access specifier.
In POP, Data can move freely from function to function in the system.
In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system.
POP does not have any proper way for hiding data so it is less secure.

Object Oriented Programming

In OOP, program is divided into parts called objects.
In OOP, Importance is given to the data rather than procedures or functions because it works as a real world.
OOP follows Bottom Up approach.
OOP has access specifiers named Public, Private, Protected, etc.
In OOP, data can not move easily from function to function,it can be kept public or private so we can control the access of data.
OOP provides Data Hiding so provides more security.

Why should I use node.js?

http://www.toptal.com/nodejs/why-the-hell-would-i-use-node-js

  • real-time websites with push capability
  • unifies the language and data format (JSON) across the stack
  • web applications with real-time, two-way connections, where both the client and server can initiate communication, allowing them to exchange data freely
  • non-blocking, event-driven I/O to remain lightweight and efficient in the face of data-intensive real-time applications that run across distributed devices.
  • You definitely don’t want to use Node.js for CPU-intensive operations
  • Node.js operates on a single-thread, using non-blocking I/O calls, allowing it to support support tens of thousands of concurrent connections
  • Although Node.js really shines with real-time applications, it’s quite a natural fit for exposing the data from object DBs (e.g. MongoDB). JSON stored data allow Node.js to function without the impedance mismatch and data conversion
  • Typical examples include: the logging or writing of user-tracking data, processed in batches and not used until a later time; as well as operations that don’t need to be reflected instantly (like updating a ‘Likes’ count on Facebook) where eventual consistency (so often used in NoSQL world) is acceptable.

Cross Site Scripting (XSS), CSRF and SQL Injection

SQL Injection:
It is the type of attack that takes advantage of improper coding of your web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.

In essence, SQL Injection arises because the fields available for user input allow SQL statements to pass through and query the database directly.

Example:

<?php
	      // We didn't check $_POST['password'], it could be anything the user wanted! For example:
	      $_POST['username'] = 'aidan';
	      $_POST['password'] = "' OR ''='";

	      // Query database to check if there are any matching users
	      $query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
	      mysql_query($query);

	      // This means the query sent to MySQL would be:
	      echo $query;
	      ?>

The query sent to MySQL will be:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

Cross Site Scripting:

In general, cross-site scripting refers to that hacking technique that leverages vulnerabilities in the code of a web application to allow an attacker to send malicious content from an end-user and collect some type of data from the victim. Always validate user input to avoid cross site scripting.

Cross Site Scripting allows an attacker to embed malicious JavaScript, VBScript, ActiveX, HTML, or Flash into a vulnerable dynamic page to fool the user, executing the script on his machine in order to gather data. The use of XSS might compromise private information, manipulate or steal cookies, create requests that can be mistaken for those of a valid user, or execute malicious code on the end-user systems. The data is usually formatted as a hyperlink containing malicious content and which is distributed over any possible means on the internet.

Examples:

SCRIPT SRC=https://hacker-site.com/xss.js
BODY ONLOAD=alert("XSS")
BODY BACK GROUND="javascript:alert('XSS')
IMG S R C="javascript:alert('XSS');
IFRAME S R C=”https://hacker-site.com/xss.html

Simplified View:
XSS is when the user trusts the server too much, CSRF is when the server trusts the user too much

Take these two URL examples that an attacker might send to a victim, the XSS example would abuse a vulnerability on the page and inject javascript into the page and cause the user’s browser to execute the malicious code, the CSRF example causes the server to except malicious input from the user and process it as if the user intended to submit password change:

XSS: http://example.com?variable=a'< script >alert(1)
CSRF: http://example.com/changePassword?userID=1&newPassword=foobar

In simple terms XSS is when you can execute arbitrary Javascript in the victim’s browser typically because input wasn’t sanitised correctly. From there you can do whatever Javascript can, send their cookies to a malicious person, rewrite the DOM to make it seem like the page has been vandalised, redirect them to a malicious page / phishing website, etc.
CSRF is when you trick a user into performing actions with the authority the browser believes they have. Let’s say to change a password you need to submit a form along with being logged in under your account. The server would check you’re logged in via a session token. If I can get this user (‘the victim’) to click on a link which tells the browser to submit the form, the browser will submit it, along with the victim’s logged in session ID (which is always sent when visiting the site). Because as far as the website is concerned the user is logged it and submitting the form it will quite happily complete the action and change the password. An attacker could now log in with the (known) password themselves.

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker’s choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.

Tips to make your website run faster

http://developer.yahoo.com/performance/rules.html

  • Minimize HTTP Requests
  • Images : CSS Sprites are the preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS background-image and background-position properties to display the desired image segment.
  • Use a Content Delivery Network
  • Add an Expires or a Cache-Control Header
  • Gzip Components
  • Put Stylesheets at the Top
  • Put Scripts at the Bottom : The problem caused by scripts is that they block parallel downloads.
  • Make JavaScript and CSS External: Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser.
  • Split Components Across Domains : The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel.
  • Reduce DNS Lookups : DNS lookups take time. Reducing the number of unique hostnames has the potential to reduce the amount of parallel downloading that takes place in the page. Avoiding DNS lookups cuts response times, but reducing parallel downloads may increase response times.
  • Minify JavaScript and CSS
  • Remove Duplicate Scripts : Due to large number of developers and size of project its possible a script etc may get loaded multiple times.
  • Don’t Scale Images in HTML
  • Avoid Empty Image src
  • Use Profiling tools to identify which parts of your code are consuming more time and more memory
  • Fetch Data in Parallel : (multi curl for PHP, node.js, etc)
  • Use EXPLAIN statement to analyze your SQL queries. Based on that add proper indexes
  • Prepared statements in SQL need to be parsed just once
  • Use Opcode Cache which will save the server from parsing your php again
  • Use Memcache DB for storing frequent calls to the database
  • Use MySQL Master Slave for faster read access
  • See if schema needs to be split vertically or horizontally for faster access