You are on page 1of 20

Programing

Techniques
By Prabhjit Singh
Why we need Programing
Techniques ?
Programing technique is about generalizing software
components so that they can be easily reused in a wide
variety of situations. Programming techniques include :

1) Complexity factor

2) Using bitwise operators

3) Iteration vs Recursions

4) Implementing design patterns


Lets starts with Arrays
• An array is a collection of variables where each variable
has the same data type.

• Each variable in an array is called an element and has an


index, also called the subscript, which denotes that
element’s location within the array.

• One advantage of using arrays is that all the elements


within an array can be declared, created, and passed to a
function as a whole.

• Arrays are of two types fixed memory allocation (fixed


length) or array list (unlimted size).
Complexity Factor : Lets
starts with Arrays
• How to reverse an Array.

• First Method used an Inbuilt method. (EASY)

• Iterate from last index of array to index 0 and put all


elements in new array. here it loops for n times, where n
is number of items in an array.

• One way to reverse the elements in an array is to use two


index variables: one index starts at the beginning of the
array, and the other starts at the end of the array. Then
write a loop that repeats n / 2 times where n is the number
of elements in the array.
Complexity Factor : Lets
starts with Arrays
public static void reverse( float[] list) {

int left = 0;

int right = list.length - 1;

while (left < right) {

// Exchange two elements.

float swap = list[ left];

list[ left] = list[ right];

list[ right] = swap;

// Move the indices toward the center.

left + +;

right--;

}
Bit Operators
• A boolean variable, named after the British mathematician George Boole, is a variable that holds either false or true
and nothing else.

• An efficient way to store many boolean variables is in a group called a bitset where each boolean variable is stored in a
single bit with 0 meaning false and 1 meaning true.

• One important operation that must be performed on a bitset is to count how many bits are set, which is sometimes called the
population count.

• A bitwise operation is a manipulation of one or two binary numbers to produce another binary number.

• There are seven standard bitwise operations that a computer can perform: left shift unsigned right shift signed right shift not
and or exclusive or

• left shift (<<)

• unsigned left shift (>>>)

• signed right shift (>>)

• not (! or ~)

• and (&)

• or (||)

• exclusive or
Bit Operators
• The left shift operator is two less than symbols (< <) and shifts all the bits in an integer to the left by a specified
number of locations, filling the right-most bits with 0 and losing the values in the left-most bits.

• e.g : x = 58 ; x << 2 = 232 // 58 * 4 = 232 , x*2^n

58 0000 0000 0000 0000 0000 0000 0011 1010

232 0000 0000 0000 0000 0000 0000 1110 1000

• The unsigned right shift operator (also called the logical right shift operator ) is three greater than symbols (> > >)
and shifts all the bits in an integer to the right by a specified number of locations, filling the left-most bits with 0 and
losing the values in the right-most bits.

• e.g : x = 58 ; x >>> 2 = 14 // 58 / 4 = 14 , x/2^n 58

0000 0000 0000 0000 0000 0000 0011 1010

14 0000 0000 0000 0000 0000 0000 0000


1110

• In a two’s complement integer, the left-most bit is the sign bit and contains a 0 if the integer is non-negative and
contains a 1 if the integer is negative. The signed right shift operator (also called the arithmetic right shift
operator). Example same as above.

• The bitwise not operator is the tilde (~) and takes an integer as input and clears every set bit and sets every clear
bit, or in other words, switches every 1 bit to 0 and every 0 bit to 1.
Bit Operators
• The bitwise and operator is the ampersand (&) and takes two integers as input and produces an
integer with bits set where the bits are set in both inputs and clear everywhere else. This is the same
operation as logical and but performed on each bit. Within a program, bitwise and is often used to test if
a bit is set and to clear bits in a variable.

• The bitwise or operator is the vertical bar (|) and takes two integers as input and produces an integer
with bits set where the bits are set in either or both inputs and clear everywhere else. This is the same
operation as logical or but performed on each bit. Within a program, bitwise or is often used to set bits in
a variable.

• The bitwise exclusive or operator is the caret ( ^) and takes two integers as input and produces an
integer with bits set where the bits in the two inputs are different and clear everywhere else. This is the
same operation as logical exclusive or but performed on each bit . Within a program, bitwise exclusive
or is often used in data encryption and can even be used to swap the values of two variables.

• All the bitwise operators , except not (~), can be combined with the assignment operator (=) to make
shortcut operators. e.g. x <<=2, x &=0x0f
Bit Operators
write code to count the number of bits set to 1 in a 64-bit number. This is sometimes called the population count.

/** Returns the number of bits set in a 64-bit word. */ e.g 0x00 00 00 04 a0 3f 6e 8c.

public static int nbits( long word) {


int n = 0;
for (int i = 0; i != 64; + + i) {
if (( word & 1) != 0) {
+ + n;
}
word > > > = 1;}
return n;}

// More Faster
way

public static int nbits( long word) {


int n = 0;
while (word != 0) {
if (( word & 1) != 0) {
+ + n; }
word > > > = 1; }
return n; }
Bit Operators
Addition Instead of If

Computers often execute if statements slowly because modern CPUs have a pipeline of instructions that are
in the process of being decoded and executed. When the CPU begins executing an if-else statement, before
it knows the value of the condition (true or false), it will predict that value (usually as true) and begin
speculatively executing the statements in the corresponding part of the if-else statement. However, when
the CPU finishes calculating the value of the condition, if it has predicted incorrectly, it must unload the
instruction pipeline and begin executing the statements in the other part of the if-else statement which takes
time. When an if statement does not have a matching else, the CPU must still predict whether the condition
is true or false and speculatively execute statements according to its prediction.

/** Returns the number of bits set in a 64-bit word. */

public static int nbits( long word) {


int n = 0;
while (word != 0) {
n + = (int) word & 1;
word > > > = 1;
}
return n;
}
Iteration and Recursion
• Iteration is the process of repeating a block of statements in a computer program by using a repetition control structure, also
known as a loop. Here is a simple example of iteration written in Java that computes n factorial (n!).

• Recursion is the process of repeating a block of statements in a computer program by using a recursive function. A recursive
function is a function that calls itself either directly or indirectly. A function F calls itself indirectly by calling function G which
calls function F. A recursive algorithm solves a problem by repeatedly dividing it into smaller sub-problems until reaching the
simpliest sub -problem and then solves that simpliest problem. All recursive algorithms must have three parts:

• A base case which is the simpliest sub-problem and when the recursion will stop

• Code to work toward the base case by dividing the problem into sub-problems

• One or more recursive function calls

/** Recursively computes n factorial (n!) * which is n * (n-1) * (n-2) * ... 1 */


public static long factorial( int n) {
if (n > 1) {
return n * factorial( n - 1);
}
return 1;
}
Iteration and Recursion
• Recursion began to make sense to me when I learned that

• Recursion comes to computer science from mathematics, and mathematicians


define some mathematical functions, such as the Fibonacci series, in a
recursive form.

• Some programming languages such as Erlang, ProLog, and Haskell, don’t


include iteration, because the inventors of those languages believed that iteration
was error prone and that recursive solutions revealed the intrinsic structure of a
problem.

• There are many programming problems more complex than the simple recursive
examples shown in text books (such as n factorial) that are elegantly solved using
recursion.
Iteration and Recursion
• Advantages of Recursion

• If a computing problem can be broken into smaller self-similar problems, a recursive solution is almost
always shorter and more elegant than an iterative solution.

• A recursive function uses existing, well-understood, and tested functionality, namely the system stack, as part
of its solution instead of requiring that another stack module be written.

• It is sometimes necessary to prove that a computing solution is correct. Proving correctness is easier for
a recursive solution than an iterative solution because recursion and proof by induction are closely
related.

• Disadvantages

• Using recursion means many function calls. In many programming languages, a function call is relatively slow
compared to other operations. In languages that don’t include iteration, the language compiler or interpreter
will transform some recursive functions into iterative ones to lower the number of function calls. If a
programmer writes a recursive function in a language that doesn’t include this optimization, that function will
likely be much slower than an iterative function that solves the same problem.

• Recursion can be hard to learn and understand especially for someone that has already learned iteration.

• A recursive function may use all the memory in the system stack which will cause the program to crash.
Design Pattern
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within
a given context in software design. A design pattern is not a finished design that can be transformed directly into
source or machine code. It is a description or template for how to solve a problem that can be used in many
different situations. Patterns are formalized best practices that the programmer can use to solve common
problems when designing an application or system.

• Design patterns can speed up the development process by providing tested, proven development paradigms.
Effective software design requires considering issues that may not become visible until
implementation. Reusing design patterns helps to prevent subtle issues later in the that can
cause
problems[citation needed], and it also improves code readability for coders and architects major with
who are familiar
the patterns.

• By definition, a pattern must be programmed anew into each application that uses it. Since some authors see
this as a step backward from software reuse as provided by components, researchers have worked to turn
patterns into components.

• Design patterns were originally grouped into the categories: creational patterns, structural patterns, and
behavioral patterns, and described using the concepts of delegation, aggregation, and consultation. For further
background on object-oriented design, see coupling and cohesion, inheritance, interface, and polymorphism.
Another classification has also introduced the notion of architectural design pattern that may be applied at the
architecture level of the software such as the Model–View–Controller pattern.
Design Pattern
Creational Pattern

• Abstract Factory :
Provide an interface for creating families of related or dependent objects without
specifying their concrete classes.
• Builder
Separate the construction of a complex object from its representation, allowing the
same construction process to create various representations.
• Factory method
Define an interface for creating a single object, but let subclasses decide which
class to instantiate. Factory Method lets a class defer instantiation to subclasses
(dependency injection).
• Prototype
Specify the kinds of objects to create using a prototypical instance, and create new
objects by copying this prototype.
• Singleton
Ensure a class has only one instance, and provide a global point of access to it.
Design Pattern
Structural patterns

• Adapter or Wrapper or Translator.


Convert the interface of a class into another interface clients expect. An adapter lets classes work
together that could not otherwise because of incompatible interfaces. The enterprise integration pattern
equivalent is the translator.
• Composite
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients
treat individual objects and compositions of objects uniformly.
• Decorator
Attach additional responsibilities to an object dynamically keeping the same interface. Decorators
provide a flexible alternative to subclassing for extending functionality.
• Facade
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.
• Module
Group several related elements, such as classes, singletons, methods, globally used, into a single
conceptual entity.
• Front Controller
The pattern relates to the design of Web applications. It provides a centralized entry point for
handling requests.
Design Pattern
Behavioral patterns

• Blackboard
Generalized observer, which allows multiple readers and writers. Communicates information
system-wide.
• Interpreter
Given a language, define a representation for its grammar along with an interpreter that uses
the representation to interpret sentences in the language.
• Iterator
Provide a way to access the elements of an aggregate object sequentially without exposing its
underlying representation.
• Null object
Avoid null references by providing a default object.
• Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy
lets the algorithm vary independently from clients that use it.
• Template method
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
Template method lets subclasses redefine certain steps of an algorithm without changing the
algorithm's structure.
• State
Allow an object to alter its behavior when its internal state changes. The object will appear to
change its class.
Design Pattern
Concurrency patterns

• Active Object
Decouples method execution from method invocation that reside in their own thread of control.
The goal is to introduce concurrency, by using asynchronous method invocation and a scheduler for
handling requests.
• Balking
Only execute an action on an object when the object is in a particular state.
• Messaging design pattern (MDP)
Allows the interchange of information (i.e. messages) between components and applications.
• Monitor object
An object whose methods are subject to mutual exclusion, thus preventing multiple objects from
erroneously trying to use it at the same time.
• Event-based asynchronous
Addresses problems with the asynchronous pattern that occur in multithreaded programs.
• Join
Join-patterns provides a way to write concurrent, parallel and distributed programs by message
passing. Compared to the use of threads and locks, this is a high level programming model.
• Lock
One thread puts a "lock" on a resource, preventing other threads from accessing or modifying it.
Last But Not Least
Characteristics of a bad Programmer

• The StackOverflow bot


• The I-am-not-a-tester
• The I-hate-documentation
• The ugly: My code works, but:
• Have variables named x, flag, str, arr, etc.
• -Most of what I write is in one giant method.
• -There is no indentation.
• -No consistent coding convention or style.
• -Global variables spewed all over the place, etc.
• The short-term investor
• He codes. He deploys. He moves on. No attempt to learn the problem. No interest in the domain. Just give
this guy a piece of code, he will slog on it overnight and hand it over.
• The protester
• “I didn’t do this”.
• “This looks bad”.
• “Not my problem”.
• “This isn’t related really to my fix, but someone way over there made a mistake”.
• “I hate this (loop this sentence 10 times a day)”.
• “I can’t fix this, get the person who made this code to fix it”.
• The dictator : My way or the highway
• The overcautious
• The careless
• Forgets to take a backup, snapshots, has multiple working directories of code.
• The lazy pseudo-hacker
• Just Use tricks to make it work for now.
Thanks Guys
For wasting your precious time with me.

You might also like