Anda di halaman 1dari 9

1) Inheritance

IPEA 4

Inherits methods & structure but can override or add new methods, and add
instance variables.

Useful for creating a hierarchy of types of objects for substitutability of a


superclass instance with a subclass instance which may be a more specialised
version of the superclass. Its also useful for programming by difference
(making a quick copy and slightly altering it, perhaps for a quick hack or to
test/debug)

2)

Encapsulation

3)

Polymorphism

Hiding information by restricting access to getters and setters, thus bundling


the data (vars) and operations on it (methods) as 1 unit
When a program can handle objects differently depending on their class/data
type (e.g. map h = new hashmap(); <- h can be treated as a hashmap so map
methods are handled differently [as hashmap methods]) (e.g. divide is
different for variable x depending on if int (int division) or float (decimal
division)

Polymorphic methods can be applied to more than 1 type of object


4)

Abstraction

Manages complexity by suppressing/hiding complex details on lower levels.

Static vs Dynamic Binding

VOCAB

Code determined at compile time vs at runtime based on class of receiver

Access to class members 4

1) No modifier allows class and package access


2) Protected additionally allows subclasses access (even if in diff package)

3) Private ONLY class


4) Public Everyone

Cohesion

How well a set of elements group together, belong together how unified
their nature is, how strongly they relate to each other. Do they do/represent
one specific thing?
High cohesion is associated with robustness, reliability, reusability and
understandability. Low cohesion is associated with being hard to test, reuse,
maintain and read.

Coupling

How much one object needs/makes use of knowledge of another to function,


how much it depends on the internal representation of it. How interrelated
they are.
High/tight coupling is correlated with low cohesion and low/loose coupling is
associated with high cohesion.

PRINCIPLES

Program to an interface, not an implementation 3: SAC

Focus on what the code needs to achieve, not how it does, to create a
structure/pattern that works even if the hows/implementation changes.

Implementation more likely to change than structure, and its already harder
moulding structure to fit implementation than vice versa so let
implementation depend on more reliable static structure.

- High cohesion, low coupling


o Abstraction since client only sees what they need to see in the
class, not specifics
o Substitutability since one object can easily replace another since
pattern/structure/interface holds
o Composition (of methods) enabled since only the parts needed for
it are exposed (the whats, not the hows)

Open-Close principle: classes, modules, functions should be open for


extension and closed for modification (since things rely on them)

Dependency inversion principle: High level modules should not rely on


low level modules, but both (and details) should rely on abstraction.

Code Re-use

- New code composed of old (e.g. classes) / composition - BLACKBOX


- Inheritance if similar to something existent - WHITEBOX

Blackbox framework

Importing and using classes within your own classes to add application-specific
behaviour (dont really look into their classes)

Whitebox framework

Inheriting skeletal implementation from a class then adding applicationspecific behaviour (rip their classes open and add to their insides)

Refactoring 2

Improving code via modification in a systematic way to prevent introducing


new bugs.

- Rename method: To rename, create new method with new name but
same body, change old methods body to call new method, and
systematically change every old reference to old method, to new one.
- Moving common subclass methods to superclass: Check/make method
bodies and signatures the same via rename method & var changing.
Make superclass method and copy body over. Change reference to old
signatures to new. Test to catch all. Delete one old method, test, repeat
until error.

Entity-Boundary-Control Pattern/UML Classes

UML

- Long standing behaviour-info combo, look for nouns & noun phrases
describing responsibility (like product and buyer, transaction and
sender)

- Object that interface with system actors, communicates between system


surroundings and insides (like databaseGateway, userInterface, GUI)
- runs a usecase with behaviour specific to it. The do-er (like
createAccount)

Relationships

- Kind of: subclass (e.g. studentRecords: kind of record)


- Part of: aggregation/collaboration (e.g. student: part of studentRecords)

Attributes: VisName: Type (e.g. +myNumber: int)

Operations: VisName(Parameter Type): Return Type (e.g. +setNumber(int):


void)
Vis: +(public) or #(protected) or (private)

Abstract classes

- Can not be instantiated, only subclassed (though if has main method,


can be invoked)

- A class can extend only ONE abstract class


- Subclasses that dont provide implementation for ALL abstract methods
must be declared abstract. Otherwise we call them concrete classes.
- An abstract (declared) method does not have an implementation
signature

Abstract classes can implement (declared) interfaces without actually


providing all implementation

Interface

- Just a PATTERN/contract cant be instantiated


- Always public
- Contains (common) method signatures ONLY so every method is
implicitly abstract (can have method bodies in java 8 though)
- Contains variables, if declared then final (declared)
- A class may implement (declared) many interfaces
- An implementation MUST provide functionality for all methods (less
flexible) (though interfaces can be made to extend (declared) interfaces)

FACTORY (incl abstract factory)

Design Patterns 5

The client asks the factory to make something, the factory knows how to
create what the client wants (knows which class it should be and what
constructor to call) and so does. They all inherit/implement the same abstract
class or interface so the client can interact with them the same way

ADAPTER (wrapper)

The client sends a request how it expects to to an interface and the


implementation implements the bad request by calling the right one,
effectively converting it like and adapter.

CHAIN OF RESPONSIBILITY

The client makes a request that a class takes on and if it cant handle it, hands
it to the next successive handler. This continues until it is handled.

STRATEGY

As the context changes, what strategy should be used (for some request if it
were called in this context) is associated with that object[-request combo] (e.g.
via an encapsulated var strategy that is used in the method body for the
request to call the right algorithm) so at any time, the clients request will be
automatically passed onto the right <<Strategy>> implementations method
(which are of course all invoked the same, but have different bodies)

OBSERVER

When an object repping internal state changes, it notifies an (abstract)


observer via update() that then notifies relevant concrete classes so they can
update themselves accordingly.
Cons:

- Garbage collection even if the concrete classes are not used, they
wont be garbage collected until the observer removes its reference to it
- Problems if the list of references changes/object state changes during
notification and update process

Threads

CONCURRNCY IN JAVA

Have their own 3

- program counter (counter of where they are in their instructions)


- stack (history)
- local variables (since theyre doing their own thing)

They share

- memory space/file handles (actual location/directory)


- heap (shared memory for communication and shared storage)

They fork/join: fork off to do concurrent tasks then join main execution thread
Pros

- Resource utilization: Allows another thread to utilize an idle resource


while the other one i) executes (only if multiple processors) or ii) is
waiting [aka asynchronous execution] (any no. processors), or both via
scheduling sequential workflows, rather than leaving them both idle
- Fairness: to share resource time (fine-grain time slicing) amongst many
threads, than have one dominate the system until completion
- Convenient: to code multiple separate tasks than coordinate tasks urself
- Complex apps: concurrent threading potential aids complex apps that
are I/O intensive like GUIs they allow better responsiveness even when
tasks have been initiated by user since reliance on time sharing is aided
by possible concurrent execution (multi processor)

Cons

- Threads share memory space of owning process


o Risk if lacks synchronisation if a thread tries to change data that
another is currently accessing (changing [race conditions] or using
[memory visibility failure]) that gives unpredictable results.
- Performancce Hazards
o Runtime overhead (context switches suspension of one thread
for another) (synchronization inhibit compiler optimization,
invalidate memory cache, shared memory bus traffic)

Performance hazards 5: Service time, responsiveness, throughput,


resource consumption, scalability.

Thread Safety

System calls or library routines are thread safe if they can be called
simultaneously by multiple threads, yet still give the same result.

LIVENESS HAZARDS 3

Liveness FAILURE occurs when an activity enters a state where it an


never progress

1) DEADLOCK

When 2 tasks are waiting on eachother, thus can never provide


the other with what they need to progress

2) STARVATION

A task is perpetually denied access to a resource it needs to


progress

3) LIVELOCK

A task cannot progress without performing an operation that


always fails

Compound actions vs Atomic

Take more than one step to complete thus potentially allowing interleaving
actions (not thread-safe sometines!) vs one step actions that dont.

Check-then-act, Read-modify-write, ifnull-thencreate (e.g. incr) are compound


types

CONCURRENCY HAZARDS TO THREAD SAFETY


1) RACE CONDITIONS

Where a thread tries to change shared data another thread is accessing


at the same time without synchronization race to see who gets there
first, outcome unknown bc thread switching.

2) MEMORY VISIBILITY FAILURE

o When one thread modifies shared data but another sees instead
stale data (not most updated)
o When an object has escaped (published when it shouldnt be)
before fully constructed
E.g. returned from non-private method
Passing to method in other class

GOLDEN RULE

If many want to access a shared (mutable) state var and even ONE wants to
modify: All access must be synchronized.
So of course STATELESS OBJECT= THREAD SAFE

Synchronization: Abstraction for concurrency

- AtomicVariable (AtomicInteger, AtomicLong)


o Automic state transitions
Automic Operation: To ALL operations, either none or all of
this op has been done
- Keyword: synchronized
o Synchronized method (in signature after vis) to lock whole method
under object method acts on
o As a block: synchronized (objectLockIsOn) {code}
lock could be on .class (by class instance) or this (instance)
- Explicit locks
o Locks give MUTUALLY EXCLUSIVE ACCESS to a thread
o Code under same lock execute atomically
o MUST used on compound actions on shared state or else race
conditions
o Can cause DEADLOCK
- Keyword: volatile variables for visibility problems
o Never cached thread-locally
o Cant be used to make incr atomic
- TheadLocal (thread confinement = thread safe) method keyword