๐ Lecture 23 โ Architectural Views, Styles, and Models
๐ Overview: This lecture introduces the concept of software architecture as a high-level structural blueprint composed of elements, forms, and rationale. It explains Krutchen's 4+1 and Clement's modified architectural view models, then covers major architectural styles including data-centered, client-server, layered, and pipes-and-filters architectures. The lecture also addresses partitioning and analysis of architectural designs, which are critical for satisfying both functional and non-functional requirements in large software systems.
๐๏ธ Topics Covered
The lecture covers architectural views including Krutchen's 4+1 model and Clement's modified version with Functional, Code, Development, Concurrency, Physical, and Scenarios views. It then discusses architectural styles: data-centered/repository model, client-server model with thin/fat/zero-install and n-tier configurations, data flow/pipes-and-filters architecture, layered architecture, and reference architectures like OSI. Finally, it covers horizontal and vertical partitioning and a step-by-step approach to analyzing architecture design.
๐ Lecture Summary
8.6 Architectural Views
Software architecture defines the high-level structure by organizing architectural elements. Perry and Wolfe proposed: Software architecture = {Elements, Forms, Rationale}. Elements are divided into three categories: data elements (information used/transformed), processing elements (transform data), and connecting elements (connect pieces together). Boehm modified this to: Software architecture = {Elements, Forms, Rationale/Constraints}.
Krutchen's 4+1 Architectural View Model proposes five views: the logical view (object model of design, for end-user functionality), the process view (concurrency and synchronization, for system integrators), the physical view (mapping software onto hardware, for system engineers), the development view (static organization in development environment, for programmers), and the use case view (scenarios to validate architecture).
๐ก Why this matters: Using multiple views allows different stakeholders (end-users, programmers, integrators, system engineers) to analyze the architecture from their own perspective, ensuring all quality attributes are addressed.
Clement's Modified Version of Krutchen's 4+1 Model
Clements modified the model to include five views: Functional View, Concurrency View, Physical View, Development View, and Code View (an extension not in the original model), plus Scenarios.
The Functional View comprises functions, key system abstractions, and domain elements, connecting dependencies and data flows. Users include domain engineers, product-line engineers, and end users. It aids understanding functionality, modifiability, reusability, tool support, and work allocation.
The Development View documents files and directories in the system. Users include development staff, configuration management staff, and project managers. Uses include maintenance, testing, configuration management, and version control.
The Code View includes classes, objects, procedures, functions, subsystems, layers, and modules. It documents calling and containing hierarchies. Primary users are programmers and designers. Intent: maintenance and portability.
The Concurrency View documents parallel processes and threads, focusing on event synchronization and parallel data flows. Used by integrators, performance engineers, and testers. Purpose: identify opportunities for parallelism to improve performance.
The Physical View depicts physical organization and deployment including processors, sensors, and storage devices. Primary users: hardware and system engineers. Used for system delivery/installation, performance, availability, scalability, and security analysis.
Scenarios are use cases describing sequences of responsibilities and change cases. They validate that the architecture supports required functionality, communicate design, tie all views together, and help understand dynamic behavior and design limits.
| View | Components | Users | Rationale |
|---|---|---|---|
| Functional View | functions, key system abstractions, domain elements | domain engineers, product-line designers, end users | functionality, modifiability, product lines/reusability, tool support, work allocation |
| Code View | classes, objects, procedures, functions, subsystems, layers, modules | programmers, designers, reusers | modifiability/maintainability, portability, subsetability |
| Development View | files, directories | managers, programmers, configuration managers | managers, programmers, configuration managers |
| Physical View | CPUs, sensors, storage | hardware engineers, system engineers | system delivery/installation, performance, availability, scalability, security |
| Concurrency View | processes, threads | performance engineers, integrators, testers | performance, availability |
What Are Views Used For?
Views are an engineering tool to achieve desired system qualities. Each view provides an engineering handle on certain quality attributes. In small systems, distinct views may collapse (e.g., concurrency and physical views may be the same). Views are documentation vehicles for current and future development, used by managers and customers. Views must be annotated to support analysis using scenarios and design rationale.
Structures document how the current system was developed and how future development should occur. Each structure provides a method for reasoning about relevant quality attributes. The uses structure is engineered for extensibility, the calls structure for reducing bottlenecks, and the module structure for modifiability.
Hierarchical Views
Every view is potentially hierarchical:
- Functional view contains sub-functions
- Development view contains directories which contain files
- Code view has modules/systems containing sub-modules/sub-systems
- Concurrency view contains processes subdivided into threads
- Physical view clusters contain computers containing processors
Architectural views relate to each other in complicated ways. One must choose views useful to the system being built and to achieving important qualities. Views should be hierarchical where needed and contain enough annotated information to support desired analyses.
Architectural Styles
An architectural model may conform to a generic architectural style. Awareness of styles simplifies defining system architectures, though most large systems are heterogeneous and do not follow a single style.
Each style encompasses:
- A set of components (e.g., database, computational modules) performing functions
- A set of connectors enabling communication, coordination, and cooperation among components
- Constraints defining how components can be integrated
- Semantic models enabling understanding of overall system properties
8.7 Architectural Models
Like analysis models, different kinds of architectural models are developed during architectural design. Static structural models show major system components; dynamic process models show process structure; interface models define sub-system interfaces.
8.8 Architectural Styles
Architectural design may be based on patterns called architectural styles. Common styles include:
- Data-centered architectures
- Client Server Architecture and variations
- Layered architectures
- Reference Architecture
Data-Centered or Repository Model
Sub-systems exchange data in two ways:
- Shared data held in a central database or repository accessed by all sub-systems
- Each sub-system maintains its own database and passes data explicitly
When large amounts of data must be shared, the repository model is most commonly used, extensively in main-frame applications.
Advantages: Efficient way to share large amounts of data; sub-systems need not know how data is produced; centralized management (backup, security); provides global view of the system; sharing model published as repository schema.
Disadvantages: Sub-systems must agree on a repository data model (compromise); data evolution is difficult and expensive; little scope for specific management policies; difficult to distribute efficiently.
8.9 Client-Server Model
The client-server model distributes data and processing, shifting from main-frame applications where data management and processing occurred on the same computer. With cheaper, powerful machines, load shifted from back-end to smaller machines.
This distributed model shows how data and processing are distributed across components. Applications are modeled as services provided by servers and clients that use these services. The system is organized as stand-alone servers (providing printing, data management) and clients calling these services, connected through a network. Clients and servers are logical processes (not always physical machines). Clients know servers, but servers do not need to know all clients.
8.10 Client/Server Software Components
A typical client-server system is composed of:
- User interaction/presentation subsystem
- Application subsystem โ implements requirements; may reside on client or server
- Database management subsystem
- Middleware โ provides mechanisms and protocols to connect clients with servers
Representative Server Types:
- File servers โ client requests records; server transmits records over network
- Database servers โ client sends SQL queries; server processes and returns results
- Transaction servers โ client invokes remote procedures on server; server executes and returns results
- Groupware servers โ enable communication among clients using text, images, bulletin boards, video
Advantages: Effective use of networked systems; cheaper hardware; easier to add/upgrade servers; straightforward data distribution.
Disadvantages: No standard way of sharing data (sub-systems may use different data organization); data interchange may be inefficient; redundant management in each server; no central register of names/services.
8.11 Representative Client/Server Configurations
Thin Client Model: Initially used to migrate legacy systems to client-server. The legacy system acts as a server; GUI implemented on a client. Chief disadvantage: heavy processing load on both server and network.
Fat Client Model: More processing delegated to the client; application processing locally extended. Suitable for new systems where client capabilities are known in advance. More complex management (new versions installed on every client).
Zero Install: No installation on client side needed; no/little processing at client side. Trade-off between using client computing power versus maintenance overhead. Similar to thin-client, but network distributes server-side processing across multiple servers. Example: web-based applications โ updates on web server reflected when users log in.
N-Tier Architecture: Enhances scalability and performance by distributing data and application using multiple server machines. May involve different server types: application server, web server, DB server.
Three-tier Architecture: Each architecture layer (presentation, application, database) runs on separate processors. Better performance than thin-client; simpler management than fat-client; highly scalable.
N-tier architecture generalizes three-tier to more than three layers, distributing different subsystems on different servers.
8.12 Data Flow or Pipes and Filters Architecture
Similar to data flow diagrams. Used when input data is processed through a series of transformations to yield output. Each processing step is a filter; the connecting link is a pipe through which information flows. Each filter works independently, requiring no knowledge of other filters.
If the dataflow has a single sequence with no alternative or parallel paths, it is called batch sequential.
Layered Architecture
A layered architecture has different layers (e.g., operating system). Each layer isolates the outer layer from inner complexities. The outer layer only needs to know the interface provided by the inner layer. If the inner layer changes but the interface stays the same, the outer layer is unaffected. This enhances portability.
Basic layers: User Interface Layer โ Application Layer โ Utility Layer โ Core Layer.
8.13 Reference Architectures
A reference architecture is not physical; it is a reference for defining protocols and designing/implementing systems developed by different parties. Derived from studying the application domain, not existing systems. Used as basis for implementation or to compare systems. Acts as a standard for evaluation.
Example: OSI model โ a layered model for communication systems. The success of the Internet (heterogeneous systems communicating) is evidence of this model's effectiveness.
8.14 Partitioning the Architecture
Partitioning distributes responsibilities to different subsystems for easier maintenance. Results in fewer side effects, easier testing and extension.
Horizontal partitioning defines separate branches of the module hierarchy for each major function; control modules coordinate communication between functions.
Vertical partitioning (factoring) divides the application from a decision-making perspective. Architecture is partitioned into horizontal layers with decision-making modules at the top and workers at the bottom.
8.15 Analyzing Architecture Design
Required characteristics may conflict. Trade-offs seek optimal combinations based on cost/benefit analysis. Analysis requires understanding what is required and establishing relative priority of attributes.
Steps for architectural analysis:
- Collect scenarios
- Elicit requirements, constraints, and environment description
- Describe architectural styles/patterns chosen (module view, process view, data flow view)
- Evaluate quality attributes by considering each attribute in isolation
- Identify sensitivity of quality attributes to various architectural attributes
- Critique candidate architectures using sensitivity analysis
โญ Key Takeaways
The most critical concepts from this lecture are the different architectural view models (Krutchen's 4+1 and Clement's modified version) which allow multiple stakeholders to analyze the system from their perspectives, and the major architectural styles (repository, client-server with its variations, pipes-and-filters, layered, and reference architectures). Partitioning can be horizontal (by function) or vertical (by decision-making level), and architectural analysis follows a structured six-step process that collects scenarios, elicits requirements, describes styles, evaluates attributes, identifies sensitivities, and critiques candidates. The choice of architecture depends on the system's specific functional and non-functional requirements, and most large systems are heterogeneous, combining multiple styles. Finally, views must be hierarchical, annotated with scenarios and rationale, and chosen specifically for the quality attributes most important to the application.
๐ง Quick Revision Questions
-
What are the three categories of architectural elements according to Perry and Wolfe's formula, and what role does each play?
-
List the five views in Clement's modified version of Krutchen's 4+1 architectural view model, and identify the primary users and rationale for each view.
-
Compare the repository model and the client-server model in terms of data sharing, management, and scalability โ what are the key advantages and disadvantages of each?
-
What is the difference between thin-client, fat-client, zero-install, and n-tier client-server configurations, and what problem does each solve?
-
What are the six steps for performing architectural analysis, and why is sensitivity analysis important in step 5?
๐ Lecture 26 โ Introduction to Design Patterns
๐ Overview: This lecture introduces design patterns as reusable solutions to recurring software design problems. It covers the historical origins from Christopher Alexanderโs architectural work, the formal GoF (Gang of Four) documentation format, and a classification of patterns into creational, structural, and behavioral categories. Three specific patterns (Observer, Singleton, and Faรงade) are examined in detail using the GoF template.
๐๏ธ Topics Covered
The lecture begins with Christopher Alexanderโs definition of patterns and how they apply to object-oriented design. It defines design patterns formally, describes their documentation structure, and traces their history from the 1970s through the 1995 GoF book. The GoF format is explained with ten components. Patterns are classified into creational, structural, and behavioral types, with subclassification into class and object patterns. Three patterns are then detailed: Observer (behavioral), Singleton (creational), and Faรงade (structural).
๐ Lecture Summary
Design Patterns
Christopher Alexander says, โEach pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice.โ Even though Alexander was talking about patterns in buildings and towns, what he says is true about object-oriented design patterns. Our solutions are expressed in terms of objects and interfaces instead of walls and doors, but the core of both kinds of patterns is a solution to a problem in a context.
Design Patterns defined
โDescription of communicating objects and classes that are customized to solve a general design in a particular context.โ Patterns are devices that allow programs to share knowledge about their design. In our daily programming, we encounter many problems that have occurred, and will occur again. The question we must ask our self is how we are going to solve it this time. Documenting patterns is one way that you can reuse and possibly share the information that you have learned about how it is best to solve a specific program design problem. Essay writing is usually done in a fairly well defined form, and so is documenting design patterns. The general form for documenting patterns is to define items such as: the motivation or context that this pattern applies to; prerequisites that should be satisfied before deciding to use a pattern; a description of the program structure that the pattern will define; a list of the participants needed to complete a pattern; consequences of using the pattern (both positive and negative); and examples.
๐ Definition โ Design Pattern: A description of communicating objects and classes that are customized to solve a general design problem in a particular context.
Historical perspective of design patterns
The origin of design patterns lies in work done by an architect named Christopher Alexander during the late 1970s. He began by writing two books, A Pattern Language [Alex77] and A Timeless Way of Building [Alex79] which, in addition to giving examples, described his rationale for documenting patterns. The pattern movement became very quiet until 1987 when patterns appeared again at an OOPSLA conference. Since then, many papers and presentations have appeared, authored by people such as Grady Booch, Richard Helm, Erich Gamma, and Kent Beck. From then until 1995, many periodicals featured articles directly or indirectly relating to patterns. In 1995, Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides published Design Patterns: Elements of Reusable Object-Oriented Software [Gamma95], which has been followed by more articles in trade journals.
The concept of design patterns is not new as we can find a number of similar pursuits in the history of program designing and writing. For instance, Standard Template Library (STL) is a library of reusable components provided by C++ compilers. Likewise, we use algorithms in data structures that implement typical operations of manipulating data in data structures. Another similar effort was from Peter Coad whose patterns are known for object-oriented analysis and design.
Anti-patterns is another concept that corresponds to common mistakes in analysis and design. These are identified in order to prevent potential design and analysis defects from entering into the design. Another similar concept is object-oriented framework that is a set of cooperative classes that make up reusable design of a system. Framework dictates the architecture of the software and describes the limitations and boundaries of architecture.
๐ก Why this matters: Understanding the historical context shows that patterns are not new inventions but distilled wisdom from decades of software engineering practice.
GOF Design Pattern Format
The basic template includes ten things as described below:
Name: Works as an idiom; name has to be meaningful.
Problem: A statement of the problem which describes its intent; the goals and objectives it wants to reach within the given context.
Context: Preconditions under which the problem and its solutions seem to occur; result or consequence; state or configuration after the pattern has been applied.
Forces: Relevant forces and constraints and their interactions and conflicts; motivational scenario for the pattern.
Solution: Static and dynamic relationships describing how to realize the pattern; instructions on how to construct the work products; pictures, diagrams, prose which highlight the patternโs structure, participants, and collaborations.
Examples: One or more sample applications to illustrate a specific context and how the pattern is applied.
Resulting context: The state or configuration after the pattern has been applied; consequences (good and bad) of applying the pattern.
Rationale: Justification of the steps or rules in the pattern; how and why it resolves the forces to achieve the desired goals, principles, and philosophies; how are the forces orchestrated to achieve harmony; how does the pattern actually work.
Related patterns: The static and dynamic relationships between this pattern and other patterns.
Known uses: To demonstrate that this is a proven solution to a recurring problem.
Classifications of patterns
Creational patterns: How to create and instantiate. Abstract the instantiation process and make the system independent of its creational process. Class creational rules use inheritance to vary the instantiated classes. Object creational rules delegate instantiation to another object. Examples: Abstract factory and factory method.
Structural patterns: Deals with objectโs structure. Class structural patterns concern the aggregation of classes to form largest structures. Object structural patterns concern the aggregation of objects to form largest structures.
Behavioral patterns: Describe the patterns of communication between classes and objects; how objects are communicating with each other. Behavioral class patterns use inheritance to distribute behavior between classes. Behavioral object patterns use object composition to distribute behavior between classes. Help in distributing objectโs intelligence; concern with algorithms and assignment of responsibilities between objects.
Observer Pattern
Name: Observer
Basic intent: It is intended to define a many to many relationship between objects so that when one object changes state all its dependants are notified and updated automatically. It provides a dependence/publish-subscribe mechanism in programming language. Smalltalk being the first pure Object Oriented language in which observer pattern was used in implementing its Model View Controller (MVC) pattern. It was a publish-subscribe mechanism in which views (GUIs) were linked with their models (containers of information) through controller objects. Therefore, whenever underlying data changes in the model objects, the controller would notify the view objects to refresh themselves and vice versa. MVC pattern was based on the observer pattern.
Motivation: It provides a common side effect of partitioning a system into a collection of cooperating classes that are in the need to maintain consistency between related objects.
Description: This can be used when multiple displays of state are needed.
Consequences: Optimizations to enhance display performance are impractical.
Many graphical user interface toolkits separate the presentational aspects of the user interface from the underlying application data. Classes defining application data and presentations can be reused independently. They can work together, too. Both a spreadsheet object and bar chart object can depict information in the same application data object using different presentations. The spreadsheet and the bar chart donโt know about each other, thereby letting you reuse only the one you need. But they behave as though they do. When the user changes the information in the spreadsheet, the bar chart reflects the changes immediately, and vice versa.
Structure:
- Subject: Provides interface for attaching/detaching Observer objects; knows its observers
- Observer: Defines updating interface for objects notified of subject changes
- ConcreteSubject: Stores state of interest to ConcreteObserver; sends notifications on state change
- ConcreteObserver: Maintains reference to ConcreteSubject; stores consistent state; implements Observer updating interface
Participants:
- Subject: Knows its observers. Any number of Observer objects may observe a subject. Provides an interface for attaching and detaching Observer objects.
- Observer: Defines an updating interface for objects that should be notified of changes in a subject.
- ConcreteSubject: Stores state of interest to ConcreteObserver objects. Sends a notification to its observers when its state changes.
- ConcreteObserver: Maintains a reference to a ConcreteSubject object. Stores state that should stay consistent with the subjectโs. Implements the Observer updating interface to keep its state consistent with the subjectโs.
Singleton Pattern
Intent: It ensures that a class only has one instance and provides a global point of access to it.
Applicability: Singleton pattern should be used when:
- There must be exactly one instance of a class and it must be accessible to clients from a well-known access point.
- Controlling the total number of instances that would be created for a particular class.
- The sole instance should be extensible by sub classing and clients should be able to use an extended instance without modifying their code.
Structure: Singleton defines an Instance operation that lets clients access its unique instance. Instance is a class operation (a class method in Smalltalk and a static member function in C++). May be responsible for creating its own unique instance.
Participants: Singleton defines an instance operation that lets clients access its unique instance. Instance is a class operation (that is, a class method in Smalltalk and a static member function in C++). May be responsible for creating its own unique instance.
Singleton Pattern Example: The Singleton class is declared as:
class Singleton {
public:
static Singleton* Instance();
protected:
Singleton();
private:
static Singleton* _instance;
};
The corresponding implementation is:
Singleton* Singleton::_instance = 0;
Singleton* Singleton::Instance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}
Clients access the singleton exclusively through the Instance member function. The variable _instance is initialized to 0, and the static member function Instance returns its value, initializing it with the unique instance if it is 0.
Faรงade Pattern
Intent: It provides a unified interface to a set of interfaces in a sub-system. Faรงade defines a higher level interface that makes a subsystem easier to use.
Applicability: You would use faรงade when:
- You want to provide a simple interface to a complex sub-system.
- There are many dependencies between clients and the implementation classes of an abstraction.
- You should introduce a faรงade to decouple the system from clients and other subsystems.
- You want to layer your subsystem.
Abstract example of faรงade: Structuring a system into subsystems helps reduce complexity. A common design goal is to minimize the communication and dependencies between subsystems. One way to achieve this goal is to introduce a faรงade object that provides a single, simplified interface to the more general facilities of a subsystem.
Structure: The Faรงade sits between client classes and subsystem classes, providing a single point of interaction.
Participants:
- Faรงade: Knows which subsystem classes are responsible for a request. Delegates client requests to appropriate subsystem objects.
- Subsystem classes: Implement subsystem functionality. Handle work assigned by the Faรงade object. Have no knowledge of the faรงade, that is, they keep no references to it.
โญ Key Takeaways
Design patterns are proven, reusable solutions to recurring design problems, documented in a structured format (GoF) comprising name, problem, context, forces, solution, examples, resulting context, rationale, related patterns, and known uses. Patterns are classified into three categories: creational (how objects are created), structural (how objects/classes are composed), and behavioral (how objects communicate). The Observer pattern establishes a one-to-many dependency so that changes in one object automatically notify all dependents. The Singleton pattern ensures a class has exactly one instance with global access. The Faรงade pattern provides a simplified, unified interface to a complex subsystem, reducing dependencies between clients and subsystem classes.
๐ง Quick Revision Questions
- What are the ten components of the GoF design pattern format, and what does each describe?
- How do creational, structural, and behavioral patterns differ, and into what two subcategories is each divided?
- In the Observer pattern, what is the role of the Subject, and how does it interact with ConcreteObserver objects?
- In the Singleton pattern implementation, why is the _instance variable initialized to 0, and what happens during the first call to Instance()?
- How does the Faรงade pattern reduce complexity and dependencies between clients and a subsystem?
๐ Lecture 28 โ Good Programming Practices and Guidelines
๐ Overview: This lecture focuses on how to write maintainable code that is easy for humans to understand. It covers the principles of self-documenting code, coding style guides, and comprehensive naming conventions for Java and C++. These practices are critical for producing software that can be efficiently maintained and enhanced over time.
๐๏ธ Topics Covered
This lecture covers the concept of maintainable code, emphasizing that code should be written for human readers, not just computers. It introduces the three guiding principles of maintainability: simplicity, clarity, and generality/flexibility. The concept of self-documenting code is explained as code that explains itself without needing external comments or documentation. The lecture details factors that contribute to self-documenting code, such as function size and identifier names. It then introduces a Coding Style Guide to ensure consistency across a project. Finally, it provides a comprehensive set of naming conventions for Java and C++, including Hungarian Notation, CamelCase, and specific rules for variables, functions, constants, and boolean flags.
๐ Lecture Summary
10.1 Maintainable Code
In most cases, maintainability is the most desirable quality of a software artifact. The three basic principles that guide maintainability are: simplicity, clarity, and generality or flexibility. Fowler states, "Any fool can write code that computers can understand, good programmers write code that humans can understand." The software will be easy to maintain if it is easy to understand and easy to enhance. ๐ก Why this matters: Code is read far more often than it is written, especially during maintenance. Writing for human readers directly reduces long-term costs.
Self Documenting Code
A self documenting code is a code that explains itself without the need of comments and extraneous documentation. The meaning of the code should be evident just by reading the code.
Function Size The size of individual functions plays a significant role in understandability. As a function becomes longer, it becomes more difficult to understand. Ideally, a function should not be larger than 20 lines of code and in any case should not exceed one page in length. The idea is that the entire context of a function should be present on one screen or one printed page.
Identifier Names Identifier names play a significant role in enhancing readability. Names should be chosen to make them meaningful. Using meaningful names and named constants eliminates the need for explanatory comments, making the code self-documenting.
๐ Definition โ Self Documenting Code: Code that explains itself without the need for comments and extraneous documentation; its meaning should be evident just by reading the code. ๐ Rule: Keep functions to โค 20 lines (one screen) or โค one printed page. ๐ Example:
// Poor Coding Practice - requires comment
if (x==0) // this is the case when we are allocating a new number
// Improved - meaningful variable name
if (AllocFlag == 0)
// Self-Documenting - meaningful name and named constant
if (AllocFlag == NEW_NUMBER)
10.2 Coding Style Guide
Consistency plays a very important role in making code self-documenting. A coding style guide is aimed at improving the coding process and implementing standardized and relatively uniform code throughout the application or project. Since multiple programmers participate in developing a large piece of code, a consistent style must be adopted by all. Each organization should develop a style guide for its entire team.
10.3 Naming Conventions
Hungarian Notation is a variable naming convention that includes information about the variable in its name (such as data type, whether it is a reference variable or a constant). Bicapitalization or CamelCase is the practice of writing compound words where terms are joined without spaces, and every term is capitalized. The lecture's style guide uses a naming convention where Hungarian Notation is mixed with CamelCase.
๐ Definition โ Hungarian Notation: A variable naming convention that includes information about the variable (e.g., data type) in its name. ๐ Definition โ CamelCase (Bicapitalization): The practice of writing compound words where terms are joined without spaces, and every term is capitalized.
General Naming Conventions for Java and C++
- Types: Nouns, mixed case starting with upper case. (e.g.,
Line,FilePrefix) - Variables: Mixed case starting with lower case. (e.g.,
line,filePrefix). This distinguishes variables from types (e.g.,Line line;). - Constants: All uppercase with underscores separating words. (e.g.,
MAX_ITERATIONS,COLOR_RED). Use should be minimized; implementing the value as a method is often a better choice for readability and a uniform interface (e.g.,int getMaxIterations()). - Methods/Functions: Verbs, mixed case starting with lower case. (e.g.,
getName(),computeTotalWidth()) - Template Types (C++): A single uppercase letter. (e.g.,
template<class T> ...) - Global Variables (C++): Always referred to using the
::operator. (e.g.,::mainWindow.open()) - Private Class Variables: Should have a
_suffix to distinguish class scope from local scratch variables. (e.g.,private int length_;) - Abbreviations/Acronyms: Should not be uppercase when used as a name. (e.g.,
exportHtmlSource(), notexportHTMLSource()) - Generic Variables: Should have the same name as their type. (e.g.,
void setTopic(Topic topic))- Non-generic variables can be named by combining role and type (e.g.,
Point startingPoint).
- Non-generic variables can be named by combining role and type (e.g.,
- Language: All names should be written in English.
- Scope Length: Variables with a large scope should have long names; variables with a small scope can have short names.
- Object Implicit in Method Names: The name of the object is implicit and should be avoided in a method name. (e.g.,
line.getLength(), notline.getLineLength())
Specific Naming Conventions for Java and C++
- get/set: Used where an attribute is accessed directly (e.g.,
employee.getName(),matrix.setElement(2, 4, value)). - is prefix: Used for boolean variables and methods (e.g.,
isSet,isVisible). Alternatives includehas,can, andshouldprefixes (e.g.,boolean hasLicense()). - compute prefix: Used in methods where something is computed (e.g.,
matrix.computeInverse()). This signals a potentially time-consuming operation. - find prefix: Used in methods where something is looked up (e.g.,
vertex.findNearestVertex()). This signals a simple look-up with minimal computation. - initialize: Used where an object or concept is established (e.g.,
printer.initializeFontSet()). - List suffix: Used on names representing a list of objects (e.g.,
vertexList). Using the plural form should be avoided as it differs from the singular by only one character. - n prefix: Used for variables representing a number of objects (e.g.,
nPoints,nLines). - No suffix: For variables representing an entity number (e.g.,
tableNo,employeeNo). An alternative is to prefix them with ani(e.g.,iTable,iEmployee). - Iterator variables: Should be called
i,j,k, etc., following mathematical conventions. Variables namedj,kshould be used for nested loops only. - Complement names: Must be used for complement entities to reduce complexity by symmetry (e.g.,
get/set,add/remove,create/destroy,open/close,show/hide). - Abbreviations: Abbreviations in names should be avoided (e.g., use
computeAverage(), notcompAvg()). Domain-specific phrases that are known by their acronym should be kept abbreviated (e.g.,html, notHypertextMarkupLanguage). - Negated boolean names: Must be avoided to prevent double negatives. (e.g., use
boolean isError;, notboolean isNotError;) - Functions vs. Procedures: Functions (methods returning an object) should be named after what they return; procedures (void methods) should be named after what they do.
โญ Key Takeaways
The most critical concept from this lecture is that maintainability is a primary quality goal, achieved by writing self-documenting code that is simple, clear, and flexible. The most powerful tool for this is choosing meaningful names for identifiers (variables, functions, constants) and using named constants instead of magic numbers, which makes code explain itself without comments. Consistency enforced by a coding style guide is essential for team projects, ensuring uniform code that is easy for any team member to read and maintain. You must remember the rules for function size (โค20 lines/one page) and the specific naming conventions for Java and C++, such as using get/set prefixes for accessors, is/has/can prefixes for booleans, and differentiating between types (PascalCase), variables (camelCase), and constants (UPPER_CASE). Finally, avoid abbreviations, negated boolean names, and ensure methods are named after what they return or do.
๐ง Quick Revision Questions
- What are the three basic principles that guide maintainability in code?
- What is the recommended maximum size for a function in lines of code, and why?
- In Java/C++ naming conventions, what naming style (e.g., PascalCase, camelCase, UPPER_CASE) is used for: a) types, b) variables, c) constants?
- Which specific prefixes should be used for boolean methods and variables, and why should negated boolean names (like
isNotError) be avoided? - What is the purpose of using a coding style guide in a software project?