W3 & W4 Flashcards

1
Q

Procedural Abstraction

A

the hiding of details regarding an implementation within a procedure or function, allowing users to focus on high-level operations
Can be done within:
- An expression (combination of variables, operators and constants that when evaluated produces a value)
- A statement (complete line of code that performs an action)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can Procedural Abstraction be done ?

A

Can be done by means of methods that:
- Operate on parameter objects
- Return a primitive value, object, or void

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is modularisation for data (data abstraction)

A

Combining variables of primitive types that frequently occur together into a single abstraction with a single name, instead of handling them separately

e.g., the numerator and denominator of a fraction, or a pair or triple of coordinates of a point in the plane

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can Modularisation for data be done?

A

Grouping can be accomplished by String, array, and class, but only class can introduce a new name for the type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Top-down Design

A
  • Given one big problem, split it into smaller subproblems
  • Continue until reaching trivially solvable problems -> solutions
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Bottom-up Design

A
  • Given many small solutions, combine them into bigger solutions
  • Continue until reaching a solution of the main problem
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Data type definition

A

A data type is a set of values and the accompanying operations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Primitive data type

A

int, double, char, boolean, String

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Enumerations

A
  • Special data type that consists of a set of named constants (enumerators)
  • Objects of an enumeration can take any of the values of the enumerators

Defined as follows:

PrimaryColor { RED, GREEN, BLUE }
PrimaryColor v = PrimaryColor.Red

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Operations for Enumeration T

A
  • T.VALUE (where VALUE is possible value)
  • T.values()- v.name() (v is an object of type T)
  • v.toString()
    -T.valueOf(s) - returns the enumeration constant for name s
  • v.ordinal(s) - returns the position of an enumeration constant s within its enum declaration\
  • v.compareTo(w) - negative return value - the first (v) comes before second (w)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Records

A

Provide a concise way to declare unchangeable data-carrying classes by automatically generating standard methods such as constructors, getters, equals(), hashCode(), and toString() based on the class’s fields

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Features of Records

A
  • Cannot change the values in a record
  • Can only read
  • Comes with many predefined method getterMethod()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Abstract Data Type

A

A high-level description of a set of operations that can be performed on a certain type of data, along with the constraints or properties that these operations must adhere to.

  • It defines what the data type does, not how it does it
  • ADTs hide the representation of data and implementation of operations
  • They are usually abstract classes/interfaces that are implemented
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Abstract Data Classes

A
  • A method can be declared abstract, and this means that it does not have an implementation
  • Any class containing abstract methods must be declared abstract
  • An abstract class cannot be instantiated
  • A subclass can define additional instance variables and implementations for inherited abstract methods by overriding
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Public invariants in ADTs

A

The properties or conditions that must be true for the data type’s public methods to function correctly (kinda like robustness)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Interfaces

A

Interfaces define a collection of method headers with contracts

Can define constants with public static final

Can have default method implementations but still no instance variables

Somewhat like a class with abstract methods but a class can implement one or more interfaces via implements by implementing each of the methods in the interface(s)

Interfaces can be viewed as a type; its values are the values of all classes that implement the interface

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Interfaces vs. Abstract Classes

A
  • Abstract classes support single inheritance while interfaces support multiple
  • Interfaces cannot have constructors while AC can
  • All fields in interfaces are implicitly public, static, and final
  • Interfaces cannot have instance variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

ADTs as specification

A

abstract classes and interfaces can both be used to hold just the specification of a class, leaving the actual implementation to the classes that extend/implement them

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

ADT implementation - Components for values

A
  1. Data representation
    - defined in terms of instance variables that represent intended abstract values of the ADT
  2. Representation invariant
    - refers to the conditions to be satisfied by the instance variables in order to make sense as a representation of an abstract value
  3. Abstraction function
    - maps each representation that satisfies the representation invariant to the represented abstract value
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

ADT implementation - Conditions for Operations

A
  • Involves providing a method implementation adhering to the contract for each operation
  • The pre- and postconditions of each operation must be re-interpreted in terms of the data representation, using the abstraction function
  • Also, the public invariant must be honoured
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Polymorphisms

A

The ability of objects of different classes to be treated as objects of a common base class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Primitive vs. class type variables

A
  • A variable of a primitive type always holds a value of that exact primitive type
  • A variable of a class type T can hold a null reference or a reference to an instance of class T or of any class that is a subclass of T
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Liskov Substitution Principle (LSP)

A

Let U be a subclass of T.

Type U is called a subtype of type T when:- In each place where an object of type T can be used, you can substitute an object of type U without affecting the correctness of the program.

A subtype is not only syntactically a substitute (it compiles), but also semantically (it works).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Strategy Design Pattern

A

Problem: Accommodate multiple implementations of the same method by allowing selection at runtime.

Solution:
- Put specification of method in (abstract) class or interface
- Put implementations in subclasses of specification type
- Declare variable with specification type
- Assign to variable an object of an implementation type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Components of Strategy Design Pattern

A
  1. Strategy Interface:
    - an interface that declares the method(s) that represent the algorithm or strategy
    - defines a family of algorithms without specifying their concrete implementations
  2. Concrete Strategy:
    - implements the Strategy interface and adds a specific implementation of the interface’s method specifications
  3. Context:
    - class that holds a reference to a strategy object and uses it to perform a specific operation
26
Q

Code Example for Strategy Design Pattern

A

// Strategy interface
interface PaymentStrategy {
void pay(int amount);
}

// Concrete strategy 1
class CreditCardPayment implements PaymentStrategy {
private String cardNumber;

public CreditCardPayment(String cardNumber) {
    this.cardNumber = cardNumber;
}

@Override
public void pay(int amount) {
    System.out.println("Paid " + amount + " using credit card " + cardNumber);
} }

// Concrete strategy 2
class PayPalPayment implements PaymentStrategy {
private String email;

public PayPalPayment(String email) {
    this.email = email;
}

@Override
public void pay(int amount) {
    System.out.println("Paid " + amount + " using PayPal with email " + email);
} }

// Context class
class ShoppingCart {
private PaymentStrategy paymentStrategy;

public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
    this.paymentStrategy = paymentStrategy;
}

public void checkout(int amount) {
    if (paymentStrategy != null) {
        paymentStrategy.pay(amount);
    } else {
        System.out.println("Please set a payment strategy before checkout.");
    }
} }
27
Q

Client Code Example for Strategy Design Pattern

A

// Client code
public class StrategyPatternExample {
public static void main(String[] args) {
// Creating context
ShoppingCart cart = new ShoppingCart();

    // Using credit card payment strategy
    cart.setPaymentStrategy(new CreditCardPayment("1234-5678-9101-1121"));
    cart.checkout(100);

    // Using PayPal payment strategy
    cart.setPaymentStrategy(new PayPalPayment("john.doe@example.com"));
    cart.checkout(50);
} }
28
Q

Intent of the Singleton Design Pattern

A
  • Ensures that not more than one instance of a class is ever created
  • Provides a global point of access to this instance
29
Q

Solution of the Singleton Design Pattern:

A
  • Make the constructor of the class private to prevent clients from creating instances directly
  • Create a private static instance of the class
  • Add a public static synchronised method getInstance() that returns an instance of the class if one has not already been created
  • If a class has already been created, getInstance() returns that instance
30
Q

Singleton vs. Global variable

A

Benefits:
- Both allow easy access
- Singleton ensures at most one instance is created

Drawbacks:
- Global variables creates name space pollution
- Global variables creates uncertain intialisation order
- Global variable no access control on variable
- Both create weakened modularity, as all modules will have depend on only one instance
- Testing is more difficult because all test most work on the same variable
- Code reuse is hindered because you must reuse the global variable

31
Q

How to avoid dependency on globals?

A

Parameterizing modules and supplying actual concrete globals as arguments

Make other modules depend on an abstract interface, hence they do not depend on concrete globals

Create an interface that holds the variable that would have otherwise been global and have any class that would make use of that variable implement the interface

32
Q

Template Method Pattern Motivation

A
  • Some code fragments may resemble each other without being duplicates
  • Resemblance is in overall structure, and hence parameters are not a solution
  • Difference is in some steps
33
Q

Temple Method Pattern Intent

A

Create an abstract class with a final templateMethod() that calls some other methods in it.Make those methods abstract so that they can be edited by the classes that extend the superclass.

34
Q

Alternative to Template Method Patter

A
  • Consider each step a Strategy and apply strategy design pattern
  • Introduce a template method class with a constructor with parameter for each abstract step type and instance variable for each abstract step
  • Client code passes concrete steps into the class
35
Q

Dependency Inversion Principle (DIP)

A

high-level modules should not depend on low-level modules, but both should depend on abstractions

For high-level modules write abstract classes and extend the class and @overide the method

36
Q

Factory Method Design Pattern Motivation

A

Tackles the problem of new statements requiring constructors of a concrete class, which makes client code depend on the concrete class

37
Q

Factory Method Design Pattern Intent

A

to define an interface for creating an object, but subclasses decide which class to instantiate (creating an object)

38
Q

Factory Method Design Pattern how to construct

A
  1. Create two different abstract classes, one called product and one called productCreator
  2. Inside productCreator add two methods one abstract, and one with an implementation.
  3. Call the former (abstract) createProduct method and the latter clientCode.
  4. CreateProduct has no implementation as it is abstract and clientCode creates a new product object and assigns to it the ouptut of createProduct
  5. For each of the types of products relevent create a class that extends the product abstract class and create a class that extends the product creator class. 6. For each of the classes extending the productCreator class overide the createProduct method, returning an object of the product subclass represented by the product creator subclass.
39
Q

Encapsulate what varies

A

Identify the aspects of your application that vary, and separate them from what stays the same

40
Q

Generic Types Definitions

A
  • A generic type is equivalent to a parameterized type
  • E.g., List<E> where E is a formal type parameter</E>
  • Are used by substituting concrete class types for the formal type parameter
  • E.g., List<String></String>
  • Benefits are improved readability, reusability, and robustness
41
Q

Iteration can abstract:

A
  • Type of collection
  • Type of its items
  • Implementation details of how to accomplish iteration
42
Q

Testing cases for Iterators

A
  • Check that every element is returned exactly once (no misses, no duplicates)
    -Check that iterator works without and with multiple calls to hasNext()
43
Q

Some Iterator Anti-Patterns

A
  • Giving access to internal data representation to let the client iterate
  • leaks representation and client can break rep invariant
  • Include operations for iteration in collection class itself, which leads to not being able to have multiple iterations active concurrently
44
Q

Dynamic Structure

A
  • A stack of call methods, where a lower method calls are added on the stack when the highest method in the stack will call them
45
Q

Top-level class

A

class that is not defined as nested or inner class within another class, but is the primary, outermost class in a Java source file

46
Q

Nested class

A

A class that is defined within another class

47
Q

Types of nested classes

A
  • Static member class
  • Non-Static member class
  • Named local class
  • Anonymous class
48
Q

Static member class

A

A class inside another class with static header OR
A class in the same file with another class but not inside it OR
A class in a different file

  • If it is in the same file, it cannot be public
  • Only has access to instance variables and methods of outclass if they are static
  • Can refer directly to all static members of outer class without qualifying there name
49
Q

Non-static member class

A
  • Has to be in a class without static header
  • Each instance of nested class is associated with the instance of the top-level class inside which it was constructed
  • Creating and accessing objects of inner class is done statically
  • Can access all member of the outclass
  • Inner class cannot contain static members unless they are also final
50
Q

Named local class

A
  • Define within a block of code, typically within a method
  • Can only access the variables of the enclosing block of code if they are declared as final or effectively final (it is assigned once and never changed but does not have the final thing)
51
Q

Anonymous class

A
  • Special type of local class that does not have a named identifier
  • often used for one-time use
  • defined directly as a new instance is created
  • e.g. of definition, Class class = new Class() {///inside of class }
  • Limitations - Cannot define their own constructors
52
Q

Benefits of Nested Classes and Interfaces

A
  • Logical Grouping (increased coherence)
  • Encapsulation (decreased coupling)
  • Improving readability and maintainability
  • Simpler code
53
Q

Sharing/aliasing def

A

which is when two distinct variables name the same object

54
Q

Immutable

A

When the state of a T object cannot change after construction

55
Q

Two Objects are Equal When

A

they are behaviourally indistinguishable

That is, every sequence of operation (queries and commands), when applied to both objects, yields the same result.

56
Q

Two objects are said to be similar when ..

A

observationally indistinguishable. That is, every sequence of queries only (no commands), when applied to both objects, yields the same result.

57
Q

==

A

checks whether two object references point to the exact same memory location

58
Q

.equals

A

checks whether the actual contents or values of objects to determine if they are equivalent

59
Q

Mutable vs Immutable Objects

A

Mutable objects are equal when they are the same object,i.e., they are in the same place in memory.

Immutable objects are ALSO equal if they’re similar, i.e., if they have the same state, but not necessarily in the same place in memory.

60
Q

Iterator Design Pattern

A

behavioral pattern that provides a way to access the elements of a collection sequentially without exposing the underlying representation of the collection

defines a standardized interface for iterating over the elements of a collection, allowing clients to traverse the elements without being aware of the specific details of the collection’s implementation