C++ Types, Variables and Arithmetic

BEFORE: C++ Declaration of variables

In C++ every name and every expression has a type that determines the operations that may be performed on it. For example, the declaration:

…..

{

int inch;

…..

…..

}

…..

…..

specifies that inch is of type int; that is, inch is an integer variable.

C++ offers a variety of fundamental types, which correspond directly to hardware facilities.

For example:

bool // Boolean, possible values are true and false

char // character, for example, ’a’, ’z’, and ’9’

int // integer, for example, 1, 42, and 1066

double // double-precision floating-point number, for example, 3.14 and 299793.0

Each of the fundamental types has a fixed size that determines the range of values that can be stored in them (for integers) or the precision and range of those values (for floating point numbers). A char variable is of the natural size to hold a character on a given machine (typically an 8-bit byte), and the sizes of other types are quoted in multiples of the size of a char. The size of a type is implementation defined (i.e., it can vary among different machines) and can be obtained by the sizeof operator; for example sizeof(char) equals 1 and sizeof(int) is often 4. We can represent sizes graphically:

The arithmetic operators can be used for appropriate combinations of these types:

x+y // plus

+x // unar y plus

x−y // minus

−x // unar y minus

x∗y // multiply

x/y // divide

x%y // remainder (modulus) for integers

So can the comparison operators:

x==y // equal

x!=y // not equal

x<y // less than

x>y // greater than

x<=y // less than or equal

x>=y // greater than or equal

In assignments and in arithmetic operations, C++ performs all meaningful conversions between the basic types so that they can be mixed freely, as follows:

….

….

void some_function() // function that doesn’t return a value

{

double d = 2.2; // initialize floating-point number

int i = 7; // initialize integer

d = d+i; // assign sum to d

i = d∗i; // assign product to i (truncating the double to an int)

}

…..

…..

Note that = is the assignment operator and == tests equality.

C++ offers a variety of notations for expressing initialization, such as the = used above, and a universal form based on curly brace delimited initializer lists, as follows:

double d1 = 2.3;

double d2 {2.3};

complex z = 1; // a complex number with double-precision floating-point scalars

complex z2 {d1,d2};

complex z3 = {1,2}; // the = is optional with { … }

vector v {1,2,3,4,5,6}; // a vector of ints

A constant cannot be left uninitialized and a variable should only be left uninitialized in extremely rare circumstances. Don’t introduce a name until you have a suitable value for it.

When defining a variable, you don’t actually need to state its type explicitly when it can be deduced from the initializer:

auto b = true; // a bool

auto ch = ’x’; // a char

auto i = 123; // an int

auto d = 1.2; // a double

auto z = sqrt(y); // z has the type of whatever sqrt(y) returns

With auto, we use the = syntax because there is no type conversion involved that might cause problems.

In addition to the conventional arithmetic and logical operators, C++ offers more specific operations for modifying a variable:

x+=y // x = x+y

++x // increment: x = x+1

x−=y // x = x-y

−−x // decrement: x = x-1

x∗=y // scaling: x = x*y

x/=y // scaling: x = x/y

x%=y // x = x%y

These operators are concise, convenient, and very frequently used.

C++ supports two notions of immutability:

const: meaning roughly ‘‘I promise not to change this value’’. This is used primarily to specify interfaces, so that data can be passed to functions without fear of it being modified. The compiler enforces the promise made by const.

constexpr: meaning roughly ‘‘to be evaluated at compile time’’. This is used primarily to specify constants, to allow placement of data in memory where it is unlikely to be corrupted, and for performance.

For example:

doub le sum(const vector&); // sum will not modify its argument

const int dmv = 17; // dmv is a named constant

conste xpr double max1 = 1.4∗square(dmv); // OK if square(17) is a constant expression

const double max2 = 1.4∗square(dmv); // OK, may be evaluated at run time

v ector v { 1.2, 3.4, 4.5 }; // v is not a constant

const double s1 = sum(v); // OK: evaluated at run time

conste xpr double s2 = sum(v); // error : sum(v) not constant expression

Next example will illustrate what we have discussed so far:

double square(double x) //eleva al cuadrado un número tipo double-precision //                                                       //floating point

{

return x * x;

}

void print_square(double x)

{

std::cout << “the square of” << x << “is” << square(x) << ‘\n’;

}

int main()

{

}

Output:

The std:: specifies that the name cout is to be found in the standard-library namespace. Without std:: operator, the statement ” cout << “the square of” << x << “is” << square(x) << ‘\n’;” has no sense.

A ‘‘return type’’ void indicates that a function does not return a value.

`Numeric Data.`

C++ contains intrinsic data types to store numeric values in your application code. It’s important to remember that these values are binary-based and not as flexible as their base 10 counterparts. For example, in mathematical terms of a base 10 integer, the definition is a value that is negative infinity to positive infinity whole numbers. Modern computers still cannot represent numbers these large. Take as an example the int type in the Numeric Data Types table. The range does not exceed 3 billion in either direction.

Note: I recommend Visual Studio IDE (Interface Development Environment) , and after Introducción a C++ en Visual Studio.

BEFORE: C++ Declaration of variables

Source:

Review by: Larry Francis Obando – Technical Specialist – Educational Content Writer.

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Caracas, Quito, Guayaquil, Cuenca – Telf. 00593998524011

WhatsApp: +593998524011

Anuncios

C++ Tipos de variables y aritmética

ANTERIOR: C++ Declaración de variables

En C ++, cada nombre y cada expresión tiene un tipo que determina las operaciones que se pueden realizar en él. Por ejemplo, la declaración:

…..

{

int inch;

…..

…..

}

…..

…..

especifica que inch es del tipo int; es decir, inch es una variable entera.

C ++ ofrece una variedad de tipos fundamentales de variables, que se corresponden directamente con las características de un hardware en particular.

Por ejemplo:

bool // Boolean, los valores posibles son verdadero(true) o falso (false)

char // Carácter, por ejemplo ’a’, ’z’, and ’9’

int // Entero, por ejemplo, 1, 42, and 1066

double // doble precisión con punto flotante (double-precision floating-point number), por ejemplo, 3.14 and 299793.0

Cada uno de los tipos fundamentales tiene un tamaño fijo que determina el rango de valores que puede almacenarse en ellos (para enteros) o la precisión y rango de esos valores (para números con punto flotante). Una variable char tiene un tamaño natural típico de un byte (8 bits). Los tamaños de otros tipos de variables se calculan como múltiplos del tamaño de una variable char. El tamaño de un tipo está definido por la implementación (es decir, puede variar entre diferentes máquinas). Dicho tamaño puede ser consultado mediante el operador sizeof; por ejemplo sizeof (char) es igual a 1 y sizeof (int) es a menudo 4. Podemos representar gráficamente los tamaños:

Los operadores aritméticos se pueden usar y combinar de la siguiente manera:

x+y // suma

+x // signo positivo

x−y // resta

−x // signo negativo

x∗y // multiplicación

x/y // división

x%y // resto (módulo) para enteros

x==y // igual

x!=y // diferente

x<y // menor que

x>y // mayor que

x<=y // menor o igual quel

x>=y // mayor o igual que

En asignaciones y en operaciones aritméticas, C ++ realiza todas las conversiones significativas entre los tipos básicos de variables, para que puedan mezclarse libremente como se observa en la siguiente declaración:

…..

…..

void some_function() // no retorna ningún valor al ejecutar esta función

{

double d = 2.2; // inicializa el número d tipo floating-point

int i = 7; // inicializa el entero i

d = d+i; // asigna una suma al número d

i = d∗i; // asigna un producto al número i

}

…..

…..

Notar que = es el operador de asignación, mientras que == es el operador que evalúa una igualdad.

C ++ ofrece una variedad de notaciones para expresar la inicialización, como el = usado anteriormente, y una forma universal basada en listas de inicializadores delimitados por llaves, como se ilustra a continuación:

double d1 = 2.3;

double d2 {2.3};

complex z = 1; // un número complejo del tipo double-precision floating-point

complex z2 {d1,d2};

complex z3 = {1,2}; // el operador = es opcional con { … }

vector v {1,2,3,4,5,6}; // un vector de variables tipo ints

Una constante no puede dejarse sin inicializar y una variable solo debe dejarse sin inicializar en circunstancias extremadamente raras. No introduzca un nombre hasta que tenga un valor adecuado para ello.

Al definir una variable, en realidad no necesita indicar su tipo explícitamente cuando

auto b = true; // tipo boolean

auto ch = ’x’; // tipo char

auto i = 123; // tipo int

auto d = 1.2; // tipo double

auto z = sqrt(y); // z tiene el mismo tipo que el entregado por la operación sqrt(y)

Con el operador auto, usamos la sintaxis = porque no hay una conversión involucrada que pueda causar problemas.

Además de los operadores lógicos y aritméticos convencionales, C ++ ofrece operaciones más específicas para modificar una variable:

x+=y // x = x+y

++x // incrementa en uno: x = x+1

x−=y // x = x-y

−−x // reduce en uno: x = x-1

x∗=y // escala: x = x*y

x/=y // escala: x = x/y

x%=y // porcentaje de, x = x%y

const: lo que significa aproximadamente ”Prometo no cambiar este valor”. Esto se usa principalmente para especificar interfaces, de modo que los datos se pueden pasar a funciones sin temor a que se modifiquen. El compilador hace cumplir la promesa hecha por const.

• constexpr: que significa aproximadamente ”para ser evaluado en tiempo de compilación”. Esto se usa principalmente para especificar constantes, para permitir la ubicación de datos en la memoria donde es poco probable que se corrompan y para mejorar el rendimiento.

double sum(const vector&); // la variable sum no modificará su argumento

const int dmv = 17; // dmv es una constante

constexpr double max1 = 1.4∗square(dmv); // OK si square(17) es una expresión constante

const double max2 = 1.4∗square(dmv); // OK, puede ser evaluado en run time

vector v { 1.2, 3.4, 4.5 }; // v no es una constante

const double s1 = sum(v); // OK: evaluado en run time

constexpr double s2 = sum(v); // error : sum(v) no es una expresión constante

El siguiente ejemplo ilustra por sí mismo lo estudiado hasta ahora:

#include “stdafx.h”

#include <iostream>

double square(double x) //eleva al cuadrado un número tipo double-precision                                                           //floating point

{

return x * x;

}

void print_square(double x)

{

std::cout << “the square of” << x << “is” << square(x) << ‘\n’;

}

int main()

{

}

Output:

Std :: especifica que el nombre cout se encuentra en el espacio de nombres de la biblioteca estándar. Sin el operador std :: , la declaración “cout << “the square of” << x << “is” << square(x) << ‘\n’;” no tiene sentido.

Un término void indica que la función print_square(double x) no devuelve ningún valor.

`Numeric Data`

C ++ contiene tipos de datos intrínsecos para almacenar valores numéricos en el código de su aplicación. Es importante recordar que estos valores están basados en binarios y no son tan flexibles como sus equivalentes de base 10. Por ejemplo, en términos matemáticos de un entero de base 10, la definición es un valor que es infinito negativo hasta infinitos positivos. Las computadoras modernas todavía no pueden representar números tan grandes. Tome como ejemplo el tipo int en la tabla de Tipos de Datos Numéricos. El rango no excede los 3 mil millones en cualquier dirección.

ANTERIOR: C++ Declaración de variables

Nota: Para ejecutar los ejercicios propuestos recomiendo descargar el IDE (Interface Development Environment) Visual Studio, y luego para cada ejercicio seguir los pasos recomendados en el link: Introducción a C++ en Visual Studio.

Fuente:

Revisión literaria hecha por: Larry Francis Obando – Technical Specialist – Educational Content Writer.

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Caracas, Quito, Guayaquil, Cuenca – Telf. 00593998524011

WhatsApp: +593998524011

C++ Statements&Declaration of Variables.

`Statements`

A C++ program is comprised of various components such as functions, methods, classes, etc. The instructions that form part of a C++ program typically reside inside of functions or methods. These functions are comprised of C++ statements. You will find yourself using various types of statements in your C++ code as listed here:

• declarations – these are used to declare variables and constants that will be used in your application
• assignments – these are used to assign values to variables in your application code
• preprocessor directives – covered in the topic on Code Formatting
• function declarations – covered in the topic on Code Formatting
• executable statements – these are used to perform operations and execute instructions. Examples would be cout << “Hello World!”; which outputs Hello World! to the console.

In C, all variables must be declare before they are used in executable statements. Their actual use appears elsewhere in the scope, sometimes far away. So, we should go back at the beginning of the program if we want to see its type or its initialization.

C++ allows the declaration of a variable anywhere in the scope. This means that a variable can be declared right at the place of its first use. This makes the program much easier to write or read, so that reducing the errors is more efficient.

`Declaration`

A declaration is a statement that introduces a name into the program. It specifies a type for the named entity:

• A type defines a set of possible values and a set of operations (for an object).
• An object is some memory that holds a value of some type.
• A value is a set of bits interpreted according to a type.
• A variable is a named object.

We first look at the definition of scope and dynamic initialization of the variables.

`Scope Resolution Operator.`

C++ is a block-structured language. The same variable name can be used to have different meanings in different blocks. The scope of the variable extends from the point of its declaration till the end of the block containing the declaration. A variable declared inside a block is said to be local to that block. Consider the following segment of a program:

…..

{

int x = 20;

…..

…..

}

…..

…..

{

int x = 10;

…..

…..

}

The two declaration of x to two different memory locations containing different values. Statements in the second block cannot to the variable x declared in the first block. Another style is as follows:

Block two is contained in the block one. The declaration inner inner block hides a declaration of the same variable in an outer block, therefore, each declaration of x causes it to refer a different data object. Within the inner block, the variable x will refer to the data object declared therein.

In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this problem by introducing a new operator :: called the scope resolution operator. This can be to uncover a hidden variable. It takes the following form:

This operator allows access to the global version of a variable. To illustrate the concepts presented so far, let’s see an example:

#include <iostream>

using namespace std;

int m = 10; //global m

int main()

{

int m=20; //local m

{

int k = m;

int m = 30;//local m to inner block

cout << “We are in a inner block \n”;

cout << “k = ” << k << “\n”;

cout << “m = ” << m << “\n”;

cout << “::m = ” << :: m << “\n”;

}

cout << “\n We are in a outer block \n”;

cout << “m = ” << m << “\n”;

cout << “::m = ” << ::m << “\n”

return 0;

}

Output:

A major application of the scope resolution operator is in the classes to identify the class to which a member function belongs. This will be dealt in detail later where the classes are introduced.

In the previous example the operator int determines the type of the data as integer. This lead us to the definition of data types in C++.

`Basic Data Types`

Data types in C++ can be classified under various categories as shown in Figure 3.1:

Both C and C++ compilers support all the built-in data type (also called basic data types), which seize and range is shown as follows:

The type void has two normal uses: 1) to specify the return type of a function when it is not returning any value, and 2) to indicate an empty argument list to a function. Example:

void functl(void);

We will explain more about every type of data as we come into more complex examples.

Note: I recommend Visual Studio IDE (Interface Development Environment) , and after Introducción a C++ en Visual Studio.

Source:

Review by: Larry Francis Obando – Technical Specialist – Educational Content Writer.

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Caracas, Quito, Guayaquil, Cuenca – Telf. 00593998524011

WhatsApp: +593998524011

C++ Declaración de variables

SIGUIENTE: C++ Tipo de variables y aritmética

`Statements`

Un programa C ++ se compone de varios componentes, tales como funciones, métodos, clases, etc. Las instrucciones que forman parte de un programa C ++ normalmente residen dentro de funciones o métodos. Estas funciones están compuestas por “statements” C ++. Encontrarás varios tipos de “statements” en tu código C ++ como se detalla a continuación:

• declaraciones (declarations) – estas se usan para declarar variables y constantes que se usarán en la aplicación
• asignaciones (assignments) – estas se usan para asignar valores a las variables en su código de aplicación
•  directivas del pre procesador (preprocessor directives) – cubierto en el tema sobre Formato de código
• comentarios (comments) – documentación del código
• declaración de funciones (function declarations) – cubierto en el tema sobre Formato de código
• declaraciones ejecutables (executable statements) – estos se utilizan para realizar operaciones y ejecutar instrucciones. Ejemplos serían cout << “Hello World!”; que imprime la palabra Hello World! e la consola.

En C, todas las variables deben declararse antes de que se utilicen en sentencias ejecutables. Su uso real aparece en otra parte del campo de aplicación (scope), a veces muy lejos. Entonces, deberíamos volver al comienzo del programa si queremos ver su tipo o su inicialización.

C ++ permite la declaración de una variable en cualquier parte del scope. Esto significa que una variable puede declararse directamente en el lugar de su primer uso. Esto hace que el programa sea mucho más fácil de escribir o leer, por lo que reducir los errores es más eficiente.

`Declaración`

Una declaración es una sentencia que introduce un nombre en el programa. Especifica un tipo para la entidad nombrada:

• Un tipo (type) define un conjunto de valores posibles y un conjunto de operaciones (para un objecto).
• Un objeto (object) es una unidad de memoria que tiene un valor de algún tipo.
• Un valor (value) es un conjunto de bits interpretados de acuerdo a un tipo.
• Una variable (variable) es el nombre de un objeto.

Primero observamos la definición de alcance (scope) de las variables.

`Operador scope (Scope Resolution)`

C ++ es un lenguaje estructurado por bloques. El mismo nombre de variable se puede usar para tener diferentes significados en diferentes bloques. El scope de la variable se extiende desde el punto de su declaración hasta el final del bloque que contiene la declaración. Una variable declarada dentro de un bloque se dice que es local a ese bloque. Considere el siguiente segmento de un programa:

…..

{

int x = 20;

…..

…..

}

…..

…..

{

int x = 10;

…..

…..

}

Las dos declaraciones de x se remiten a dos ubicaciones de memoria diferentes que contienen diferentes valores. Las declaraciones en el segundo bloque no pueden acceder a la variable x declarada en el primer bloque. Otro estilo es el siguiente:

El bloque dos está contenido en el bloque uno. El bloque interno de declaración, oculta una declaración de la misma variable en un bloque externo, por lo tanto, cada declaración de x hace que remita un objeto de datos diferente. Dentro del bloque interno, la variable x se referirá al objeto de datos declarado allí.

En C, no se puede acceder a la versión global de una variable desde dentro del bloque interno. C ++ resuelve este problema introduciendo el nuevo operador :: llamado operador de resolución de alcance (scope resolution operator). Esto puede ser para descubrir una variable oculta. Toma la siguiente forma:

Este operador permite el acceso a la versión global de una variable. Para ilustrar los conceptos presentados hasta ahora, veamos el siguiente ejemplo:

#include <iostream>

using namespace std;

int m = 10; //global m

int main()

{

int m=20;//local m

{

int k = m;

int m = 30;//local m to inner block

cout << “We are in a inner block \n”;

cout << “k = ” << k << “\n”;

cout << “m = ” << m << “\n”;

cout << “::m = ” << :: m << “\n”;

}

cout << “\n We are in a outer block \n”;

cout << “m = ” << m << “\n”;

cout << “::m = ” << ::m << “\n”

return 0;

}

Salida:

Una aplicación principal del operador :: está en classes para identificar la clase a la que pertenece una función miembro. Esto se tratará en detalle más adelante donde hablaremos de classes.

En el ejemplo anterior, el operador int determina el tipo de datos como un entero. Esto nos lleva a la definición de tipos de datos en C ++.

`Tipos Básicos de Datos (Basic Data Types)`

Los tipos de datos en C ++ se pueden clasificar en varias categorías, como se muestra en la Figura 3.1:

Los compiladores C y C ++ son compatibles con todos los tipos de datos built-in (también llamados tipos básicos de datos), que se capturan y se muestran de la siguiente figura:

El tipo void tiene dos usos normales: 1) para especificar el tipo de retorno de una función cuando no devuelve ningún valor, y 2) para indicar una lista de argumento vacía para una función. Ejemplo:

void functl(void);

Explicaremos más acerca de cada tipo de datos a medida que ingresamos a ejemplos más complejos.

SIGUIENTE: C++ Tipo de variables y aritmética

Nota: Para ejecutar los ejercicios propuestos recomiendo descargar el IDE (Interface Development Environment) Visual Studio, y luego para cada ejercicio seguir los pasos recomendados en el link: Introducción a C++ en Visual Studio.

Fuente:

Revisión Literaria hecha por: Larry Francis Obando – Technical Specialist – Educational Content Writer.

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Caracas, Quito, Guayaquil, Cuenca – Telf. 00593998524011

WhatsApp: +593998524011

C++ Principios de la programación orientada a objetos

SIGUIENTE: C++ Declaración de variables

Jueves 29 marzo 2018, 05:17 am

Today’s literature review:

1. BalaguruswamyObjectOrientedProgrammingWithC++Fourth
1. 1.3 A look at Procedure-Oriented Programming
3. 1.5 Basic concepts
4. 2.3 A simple program “Hello world”

La Programación Orientada a Objetos (Object-Oriented Programming – OOP) es un enfoque que proporciona una forma de modularización de programas mediante la creación de un área de memoria particionada para datos y funciones que se pueden usar como plantillas para crear copias de dichos módulos bajo demanda. Por lo tanto, se considera que un objeto es un área particionada de la memoria de la computadora que almacena datos y un conjunto de operaciones que pueden acceder a esos datos. Como las particiones de memoria son independientes, los objetos se pueden usar en una variedad de programas diferentes sin modificación…..(Balagurusamy, 2008).

1.3 Las características exhibidas por la programación orientada a procedimientos (Procedure-Oriented Programming – POP) son:

• El énfasis está en hacer cosas (algoritmos)
• Los grandes programas se dividen en pequeños programas llamados funciones.
• La mayoría de las funciones comparten datos globales.
• Los datos se mueven abiertamente alrededor del sistema de una función a otra.
• Las funciones transforman datos de un tipo a otro,
• La técnica emplea es un enfoque de arriba hacia abajo para el diseño del programa.

1.4 En contraposición OOP trata los datos como un elemento crítico en el desarrollo del programa y no permite que fluyan libremente alrededor de un sistema. Ata datos más de cerca a las funciones que operan en él, y los protege de modificaciones accidentales de funciones externas. OOP permite la descomposición en una serie de entidades llamadas objetos y luego construye datos y funciones alrededor de estos objetos. La organización de data y las funciones en programación orientada a objetos se muestra en la Figura 1.6

OOP es un enfoque que proporciona una forma de modularización de programas mediante la creación de un área de memoria particionada para datos y funciones que se pueden usar como plantillas para crear copias de dichos módulos según la demanda. Por lo tanto, se considera que un objeto es un área particionada de la memoria de la computadora que almacena datos y un conjunto de operaciones que pueden acceder a esos datos. Dado que las particiones de memoria son independientes, los objetos pueden usarse en una variedad de programas diferentes sin modificaciones.

Un programa orientado a objetos consiste en un conjunto de objetos que se comunican entre sí. El proceso de programación en un lenguaje orientado a objetos, por lo tanto, implica los siguientes pasos básicos:

• Crear clases que definen objetos y su comportamiento,
• Crear objetos a partir de definiciones de clase y,
• Establecer la comunicación entre los objetos.

Los objetos se comunican entre sí al enviar y recibir información de la misma manera que las personas se transmiten mensajes entre sí. Eso hace que sea más fácil hablar sobre la construcción de sistemas que modelan o simulan directamente sus contrapartes del mundo real.

Un mensaje para un objeto es una solicitud de ejecución de un procedimiento y, por lo tanto, invocará una función (procedure) en el objeto receptor que genera el resultado deseado. La transmisión de mensajes (Message passing) implica especificar el nombre del objeto, el nombre de la función (message) y la información que se enviará. Ejemplo:

Los sistemas de negocio reales a menudo son muy complejos y contienen muchos más objetos con atributos y métodos complicados. OOP es útil en este tipo de dominios de aplicación porque puede simplificar un problema complejo. Las áreas prometedoras para la aplicación de OOP incluyen:

• Real-time systems
• Simulation and modeling
• Object-oriented databases
• Hypertext, hypermedia and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems

La programación orientada a procedimientos (POP) tiene mayores desventajas: (1) los datos se mueven libremente alrededor del programa y, por lo tanto, son vulnerables a los cambios causados por cualquier función en el programa; (2) POP no modela muy bien los problemas del mundo real. El OOP fue inventado para superar los inconvenientes de POP.

En OOP, un problema se considera como una colección de varias entidades llamadas objetos (Objects ). Los objetos son instancias de clases. El aislamiento de datos (Insulation) del acceso directo por el programa se denomina ocultación de datos (data hiding).

La abstracción de datos (Data abstraction) se refiere a reunir características esenciales sin incluir detalles de fondo.

La herencia (Inheritance) es el proceso por el cual los objetos de una clase adquieren propiedades de objetos de otra clase.

Polimorfismo (Polymorphism) significa un nombre, formas múltiples. Nos permite tener más de una función con el mismo nombre en un programa. También permite la sobrecarga de los operadores (overloading) para que una operación pueda mostrar diferentes comportamientos en diferentes instancias.

La vinculación dinámica (Dynamic binding) significa que el código asociado con un procedimiento dado no se conoce hasta el momento de la llamada en tiempo de ejecución (run-time).

//“Hello World” program

#include “stdafx.h”

#include <iostream>

using namespace std;

int main()

{

cout << “Hello World\n”;

return 0;

}

Un programa C++ es una colección de funciones. El ejemplo anterior contiene una sola función, main(). La ejecución del programa inicia con main(). Cada programa C++ debe tener una main().

cout ( C Out) representa la salida estándar en C++

El operador << es el operador de inserción o colocar en. Inserta los contenidos de la variable a su derecha al objeto a su izquierda, como se muestra en la Figura 2.1

Aquí, el identificador cout es un objeto predefinido que representa la pantalla y tiene una interfaz simple. Si cadena representa una variable de cadena, la siguiente instrucción mostrará su contenido:

cout << string;

El operador << es también el operador de desplazamiento a la izquierda ( left-shift operator), es un ejemplo de una sobrecarga del operador (una función que se puede comportar diferente dependiendo del argumento que recibe), un aspecto importante del polimorfismo. Hemos utilizado la siguiente directiva #include:

#include <iostream>

Esta directiva hace que el preprocesador agregue los contenidos del archivo iostream al programa. Contiene declaraciones para el identificador cout y el operador <<. El archivo de encabezado iostream debe incluirse al comienzo de todos los programas que usan declaraciones de entrada / salida.

Namespace, el espacio de nombres, es un nuevo concepto introducido por el comité de estándares ANSI C ++. Esto define un ámbito, un campo de aplicación o envergadura, para los identificadores que se usan en un programa. Para usar los identificadores definidos en el ámbito del espacio de nombres, debemos incluir la directiva using, como:

using namespace std;

En C ++, main () devuelve un valor de tipo entero (integer) al sistema operativo. Por lo tanto, cada main () en C ++ debe terminar con una declaración return (0); de lo contrario, puede ocurrir un error. El tipo de retorno para main () se especifica explícitamente como int.

Un programa un poco más complejo

Supongamos que nos gustaría leer dos números del teclado y mostrar su promedio en la pantalla.

#include “stdafx.h”

#include <iostream>

using namespace std;

int main()

{

float number1, number2, sum, average;

cout << “Enter two numbers: “; // prompt

cin >> number1; // reads number

cin >> number2; // read number from the keyboard

sum = number1 + number2;

average = sum / 2;

cout << “Sum=” << sum << “\n“;

cout << “Average=” << average << “\n“;

return 0;

}

Comentarios:

El programa usa cuatro variables que son declaradas como tipo flotante por la declaración:

float number1, number2, sum, average;

Todas las variables deben declararse antes de ser utilizadas en el programa.

cin >> number1;

hace que el programa espere a que el usuario escriba un número, que se coloca en la variable number1. El identificador cin (C in) es un objeto predefinido en C ++ que corresponde con la entrada estándar tipo string.

El operador >> se conoce como extracción o obtiene del operador. Extrae el valor del teclado y lo asigna a la variable a su derecha. Este operador también puede estar overloaded.

Hemos utilizado el operador de inserción << repetidamente en las dos últimas declaraciones para imprimir los resultados:

cout << “Sum=” << sum << “\n”;

cout << “Average=” << average << “\n”;

Primero, envía la cadena “Sum =” a cout y luego envía el valor de sum. Finalmente, envía el carácter de nueva línea \ n para que la próxima salida esté en la nueva línea. Cuando se conecta en cascada un operador de salida, debemos asegurar espacios en blanco entre los diferentes elementos. La declaración dos se puede combinar como:

cout << “Sum=” << sum << “\n”

<< “Average=” << average << “\n”;

Esta es una afirmación pero proporciona dos líneas de salida. También podemos conectar en cascada el operador de entrada >> como se muestra a continuación:

cin >> number1 >> number2;

Los valores se asignan de izquierda a derecha.

SIGUIENTE: C++ Declaración de variables

Nota: Para ejecutar los ejercicios propuestos recomiendo descargar el IDE (Interface Development Environment) Visual Studio,  y luego para cada ejercicio seguir los pasos recomendados en el link: Introducción a C++ en Visual Studio.

Fuente:

Revisión literaria hecha por Larry Francis Obando – Technical Specialist – Educational Content Writer.

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Caracas, Quito, Guayaquil, Cuenca – Telf. 00593998524011

WhatsApp: +593984950376

C++ Principles of object-oriented programming

Jueves 29 , 05:17 am

Today’s literature review:

1. BalaguruswamyObjectOrientedProgrammingWithC++Fourth
1. 1.3 A look at Procedure-Oriented Programming
3. 1.5 Basic concepts
4. 2.3 A simple program “Hello world”

Object-Oriented Programming (OOP) is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. Thus, an object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in a variety of different programs without modification…(Balagurusamy, 2008).

1.3 Characteristics exhibited by procedure-oriented programming (POP) are:

• The emphasis is on doing things (algorithms)
• Large programs are divided into small programs called functions.
• Most of the functions shared global data.
• Data move openly around the system from function to function.
• Functions transform data from one type to another,
• The technique employs top-down approach in program design.

1.4 Object-Oriented Programming (OOP) treats data as a critical element in the program development and does not allow it to flow freely around a system. It ties data more closely to the functions that operate on it, and protects it from accidental modifications from outside functions. OOP allows decomposition into a number of entities called objects and then builds data and function around these objects. The organization of dta and functions in object-oriented programming is shown in Figure 1.6

Object-Oriented Programming (OOP) is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. Thus, an object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in a variety of different programs without modification.

An object-oriented program consists of a set of objects that communicate with each other. The process of programming in a object-oriented language, therefore, involves the following basic steps:

• Creating classes that define objects and their behaviour,
• Creating objects from class definitions and,
• Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. That makes it easier to talk about building systems that directly model or simulate their real-world counterparts.

A message for an object is a request for execution of a procedure, and therefore will invoke a function (procedure) in the receiving object that generates the desired result. Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent. Example:

Real-business systems are often much complex and contain many more objects with complicated attributes and methods. OOP is useful in these types of application domains because it can simplify a complex problem. The promising areas for application of OOP include:

• Real-time systems
• Simulation and modeling
• Object-oriented databases
• Hypertext, hypermedia and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems

Procedure-oriented programming (POP) has to majors drawbacks: (1) data move freely around the program and are therefore vulnerable to changes caused by any function in the program; (2) POP does not model very well the real-world problems. OOP was invented to overcome the drawbacks of POP.

In OOP, a problem is considered as a collection of a number of entities called objects. Objects are instances of classes. Insulation of data from direct access by the program called data hiding.

Data abstraction refers to putting together essential features without including background details.

Inheritance is the process by which objects of one class acquire properties of objects of another class.

Polymorphism means one name, multiple forms. It allows us to have more than one function with the same name in a program. It also allows overloading of operators so that an operation can exhibit different behaviours in different instances. Dynamic binding means that the code associated with a given procedure is not known until the time of the call at run-time.

//“Hello World” program

#include “stdafx.h”

#include <iostream>

using namespace std;

int main()

{

cout << “Hello World\n”;

return 0;

}

A C++ program is a collection of functions. The above example contains only one function, main(). Execution begins at main(). Every C++ program must have a main().

cout ( C Out) represents the standard output stream in C++

The operator << the insertion or put to operator. It inserts the contents of the variable on its right to the object on its left, as it is shown in Figure 2.1

Here, the identifier cout is a predefined object representing the screen and it has a simple interface. If string represents a string variable, then the following statement will display its contents:

cout << string;

The operator << is also the bit-wise left-shift operator is an example of an operator overloading, an important aspect of polymorphism. We have used the following #include directive:

#include <iostream>

This directive causes the preprocessor to add the contents of the iostream file to the program. It contains declarations for the identifier cout and the operator<< . The header file iostream should be included at the beginning of all programs that use input/output statements.

Namespace is a new concept introduced by the ANSI C++ standards committee. This defines a scope for the identifiers that are used in a program. For using the identifiers defined in the namespace scope we must include the using directive,like:

using namespace std;

In C++, main() returns an integer type value to the operating system. Therefore, every main() in C++ should end with a return(0) statement; otherwise an error may occur. The return type for main() is thus explicitly specified as int.

A slightly more complex program

Assume that we would like to read two numbers from the keyboard and display their average on the screen.

#include “stdafx.h”

#include <iostream>

using namespace std;

int main()

{

float number1, number2, sum, average;

cout << “Enter two numbers: “; // prompt

cin >> number1; // reads number

cin >> number2; // read number from the keyboard

sum = number1 + number2;

average = sum / 2;

cout << “Sum=” << sum << “\n“;

cout << “Average=” << average << “\n“;

return 0;

}

The program uses four variables that are declared as type float by the statement

float number1, number2, sum, average;

All variables must be declared before they are used in the program.

Input Operator. The statement:

cin >> number1;

causes the program to wait for the user to type in a number, which is placed in the variable number1. The identifier cin ( C in) is a predefined object in C++ that corresponds to the standard input stream.

The operator >> is known as extraction or get from operator. It extracts the value from the keyboard and assigns it to the variable on its right. This operator can also be overloaded.

We have used the insertion operator << repeatedly in the last two statements for printing results:

cout << “Sum=” << sum << “\n”;

cout << “Average=” << average << “\n”;

First, send the string  “Sum=” to cout and then sends the value of sum. Finally, it sends the newline character \n so that the next output will be in the new line. When cascading an output operator we should ensure blank spaces between different items. The two statement can be combined as:

cout << “Sum=” << sum << “\n”

<< “Average=” << average << “\n”;

This is one statement but provides two lines of output. We can also cascade input operator >> as shown below:

cin >> number1 >> number2;

The values are assigned from left to the right.

Note: I recommend Visual Studio IDE (Interface Development Environment) ,  and after Introducción a C++ en Visual Studio.

Source:

Review by: Larry Francis Obando – Technical Specialist – Educational Content Writer.

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Caracas, Quito, Guayaquil, Cuenca – Telf. 00593998524011

WhatsApp: +593984950376

UML – Analysis activities: From Use Case to Class Diagram

Computer science and programming

UML Analysis activities – From Use Case to Class Diagram

Miércoles 29 noviembre, 10:16 am

Fuente:

Object-Oriented Software Engineering

1. Analysis p 173
2. Identifying Associations pp 190
3. Identifying Aggregates pp 192
4. Identifying Attributes pp 193

Identifying Associations

In this section, we discuss the use of class diagrams for representing associations among objects. An association shows a relationship between two or more classes. For example, a FieldOfficer writes an EmergencyReport (see Figure 5-13).

Associations have several properties:

• A name to describe the association between the two classes (e.g., Writes in Figure 5-13). Association names are optional and need not be unique globally.
• A role at each end, identifying the function of each class with respect to the associations (e.g., author is the role played by FieldOfficer in the Writes association).
• A multiplicity at each end, identifying the possible number of instances (e.g., *
• indicates a FieldOfficer may write zero or more EmergencyReports, whereas 1
• indicates that each EmergencyReport has exactly one FieldOfficer as author).

Initially, the associations between entity objects are the most important, as they reveal more information about the application domain. According to Abbott’s heuristics (see Table 5-1), associations can be identified by examining verbs and verb phrases denoting a state (e.g., has, is part of, manages, reports to, is triggered by, is contained in, talks to, includes). Every association should be named, and roles should be assigned to each end.

The object model will initially include too many associations if developers include all associations identified after examining verb phrases. In Figure 5-14, for example, we identify two relationships: the first between an Incident and the EmergencyReport that triggered its creation; the second between the Incident and the reporting FieldOfficer. Given that the EmergencyReport and FieldOfficer already have an association modeling authorship, the association between Incident and FieldOfficer is not necessary. Adding unnecessary associations complicates the model, leading to incomprehensible models and redundant information.

Most entity objects have an identifying characteristic used by the actors to access them. FieldOfficers and Dispatchers have a badge number. Incidents and Reports are assigned numbers and are archived by date. Once the analysis model includes most classes and associations, the developers should go through each class and check how it is identified by the actors and in which context.

Identifying Aggregates

Aggregations are special types of associations denoting a whole–part relationship. For example, a FireStation consists of a number of FireFighters, FireEngines, Ambulances, and a LeadCar. A State is composed of a number of Counties that are, in turn, composed of a number of Townships (Figure 5-15). An aggregation is shown as a association with a diamond on the side of the whole part.

There are two types of aggregation, composition and shared. A solid diamond denotes composition. A composition aggregation indicates that the existence of the parts depends on the whole. For example, a County is always part of exactly one State, a Township is always part of a County. As political boundaries do not change often, a Township will not be part of or shared with another County.

A hollow diamond denotes a shared aggregation relationship, indicating the whole and the part can exist independently. For example, although a FireEngine is part of at most one FireStation at the time, it can be reassigned to a different FireStation during its life time. Aggregation associations are used in the analysis model to denote whole–part concepts. Aggregation associations add information to the analysis model about how containment concepts in the application domain can be organized in a hierarchy or in a directed graph. Aggregations are often used in the user interface to help the user browse through many instances.

If you are not sure that the association you are describing is a whole–part concept, it is better to model it as a one-to-many association, and revisit it later when you have a better understanding of the application domain.

Identifying Attributes

Attributes are properties of individual objects. For example, an EmergencyReport, as described in Table 5-2, has an emergency type, a location, and a description property (see Figure 5-16).

These are entered by a FieldOfficer when she reports an emergency and are subsequently tracked by the system. When identifying properties of objects, only the attributes relevant to the system should be considered.

Properties that are represented by objects are not attributes. For example, every EmergencyReport has an author that is represented by an association to the FieldOfficer class. Developers should identify as many associations as possible before identifying attributes to avoid confusing attributes and objects. Attributes have:

• A name identifying them within an object. For example, an EmergencyReport may have a reportType attribute and an emergencyType attribute. The reportType describes the kind of report being filed (e.g., initial report, request for resource, final report). The emergencyType describes the type of emergency (e.g., fire, traffic, other). To avoid confusion, these attributes should not both be called type.
• A brief description.
• A type describing the legal values it can take. For example, the description attribute of an EmergencyReport is a string. The emergencyType attribute is an enumeration that can take one of three values: fire, traffic, other. Attribute types are based on predefined basic types in UML

Attributes can be identified using Abbott’s heuristics (see Table 5-1). In particular, a noun

phrase followed by a possessive phrase (e.g., the description of an emergency) or an adjective phrase (e.g., the emergency description) should be examined. In the case of entity objects, any property that must be stored by the system is a candidate attribute.

Note that attributes represent the least stable part of the object model. Often, attributes are discovered or added late in the development when the system is evaluated by the users. Unless the added attributes are associated with additional functionality, the added attributes do not entail major changes in the object (and system) structure. For these reasons, the developers need not spend excessive resources in identifying and detailing attributes that represent less important aspects of the system.

Literature Review by: Larry Francis Obando – Technical Specialist

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

WhatsApp: 00593984950376

UML Analysis – Basics

Computer science and programming

Jueves 09 noviembre, 09:44 am

Fuente:

Object-Oriented Software Engineering

1. Analysis p 173
2. Overview of Analysis
3. Analysis Concepts pp 176
4. Analysis Activities pp 179

Analysis

Analysis results in a model of the system that aims to be correct, complete, consistent, and unambiguous. Developers formalize the requirements specification produced during requirements elicitation and examine in more detail boundary conditions and exceptional cases. Developers validate, correct and clarify the requirements specification if any errors or ambiguities are found. The client and the user are usually involved in this activity when the requirements specification must be changed and when additional information must be gathered. In object-oriented analysis, developers build a model describing the application domain.

Formalization helps identify areas of ambiguity as well as inconsistencies and omissions in a requirements specification. Once developers identify problems with the specification, the address them by eliciting more information from the users and the client. Requirements elicitation and analysis are iterative and incremental activities that occur concurrently.

An Overview of Analysis

Analysis focuses on producing a model of the system, called the analysis model, which is correct, complete, consistent, and verifiable. Analysis is different from requirements elicitation in that developers focus on structuring and formalizing the requirements elicited from users (Figure 5-2).

This formalization leads to new insights and the discovery of errors in the requirements. As the analysis model may not be understandable to the users and the client, developers need to update the requirements specification to reflect insights gained during analysis, then review the changes with the client and the users. In the end, the requirements, however large, should be understandable by the client and the users.

The analysis model is composed of three individual models: the functional model, represented by use cases and scenarios, the analysis object model, represented by class and object diagrams, and the dynamic model, represented by state machine and sequence diagrams (Figure 5-3).

In the previous chapter, we described how to elicit requirements from the users and describe them as use cases and scenarios. In this chapter, we describe how to refine the functional model and derive the object and the dynamic model. This leads to a more precise and complete specification as details are added to the analysis model.

Analysis Object Model

The analysis model represents the system under development from the user’s point of view. The analysis object model is a part of the analysis model and focuses on the individual concepts that are manipulated by the system, their properties and their relationships. The analysis object model, depicted with UML class diagrams, includes classes, attributes, and operations. The analysis object model is a visual dictionary of the main concepts visible to the user.

Dynamic Model

The dynamic model focuses on the behavior of the system. The dynamic model is depicted with sequence diagrams and with state machines. Sequence diagrams represent the interactions among a set of objects during a single use case. State machines represent the behavior of a single object (or a group of very tightly coupled objects). The dynamic model serves to assign responsibilities to individual classes and, in the process, to identify new classes, associations, and attributes to be added to the analysis object model.

Entity, Boundary, and Control Objects

The analysis object model consists of entity, boundary, and control objects [Jacobson et al., 1999]. Entity objects represent the persistent information tracked by the system. Boundary objects represent the interactions between the actors and the system. Control objects are in charge of realizing use cases. In the 2Bwatch example, Year, Month, and Day are entity objects; Button and LCDDisplay are boundary objects; ChangeDateControl is a control object that represents the activity of changing the date by pressing combinations of buttons.Modeling the system with entity, boundary, and control objects provides developers with simple heuristics to distinguish different, but related concepts.

To distinguish between different types of objects, UML provides the stereotype mechanism to enable the developer to attach such meta-information to modeling elements.

For example, in Figure 5-5, we attach the «control» stereotype to the ChangeDateControl object. In addition to stereotypes, we may also use naming conventions for clarity and recommend distinguishing the three different types of objects on a syntactical basis: control objects may have the suffix Control appended to their name; boundary objects may be named to clearly denote an interface feature (e.g., by including the suffix Form, Button, Display, or Boundary); entity objects usually do not have any suffix appended to their name.

Generalization and Specialization

Modeling with UML, inheritance enables us to organize concepts into hierarchies. At the top of the hierarchy is a general concept, and at the bottom of the hierarchy are the most specialized concepts.

Generalization is the modeling activity that identifies abstract concepts from lower-level ones.

Specialization is the activity that identifies more specific concepts from a high-level one.

In some instances, modelers call inheritance relationships generalization-specialization relationships. In this book, we use the term “inheritance” to denote the relationship and the terms “generalization” and “specialization” to denote the activities that find inheritance relationships.

Analysis Activities: From Use Cases to Objects

In this section, we describe the activities that transform the use cases and scenarios produced during requirements elicitation into an analysis model. Analysis activities include:

1. Identifying Entity Objects
2. Identifying Boundary Objects
3. Identifying Control Objects
4. Mapping Use Cases to Objects with Sequence Diagrams
5. Modeling Interactions among Objects with CRC Cards
6. Identifying Associations
7. Identifying Aggregates
8. Identifying Attributes
9. Modeling State-Dependent Behavior of Individual Objects
10. Modeling Inheritance Relationships
11. Reviewing the Analysis Model

Identifying Entity Objects

Participating objects form the basis of the analysis model. Natural language analysis is an intuitive set of heuristics for identifying objects, attributes, and associations from a requirements specification. Abbott’s heuristics maps parts of speech (e.g., nouns, having verbs, being verbs, adjectives) to model components (e.g., objects, operations, inheritance relationships, classes). Table 5-1 provides examples of such mappings by examining the ReportEmergency use case:

The following heuristics can be used in conjunction with Abbott’s heuristics:

As it was mentioned before, Entity Objects represent the persistent information tracked by the system. For entity objects we recommend always to start with the names used by end users and application domain specialists. Describing objects, even briefly, allows developers to clarify the concepts they use and avoid misunderstandings (e.g., using one object for two different but related concepts).

For example, after a first examination of the ReportEmergency use case (Figure 5-7), we use application domain knowledge and interviews with the users to identify the objects Dispatcher, EmergencyReport, FieldOfficer, and Incident. Note that the EmergencyReport object is not mentioned explicitly by name in the ReportEmergency use case. Step 4 of the use case refers to the emergency report as the “information submitted by the FieldOfficer.” After review with the client, we discover that this information is usually referred to as the “emergency report” and decide to name the corresponding object EmergencyReport.

The definition of entity objects leads to the initial analysis model described in Table 5-2.

Identifying Boundary Objects

Boundary objects represent the system interface with the actors. In each use case, each actor interacts with at least one boundary object. The boundary object collects the information from the actor and translates it into a form that can be used by both entity and control objects.

We find the boundary objects of Table 5-3 by examining the ReportEmergency use case.

We have made progress toward describing the system. We now have included the interface between the actor and the system. We are, however, still missing some significant pieces of the description, such as the order in which the interactions between the actors and the system occur. In the next section, we describe the identification of control objects.

Identifying Control Objects

Control objects are responsible for coordinating boundary and entity objects. Control objects usually do not have a concrete counterpart in the real world. Often a close relationship exists between a use case and a control object; a control object is usually created at the beginning of a use case and ceases to exist at its end. It is responsible for collecting information from the boundary objects and dispatching it to entity objects. For example, control objects describe the behavior associated with the sequencing of forms, undo and history queues, and dispatching information in a distributed system.

We model the control flow of the ReportEmergency use case with a control object for each actor: ReportEmergencyControl for the FieldOfficer and ManageEmergency-Control for the Dispatcher, respectively (Table 5-4).

The decision to model the control flow of the ReportEmergency use case with two control objects stems from the knowledge that the FieldOfficerStation and the DispatcherStation are actually two subsystems communicating over an asynchronous link.

Literature Review by: Larry Francis Obando – Technical Specialist

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

WhatsApp: 00593984950376

UML – Requirements Elicitation

The client, the developers, and the users identify a problem area and define a system that addresses the problem. Such a definition is called a requirements specification and serves as a contract between the client and the developers…The requirements specification is structured and formalized during analysis to produce an analysis model…(August 7, 2017).

The first step of requirements elicitation is the identification of actors. This serves both to define the boundaries of the system and to find all the perspectives from which the developers need to consider the system…(September 18, 2017).

 Actividad WBS (Overview) Fuente: Object-Oriented Software Engineering Requirement Elicitation concepts – Functional requirements Requirement Elicitation activities -Identifying actors – Identifying scenarios – Identifying Use Cases – Identifying relationships between actors and Use Cases – Identifying Initial Analysis Objects -Identifying Non-functional requirements – Documenting Requirements Elicitation- (p 152). A requirement is a feature that the system must have or a constraint that it must satisfy to be accepted by the client. Requirements engineering aims at defining the requirements of the system under construction. Requirements engineering includes two main activities; Requirements Elicitation, which results in the specification of the system that the client understands, and analysis, which results in an analysis model that the developers can unambiguously interpret. Requirements elicitation is the more challenging of the two because it requires the collaboration of several groups of participants with different backgrounds. On the one hand, the client and the users are experts in their domain and have a general idea of what the system should do, but they often have little experience in software development. On the other hand, the developers have experience in building systems, but often have little knowledge of the everyday environment of the users.

Requirement elicitation

Overview

A requirement is a feature that the system must have or a constraint that it must satisfy to be accepted by the client. Requirements engineering aims at defining the requirements of the system under construction. Requirements engineering includes two main activities; Requirements Elicitation, which results in the specification of the system that the client understands, and analysis, which results in an analysis model that the developers can unambiguously interpret. Requirements elicitation is the more challenging of the two because it requires the collaboration of several groups of participants with different backgrounds. On the one hand, the client and the users are experts in their domain and have a general idea of what the system should do, but they often have little experience in software development. On the other hand, the developers have experience in building systems, but often have little knowledge of the everyday environment of the users.

Scenarios and use cases provide tools for bridging this gap. A scenario describes an example of system use in terms of a series of interactions between the user and the system. A use case is an abstraction that describes a class of scenarios. Both scenarios and use cases are written in natural language, a form that is understandable to the user. In this chapter, we focus on scenario-based requirements elicitation.,,Requirements elicitation is about communication among developers, clients, and users to define a new system…Requirements elicitation methods aim at improving communication among developers, clients, and users…Developers construct a model of the application domain by observing users in their environment. Developers select a representation that is understandable by the clients and users (e.g., scenarios and use cases). Developers validate the application domain model by constructing simple prototypes of the user interface and collecting feedback from potential users…Requirements elicitation focuses on describing the purpose of the system. The client, the developers, and the users identify a problem area and define a system that addresses the problem. Such a definition is called a requirements specification and serves as a contract between the client and the developers…The requirements specification is structured and formalized during analysis to produce an analysis model:

Both requirements specification and analysis model represent the same information. They differ only in the language and notation they use; the requirements specification is written in natural language, whereas the analysis model is usually expressed in a formal or semiformal notation.

Requirements elicitation and analysis focus only on the user’s view of the system. For example, the system functionality, the interaction between the user and the system, the errors that the system can detect and handle, and the environmental conditions in which the system functions are part of the requirements. The system structure, the implementation technology selected to build the system, the system design, the development methodology, and other aspects not directly visible to the user are not part of the requirements.

Requirements elicitation includes the following activities:

1. Identifying actors
2. Identifying scenarios
3. Identifying use cases
4. Refining use cases
5. Identifying relationships among use cases
6. Identifying nonfunctional requirements

Elicitation concepts

Functional requirements describe the interactions between the system and its environment independent of its implementation. The environment includes the user and any other external system with which the system interacts… The functional requirements focus only on the possible interactions between the system and its external world. This description does not focus on any of the implementation details.

Nonfunctional requirements describe aspects of the system that are not directly related to the functional behavior of the system. Nonfunctional requirements include a broad variety of requirements that apply to many different aspects of the system, from usability to performance. The FURPS+ model2 used by the Unified Process [Jacobson et al., 1999] provides the following categories of nonfunctional requirements:

Elicitation Activities

Identifying Actors: Actors represent external entities that interact with the system. An actor can be human or an external system. In the SatWatch example, the watch owner, the GPS satellites, and the Webify Watch serial device are actors (see Figure 4-4). They all exchange information with the SatWatch.

Figure 4-4 Actors for the SatWatch system. WatchOwner moves the watch (possibly across time zones) and consults it to know what time it is. SatWatch interacts with GPS to compute its position. Webify Watch upgrades the data contained in the watch to reflect changes in time policy.

The first step of requirements elicitation is the identification of actors. This serves both to define the boundaries of the system and to find all the perspectives from which the developers need to consider the system. When the system is deployed into an existing organization (such as a company), most actors usually exist before the system is developed: they correspond to roles in the organization. During the initial stages of actor identification, it is hard to distinguish actors from objects. For example, a database subsystem can at times be an actor, while in other cases it can be part of the system. Note that once the system boundary is defined, there is no trouble distinguishing between actors and such system components as objects or subsystems. Actors are outside of the system boundary; they are external. Subsystems and objects are inside the system boundary; they are internal.

Thus, any external software system using the system to be developed is an actor. When identifying actors, developers can ask the following questions:

Questions for identifying actors:

• Which user groups are supported by the system to perform their work?

• Which user groups execute the system’s main functions?

• Which user groups perform secondary functions, such as maintenance and administration?

• With what external hardware or software system will the system interact?

Identifying Scenarios: A scenario is “a narrative description of what people do and experience as they try to make use of computer systems and applications” [Carroll, 1995]. A scenario is a concrete, focused, informal description of a single feature of the system from the viewpoint of a single actor. Scenarios cannot (and are not intended to) replace use cases, as they focus on specific instances and concrete events (as opposed to complete and general descriptions). However, scenarios enhance requirements elicitation by providing a tool that is understandable to users and clients…

Figure 4-6 is an example of scenario for the FRIEND system, an information system for incident response. In this scenario, a police officer reports a fire and a Dispatcher initiates the incident response.

Scenarios can have many different uses during requirements elicitation and during other activities of the life cycle. Below is a selected number of scenario types taken from [Carroll, 1995]:

As-is scenarios describe a current situation. During reengineering, for example, the current system is understood by observing users and describing their actions as scenarios.

Visionary scenarios describe a future system. Visionary scenarios are used both as a point in the modeling space by developers as they refine their ideas of the future system and as a communication medium to elicit requirements from users.

Evaluation scenarios describe user tasks against which the system is to be evaluated. The collaborative development of evaluation scenarios by users and developers also improves the definition of the functionality tested by these scenarios.

Training scenarios are tutorials used for introducing new users to the system. These are step-by-step instructions designed to hand-hold the user through common tasks.

In requirements elicitation, developers and users write and refine a series of scenarios in order to gain a shared understanding of what the system should be. Initially, each scenario may be high level and incomplete, as the warehouseOnFire scenario is. The following questions can be used for identifying scenarios.

Questions for identifying scenarios

• What are the tasks that the actor wants the system to perform?

• What information does the actor access? Who creates that data? Can it be modified or removed? By

whom?

• Which external changes does the actor need to inform the system about? How often? When?

• Which events does the system need to inform the actor about? With what latency?

Identifying Use Cases: A scenario is an instance of a use case; that is, a use case specifies all possible scenarios for a given piece of functionality. A use case is initiated by an actor. After its initiation, a use case may interact with other actors, as well. A use case represents a complete flow of events through the system in the sense that it describes a series of related interactions that result from its initiation…Figure 4-7 depicts the use case ReportEmergency of which the scenario warehouseOnFire (see Figure 4-6) is an instance

Generalizing scenarios and identifying the high-level use cases that the system must support enables developers to define the scope of the system. Initially, developers name use cases, attach them to the initiating actors, and provide a high-level description of the use case as in Figure 4-7. The name of a use case should be a verb phrase denoting what the actor is trying to accomplish. The verb phrase “Report Emergency” indicates that an actor is attempting to report an emergency to the system (and hence, to the Dispatcher actor). This use case is not called “Record Emergency” because the name should reflect the perspective of the actor, not the system. It is also not called “Attempt to Report an Emergency” because the name should reflect the goal of the use case, not the actual activity

Attaching use cases to initiating actors enables developers to clarify the roles of the different users. Often, by focusing on who initiates each use case, developers identify new actors that have been previously overlooked.

Describing the flow of events of a use case enables developers and clients to discuss the interaction between actors and system. This results in many decisions about the boundary of the system, that is, about deciding which actions are accomplished by the actor and which actions are accomplished by the system.

Identifying relationships between actors and Use Cases: Communication relationships between actors and use cases represent the flow of information during the use case. The actor who initiates the use case should be distinguished from the other actors with whom the use case communicates. By specifying which actor can invoke a specific use case, we also implicitly specify which actors cannot invoke the use case. Similarly, by specifying which actors communicate with a specific use case, we specify which actors can access specific information and which cannot. Thus, by documenting initiation and communication relationships among actors and use cases, we specify access control for the system at a coarse level.

Identifying Initial Analysis Objects: To establish a clear terminology, developers identify the participating objects for each use case. Developers should identify, name, and describe them unambiguously and collate them into a glossary.3 Building this glossary constitutes the first step toward analysis, which we discuss in the next chapter. The glossary is included in the requirements specification and, later, in the user manuals. Developers keep the glossary up to date as the requirements specification evolves. The benefits of the glossary are manyfold: new developers are exposed to a consistent set of definitions, a single term is used for each concept (instead of a developer term and a user term), and each term has a precise and clear official meaning. The identification of participating objects results in the initial analysis object model. The identification of participating objects during requirements elicitation only constitutes a first step toward the complete analysis object model.

During requirements elicitation, participating objects are generated for each use case. If two use cases refer to the same concept, the corresponding object should be the same. If two objects share the same name and do not correspond to the same concept, one or both concepts are renamed to acknowledge and emphasize their difference. This consolidation eliminates any ambiguity in the terminology used.

Identifying Non-functional requirements: Nonfunctional requirements describe aspects of the system that are not directly related to its functional behavior. Nonfunctional requirements span a number of issues, from user interface look and feel to response time requirements to security issues. Nonfunctional requirements are defined at the same time as functional requirements because they have as much impact on the development and cost of the system.

Documenting Requirements Elicitation: The results of the requirements elicitation and the analysis activities are documented in the Requirements Analysis Document (RAD). This document completely describes the system in terms of functional and nonfunctional requirements.Figure 4-16 is an example template for a RAD:

Written by: Larry Francis Obando – Technical Specialist

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, Caracas.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Ecuador (Quito, Guayaquil, Cuenca) – 0998524011

WhatsApp: 00593998524011

Copywriting, Content Marketing, Tesis, Monografías, Paper Académicos, White Papers (Español – Inglés)

1. SuperClass
1. Fuente. KULeuvenX: UMLx UML Class Diagrams for Software Engineering (Copia Textual – Literature Review).

Superclass

In this presentation we’ll explain the concept of generalization and specialization. This concept is actually a UML association construct. It relates to inheritance, fundamental concept of object oriented programming. This concept states that a class can inherit attributes and operations from a parent class.

In this example We have the general concept of account and two more specific concepts of checking account and saving account that inherit the characteristics of the more general concept of account. The more general concept is called generalization, superclass or supertype and the more specific concept is called the specialization, subclass or subtype. Graphically, the generalization/specialization association is drawn as a line connecting the super type to the subtype, and which is adorned with a triangle pointing towards the super type.

The principle of inheritance states that a subtype inherits the features of the super type. So, in this case, the superclass ‘account’, has defined two attributes: ‘IBAN number’ and ‘balance’. Those attributes will be inherited by checking account. So, also checking account will have an IBAN number and a balance. In addition, the checking account can extend what it inherited from account with its own attributes. And, in this case, checking account defines an additional attribute: ‘credit card’. Likewise, the savings account inherits from account that it has an IBAN number and a balance. But, it extends this with four attributes relating to a savings plan…Here, we graphically represent how a generalization/specialization is similar to a superset/subset relation.

Generalization sets.

Sometimes it is difficult to decide how to define the specialisations of a super type because different partitionings are possible. Take the example of vehicles. If you look at the transportation medium, you would have a partition like this:

This examples illustrates how in certain cases a single concept can be partitioned in two different ways. In UML, the concept of generalization set provides a way to group Specializations into orthogonal dimensions. Each group is represented by a generalization set. There are three different notations to represent generalisation sets.

First, by putting a name next to the Generalization relationship lines, that name designates a GeneralizationSet to which the Specialization belongs.

Second, two or more lines can be drawn to the same arrowhead and labelled by a single

generalization set name. This is called the “shared target” style.

With either of these two notations, if there are no labels on the Generalization arrows it cannot be determined from the diagram whether there are any generalization sets in the model.

Finally, a generalization set may be designated by drawing a dashed line across those lines with separate arrowheads that are meant to be part of the same set. Here, the generalization set is labelled with a single name, instead of each line labelled.

Constraints on Generalization/Specialization.

The concept of generalization/specialization comes with constraints and there are two types of constraints to consider. The first is whether the specialization is complete or incomplete. The question to ask is whether the subclasses cover all the elements of the superclass. Let’s consider an example where the superclass are the pet animals. That is the general concept. And you have three subtypes or specialized concepts namely cats, dogs and horses. The question to ask is: are there other pet animals than cats, dogs and horses? If yes, then the specialization of the subclasses is an incomplete specialization of the general concept. If there are no other pet animals than cats, dogs and horses, then the specialization is complete.

The other constraint to consider is whether or not subclasses are disjoint or overlapping. The question to ask here is: are there overlapping subclasses? For our example: Are there animals that can be dog and cat at the same time? Or cat and horse at the same time? Or dog and horse at the same time? If that’s not the case, then your classes are disjoint. If it is possible that an animal is a cat and a dog at the same time or a cat and a horse or a dog and a horse at the same time, then you have overlapping subclasses. If you don’t specify anything then by default it is assumed that your subclasses are disjoint.

The way to write these constraints down is simply by including the words that indicate the correct constraint between brackets next to the triangle.

Reading a diagram with inheritance (Inherited associations).

The general rule is that you have to read inheritance as an OR. So if you read the association between customer and account in this direction, the way to read the diagram is as follows.

A customer can have zero to many accounts and these accounts are either checking accounts or savings account because the specialization is complete and disjoint.

In the other direction, from account to customer, the way to read the diagram is that each account, be it the checking account or savings account, must have exactly one customer as an owner. In other words, checking account and savings account inherit from account that they belong to exactly one owner.

And here’s another example. Reading from student to course means that a student can follow zero to many courses and that these courses are advanced or intermediate or both, or just courses. Because inheritance is overlapping and incomplete.

In the other direction, reading from course to student we can see that each course is followed by zero to many students. And, because of the inheritance relationship, the advanced course and intermediate course inherit from course the fact that they are followed by zero to many students. So each course, advanced or intermediate, or just course is followed by zero to many students.

In the case of multiple inheritance trees in a single diagram, extra care is required. Consider this example. The association between Flight and Airplane seems to read as a general rule “Each flight has to be done with an airplane, and each Airplane can serve for zero to many flights.” While this seems a logical interpretation, the actual meaning is different.

The blue part of the model should be read as “A Flight, which could be either a cargo flight or a passenger flight” Similarly, the orange part of the model should be read as “An airplane, which could either be a passenger airplane or a cargo airplane.” In combination with the association, the true meaning of the model is: A flight of any kind, be it cargo or passenger flight, is always done with one airplane of any kind, be it a passenger or a cargo plane. So if you want to capture that passenger flights can only be done with passenger planes, and that cargo flights can only be done with cargo planes, then you need to model this at the level of the specialisations. And obviously, the association at the level of the super type then needs to be removed.

And what if cargo flights can be done with any kind of planes? Then the association connects “Cargo Flight” to the superclass “Airplane” rather than to the subclass. And the model looks like this.

AssociationClass

Let’s take a look again at the example of projects, products and suppliers. Suppose that prior to buying a product for a project, you need to be able to look up the different prices different suppliers ask for a product. So, next to keeping track of which product has been sourced from which supplier for a project, you also want to know which supplier offers which product.

So, where would you keep the price attribute? Would you model this as an attribute of supplier? Definitively not. Is it an attribute of product? Since each supplier has its own price for a given product, you can’t model it as an attribute of product either.

The price is rather an attribute of the combination of supplier and product. It’s therefore an attribute of the association between supplier and product. As a result, the association exhibits the characteristics of a class. In UML this is capture by the concept of associationclass.

An association class is both an association and a class at the same time. The association class is therefore named like a Class, and it can have attributes and operations. In this example, a good name for the association class is “ProductOffer”. And next to the price, this association class could also contain other attributes such as shipping conditions, average shipping time, etcetera.

In the example of the projects, products and suppliers, also the other associations may be converted to association classes, depending on required attributes. For example, the association that models which products are required by which projects, may be turned into an association class ProductRequirement capturing the required quantity, the maximum price that should be paid and the deadline by which products should be available.

The use of the concept of association class adds complexity to a model, in the sense that it is an extra symbol one needs to understand. To a large extent, a model using only classes and associations can express the same thing. For example, the product offer can also be modelled as a conventional class, related to a single supplier and a single product.

Larry Francis Obando – Technical Specialist

Escuela de Ingeniería Eléctrica de la Universidad Central de Venezuela, CCs.

Escuela de Ingeniería Electrónica de la Universidad Simón Bolívar, Valle de Sartenejas.

Escuela de Turismo de la Universidad Simón Bolívar, Núcleo Litoral.

Contact: Ecuador (Quito, Cuenca, Guayaquil) – tlf. 0998524011

WhatsApp: 00593998524011