Class 2

Coding standards

Why should I use code standards?

Different modules specified in the design document are coded in the Coding phase according to the module specification. The main goal of the coding phase is to code from the design document prepared after the design phase through a high-level language and then to unit test this code.

 

Good software development organizations want their programmers to maintain some well-defined and standard style of coding called coding standards. They usually make their own coding standards and guidelines depending on what suits their organization best and based on the types of software they develop. It is very important for the programmers to maintain the coding standards otherwise the code will be rejected during code review.

Purpose of Having Coding Standards:

  • A coding standard gives a uniform appearance to the codes written by different engineers.
  • It improves the readability, and maintainability of the code and it reduces complexity also.
  • It helps in code reuse and helps to detect errors easily.
  • It promotes sound programming practices and increases efficiency of the programmers.

Some of the coding standards are given below:

  • A coding standard gives a uniform appearance to the codes written by different engineers.
  • It improves the readability, and maintainability of the code and it reduces complexity also.
  • It helps in code reuse and helps to detect errors easily.
  • It promotes sound programming practices and increases efficiency of the programmers.

1.- Limited use of globals

These rules tell about which types of data that can be declared global and the data that can’t be.

2.- Standard headers for different modules

  • Name of the module
  • Date of module creation
  • Author of the module
  • Modification history
  • Synopsis of the module about what the module does
  • Different functions supported in the module along with their input-output parameters
  • Global variables accessed or modified by the module

3.- Naming conventions for local variables, global variables, constants and functions

  • Meaningful and understandable variables name helps anyone to understand the reason of using it.
  • Local variables should be named using camel case lettering starting with a small letter (e.g. localData) whereas Global variables names should start with a capital letter (e.g. GlobalData). Constant names should be formed using capital letters only (e.g. CONSDATA).
  • It is better to avoid the use of digits in variable names.
  • The names of the function should be written in camel case starting with small letters.
  • The name of the function must describe the reason for using the function clearly and briefly.

4.- Indentation

  • There must be a space after giving a comma between two function arguments.
  • Each nested block should be properly indented and spaced.
  • Proper Indentation should be there at the beginning and at the end of each block in the program.
  • All braces should start from a new line and the code following the end of braces also start from a new line.

5.- Error return values and exception handling conventions

All functions that encountering an error condition should either return a 0 or 1 for simplifying the debugging.

6.- Avoid using a coding style that is too difficult to understand

Code should be easily understandable. The complex code makes maintenance and debugging difficult and expensive.

7.- Avoid using an identifier for multiple purposes

Each variable should be given a descriptive and meaningful name indicating the reason behind using it. This is not possible if an identifier is used for multiple purposes and thus it can lead to confusion to the reader. Moreover, it leads to more difficulty during future enhancements.

8.- Code should be well documented

The code should be properly commented for understanding easily. Comments regarding the statements increase the understandability of the code.

9.- Length of functions should not be very large

Lengthy functions are very difficult to understand. That’s why functions should be small enough to carry out small work and lengthy functions should be broken into small ones for completing small tasks.

10.- Try not to use the GOTO statement

GOTO statement makes the program unstructured, thus it reduces the understandability of the program and also debugging becomes difficult.

Google Style Guide

Unit testing

UNIT TESTING

Unit testing is a software testing method in which individual components of the program, called units, are tested independently with all the required dependencies.

Unit testing is mostly done by the actual programmers, who write the programs for the units.

TEST AUTOMATION

Automated execution and reporting of the outcome of test scenarios and cases. In most large and complex projects, many phases of the testing process are automated.

Sometimes the effort of automating the tests is so huge that there is a separate project for automation with a separate team dedicated to it, including a separate reporting structure with separate management.

The Benefits of Automated Unit Testing

Time and effort
As your codebase grows, the number of modules to be unit tested grows. Manual testing occupies a lot of days of the typical programmer’s calendar.
Accuracy
Test case execution is a rote and boring activity. Humans can make mistakes. However, an automated test suite will run and return the correct results every time.
Early bug reporting
Automating unit test cases gives you the distinct advantage of early reporting of bugs and errors.
Built-in support for unit testing
There are many programming languages that provide built-in support for writing unit tests by means of libraries dedicated to unit testing. Examples include Python, Java, and PHP.

Unit test in Python

# Function that receives two numbers and return the sum of the numbers
def add(x,y):
    return x+y

# Function that receives two numbers and return the subtraction of the numbers
def substract(x,y):
    return x-y

calc.py

import unittest
import calc

class TestCalc(unittest.TestCase):

    def test_add(self):
        result = calc.add(10,5)
        self.assertEqual(result, 15)

test_calc.py

Unit test in Python

Instead of:
python .\test_calc.py

Run this:
python -m unittest test_calc.py

calc.py

Reference:

Unit test in Python

DocTest

def add(x,y):
    """return the sum of the numbers
    >>> add(5,10)
    16

    >>> add(3,2)
    5
    """
    return x+y

def substract(x,y):
    """return the subtraction of the numbers
    >>> substract(5,10)
    -5

    >>> substract(3,2)
    1
    """
    return x-y

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Unit test in Python

python .\calc.py
PS C:\Users\illamas\pythonUnitTest>


python .\calc.py
**********************************************************************
File ".\calc.py", line 5, in __main__.add
Failed example:
    add(5,10)
Expected:
    16
Got:
    15
**********************************************************************
1 items had failures:
   1 of   2 in __main__.add
***Test Failed*** 1 failures.

DocTest

Reference:

Excercises

  • Factorial
    3 -> 6  
    5 -> 120

  • Palindrome
    oso = True
    anita lava la tina = True
    osa = False

  •  How many digits are inside of a number (Not cast to string, use it as integer)

    303,3 -> 2
    22432782,2 -> 4

Include the unit tests also add negative cases

Static analysis

Static And Dynamic Code Analysis

Static Analysis
A way for developers to test their code without actually executing it — is called a non-run-time environment. Static code analysis tools offer an incredibly efficient way to find programming faults and display them to software engineers.

 

Static analysis is generally considered the more thorough way to analyze code. It also has the potential to be the more economical option. Identifying code errors in the early stages means that they are typically less expensive to fix than errors that become stuck in the system.

Static And Dynamic Code Analysis

Dynamic Analysis
Then there’s dynamic code analysis, a way to test code while it’s being executed on a real or virtual processor. It’s especially effective for finding subtle defects or vulnerabilities because it looks at the code’s interaction with other databases, servers, and services.

However, dynamic analysis comes with some important caveats. For example, it will only find faults in the specific excerpt of the code that’s being executed – not the entire codebase. On the other hand, some errors not found by static analysis would show up clearly in a dynamic test, especially those related to parts of the source code that rely on external services.

 

To achieve the highest possible level of test coverage, it’s recommended to combine the two methods.

Why use static analysis?

  • Provides insight into code without executing it
  • Executes quickly in comparison with dynamic analysis
  • Can automate code quality maintenance
  • Can automate the search for bugs at the early stages (although not all)
  • Can automate the finding of security problems at an early stage
  • You already using it (if you use any IDE that already has static analyzers, Pycharm uses pep8 for example).

What types of static analysis exist?

  • Code styling analysis
  • Security linting
  • Error detection
  • UML diagram creation
  • Duplicate code detection
  • Complexity analysis
  • Comment styling analysis
  • Unused code detection

Pylint

pip install pylint 
 
 python -m pip install pylint  
    sum1 = 3 + 4;
    print("Sum is %d."; % sum1)
    # Sum is 7.
pylint my_sum.py
my_sum.py:1:0: W0301: Unnecessary semicolon

Dynamic analysis

Software quality

Software Quality

Source: IEEE Std. 730-2014 (IEEE, 2014)

 

Software quality is:

 

The degree to which a software product meets established requirements; however, quality depends upon the degree to which established requirements accurately represent stakeholder needs, wants, and expectations.

Software Quality Assurance

Source: IEEE Std. 730-2014

 

Software quality assurance is:

 

A set of activities that define and assess the adequacy of software processes to provide evidence that establishes confidence that the software processes are appropriate for and produce software products of suitable quality for their intended processes. A key attribute of SQA is the objectivity of the SQA function with respect to the project. The SQA function may also be organizationally independent of the project, that is, free from technical, managerial, and financial pressures from the project.

The Objectives of SQA Activities

  • Ensuring an acceptable level of confidence that the software product and software operation services will conform to functional technical requirements and be suitable quality for its intended use.

  • According to the extended SQA definition – ensuring an acceptable level of confidence that the software development and software operation process will conform to scheduling and budgetary requirements.

  • Initiating and managing activities to improve and increase the efficiency of software development, software operation, and SQA activities. These activities yield improvements to the prospects' achieving of functional and managerial requirements while reducing costs.

Software Product Definition

 

Source: ISO/IEC/IEEE Std. 90003:2014 (ISO/IEC/IEEE, 2014)

 

Software product is

Set of computer programs, procedures, and possibly associated documentation and data.

 

Software Product Components

  1. Computer programs “the code”. The computer programs activate the computer system to perform the required applications. The computer programs include several types of code, such as source code, executable code, test code, and so on.
  2. Procedures. Procedures define the order and schedule within which the software or project programs are performed, the method for handling common malfunctioning of software products, and so on.
  3. Documentation. The purpose of the documentation is to instruct or support new software product version developers, maintenance staff, and end users of the software product. It includes the various design reports, test reports, and user and software manuals, and so on.
  4. Data necessary for operating the software system. The required data include lists of codes and parameters, and also standard test data. The purpose of the standard test data is to ascertain that no undesirable changes in the code or software data have occurred during bug corrections and other software maintenance activities, and to support the detection of causes for any malfunctioning.

The Principles of SQA

Source: after ISO 9000:2000 (ISO, 2000)

  • Customer focus. Organizations depend on their customers, and thus need to understand their current and future needs.
  • Leadership. An organization's leaders should create an internal environment in which employees are involved in achieving the quality targets.
  • Involvement of people-employees. The involvement of employees at all levels enables benefiting from their capabilities to promote software quality issues.
  • Process approach. Managing activities and resources as processes results in their improved efficiency.
  • System approach to management. Process management achieves higher effectiveness and efficiency through identification, analysis, and understanding of interrelated processes.
  • Continual improvement. Continual combined improvement of quality and processes effectiveness and efficiency performance are a permanent objective of the organization.
  • Factual approach of decision-making. Decisions should be based on data and information.
  • Mutually beneficial supplier relationships. Understanding that an organization's supplier relationships based on mutual benefits contributes to improved performance of the organization with regard to quality, efficiency, and effectiveness.

Software Errors, Faults, and Failures

Source: after ISO 9000:2000 (ISO, 2000)

  • Customer focus. Organizations depend on their customers, and thus need to understand their current and future needs.
  • Leadership. An organization's leaders should create an internal environment in which employees are involved in achieving the quality targets.
  • Involvement of people-employees. The involvement of employees at all levels enables benefiting from their capabilities to promote software quality issues.
  • Process approach. Managing activities and resources as processes results in their improved efficiency.
  • System approach to management. Process management achieves higher effectiveness and efficiency through identification, analysis, and understanding of interrelated processes.
  • Continual improvement. Continual combined improvement of quality and processes effectiveness and efficiency performance are a permanent objective of the organization.
  • Factual approach of decision-making. Decisions should be based on data and information.
  • Mutually beneficial supplier relationships. Understanding that an organization's supplier relationships based on mutual benefits contributes to improved performance of the organization with regard to quality, efficiency, and effectiveness.

IEEE Definitions

  • Error: Human mistake that caused fault
  • Fault: Discrepancy in code that causes a failure.
  • Failure: External behavior is incorrect

Error, Fault and Failure

  1. Faulty requirements definition
  2. Client–developer communication failures
  3. Deliberate deviations from software requirements
  4. Logical design errors
  5. Coding errors
  6. Noncompliance with documentation and coding instructions
  7. Shortcomings of the testing process
  8. User interface and procedure errors
  9. Documentation errors

The Nine Causes of Software Errors

SOFTWARE QUALITY FACTORS (ATTRIBUTES)

Product operation

According to McCall's model, five software quality factors are included in the product operation category, all of which deal with requirements that directly affect the daily operation of the software

Product revision

Affect the complete range of software maintenance activities: corrective maintenance (correction of software faults and failures), adaptive maintenance (adapting the current software to additional circumstances and customers without changing the software), and perfective maintenance (enhancement and improvement of existing software with new applications with respect to relevant developments of products, services, and new government regulations and their impact etc.).

Product transition

Three quality factors are included in the product transition category, a category that pertains to the adaptation of software to other environments, and its interaction with other software systems.

Excercise

Search at least 2 factors in each of the categories for McCall's model. Add an example

ISO/IEC 25010

Source: The ISO/IEC 25010:2011

The ISO/IEC 25010 quality model

  • Functional suitability
  • Performance efficiency
  • Compatibility
  • Usability
  • Reliability
  • Security
  • Maintainability
  • Portability

Alternative software quality models

(For factors not included in McCall's and ISO/IEC 25010:2011 product quality models.)

Additional software quality factors additional to McCall's factors

1 Effectiveness
2 Evolvability
3 Expandability
4 Extensibility
5 Human Engineering
6 Manageability
7 Modifiability
8 Productivity
9 Safety
10 Satisfaction
11 Supportability
12 Survivability
13 Understandability
14 Verifiability

McCall's model factors and criteria (subfactors)

McCall's model factors and criteria (subfactors)

ISO/IEC 25010 product quality model factors and criteria (subfactors)

For factors not included in McCall/s and ISO/IEC 25010 quality models

For factors not included in McCall/s and ISO/IEC 25010 quality models

Secure design

The Top 10 OWASP vulnerabilities in 2021

  • Injection
  • Broken authentication
  • Sensitive data exposure
  • XML external entities (XXE)
  • Broken access control
  • Security misconfigurations
  • Cross site scripting (XSS)
  • Insecure deserialization
  • Using components with known vulnerabilities
  • Insufficient logging and monitoring

OWASP stands for the Open Web Application Security Project, an online community that produces articles, methodologies, documentation, tools, and technologies in the field of web application security.

Pick two categories, search descriptions, examples and sites that were hacked with this attack

Secure coding guidelines

Bonus

Version control

Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later. So ideally, we can place any file in the computer on version control.

GIT

Git is a Distributed Version Control System. So Git does not necessarily rely on a central server to store all the versions of a project’s files. Instead, every user “clones” a copy of a repository (a collection of files) and has the full history of the project on their own hard drive. This clone has all of the metadata of the original while the original itself is stored on a self-hosted server or a third party hosting service like GitHub.

Working Directory can be in three possible states

  1. It can be staged. Which means the files with the updated changes are marked to be committed to the local repository but not yet committed.
  2. It can be modified. Which means the files with the updated changes are not yet stored in the local repository.
  3. It can be committed. Which means that the changes you made to your file are safely stored in the local repository.
  • git add is a command used to add a file that is in the working directory to the staging area.
  • git commit is a command used to add all files that are staged to the local repository.
  • git push is a command used to add all committed files in the local repository to the remote repository. So in the remote repository, all files and changes will be visible to anyone with access to the remote repository.
  • git fetch is a command used to get files from the remote repository to the local repository but not into the working directory.
  • git merge is a command used to get the files from the local repository into the working directory.
  • git pull is command used to get files from the remote repository directly into the working directory. It is equivalent to a git fetch and a git merge .

References

Class 2

By Irving Norehem Llamas Covarrubias