FINAL

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Inheritance can be complicated by access controls to encapsulated entities

-A class can hide entities from its subclasses -A class can hide entities from its clients -A class can also hide entities for its clients while allowing its subclasses to see them

Arithmetic Expressions: Operators

-A unary operator has one operand -A binary operator has two operands -A ternary operator has three operands

There are two kinds of methods in a class:

-Class methods - accept messages to the class -Instance methods - accept messages to objects

There are two kinds of variables in a class:

-Class variables - one/class -Instance variables - one/object

Boolean Expressions

-Operands are Boolean and the result is Boolean -Example operators ■ C89 has no Boolean type--it uses int type with 0 for false and nonzero for true ■ One odd characteristic of C's expressions: a < b < c is a legal expression, but the result is not what you might expect: - Left operator is evaluated, producing 0 or 1 - The evaluation result is then compared with the third operand (i.e., c)

Design issues for arithmetic expressions

-Operator precedence rules? -Operator associativity rules? -Order of operand evaluation? -Operand evaluation side effects? -Operator overloading? -Type mixing in expressions?

Categories of Concurrency:

-Physical concurrency - Multiple independent processors ( multiple threads of control) -Logical concurrency - The appearance of physical concurrency is presented by time-sharing one processor (software can be designed as if there were multiple threads of control) ■Coroutines (quasi-concurrency) have a single thread of control ■A thread of control in a program is the sequence of program points reached as control flows through the program

Besides inheriting methods as is, a class can modify an inherited method

-The new one overrides the inherited one -The method in the parent is overriden

Arithmetic Expressions: Operator Associativity Rule

-The operator associativity rules for expression evaluation define the order in which adjacent operators with the same precedence level are evaluated -Typical associativity rules -Left to right, except **, which is right to left -Sometimes unary operators associate right to left (e.g., in FORTRAN) -APL is different; all operators have equal precedence and all operators associate right to left -Precedence and associativity rules can be overridden with parentheses.

Relational Expressions

-Use relational operators and operands of various types -Evaluate to some Boolean representation -Operator symbols used vary somewhat among languages (!=, /=, ~=, .NE., <>, #) ■JavaScript and PHP have two additional relational operator, === and !== - Similar to their cousins, == and !=, except that they do not coerce their operands -Ruby uses == for equality relation operator that uses coercions and eql? for those that do not

Arithmetic Expressions: Operand Evaluation Order

• Variables: fetch the value from memory • Constants: sometimes a fetch from memory; sometimes the constant is in the machine language instruction • Parenthesized expressions: evaluate all operands and operators first • The most interesting case is when an operand is a function call

Control Structure

■A control structure is a control statement and the statements whose execution it controls Design question -Should a control structure have multiple entries?

Counter-Controlled Loops

■A counting iterative statement has a loop variable, and a means of specifying the initial and terminal, and stepsize values ■Design Issues: •What are the type and scope of the loop variable? •Should it be legal for the loop variable or loop parameters to be changed in the loop body, and if so, does the change affect loop control? •Should the loop parameters be evaluated only once, or once for every iteration? ■Logically-Controlled Loops ■Repetition control is based on a Boolean expression ■Design issues: -Pretest or posttest? -Should the logically controlled loop be a special case of the counting loop statement or a separate statement?

Generic Subprograms

■A generic or polymorphic subprogram takes parameters of different types on different activations ■Overloaded subprograms provide ad hoc polymorphism ■Subtype polymorphism means that a variable of type T can access any object of type T or any type derived from T (OOP languages) ■A subprogram that takes a generic parameter that is used in a type expression that describes the type of the parameters of the subprogram provides parametric polymorphism - A cheap compile-time substitute for dynamic binding ■C++ -Versions of a generic subprogram are created implicitly when the subprogram is named in a call or when its address is taken with the & operator -Generic subprograms are preceded by a template clause that lists the generic variables, which can be type names or class names template <class Type> Type max(Type first, Type second) { return first > second ? first : second; }

Task Synchronization

■A mechanism that controls the order in which tasks execute ■Two kinds of synchronization -Cooperation synchronization -Competition synchronization ■Task communication is necessary for synchronization, provided by: - Shared nonlocal variables - Parameters - Message passing

Mixed Mode Type Conversion

■A mixed-mode expression is one that has operands of different types ■A coercion is an implicit type conversion ■Disadvantage of coercions: -They decrease in the type error detection ability of the compiler ■In most languages, all numeric types are coerced in expressions, using widening conversions ■In ML and F#, there are no coercions in expressions ■Explicit Type Conversions ■Called casting in C-based languages ■Examples - C: (int)angle - F#: float(sum) Note that F#'s syntax is similar

Selection Statements

■A selection statement provides the means of choosing between two or more paths of execution ■Two general categories: -Two-way selectors -Multiple-way selectors

Basic Definitions

■A subprogram definition describes the interface to and the actions of the subprogram abstraction -In Python, function definitions are executable; in all other languages, they are non-executable -In Ruby, function definitions can appear either in or outside of class definitions. If outside, they are methods of Object. They can be called without an object, like a function -In Lua, all functions are anonymous ■A subprogram call is an explicit request that the subprogram be executed ■A subprogram header is the first part of the definition, including the name, the kind of subprogram, and the formal parameters ■The parameter profile (aka signature) of a subprogram is the number, order, and types of its parameters ■The protocol is a subprogram's parameter profile and, if it is a function, its return type ■Basic Definitions (continued) ■Function declarations in C and C++ are often called prototypes ■A subprogram declaration provides the protocol, but not the body, of the subprogram ■A formal parameter is a dummy variable listed in the subprogram header and used in the subprogram ■An actual parameter represents a value or address used in the subprogram call statement

Language Requirements for ADTs

■A syntactic unit in which to encapsulate the type definition ■A method of making type names and subprogram headers visible to clients, while hiding actual definitions ■Some primitive operations must be built into the language processor

Introduction to Subprogram-Level Concurrency

■A task or process or thread is a program unit that can be in concurrent execution with other program units ■Tasks differ from ordinary subprograms in that: -A task may be implicitly started -When a program unit starts the execution of a task, it is not necessarily suspended -When a task's execution is completed, control may not return to the caller ■Tasks usually work together ■Two General Categories of Tasks ■Heavyweight tasks execute in their own address space ■Lightweight tasks all run in the same address space - more efficient ■A task is disjoint if it does not communicate with or affect the execution of any other task in the program in any way

Object-Oriented Concepts

■ADTs are usually called classes ■Class instances are called objects ■A class that inherits is a derived class or a subclass ■The class from which another class inherits is a parent class or superclass ■Subprograms that define operations on objects are called methods ■Calls to methods are called messages ■The entire collection of methods of an object is called its message protocol or message interface ■Messages have two parts--a method name and the destination object ■In the simplest case, a class inherits all of the entities of its parent

Multiple-Way Selection Statements

■Allow the selection of one of any number of statements or statement groups ■Design Issues: •What is the form and type of the control expression? •How are the selectable segments specified? •Is execution flow through the structure restricted to include just a single selectable segment? •How are case values specified? •What is done about unrepresented expression values? ■Implementing Multiple Selectors ■Approaches: -Multiple conditional branches -Store case values in a table and use a linear search of the table -When there are more than ten cases, a hash table of case values can be used -If the number of cases is small and more than half of the whole range of case values are represented, an array whose indices are the case values and whose values are the case labels can be used ■Iterative Statements ■The repeated execution of a statement or compound statement is accomplished either by iteration or recursion ■General design issues for iteration control statements: 1. How is iteration controlled? 2. Where is the control mechanism in the loop?

Introduction to Data Abstraction

■An abstract data type is a user-defined data type that satisfies the following two conditions: -The representation of objects of the type is hidden from the program units that use these objects, so the only operations possible are those provided in the type's definition -The declarations of the type and the protocols of the operations on objects of the type are contained in a single syntactic unit. Other program units are allowed to create variables of the defined type. ■Advantages of Data Abstraction ■Advantages the first condition -Reliability--by hiding the data representations, user code cannot directly access objects of the type or depend on the representation, allowing the representation to be changed without affecting user code -Reduces the range of code and variables of which the programmer must be aware -Name conflicts are less likely ■Advantages of the second condition -Provides a method of program organization -Aids modifiability (everything associated with a data structure is together) -Separate compilation

The Concept of Abstraction

■An abstraction is a view or representation of an entity that includes only the most significant attributes ■The concept of abstraction is fundamental in programming (and computer science) ■Nearly all programming languages support process abstraction with subprograms ■Nearly all programming languages designed since 1980 support data abstraction

Short Circuit Evaluation

■An expression in which the result is determined without evaluating all of the operands and/or operators ■Example: (13 * a) * (b / 13 - 1) If a is zero, there is no need to evaluate (b /13 - 1) ■Problem with non-short-circuit evaluation index = 0; while (index <= length) && (LIST[index] != value) index++; -When index=length, LIST[index] will cause an indexing problem (assuming LIST is length - 1 long) ■C, C++, and Java: use short-circuit evaluation for the usual Boolean operators (&& and ||), but also provide bitwise Boolean operators that are not short circuit (& and |) ■All logic operators in Ruby, Perl, ML, F#, and Python are short-circuit evaluated ■Short-circuit evaluation exposes the potential problem of side effects in expressions

Overloaded Subprograms

■An overloaded subprogram is one that has the same name as another subprogram in the same referencing environment -Every version of an overloaded subprogram has a unique protocol ■C++, Java, C#, and Ada include predefined overloaded subprograms ■In Ada, the return type of an overloaded function can be used to disambiguate calls (thus two overloaded functions can have the same parameters) ■Ada, Java, C++, and C# allow users to write multiple versions of subprograms with the same name

Design Issues for Subprograms

■Are local variables static or dynamic? ■Can subprogram definitions appear in other subprogram definitions? ■What parameter passing methods are provided? ■Are parameter types checked? ■If subprograms can be passed as parameters and subprograms can be nested, what is the referencing environment of a passed subprogram? ■Are functional side effects allowed? ■What types of values can be returned from functions? ■How many values can be returned from functions? ■Can subprograms be overloaded? ■Can subprogram be generic? ■If the language allows nested subprograms, are closures supported? ■Semantic Models of Parameter Passing

Mixed-Mode Assignment

■Assignment statements can also be mixed-mode ■In Fortran, C, Perl, and C++, any numeric type value can be assigned to any numeric type variable ■In Java and C#, only widening assignment coercions are done ■In Ada, there is no assignment coercion

Pass-by-Name (Inout Mode)

■By textual substitution ■Formals are bound to an access method at the time of the call, but actual binding to a value or address takes place at the time of a reference or assignment ■Allows flexibility in late binding ■Implementation requires that the referencing environment of the caller is passed with the parameter, so the actual parameter address can be calculated

Parameter Passing Methods of Major Languages

■C -Pass-by-value -Pass-by-reference is achieved by using pointers as parameters ■C++ -A special pointer type called reference type for pass-by-reference ■Java -All parameters are passed are passed by value -Object parameters are passed by reference ■Fortran 95+ - Parameters can be declared to be in, out, or inout mode ■C# - Default method: pass-by-value -Pass-by-reference is specified by preceding both a formal parameter and its actual parameter with ref ■PHP: very similar to C#, except that either the actual or the formal parameter can specify ref ■Perl: all actual parameters are implicitly placed in a predefined array named @_ ■Python and Ruby use pass-by-assignment (all data values are objects); the actual is assigned to the formal

Assignment Statements: Conditional Targets

■Conditional targets (Perl) ($flag ? $total : $subtotal) = 0 Which is equivalent to if ($flag){ $total = 0 } else { $subtotal = 0 } ■Assignment Statements: Compound Assignment Operators ■A shorthand method of specifying a commonly needed form of assignment ■Introduced in ALGOL; adopted by C and the C-based languaes - Example a = a + b can be written as a += b

Kinds of synchronization

■Cooperation: Task A must wait for task B to complete some specific activity before task A can continue its execution, e.g., the producer-consumer problem ■Competition: Two or more tasks must use some resource that cannot be simultaneously used, e.g., a shared counter -Competition is usually provided by mutually exclusive access (approaches are discussed later)

Fundamentals of Subprograms

■Each subprogram has a single entry point ■The calling program is suspended during execution of the called subprogram ■Control always returns to the caller when the called subprogram's execution terminates

Arithmetic Expressions: Potentials for Side Effects

■Functional side effects: when a function changes a two-way parameter or a non-local variable ■Problem with functional side effects: -When a function referenced in an expression alters another operand of the expression; e.g., for a parameter change:

Two-Way Selection Statements

■General form: if control_expression then clause else clause ■Design Issues: - What is the form and type of the control expression? - How are the then and else clauses specified? - How should the meaning of nested selectors be specified? ■Nesting Selectors ■Java example if (sum == 0) if (count == 0) result = 0; else result = 1; ■Which if gets the else? ■Java's static semantics rule: else matches with the nearest previous if ■To force an alternative semantics, compound statements may be used: if (sum == 0) { if (count == 0) result = 0; } else result = 1; ■The above solution is used in C, C++, and C# ■Statement sequences as clauses: Ruby if sum == 0 then if count == 0 then result = 0 else result = 1 end end ■Python if sum == 0 : if count == 0 : result = 0 else : result = 1

Assignment in Functional Languages

■Identifiers in functional languages are only names of values ■ ML -Names are bound to values with val val fruit = apples + oranges; - If another val for fruit follows, it is a new and different name ■F# -F#'s let is like ML's val, except let also creates a new scope

Introduction to Exception Handling

■In a language without exception handling -When an exception occurs, control goes to the operating system, where a message is displayed and the program is terminated ■In a language with exception handling -Programs are allowed to trap some exceptions, thereby providing the possibility of fixing the problem and continuing

Semantic Models of Parameter Passing

■In mode ■Out mode ■Inout mode

Implementing Parameter-Passing Methods

■In most languages parameter communication takes place thru the run-time stack ■Pass-by-reference are the simplest to implement; only an address is placed in the stack

Assignment as an Expression

■In the C-based languages, Perl, and JavaScript, the assignment statement produces a result and can be used as an operand while ((ch = getchar())!= EOF){...} ch = getchar() is carried out; the result (assigned to ch) is used as a conditional value for the while statement ■Disadvantage: another kind of expression side effect

Parameters that are Subprogram Names

■It is sometimes convenient to pass subprogram names as parameters ■Issues: •Are parameter types checked? •What is the correct referencing environment for a subprogram that was sent as a parameter? ■Parameters that are Subprogram Names: Referencing Environment ■Shallow binding: The environment of the call statement that enacts the passed subprogram - Most natural for dynamic-scoped languages ■Deep binding: The environment of the definition of the passed subprogram - Most natural for static-scoped languages ■Ad hoc binding: The environment of the call statement that passed the subprogram

Basic Concepts

■Many languages allow programs to trap input/output errors (including EOF) ■An exception is any unusual event, either erroneous or not, detectable by either hardware or software, that may require special processing ■The special processing that may be required after detection of an exception is called exception handling ■The exception handling code unit is called an exception handler

Motivations for the Use of Concurrency

■Multiprocessor computers capable of physical concurrency are now widely used ■Even if a machine has just one processor, a program written to use concurrent execution can be faster than the same program written for nonconcurrent execution ■Involves a different way of designing software that can be very useful—many real-world situations involve concurrency ■Many program applications are now spread over multiple machines, either locally or over a network

Solutions to Function side effects

■No two-way parameters in functions ■No non-local references in functions ■Advantage: it works! ■Disadvantage: inflexibility of one-way parameters and lack of non-local references •Write the language definition to demand that operand evaluation order be fixed ■Disadvantage: limits some compiler optimizations ■Java requires that operands appear to be evaluated in left-to-right order

Single vs. Multiple Inheritance

■One disadvantage of inheritance for reuse: -Creates interdependencies among classes that complicate maintenance ■Introduction ■Concurrency can occur at four levels: -Machine instruction level -High-level language statement level -Unit level -Program level ■Because there are no language issues in instruction- and program-level concurrency, they are not addressed here

Pass-by-Reference (Inout Mode)

■Pass an access path ■Also called pass-by-sharing ■Advantage: Passing process is efficient (no copying and no duplicated storage) ■Disadvantages -Slower accesses (compared to pass-by-value) to formal parameters -Potentials for unwanted side effects (collisions) -Unwanted aliases (access broadened) fun(total, total); fun(list[i], list[j]; fun(list[i], i);

Multiple Assignments

■Perl, Ruby, and Lua allow multiple-target multiple-source assignments ($first, $second, $third) = (20, 30, 40); Also, the following is legal and performs an interchange: ($first, $second) = ($second, $first);

Actual/Formal Parameter Correspondence

■Positional -The binding of actual parameters to formal parameters is by position: the first actual parameter is bound to the first formal parameter and so forth -Safe and effective ■Keyword -The name of the formal parameter to which an actual parameter is to be bound is specified with the actual parameter -Advantage: Parameters can appear in any order, thereby avoiding parameter correspondence errors -Disadvantage: User must know the formal parameter's names

Inheritance

■Productivity increases can come from reuse -ADTs are difficult to reuse—always need changes -All ADTs are independent and at the same level ■Inheritance allows new classes defined in terms of existing ones, i.e., by allowing them to inherit common parts ■Inheritance addresses both of the above concerns--reuse ADTs after minor changes and define classes in a hierarchy

User-Located Loop Control Mechanisms

■Sometimes it is convenient for the programmers to decide a location for loop control (other than top or bottom of the loop) ■Simple design for single loops (e.g., break) ■Design issues for nested loops •Should the conditional be part of the exit? •Should control be transferable out of more than one loop?

Assignment Statements

■The general syntax <target_var> <assign_operator> <expression> ■The assignment operator = Fortran, BASIC, the C-based languages := Ada ■= can be bad when it is overloaded for the relational operator for equality (that's why the C-based languages use == as the relational operator)

Iteration Based on Data Structures

■The number of elements in a data structure controls loop iteration ■Control mechanism is a call to an iterator function that returns the next element in some chosen order, if there is one; else loop is terminate ■C's for can be used to build a user-defined iterator: for (p=root; p==NULL; traverse(p)){ ... }

Pass-by-Value (In Mode)

■The value of the actual parameter is used to initialize the corresponding formal parameter -Normally implemented by copying -Can be implemented by transmitting an access path but not recommended (enforcing write protection is not easy) -Disadvantages (if by physical move): additional storage is required (stored twice) and the actual move can be costly (for large parameters) -Disadvantages (if by access path method): must write-protect in the called subprogram and accesses cost more (indirect addressing)

Categories of Subprograms

■There are two categories of subprograms -Procedures are collection of statements that define parameterized computations -Functions structurally resemble procedures but are semantically modeled on mathematical functions ■ They are expected to produce no side effects ■ In practice, program functions have side effects

Object-Oriented Programming

■Three major language features: -Abstract data types (Chapter 11) -Inheritance Inheritance is the central theme in OOP and languages that support it -Polymorphism

Unconditional Branching

■Transfers execution control to a specified place in the program ■Represented one of the most heated debates in 1960's and 1970's ■Major concern: Readability ■Some languages do not support goto statement (e.g., Java) ■C# offers goto statement (can be used in switch statements) ■Loop exit statements are restricted and somewhat camouflaged goto's

Design Considerations for Parameter Passing

■Two important considerations -Efficiency -One-way or two-way data transfer ■But the above considerations are in conflict -Good programming suggest limited access to variables, which means one-way whenever possible -But pass-by-reference is more efficient to pass structures of significant size

Assignment Statements: Unary Assignment Operators

■Unary assignment operators in C-based languages combine increment and decrement operations with assignment ■Examples sum = ++count (count incremented, then assigned to sum) sum = count++ (count assigned to sum, then incremented count++ (count incremented) -count++ (count incremented then negated)

Pass-by-Result (Out Mode)

■When a parameter is passed by result, no value is transmitted to the subprogram; the corresponding formal parameter acts as a local variable; its value is transmitted to caller's actual parameter when control is returned to the caller, by physical move -Require extra storage location and copy operation ■Potential problems: -sub(p1, p1); whichever formal parameter is copied back will represent the current value of p1 -sub(list[sub], sub); Compute address of list[sub] at the beginning of the subprogram or end?

Three ways a class can differ from its parent:

1. The subclass can add variables and/or methods to those inherited from the parent 2. The subclass can modify the behavior of one or more of its inherited methods. 3. The parent class can define some of its variables or methods to have private access, which means they will not be visible in the subclass

Pass-by-Value-Result (inout Mode)

A combination of pass-by-value and pass-by-result ■Sometimes called pass-by-copy ■Formal parameters have local storage ■Disadvantages: -Those of pass-by-result -Those of pass-by-value

Narrowing Type Conversion

A narrowing conversion is one that converts an object to a type that cannot include all of the values of the original type e.g., float to int

Widening Type Conversion

A widening conversion is one in which an object is converted to a type that can include at least approximations to all of the values of the original type e.g., int to float


Ensembles d'études connexes

Thermoregulation and Newborn Complications (2.4)

View Set

Civil Litigation Of Procedures 1345 chat 1-7

View Set

Chapter 6- Disorders of the Breasts (ob)

View Set