Learn Dart ยท 7/12

Object-Oriented Programming (OOP) Part 1: The Basics

7 min read

Welcome to the grown-up table of programming! ๐Ÿฝ๏ธ Up until now, you might have been writing code that flows from top to bottom, maybe jumping around with a few functions. That works great for scripts, but imagine building a massive app like Instagram or Uber with just a list of unrelated variables and functions. It would be a chaotic mess of spaghetti code.

Object-Oriented Programming (OOP) is the industry standard for managing complexity. It allows us to organize code by grouping related data and behaviors into reusable units.

In Dart (and Flutter), almost everything is an object. So, getting comfortable here is non-negotiable. Letโ€™s dive in! ๐ŸŠโ€โ™‚๏ธ


1. Classes and Objects: Blueprints of Data

The Definition

  • Class: A user-defined data type that acts as a blueprint or template. It defines the properties and behaviors that objects created from it will have.
  • Object: An instance of a class. It is the concrete realization of the blueprint containing actual data.

The Problem it Solves

Imagine you are building an e-commerce backend. Without OOP, you might store a user like this:

dart
String userName1 = "Alice";
int userAge1 = 25;
String userName2 = "Bob";
int userAge2 = 30;

If you have 10,000 users, you have 20,000 loose variables. If you want to add an email field, you have to go back and add userEmail1, userEmail2... it's a nightmare. ๐Ÿ˜ฑ

The Solution: Grouping

We create a User class (the blueprint). Then we stamp out as many User objects as we need.

Real-Life Analogy

Think of a Cookie Cutter (Class). It defines the shape (star, heart, circle).
The Cookies (Objects) are the actual things produced. One cookie might have chocolate chips, another might have sprinkles, but they all share the same structural definition from the cutter.

Practical Syntax

dart
// The Blueprint (Class)
class User {
  // We will fill this in a moment
}

void main() {
  // Creating an Object (Instance)
  var user1 = User(); 
  
  print(user1); // Output: Instance of 'User'
}

Industry Fact: In Dart, class names always use PascalCase (e.g., ShoppingCart, UserProfile), while variables use camelCase.


2. Instance Variables and Methods

The Definition

  • Instance Variables (Fields): Variables defined inside a class that hold the state of an object.
  • Methods: Functions defined inside a class that describe the behavior of the object.

The Problem it Solves

A blueprint is useless if it's blank. Objects need to hold data (State) and do things (Behavior).

The Solution

We add variables to hold data and functions to process that data.

dart
class User {
  // Instance Variables (State)
  // These hold the specific data for the object
  String? name; // Nullable type, creating safety
  int age = 0;  // Default value

  // Method (Behavior)
  // A function that belongs to this class
  void login() {
    print("User $name has logged in.");
  }
  
  bool isAdult() {
    return age >= 18;
  }
}

void main() {
  // user1 is an OBJECT
  var user1 = User();
  
  // Accessing variables using the dot operator (.)
  user1.name = "Alice";
  user1.age = 25;

  // invoking methods
  user1.login(); // Output: User Alice has logged in.
  print("Is adult? ${user1.isAdult()}"); // Output: Is adult? true
}

Industry Tip: In modern Dart (Flutter), we rarely leave variables strictly mutable like String? name. We usually make them final (read-only after assignment) to prevent bugs where data changes unexpectedly. But for learning basics, mutable is fine!


3. Constructors: Default, Named, and Factory

The Definition

A Constructor is a special method that runs automatically the moment an object is created. Its primary job is to initialize the object's properties.

The Problem it Solves

In the previous example, we created the user, then set the name, then set the age.

dart
var u = User();
u.name = "Bob"; // What if I forget this line? Result: Bug. ๐Ÿ›

We need a way to force data to be provided right when the object is born.

A. The Generative (Standard) Constructor

Dart has a beautiful shortcut for this called "initializing formals" (this.variable).

dart
class User {
  String name;
  int age;

  // The Constructor
  // "this.name" automatically takes the argument and assigns it to the variable.
  User(this.name, this.age);
}

void main() {
  // Now we MUST provide data to create a User.
  var user1 = User("Alice", 25); 
}

B. Named Constructors

Sometimes you need to create an object in a different way. Dart allows you to name your constructors for clarity. This is heavily used in industry when parsing data from the internet (JSON).

dart
class User {
  String name;
  int age;

  User(this.name, this.age);

  // A Named Constructor
  // Syntax: ClassName.identifier
  User.guest() {
    name = "Guest User";
    age = 0;
  }
}

void main() {
  var standardUser = User("Alice", 25);
  var guestUser = User.guest(); // Clear intent
}

C. Factory Constructors

This is a slightly advanced concept but very common in Flutter.
A normal constructor always creates a new instance.
A Factory constructor can decide not to create a new instance. It can return an existing one from a cache, or a subtype.

Scenario: Imagine a connection to a database. You don't want 500 separate connections open. You want to reuse the same one.

dart
class DatabaseConnection {
  // 1. Static variable to hold the single instance
  static final DatabaseConnection _instance = DatabaseConnection._internal();

  // 2. Factory constructor returns the existing instance
  factory DatabaseConnection() {
    return _instance;
  }

  // 3. Private named constructor (so no one can create a new one directly)
  DatabaseConnection._internal();
}

void main() {
  var db1 = DatabaseConnection();
  var db2 = DatabaseConnection();
  
  // They are the exact same object in memory!
  print(identical(db1, db2)); // Output: true
}

4. Encapsulation: Getters and Setters

The Definition

Encapsulation is the practice of hiding the internal details of how an object works and exposing only what is necessary. It restricts direct access to some of an object's components.

The Problem it Solves

Imagine a bank account object.

dart
class BankAccount {
  double balance = 0;
}
// ...
account.balance = -1000000; // ๐Ÿ˜ฑ catastrophic failure

If variables are public, anyone can set them to invalid values. We need a bouncer at the door to check IDs.

The Solution: Private Variables & Accessors

In Dart, there is no private keyword. Instead, we start a variable name with an underscore _ to make it library-private.

We then use Getters (to read) and Setters (to write with logic).

dart
class BankAccount {
  // Private variable (only visible inside this file/library)
  double _balance = 0;

  // Getter: Allows the outside world to READ the balance
  double get balance => _balance;

  // Setter: Allows the outside world to WRITE, but with validation logic
  set deposit(double amount) {
    if (amount > 0) {
      _balance += amount;
      print("Deposited: $amount");
    } else {
      print("Error: Cannot deposit negative money!");
    }
  }
}

void main() {
  var account = BankAccount();
  
  // account._balance = 500; // ERROR: Cannot access private field
  
  account.deposit = 100; // Uses the setter logic
  account.deposit = -50; // Uses the setter logic -> Prints Error
  
  print("Current Balance: ${account.balance}"); // Uses the getter
}

Industry Standard: Don't use getters and setters for everything. If you don't need validation logic, just use a public variable. Dart's "Implicit Getter/Setter" feature handles the rest internally. Use explicit get and set only when you need to compute something or protect data.


Summary Checklist ๐Ÿ“

  1. Classes are blueprints; Objects are the houses built from them.
  2. Instance Variables hold state; Methods define behavior.
  3. Use Constructors to initialize data cleanly.
  4. Use Named Constructors (like .fromJson) for alternative setups.
  5. Use Factory Constructors when you want to cache or reuse instances.
  6. Prefix variables with _ to make them Private.
  7. Use Getters/Setters to validate data before changing it.

References & Extra Reading ๐Ÿ“š

Challenge

Challenge: Implement a Dart Class for Inventory Management

Your task is to implement a Dart class named InventoryItem that models an item in a store's inventory. This class must demonstrate core Object-Oriented Programming principles including encapsulation, constructors, methods, getters, and setters.

Requirements:

  1. Class and Properties:

    • Define a class named InventoryItem.
    • It must have the following instance variables:
      • id: A public, final String to uniquely identify the item.
      • name: A public String.
      • price: A public double.
      • _quantity: A library-private int to store the stock count.
  2. Constructors:

    • Generative Constructor: Create a default constructor that accepts name, quantity, and price. It must automatically generate and assign a unique String value to the id property.
    • Named Constructor: Create a named constructor InventoryItem.fromMap that takes a Map<String, dynamic> as an argument. This map will contain the keys 'name', 'quantity', and 'price'. This constructor should also generate a unique id.
    • Factory Constructor: Implement a factory constructor InventoryItem.cached. This constructor should accept an id (String) and item data as a Map<String, dynamic>. It must maintain a static internal cache. If an InventoryItem with the given id already exists in the cache, it must return the existing instance. Otherwise, it should create a new instance using the provided map data, add it to the cache, and then return it.
  3. Encapsulation (Getters and Setters):

    • Create a public getter named quantity that returns the value of the private _quantity variable.
    • Create a public setter named quantity that takes an int value. This setter must include validation logic: if the provided value is negative, it must throw an ArgumentError.
  4. Methods:

    • Implement a public method updateStock(int amount) which modifies the _quantity. This method should handle both adding stock (positive amount) and removing stock (negative amount). It must ensure that the resulting stock quantity never becomes negative by using the logic from your setter.
    • Implement a public method displayDetails() that returns a String containing the item's information formatted as follows: ID: [id], Name: [name], Price: $[price], Quantity: [quantity].

Expected result

Your code should consist of a single, complete InventoryItem class that fulfills all the requirements specified in the instructions. A successful implementation will:

  • Correctly define all required instance variables, with _quantity being private and id being final.
  • Provide a generative constructor that properly initializes all properties and assigns a unique ID.
  • Provide a named constructor fromMap that correctly instantiates an object from a Map.
  • Provide a factory constructor cached that manages a static cache, returning a cached instance if the ID exists, or creating and caching a new one if it doesn't.
  • Include a quantity getter that exposes the value of _quantity.
  • Include a quantity setter that throws an ArgumentError when an attempt is made to set a negative value.
  • Contain an updateStock method that correctly adjusts the item's quantity.
  • Contain a displayDetails method that returns a formatted string with the object's current state.
dart

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.