TDT4240: Software Architecture
## Introduction
### Glossary
|| Module || Code that together serves some functionality X. ||
|| Component || Two or more modules that serves some services Y ||
|| System || "A collection of components organized to accomplish a specific function or set of functions." (From the 2000 IEEE-standard, see the section at the end of this artcile) ||
|| Architectural description (AD) || "A collection of products to document an architecture" (IEEE, 2000)||
|| Architecture || "The fundamental organization of a system emodied in its components, their relationships to each other, and to the environment, and the principles guiding its design av evolution." (IEEE, 2000)||
|| Pattern || "[..] Usually describes software abstractions used by advanced designers and programmers in their software. [..] It can be applied to both the thing (for example, a collection class and its associated iterator) and the directions of rmaking a thing." - Coplien J. (1998) ||
|| Architectural patterns || A pattern that can be used when designing an architecture. ||
|| Design patterns || A pattern that can be used for solving a problem in a subsystem, or a coding problem in a module. ||
|| View|| "A representation of a whole system from the perspective of a related set of concerns" (IEEE, 2000) Eg. a logical view and a development view of the system. ||
This means the arhcitectural patterns are at a higher level than the design patterns.
## Architectural patterns
### Module Patterns
#### Layered Pattern
Layers are always drawn as a stack of boxes.
All layers can use the public interfaces of the other layers (layer bridging).
### Component-and-Connector Patterns
#### Broker Pattern
The broker pattern solves the problem of having many services distibuted among multiple servers.
It sets a broker between the client and the servers.
The broker forwards the client to the correct server and the servers response to the client that ordered it.
#### Model-View-Controller Pattern
We divide the software in to a model with the application data, a view that displays it and a controller that manages the notifications of state changes.
||View|| A view is shown to the user. It reads and visualizes data. ||

#### Pipe-and-Filter Pattern
Software needed is supposed to transform streams of data multiple time.
The solution is a pipeline with filters, altering the data in the correct order.
#### Client-Server Pattern
Shared resources and services needs to be easily accessed and we have a large number of clients.
Clients requests services from servers. Note that some components can be both clients and servers.
#### Peer-to-Peer Pattern
Peer-to-peer is typically a request-reply system. A peers search for another is often directed through peers in the middle, thus forming a swarm. Bittorrent much?
#### Service-Oriented Pattern
#### Publish-Subscribe Pattern
Components work together via announced messages or events. Components may subscribe to a set of events. Any component may be both publisher and subscriber.
#### Shared-Data Pattern
Shared data between multiple data accessors and shared data stores. The connector enables data reading and writing to these stores.
### Allocation Patterns
#### Map-Reduce Pattern
#### Multi-Tier Pattern
If tiers group components of similar functionality it is c&c.
Allocation if tiers are distributed.
Computationally independent nodes.
## Design patterns
### Singleton pattern
A class is only instantiated once and can be changed by everyone.
The constructor is private, so the object will only be created inside the class.
It is important that we can retrieve the instance created from outside the class.
A singleton pattern is not necessarily optimized for multithreading.
### Observer pattern
For example: A program taking an integer and presenting it in different numeral systems.
A subclass notifies the observer that an integer has been entered, the observer notifies all subclasses, in our example the octal, binary, and hexa- classes. They return their updated state.
### State pattern
A main class listens to what state the program is in, and changes based on what state the program is in.
For example:
A program starting to run will trigger the onCreate, or start method.
When the running state is set to false this will trigger the onDestroy method.
### Template pattern
In java term (might want to generalize this a bit more), we have an abstract parent class thus it cannot be instantiated. It is extended by child classes inheriting its properties.
For example: The Zoo animals
A zoo animal is a class containing legs, methods for feeding. That is inherited by elephants, dogs etc...
The elephants eat other things than dogs, so we initialize the actual methods in dogs and elephants class.
### Abstract factory pattern
The abstract factory pattern creates an abstract factory with some general properties. We then make factories for each of these properties. Each of these factories makes an interface able to generate our instance of for example shape in the figure below (TODO explanation needs to be simpler):

# Quality Attributes (Chapters 5 - 12)
Testable property of a system to tell how well the system is satisfying the needs of the stakeholders. The attributes hold three types of categories:
- Functional Requirements: What the system must do, behave or react.
- Quality Attribute Requirements: Qualification of functional requirements. For instance how fast a function must perform.
- Constraints: Design decision with zero degrees of freedom. For instance the use of certain programming language.
### Availability
It refers to the property of software that is there and ready to carry out its task when you need it to bee. It encompasses both reliability and dependability.
|| Reliability || Delivers data to the right recipent at the right time. ||
|| Dependability || "The ability to avoid failures that rare more frequent and more severe than acceptable." - Avizienis ||
This means that availability is about detecting and preventing faults, but also recovering from them. The book points out that one could say "failure is not an option", but that it is a lousy design philosophy as it would not work in practice.
The term "high availability" typically refers to "5 nine"-availability (99.999 % avaiaibility) or higher, which translates to 1 minute and 18 seconds of downtime over 90 days, or 5 minutes and 15 seconds over a year.
#### General scenario
|| __Source of stimulus__ || ||
|| __Stimulus__ || ||
|| __Artifacts__ || ||
|| __Environment__ || ||
|| __Response__ || ||
|| __Response measure__ || ||
#### Tactics
The goal of these tactics is to mask or repair the fault.

** Detect faults **
|| Monitor || A component monitors all services and reports inconsistencies ||
|| Sanity checking || Checks validity or how reasonable the output from a component ||
** Recover from faults **
** Prevent faults **
### Interoperability
> Interoperability is about the degree to which two or more systems can usefully exchange meaningful information via interfaces in a particular context.
It includes:
|| Syntactic interoperability || The ability to exchange data. ||
|| Semantic interoperability || The ability to correctly interpet the data being exchanged. ||
A system cannot be interoperable in isolation. They can interoperate in indirect ways.
Reasons you would want interoperability in your system:
- Your system provides a service to be used by other (unknown) systems
|| Discovery || The system/consumer of some service has to know (discover) the location, identity and interface of the service to be used. This may be done during runtime, or prior to runtime. ||
|| Handling of the response || The service can either: Report back with a response, broadcast the response or send the response to another system. ||
One also has to manage available interfaces.
#### General scenario
|| __Source of stimulus__ || A system that initiates a request. ||
|| __Stimulus__ || request to exchange information among systems ||
|| __Artifacts__ || The systems that wish to interoperate ||
|| __Response measure__ || Percentage of information exchanges correctly processed, or the percentage correctly rejected. ||
See example on page 107, figure 6.1.
#### Tactics

**Locate**
|| || ||
** Manage interfaces **
### Modifiability
> Change happens.
Four questions to consider when planning for modifiability:
- What can change?
- What is the likelihood of the change?
- Where is the change made, and who makes it?
- What is the cost of the change?
Important measures:
|| Coupling || How modules or components are tied together. You'll want _loose coupling_, which means that they aren't too tight. It's important because it'll make it harder to modify the system. E.g. if module A is dependent on B and C, which in turn is dependent on each other and on A. ||
#### General scenario
|| __Source of stimulus__ || Who makes the change: End user, developer, sysadmin. ||
|| __Stimulus__ || Someone wants the change.. ||
|| __Artifacts__ || Code, data, interfaces, components, resources, configurations .. ||
|| __Environment__ || Runtime, compile time, build tme, inititation time, design time. ||
|| __Response__ || Make, test or deploy modification ||
|| __Response measure__ || Cost in terms of time, effort, money, new defects, complexity ||
#### Tactics

||** Reduce the size of a module** || ||
|| ** Increase cohesion ** || ||
|| **Reduce coupling** || ||
|| Encapsulate || Private and public methods. Have explicit interfaces for other modules to use, hide what's irrelevant to them. ||
|| Use an intermediary || But something in between dependencies. If A is dependent on B, but X in between to handle that communication. This leaves A and B more free from each other.The intermediary depends on the type of dependency. ||
|| Restrict dependencies || Some module A can only talk with a given set of modules X. In practice this means you'll restrict modules visibility. ||
|| Refactor || Rewrite code so that you do not have duplicated code or responsibilites, and so that the code can be easiliy understood by developers. ||
|| Abstract common services || In the case two modules provide _almost_ the same services, it will increase modifiability to let them implement some abstract service. (In Java, this means creating an abstract class.) ||
** Defer binding**
> A parameterized function $f(a, b)$ is more general than the similar function $f(a)$ that assumes $b=0$. When we bind the value of some parameters at a different phase in the life cycle than the one in which we defined the parameters, we are applying the defer binding tactic.
You'll want to bind as late as possible, so a change will only mean a change of argument, not the inner workings of a module.
### Performance
>It's about time.
Performance describes the software's ability to meet time requirements.
#### General scenario
|| __Source of stimulus__ || Internal or external to the system ||
|| __Stimulus__ || Arrival of a periodic, sporadic or stochastic ||
|| __Artifacts__ || System, or one or more components of the system ||
|| __Environment__ || Operational: normal, emergency, peak or overload ||
|| __Response__ || Process events, change level of service ||
|| __Response measure__ || Latency, deadline, throughput, jitter, miss rate ||
#### Tactics
![Figure 8.3 from the book] (http://i.imgur.com/sFNjw2Q.jpg)
||**Control resource demand** || Work to produce smaller demand ||
|| Managing sampling rate || Reduce the sampling rate environmental data is captured. ||
|| Limit event response || Queue up events, or processor utilization measure. ||
|| Prioritize events || Priortize events depending on how important it is to process them. ||
|| Reduce overhead || Reduce intermediaries (important for modifiability). Modifiability/performance-tradeoff. ||
|| Bound execution times || Limit how much time can be used to process an event. ||
|| Increase resource efficiency || Improve critical algorithms. ||
||**Manage resources**|| Work to make the resources at hand work more efficiently ||
|| Increase resources || Costs money. ||
|| Introduce concurrency || Process in parallel when possible ||
|| Maintain multiple copies of computations aka Caching || Introduces new responsibilities, like keeping data syncronized and chosing what data to be cached. ||
|| Bound queue sizes || Limit the events that can arrive, and you'll limit the resources spent on processing events. Need policy for what happens wtih queue overflow. Often paired with limit event response tactic. ||
|| Schedule resources || If there's contention for a resource, the resource must be scheduled. ||
### Security
Measures the system's ability to protect data from those who are not meant to have access, while still giving those who are authorized access.
Simple characteristic of security (for short: CIA):
|| 1. Confidensiality || Data is protected from unauthorized access. ||
|| 2. Integrity || Data is not subject to unauthorized manupulation. ||
|| 3. Availability || System and data is available for legitimate use. ||
Other characteristics used to support CIA:
|| 4. Authenication || Verifies identities ||
|| 5. Nonrepudiation || Guarantees the sender of a message later can't deny sending it. ||
|| 6. Authorization || Grants users privileges to perform a task (or tasks) ||
#### General scenario
|| __Source of stimulus__ || Human or another system. May or may not have been already identified. ||
|| __Stimulus__ || Unauthorized attempt to display, change or delete data, access system services, change system's behavior or reduce availability. ||
|| __Artifacts__ || System services, data within the system, a component or resources of the system, data delivered to or from the system. ||
|| __Environment__ || Online or offline. With or without a firewall. Fully, partially or not operational. ||
|| __Response__ || Stop unathorized use. Logging. Recovering from the attack. ||
|| __Response measure__ || Time used to end the attack. Number of attacks detected. How long it takes to recover from an attack. How much data was vulnerable to an attack. Value of system/data compromised. ||
#### Tactics
> One method of thinking about how to achieve security in a system is to think about physical security.

|| ** Detect attacks** || If you detect the attacks, you can stop the attack. Very clever. ||
|| Detect intrusion || Compare network traffic and check for malicious patterns, eg. TCP-falgs, payload sizes, source or destination adress, port etc. ||
|| Detect service denial || Compare incoming traffic with know patterns of DDoS-attacks.||
|| Verify message integrity || Use checksums or hash-values to see if messages are valid. ||
|| Detect message delay || Detect possible man-in-the-middle attacks. Check the time it takes to deliver messages, and check that this time stays about the same for the messages sent. ||
|| ** Resist attacks** || We're under attack, now let's resist it! ||
|| Identify actors || Use input to identify attacker ||
|| Authenticate actors || Certificates, passwords etc. ||
|| Authroize acors || Auhenticated users are allowed to modify and add data.||
|| Limit access || Different degree of access ||
|| Limit exposure || Hide facts about the system. "Security by obscurity." ||
|| Encrypt data || So, yeah ||
|| Seperate entities || Physical seperation, virtualization etc. Components are not at the same place, and may be less affected by each other. ||
|| Change default settings || Don't have default settings. ||
|| ** React to attacks** || ||
|| Revoke access || Limit access if you believe an attack is under way ||
|| Lock computer || Upon repeated failed login attempts, lock the system. ||
|| Inform actors || Inform people who may need to act.. ||
|| ** Recover from attacks** || Restore systems and data. Maintain audit trail. ||
### Testability
To what degree the system is testable. Used to demonstrate faults, or the
You'll want to plan for testing in the project plan, as it is very important for systems, especially big ones. You'll want a testing infrastructure that makes it easy to test, to introduce tests and mimic faults to see if the system can handle them. The infrastructure should also enable logging system states. You'll also want these to run automatically with development cycles/increments.
#### General scenario
|| __Source of stimulus__ || Unit, integration, system, acceptance testers. Users. Manually running tests, or automatically. ||
|| __Stimulus__ || The completion of a coding segment. ||
|| __Artifacts__ || The part of the system being tested. ||
|| __Environment__ || Design, development, compile, integration, deployment or run time ||
|| __Response__ || Execute test suite and capture results, capture activity that resulted in the fault, control and monitor the state of the syste ||
|| __Response measure__ || Effort to find the fault or class of faults, test coverage, reduction in risk exposure ... ||
#### Tactics

|| **Control and observe system state** || You cannot test something if you cannot observe what happens when you do. ||
|| Specialized testing interfaces || Capture variables. Can be done with special get and set methods, report-method, reset-method or a method to turn on verbose output. ||
|| Record/playback || Record state when it's crossing an interface||
|| Localize state storage ||Hard to test with distributed states ||
|| Abstract data soures || Make it easy to switch data sources through making the interfaces they go through abstract. E.g. with a banking system you would want a test database in development, but another in production. This means you want to be able to switch data sources easiliy. ||
|| Sandbox|| Isolate a part of the system from the real world for experimentation. Eg. virtualization (with resources for instance.) ||
||Executable assertions || Hard-code assertion and place assertion at specified places to check if values are okay. ||
|| **Limit Complexity** || Complex software is harder to test. It's hard to replicate a state when the state space is large (that is: THe Software is complex.) ||
|| Limit structural complexity|| Avoid or resolve cyclic dependencies, encapsulate and isolate environmental dependencies and reduce dependencies in general. High cohesion and loose coupling ( see modifiability) can also helo testability. ||
|| Limit nondeterminism|| That is limit behaviroial complexity. Determninistic systems are easier to test. Find all sources of nondetermnism such as unconstrained parallelism and weeding them out as much as possible. All nonterminism cannot be removed. ||
### Usability
> Usability is concerned with how easy it is for the ser to accomplish a desired task and the kind of user support the system provides.
Over the last few years this has become increasingly important, as users don't want to use (or buy) systems which are hard to use.
Comprises the following areas:
- Learning system features
- Using a system efficiently
- Minimizing the impact of errors
- Adapting the system to user needs
- Increasing confidence and satiscation
#### General scenario
|| __Source of stimulus__ || End user, possibly in a specialiced role. ||
|| __Stimulus__ || End user does/attempts something in relation to the usability areas mentioned above. ||
|| __Artifacts__ || The system or the part the user interacts with ||
|| __Environment__ || Runtime or configuration time. ||
|| __Response__ || Provide the user with the feature needed or anticipate the user's needs ||
|| __Response measure__ || Taks tme, number of errors, number of tasks accomplised, user satisfaction, gain of user knowledge, ratio of successful operations to total operations or amount of time or data lsot whenan error occurs. ||
#### Tactics

|| **Support user initative ** || When the system is running, you enchance usability by giving the user feedback on what he or she is doing. ||
|| Cancel || Let the user cancel operations. This means the system must listen for the cancel command.||
|| Undo || Let the user undo actions. ||
|| Pause/resume || Let the user pause and resume processes that takes a lot of time. ||
|| Aggregate ||Let the user lower-level objects to a single group so the user can do the same operation on the whole group. ||
|| **Support system initative ** || ||
|| Maintain task model || Task model is used to give system context of what the user is trying to do, so it can help the user get there. Eg. knowing all sentences start with a capital letter and knowing the user is writing a text, the system can correct the text when the user forgets to use a capital letter. ||
|| Maintain user model || Represents user's knowledge of the system. Can control the amount of assistance the system gives. Can let the user customize the system. ||
|| Maintain system model || System model used to determine expected system behavior, eg. so it can give the user an estimate on how much time an operation will take. ||
### Other Quality Attributes
A few more arise frequently:
|| Variability || A special form of modifiability. It descirbes to which degree the system, documentation and staff supports making variants of the system. ||
|| Portability || Special form of modifiability. In which degree the system can be made to run on a different platform than what was orignally intended. ||
|| Development distributability || To what extent can the development of the software be distributed.||
|| Scalability || How can the system handle more resources. Two types: Horizontal and vertical. Horizontal refers to adding more resources to logical units, eg. add another server to a cluster of servers. Called _elasticity_ in cloud environments. Vertical: Add more resources to a physical unit, eg. more memory to a single server. ||
|| Deployability || How an executable arrives at a host, and how it is invoked. That means: How easy is it to deploy the system. ||
|| Mobility ||Problems of movement, battery, reconnecting etc. ||
|| Monitorability || The ability of the opertaions staff to monitor the system.||
|| Safety || Does the system lead to unsafe actions, eg. can a missile system fire random missiles. ||
# Architecture in the cloud (Chapter 26)
# Architecture for the edge (Chapter 27)
# Syllabus articles
This should be updated every year. This is from 2015:
- "Game Architecture and Design - A New Edition", Andrew Rollings and Dave Morris. Only the following pages from chapter 17 are in the syllabus: page 462 (from Hardware Abstraction) to page 500 (before State Transitions and Properties).
- IEEE (2000), "IEEE Recommended Practice for Architectural Description of Software-Intensive Systems", Software Engineering Standards Committee of the IEEE Computer Society.
- Kruchten, P. (1995), "The 4+1 View Model of Architecture, IEEE Software", 12, 6, Pp. 42 - 50. [Link](http://www.cs.ubc.ca/~gregor/teaching/papers/4+1view-architecture.pdf)
- Coplien J. O. (1998): "Software Design Patterns: Common Questions and Answers", The Patterns Handbook: Techniques, Strategies, and Applications, Cambridge University Press, New York, pp. 311-320.
The second and third one could be brought to the exam.
## IEEE (2000): "IEEE Recommended Practice for Architectural Description of Software-Intensive Systems"
Meant to give some guidlines to those who develop, design, oversee, evaluate, describe etc. computer systems.
Introudces a conceptual framework, or frame of references, for architectural description.
Describes how you select views based on stakeholders and requirements. Description of the different stakeholders and their roles.
It goes on to explaining some terms. These explanations has been placed in the introduction to this Wikipendium-article.
Goes on to descirbe practices in the _architectural documentation (AD)_. Each of these points are explained in detail.
1. AD Identification, version and overview information
2. Identification of system stakeholders and their concerns judged to be relevant to the architecture
3. Specification of each viewpoint that has been selected to organize representation of the architeture and the rationale for those selections
4. One or more architectural views
5. A record of all known inconsitencies aong the AD's requirent consituns
6. A rational for selection of the architecture
## Krutchen (1995): "The 4+1 View Model of Architecture, IEEE Software"
Describes the 4+1 view model of AD views.

Overview over the views:
|| **Name** || **For** || **Description** ||
|| Logical view || End-user, functionality || S"upports the functionality requirements. The system is decomposed into a set of key abstractions, taken (mostly) from the problem domain in the form of objects and object classes." ||
|| Process view || Integrators, perfomance, scalability|| Adresses some non-functional requirements. Looks on how different processes will work on different tasks, and how they will communicate with each other. ||
|| Development view || Programmers, software management || "Focuses on the actual software module oranization on the software development environment." It shows how the complete system can be divided into small chunks, like modules and library. This is used by developers/software manager to give tasks to different team memebrs.||
|| Physical view || System engineers, toplogy, communications || "Mapping software to hardware." Fouces on non-function requirements and how the physical hardware will fulfill these. ||
|| Scenarios || - || Shows how all the views work together, throgh instances of more general use cases caled scenarios. ||
The article includes the notation, notion and examples of each view.
The article goes on to pointing out how all the views are in some way connected, and are not indpendend on each other. They describe how this is. It also secribes how you can tailor this model for your project.
## Coplien (1998): "Software Design Patterns: Common Questions and Answers"
Starts by explaining what a pattern is (see the introduction of this article), and where software patterns come from. This is also the subject of the article. It introduces a few terms, which are explained below. A great read if you're unsure of what patterns are.
Some terms the text explains:
|| Non-generative pattern aka Gamma patterns || Observed in already built systems. Descriptive and passive. ||
|| Generative pattern || Patterns that generate code or systems. Prescriptive, active. ||
|| Alexandrian form || Most patterns is expressed in this form. It includes: The name of the pattern, the problem the pattern is trying ot solve, the context it is to be used in (eg. a specific language), forces/tradeoffs, the actual solution, examples of use, uresolved results/resulting context and a design rational which tells where the pattern came from, why it works and why it is used. ||
|| Pattern language || "Structured collection of patterns that build on each other to transform needs and contraints into architecture."||
|| Idioms || Special kind of pattern tied to specific langauge. You'll want your patterns to not depend on a a language (cast idioms to patterns).
The last two pages describes the pattern "Type Promotion" of C++ on the Alexandrian form, cast from an idiom.