Skip to content
๐Ÿง  Static vs Dynamic Variables

๐Ÿง  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 ModeDescription
Static TypingType is known and checked at compile time
Dynamic TypingType 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 thing has quack() and walk(), 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 TypeDescriptionExample
Static BindingVariable type and method calls resolved at compile timeint x = 5; x.toString()
Dynamic BindingResolved at runtime based on actual objectx = "hello"; x.upper()

๐Ÿงช Summary Table

FeatureStatic TypingDynamic Typing
Type Known AtCompile TimeRuntime
FlexibilityLowHigh
Error DetectionEarlyLate
PerformanceOptimizedSlower (potentially)
Duck TypingโŒ Not applicableโœ… Core philosophy
Language ExamplesC, Java, RustPython, 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