Effective programming
Principals
KISS: “Keep It Simple, Stupid (KISS)“ states that most systems work best if they are kept
simple rather than making it complex, so when you are writing code your solution should not
be complicated that takes a lot of time and effort to understand. It means you should be
writing code as simple as possible. If your code is simple then other developers won’t face
any problem understanding the code logic and they can easily proceed further with your
code. So always try to simplify your code using different approaches like breaking a complex
problem into smaller chunks or taking out some unnecessary code you have written.
DRY: “Don’t Repeat Yourself (DRY)” principal goal is to reduce the repetition of code. It
states that a piece of code should be implemented in just one place in the source code.
Duplication of data, logic, or function in code not only makes your code lengthy but also
wastes a lot of time when it comes to maintaining, debug or modify the code. If you need to
make a small change in your code then you need to do it at several places.
YAGNI: “You Aren’t Gonna Need It (YAGNI)” This principle means you should never
code for functionality on the chance that you may need in the future. Don't try and solve a
problem that doesn't exist.
Open/Closed: This principle means you should aim to make your code open to extension but
closed to modification. This is an important principle when releasing a library or framework
that others will use.
Separation of Concerns (SoC): Separation of Concerns Principle partition a complicated
application into different sections or domains. Each section or domain addresses a separate
concern or has a specific job. Each section is independent of each other and that’s why each
section can be tackled independently also it becomes easier to maintain, update, and reuse the
code.
Effective programming provides many benefits:
Performance: Using effective programming techniques, programs can be made faster
and more efficient, meaning they run faster and use fewer resources.
Reliability: Code written using effective programming techniques can contain fewer
errors and security vulnerabilities, making it safer for users to use the programs.
Maintenance: Effective programming techniques such as code readability, modularity,
and reusability make it easier to maintain programs. This saves time and cost when the code
needs to be updated, restructured, or modified.
Testing: Effective programming techniques make it easier to test code, meaning tests
are written and used to ensure software works correctly.
Errors: Effective programming techniques can help make the code less prone to errors,
making the program run more safely and with fewer problems.
Problem Solving
Before being ready to solve a problem, there are some steps and procedures to be followed to
find the solution.
Basically, they are divided into four categories:
Analyzing the problem
Developing the algorithm
Coding
Testing and debugging
Analyzing the Problem
Every problem has a perfect solution; before we are ready to solve a problem, we must look over
the question and understand it. When we know the question, it is easy to find the solution for it.
If we are not ready with what we have to solve, then we end up with the question and cannot find
the answer as expected. By analyzing it, we can figure out the outputs and inputs to be carried
out. Thus, when we analyze and are ready with the list, it is easy and helps us find the solution
easily.
Developing the Algorithm
An algorithm is a step-by-step procedure to resolve any problem. An algorithm is an effective
method expressed as a finite set of well-defined instructions.
An algorithm is used to provide a solution to a particular problem in form of well-defined steps.
Whenever you use a computer to solve a particular problem, the steps which lead to the solution
should be properly communicated to the computer. While executing an algorithm on a computer,
several operations such as additions and subtractions are combined to perform more complex
mathematical operations. Algorithms can be expressed using natural language, flowcharts,
pseudo-code, Programming language etc.
EXAMPLE: Write an algorithm to multiply two numbers and display the result.
Step 1 - START
Step 2 - declare three integers a, b & c
Step 3 – define values of a & b
Step 4 – multiply values of a & b
Step 5- store output of step 4 to c
Step 6 – print c
Step 7 - STOP
Algorithm has the following characteristics
Unambiguous - Algorithm should be clear and unambiguous. Each of its steps and their
inputs/outputs should be clear and must lead to only one meaning.
Effectiveness - An algorithm is also generally expected to be effective. This means that
all of the operations to be performed in the algorithm must be sufficiently basic that they
can in principle be done exactly and in a finite length of time.
Input - An algorithm should have zero or more well-defined inputs.
Output - An algorithm should have 1 or more well-defined outputs, and should match
the desired output.
Finiteness - Algorithms must terminate after a finite number of steps.
Feasibility - Should be feasible with the available resources.
Independent - An algorithm should have step-by-step directions, which should be
independent of any programming code.
The common elements of algorithms
Acquire data (input)
Some means of reading values from an external source; most algorithms require data values to
define the specific problem.
Computation
Some means of performing arithmetic computations, comparisons, testing logical conditions, and
so forth...
Selection
Some means of choosing among two or more possible courses of action, based upon initial data,
user input and/or computed results
Iteration
Some means of repeatedly executing a collection of instructions, for a fixed number of times or
until some logical condition holds
report results (output)
Some means of reporting computed results to the user, or requesting additional data from the
user
Advantages of algorithm
It is a step-wise representation of a solution to a given problem, which makes it easy to
understand.
An algorithm uses a definite procedure.
It is not dependent on any programming language, so it is easy to understand for anyone
even without programming knowledge.
Every step in an algorithm has its own logical sequence so it is easy to debug.
How to Write Algorithms
Step 1 Define your algorithms input: Many algorithms take in data to be processed, e.g. to
calculate the area of rectangle input may be the rectangle height and rectangle width.
Step 2 Define the variables: Algorithm's variables allow you to use it for more than one place.
We can define two variables for rectangle height and rectangle width as HEIGHT and WIDTH
(or H & W). We should use meaningful variable name e.g. instead of using H & W use HEIGHT
and WIDTH as variable name.
Step 3 Outline the algorithm's operations: Use input variable for computation purpose, e.g. to
find area of rectangle multiply the HEIGHT and WIDTH variable and store the value in new
variable (say) AREA. An algorithm's operations can take the form of multiple steps and even
branch, depending on the value of the input variables.
Step 4 Output the results of your algorithm's operations: In case of area of rectangle output
will be the value stored in variable AREA. If the input variables described a rectangle with a
HEIGHT of 2 and a WIDTH of 3, the algorithm would output the value of 6.
Flowchart
A flowchart is the graphical or pictorial representation of an algorithm with the help of different
symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms, we
can easily understand a program. The main purpose of a flowchart is to analyze different
processes. Several standard graphics are applied in a flowchart:
Terminal Box - Start / End
Input / Output
Process / Instruction
Decision
Connector / Arrow
How to Use Flowcharts to Represent Algorithms
Flowcharts are used as a program planning tool to visually organize the step-by-step process of a
program. Here are some examples:
Example 1: Print 1 to 20:
Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Step 4: If X is less than 20 then go back to step 2.
Flowchart:
Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)
Algorithm:
Step 1: Read temperature in Fahrenheit,
Step 2: Calculate temperature with formula C=5/9*(F-32),
Step 3: Print C,
Flowchart:
Example 3: Determine Whether A Student Passed the Exam or Not:
Algorithm:
Step 1: Input grades of 4 courses M1, M2, M3 and M4,
Step 2: Calculate the average grade with formula "Grade=(M1+M2+M3+M4)/4"
Step 3: If the average grade is less than 60, print "FAIL", else print "PASS".
Flowchart:
PSEUDO-CODE
Pseudo-code is one of the tools that can be used to write a preliminary plan that can be
developed into a computer program. Pseudo-code is a generic way of describing an algorithm
without use of any specific programming language syntax. It is, as the name suggests, pseudo
code —it cannot be executed on a real computer, but it models and resembles real programming
code, and is written at roughly the same level of detail.
Pseudo-code, by nature, exists in various forms; although most borrow syntax from popular
programming languages (like C, Lisp, or FORTRAN). Natural language is used whenever
details are unimportant or distracting.
Example: Algorithm
Linear Search ( Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Pseudocode
procedure linear_search (list, value)
for each item in the list
if match item == value
return the item's location
end if
end for
end procedure
Linear search program in C
#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
Output of program:
Algorithm vs. Pseudo-code vs. Program
1. An algorithm is defined as a well-defined sequence of steps that provides a solution for a
given problem, whereas a pseudo-code is one of the methods that can be used to represent
an algorithm.
2. While algorithms are generally written in a natural language or plain English language,
pseudo-code is written in a format that is similar to the structure of a high-level
programming language. Program on the other hand allows us to write a code in a
particular programming language.
So, as depicted above you can clearly see how the algorithm is used to generate the pseudo-code
which is further expanded by following a particular syntax of a programming language to create
the code of the program.
Coding
Once we finalize the algorithm, we must convert the decided algorithm into a code or program
using a dedicated programming language that is understandable by the computer to find a desired
solution. In this stage, a wide variety of programming languages are used to convert the
algorithm into code. E.g Java, C, C++, Python, PHP, Perl etc.
Testing and Debugging
The designed and developed program undergoes several rigorous tests based on various real-time
parameters and the program undergoes various levels of simulations. It must meet the user's
requirements, which have to respond with the required time. It should generate all expected
outputs to all the possible inputs. The program should also undergo bug fixing and all possible
exception handling. If it fails to show the possible results, it should be checked for logical errors.
Industries follow some testing methods like system testing, component testing and acceptance
testing while developing complex applications. The errors identified while testing are debugged
or rectified and tested again until all errors are removed from the program.