SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
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 later in
the implementation. Reusing design patterns helps to prevent subtle issues that can cause major
problems[citation needed], and it also improves code readability for coders and architects who are familiar
with 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.

Contenu connexe

Tendances

Comparison of Adders for optimized Exponent Addition circuit in IEEE754 Float...
Comparison of Adders for optimized Exponent Addition circuit in IEEE754 Float...Comparison of Adders for optimized Exponent Addition circuit in IEEE754 Float...
Comparison of Adders for optimized Exponent Addition circuit in IEEE754 Float...IJERD Editor
 
Recurrence Relation
Recurrence RelationRecurrence Relation
Recurrence RelationNilaNila16
 
Principle source of optimazation
Principle source of optimazationPrinciple source of optimazation
Principle source of optimazationSiva Sathya
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in CUri Dekel
 
Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...Blue Elephant Consulting
 
Computer Programming (C++)Pointers and Arrays
Computer Programming (C++)Pointers and ArraysComputer Programming (C++)Pointers and Arrays
Computer Programming (C++)Pointers and ArraysAhmedToheed3
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1tanmaymodi4
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notesSrikanth
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional ProgrammingPhilip Schwarz
 
Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105NUST Stuff
 

Tendances (16)

Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
Comparison of Adders for optimized Exponent Addition circuit in IEEE754 Float...
Comparison of Adders for optimized Exponent Addition circuit in IEEE754 Float...Comparison of Adders for optimized Exponent Addition circuit in IEEE754 Float...
Comparison of Adders for optimized Exponent Addition circuit in IEEE754 Float...
 
Recurrence Relation
Recurrence RelationRecurrence Relation
Recurrence Relation
 
Pointers
PointersPointers
Pointers
 
Principle source of optimazation
Principle source of optimazationPrinciple source of optimazation
Principle source of optimazation
 
Introduction to pointers and memory management in C
Introduction to pointers and memory management in CIntroduction to pointers and memory management in C
Introduction to pointers and memory management in C
 
Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...Intro To C++ - Class 11 - Converting between types, formatting floating point...
Intro To C++ - Class 11 - Converting between types, formatting floating point...
 
Computer Programming (C++)Pointers and Arrays
Computer Programming (C++)Pointers and ArraysComputer Programming (C++)Pointers and Arrays
Computer Programming (C++)Pointers and Arrays
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
Datastructure notes
Datastructure notesDatastructure notes
Datastructure notes
 
Ppl
PplPpl
Ppl
 
Pointers In C
Pointers In CPointers In C
Pointers In C
 
Ch02
Ch02Ch02
Ch02
 
Definitions of Functional Programming
Definitions of Functional ProgrammingDefinitions of Functional Programming
Definitions of Functional Programming
 
Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105Lecture#2 Computer languages computer system and Programming EC-105
Lecture#2 Computer languages computer system and Programming EC-105
 
Ch08
Ch08Ch08
Ch08
 

Similaire à Programming techniques

Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingestorebackupr
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdfjamvantsolanki
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++Online
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfMichpice
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxssusere336f4
 
Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5FabMinds
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressionsmaznabili
 
Introduction to golang
Introduction to golangIntroduction to golang
Introduction to golangwww.ixxo.io
 
C programming language
C programming languageC programming language
C programming languageAbin Rimal
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherBlue Elephant Consulting
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptxYagna15
 

Similaire à Programming techniques (20)

Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
Report on c
Report on cReport on c
Report on c
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
 
Operation and expression in c++
Operation and expression in c++Operation and expression in c++
Operation and expression in c++
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
 
CPP07 - Scope
CPP07 - ScopeCPP07 - Scope
CPP07 - Scope
 
Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5Python Programming | JNTUK | UNIT 1 | Lecture 5
Python Programming | JNTUK | UNIT 1 | Lecture 5
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
C Language Part 1
C Language Part 1C Language Part 1
C Language Part 1
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
 
Introduction to golang
Introduction to golangIntroduction to golang
Introduction to golang
 
C language
C languageC language
C language
 
Python recursion
Python recursionPython recursion
Python recursion
 
C programming language
C programming languageC programming language
C programming language
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each OtherIntro To C++ - Class #17: Pointers!, Objects Talking To Each Other
Intro To C++ - Class #17: Pointers!, Objects Talking To Each Other
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
 

Dernier

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Dernier (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Programming techniques

  • 2. 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
  • 3. 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).
  • 4. 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.
  • 5. 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--; } }
  • 6. 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
  • 7. 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.
  • 8. 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
  • 9. 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; }
  • 10. 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; }
  • 11. 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; }
  • 12. 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.
  • 13. 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.
  • 14. 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 later in the implementation. Reusing design patterns helps to prevent subtle issues that can cause major problems[citation needed], and it also improves code readability for coders and architects who are familiar with 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.
  • 15. 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.
  • 16. 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.
  • 17. 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.
  • 18. 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.
  • 19. 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.
  • 20. Thanks Guys For wasting your precious time with me.