๐ง Static vs Dynamic Variables
Understanding how variables behaveโhow they’re typed, bound, and interpretedโis key to mastering programming paradigms. This note explores static vs dynamic typing, variable binding, and the philosophy of duck typing.
๐งฉ What Is Variable Typing?
Typing refers to how a variableโs data type is determined, enforced, and checked.
| Typing Mode | Description |
|---|---|
| Static Typing | Type is known and checked at compile time |
| Dynamic Typing | Type is determined at runtime, based on actual value |
๐งฑ Static Typing
int x = 5
x = "hello" โ Compile-time error- โ
Type is declared explicitly (
int,float, etc.) - โ Errors are caught early by the compiler
- โ IDEs offer better autocomplete and refactoring
- โ Less flexible for generic or polymorphic code
๐ง Languages: C, C++, Java, Rust, Go
๐ Dynamic Typing
x = 5
x = "hello" โ
Allowed- โ No need to declare types
- โ Flexible and concise
- โ Type errors only show up at runtime
- โ Harder to optimize or refactor
๐ง Languages: Python, JavaScript, Ruby, Lua
๐ฆ Duck Typing โ Behavior Over Type
โIf it walks like a duck and quacks like a duck, itโs a duck.โ
Duck typing is a dynamic typing philosophy where the objectโs behavior matters more than its declared type.
def quack_and_walk(thing):
thing.quack()
thing.walk()- โ
No need to check
type(thing) - โ
As long as
thinghasquack()andwalk(), it works - โ May cause runtime errors if methods are missing
๐ง Emphasizes interface by behavior, not inheritance or type declaration.
๐ง Variable Binding โ Static vs Dynamic
| Binding Type | Description | Example |
|---|---|---|
| Static Binding | Variable type and method calls resolved at compile time | int x = 5; x.toString() |
| Dynamic Binding | Resolved at runtime based on actual object | x = "hello"; x.upper() |
๐งช Summary Table
| Feature | Static Typing | Dynamic Typing |
|---|---|---|
| Type Known At | Compile Time | Runtime |
| Flexibility | Low | High |
| Error Detection | Early | Late |
| Performance | Optimized | Slower (potentially) |
| Duck Typing | โ Not applicable | โ Core philosophy |
| Language Examples | C, Java, Rust | Python, JS, Ruby |
๐ Related Notes
- Type Systems โ Nominal vs Structural
- Polymorphism โ Static, Dynamic, and Duck
- Function Overloading vs Duck Behavior
- Error Handling in Dynamic Languages
- Compile-Time vs Runtime Logic
Last updated on