I. What Is Modularity?
Modularity is a software design philosophy: breaking a complex program into multiple components that each have relatively independent responsibilities, clear boundaries, and can be composed together.
Each module is responsible for a set of related functionality and interacts with other modules through well-defined interfaces.
1. What Problems Does Modularity Solve?
As a program grows in scale, when all code is concentrated in a single file or a single global scope, a series of problems arise:
- Name collisions: different pieces of code define the same name, causing overwrites or ambiguity.
- Tangled responsibilities: unrelated functionality is mixed together, making it hard to understand and maintain.
- Complex dependencies: modules call each other, forming dependency relationships that are hard to manage.
- High modification risk: a local change may affect a large amount of unrelated code.
- Difficult reuse: functionality is tightly coupled to specific business logic, making it hard to use independently.
- High collaboration cost: code conflicts easily arise when multiple people develop together.
The core goal of modularity is to reduce system complexity by decomposing complex problems into parts that can be understood and maintained independently.
2. Basic Characteristics of a Module
| Characteristic | Meaning |
|---|---|
| High cohesion | The functionality inside a module is organized around the same responsibility |
| Low coupling | Unnecessary dependencies between modules are minimized |
| Clear interface | A limited, stable set of operations is exposed to the outside |
| Information hiding | Internal implementation details are hidden |
| Independent evolution | Internal implementation can change as long as the interface remains stable |
| Composability | Multiple modules can be combined to accomplish more complex functionality |
Among these, high cohesion and low coupling are important principles of modular design.
High cohesion emphasizes that the elements inside a module have strong functional relatedness.
Low coupling emphasizes that modules interact only through necessary interfaces and avoid depending on each other's internal implementations.
3. Basic Structure of a Module
A typical module can be divided into three parts:
- Public Interface: the functions, types, variables, or classes that other modules are allowed to use.
- Implementation: the module's own concrete implementation logic.
- Dependencies: other modules that this module needs in order to run or compile.
Module A
├── Public Interface
│ ├── create()
│ └── execute()
├── Internal Implementation
│ ├── validate()
│ └── process()
└── External Dependencies
└── Module B
Callers usually only need to know the public interface and do not need to know how the internal implementation accomplishes the task.
II. The Relationship Between Modules and Namespaces
Modules and namespaces often appear together, but they are not the same concept.
1. What Is a Module?
A module is a mechanism for organizing code and defining boundaries.
It usually has:
- An independent code unit.
- Its own scope or naming organization rules.
- An export mechanism to the outside.
- An import mechanism for other modules.
- Explicit dependency relationships.
The specific meaning of a module depends on the language implementation.
For example:
- Python: a
.pyfile usually corresponds to one module. - JavaScript: an ES Module usually corresponds to one source file.
- Java: classes and packages are the main organizational units, and the Java module system also provides a higher-level module boundary.
- Go: multiple source files can form a package, and a package is the basic unit of code organization and importing.
- Rust: modules are declared with
mod, and modules can be organized across files. - C++: code is traditionally organized through header files, source files, and namespaces, and C++20 Modules can also be used.
2. What Is a Namespace?
A namespace is a mechanism for organizing and isolating names.
It provides a context for identifiers so that identically named identifiers in different scopes can be distinguished.
For example:
UserService
├── createUser()
└── deleteUser()
OrderService
├── createOrder()
└── deleteOrder()
Both modules can have a function such as create() without directly colliding in name.
When using namespaces, a specific identifier can be accessed by its qualified name:
UserService.createUser()
OrderService.createOrder()
3. Core Differences Between the Two
| Comparison Dimension | Module | Namespace |
|---|---|---|
| Core purpose | Organize code and manage dependencies | Organize names and isolate identifiers |
| Mainly addresses | Code structure, encapsulation, reuse, dependencies | Name conflicts, name ownership |
| Contains implementation | Usually contains code or declarations | Does not necessarily contain an independent implementation |
| Has import/export | Usually yes | Depends on the language |
| Manages dependencies | Usually yes | Usually not directly responsible |
| Must compile independently | Not necessarily | Not required |
| Typical examples | Python Module, ES Module | C++ Namespace, C# Namespace |
Note:
A module is not necessarily the same as a namespace, and a namespace is not necessarily the same as a module.
Some languages combine modules and namespaces, while others provide separate mechanisms.
III. How Namespaces Work
1. Identifiers and Name Conflicts
An identifier is a name used in a program to mark entities such as variables, functions, types, and modules.
For example:
def create():
pass
class User:
pass
user_name = "Alice"
Here, create, User, and user_name are all identifiers.
If the same name is defined in different code areas, a name conflict may occur.
For example:
# user.py
def create():
print("创建用户")
# order.py
def create():
print("创建订单")
If two functions directly enter the same namespace, a later-defined name may overwrite an earlier one or cause ambiguity in access.
Namespaces solve this problem by establishing name ownership relationships.
2. Qualified Names
A qualified name explicitly identifies the ownership of an identifier through a namespace path.
For example:
User::create();
Order::create();
Here:
User: namespace.Order: namespace.create: function in the namespace.::: scope resolution operator in C++.
The value of qualified names is that even if identifiers with the same name exist in different namespaces, the access target can be specified explicitly.
3. Name Lookup
Name lookup is the process by which a compiler or runtime determines the target entity based on an identifier and its context.
Lookup rules differ between languages.
Take C++ as an example:
namespace App {
int value = 100;
}
int main() {
int value = 200;
std::cout << value << std::endl;
std::cout << App::value << std::endl;
}
Output:
200
100
Here:
value: looked up in the current local scope, where the local variable is found.App::value: directly accesses the variable in theAppnamespace through a qualified name.
Name lookup usually needs to consider:
- The current scope.
- Outer scopes.
- Explicit qualified paths.
- Imported or exposed names.
- Visibility and access control rules defined by the language.
The lookup order of one language cannot be directly applied to other languages.
IV. Module Import and Export Mechanisms
Modules usually establish collaborative relationships through imports and exports.
1. Export
Export means that a module explicitly allows external access to certain members.
For example, in JavaScript:
// math.js
export function add(a, b) {
return a + b;
}
export const PI = 3.1415926;
Here, add and PI are publicly exported members.
Variables and functions inside a module that are not exported do not automatically become members that other ES Modules can directly import.
2. Import
Import means that the current module needs to use functionality provided by another module.
// app.js
import { add, PI } from "./math.js";
console.log(add(10, 20));
console.log(PI);
Imports and exports establish explicit module dependencies.
3. Default Exports and Named Exports
ES Module supports two common export methods.
Named Export
export function add(a, b) {
return a + b;
}
export const VERSION = "1.0";
When importing, you usually use the corresponding exported names:
import { add, VERSION } from "./math.js";
You can also use an alias with as:
import { add as sum } from "./math.js";
Default Export
export default class UserService {
createUser() {}
}
When importing, you can specify your own local name:
import Service from "./UserService.js";
An ES Module can have at most one default export, but it can have multiple named exports.
4. Basic Import/Export Flow
flowchart TD
A["Module A defines functionality"] --> B["Declare public exports"]
B --> C["Module B declares imports"]
C --> D["Resolve module specifier"]
D --> E["Establish module dependency"]
E --> F["Access exported members"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This describes a conceptual flow. The specific order of module resolution, loading, instantiation, and execution is determined by the language specification and runtime.
V. Modules and Namespaces in Different Programming Languages
Languages differ considerably in how they design modules, packages, and namespaces. Understanding these differences helps avoid conflating the concepts.
1. Python: Modules and Packages
Python organizes code through modules and packages.
Modules
A Python file is usually a module.
# math_utils.py
def add(a, b):
return a + b
PI = 3.1415926
Import:
import math_utils
print(math_utils.add(10, 20))
print(math_utils.PI)
You can also import specific members:
from math_utils import add
print(add(10, 20))
math_utils provides a module namespace; global names in the module are usually accessed through the module object.
Packages
Packages are used to organize multiple related modules. A common structure is as follows:
project/
├── main.py
└── services/
├── __init__.py
├── user.py
└── order.py
Import:
from services import user
from services.order import create_order
Modern Python also supports implicit namespace packages without __init__.py. Therefore, you cannot assume that every Python package must contain __init__.py.
Python's __all__
# user.py
__all__ = ["create_user"]
def create_user():
pass
def delete_user():
pass
__all__ is mainly used to control the names imported when using from module import *.
It is not an enforced access control mechanism, nor does it make unexported members truly inaccessible.
2. JavaScript: ES Modules
JavaScript ES Modules use import and export to organize modules.
// user.js
export class User {
constructor(name) {
this.name = name;
}
}
export function createUser(name) {
return new User(name);
}
Import:
// app.js
import { User, createUser } from "./user.js";
const user = createUser("Alice");
Important characteristics of ES Modules:
- Each module has its own module scope.
- By default, declarations in a module do not automatically become global variables.
- Use
exportto explicitly expose members. - Use
importto establish module dependencies. - Named exports use a binding mechanism; the importing side cannot reassign or modify the imported binding.
- ES Module import bindings have the characteristic of live binding (Live Binding).
Live Binding
// counter.js
export let count = 0;
export function increment() {
count++;
}
// app.js
import { count, increment } from "./counter.js";
console.log(count); // 0
increment();
console.log(count); // 1
What the importing side reads is the current binding value of the exported variable, rather than a simple copy of an independent variable.
It is important to distinguish this: live binding in ES Modules does not mean the importing side can directly modify the exported variable. The import binding itself is read-only.
3. Java: Packages and Modules
Java uses Packages to organize classes, interfaces, and other types.
package com.example.user;
public class UserService {
public void createUser() {
System.out.println("创建用户");
}
}
Other classes can use it by importing it:
import com.example.user.UserService;
public class Main {
public static void main(String[] args) {
UserService service = new UserService();
service.createUser();
}
}
The main purposes of Java Packages:
- Organize related types.
- Avoid class name conflicts.
- Provide package-level access control.
- Establish a hierarchy of type names.
For example:
com.example.user.UserService
com.example.order.OrderService
Fully qualified names can distinguish types in different packages.
Java Module System
Java 9 introduced the module system (JPMS), which provides a higher-level module boundary above Packages.
Declare a module via module-info.java:
module com.example.app {
requires java.sql;
exports com.example.user;
}
Here:
requires: declares module dependencies.exports: declares packages exposed to the outside.opens: allows specific deep reflective access.usesandprovides: support the service loading mechanism.
Java Packages and Modules are not at the same level. One module can contain multiple Packages.
4. C++: Namespaces and Modules
C++ provides both namespaces and a module mechanism.
Namespaces
namespace User {
void create() {}
}
namespace Order {
void create() {}
}
int main() {
User::create();
Order::create();
}
User and Order are two different namespaces, and they can contain functions with the same name.
C++ also supports nested namespaces:
namespace Company {
namespace Product {
void create() {}
}
}
You can also use the simplified syntax:
namespace Company::Product {
void create() {}
}
Access:
Company::Product::create();
C++ using Declarations and Directives
using std::string;
This brings std::string into the current scope.
using namespace std;
This makes names in the std namespace considered during name lookup.
The two are not equivalent.
Using using namespace extensively in header files can pull a large number of names into every translation unit that includes that header, increasing the risk of name conflicts.
For this reason, public header files should generally avoid global-scope using namespace.
C++20 Modules
C++20 introduced the standard module mechanism:
// math.cppm
export module math;
export int add(int a, int b) {
return a + b;
}
Usage:
// main.cpp
import math;
int main() {
return add(10, 20);
}
C++ modules can reduce reliance on the traditional textual inclusion mechanism of header files and provide clearer module interface boundaries.
However, C++ modules are not the same thing as namespaces: modules handle modular organization and interface visibility, while namespaces handle name organization.
5. Go: Packages
Go uses packages as its primary unit of code organization.
project/
├── go.mod
├── main.go
└── user/
└── user.go
user/user.go:
package user
type User struct {
Name string
}
func Create(name string) *User {
return &User{Name: name}
}
func validate() bool {
return true
}
Importing from another package:
package main
import (
"fmt"
"project/user"
)
func main() {
u := user.Create("Alice")
fmt.Println(u.Name)
}
Go's export rules are somewhat unusual:
- Identifiers starting with an uppercase letter are accessible from other packages.
- Identifiers starting with a lowercase letter are accessible only within the current package.
For example:
func Create() {}
func validate() {}
Create can be exported, while validate cannot be accessed directly from other packages.
Go's packages simultaneously take on the responsibilities of code organization, namespacing, and access boundaries.
6. Rust: Modules and Crates
Rust uses modules to organize code, and a crate is the unit of compilation.
Common hierarchy:
- Crate: the basic unit of Rust compilation.
- Module: organizes declarations such as types, functions, and variables.
- Path: locates module members via a path.
- Visibility: controls the visibility of members.
For example:
mod user {
pub struct User {
pub name: String,
}
pub fn create(name: String) -> User {
User { name }
}
fn validate() -> bool {
true
}
}
fn main() {
let user = user::create(String::from("Alice"));
println!("{}", user.name);
}
Here:
mod user: declares a module.pub struct User: a public struct.pub fn create: a public function.fn validate: a private function.user::create: accesses a function via the module path.
Rust uses private visibility by default; access must be explicitly opened up with pub.
In addition, Rust's visibility rules are tied to the module hierarchy: forms such as pub, pub(crate), and pub(super) can express access permissions over different scopes.
VI. Module Loading and Execution Mechanisms
Modules are not only about code organization; they also involve how modules are resolved, loaded, and executed at runtime.
Different languages' module systems differ noticeably at this layer.
1. Module Identifier Resolution
Import statements usually need to specify a module identifier.
For example:
import { add } from "./math.js";
The runtime or build tool needs to determine the actual module that ./math.js corresponds to.
Module resolution may involve:
- Relative paths.
- Absolute paths.
- Package names.
- Search directories.
- File extensions.
- Package configuration.
- Conditional exports.
- Differences in platform and runtime environment.
For example, Node.js's module resolution rules are not entirely the same as the resolution mechanism of native ES Modules in browsers.
2. Module Loading Process
A typical module loading process can be abstracted as:
flowchart TD
A["Execute import request"] --> B["Resolve module specifier"]
B --> C{"Is the module already loaded?"}
C -->|"Yes"| D["Reuse existing module record"]
C -->|"No"| E["Locate module resource"]
E --> F{"Does the resource exist?"}
F -->|"No"| G["Loading failed"]
F -->|"Yes"| H["Read or fetch module content"]
H --> I["Parse module structure"]
I --> J["Establish dependency relationships"]
J --> K["Instantiate module"]
K --> L["Execute module code"]
L --> M["Provide exported members"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#FBE9E9,stroke:#D9AAAA,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style K fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style L fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style M fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This is an abstraction of common module systems; not all languages follow exactly the same steps.