Skip to content
intermediatePhase 49 · Low-Level Design

Classes and Objects

Model real-world entities with classes, properties, and methods.

45m
0 problems
Topic Progress0%

Class Definition

A class is a blueprint that defines the structure and behavior of objects. It encapsulates data (attributes) and operations (methods) into a single unit.

Anatomy of a Class

┌──────────────────────────────┐
│          ClassName            │
├──────────────────────────────┤
│  Attributes (Fields)         │
│  - id: int                   │
│  - name: String              │
│  - email: String             │
├──────────────────────────────┤
│  Methods (Functions)         │
│  + getDetails(): String      │
│  + updateEmail(e: String): void │
│  + validate(): boolean       │
└──────────────────────────────┘

Class Design Guidelines

Naming Conventions:

  • Use PascalCase: UserProfile, OrderService
  • Nouns for entity classes: User, Product, Order
  • Verbs for service classes: PaymentService, EmailSender
  • Adjectives for interfaces: Serializable, Comparable

Attribute Design:

// Good: Clear, typed, encapsulated
class User {
    private String id;
    private String name;
    private String email;
    private LocalDateTime createdAt;
}

// Bad: Unclear types, public fields
class User {
    public var data;
    public int x;
}

Method Design:

// Good: Single responsibility, clear naming
class OrderService {
    public Order createOrder(Cart cart) { ... }
    public void cancelOrder(String orderId) { ... }
    public OrderStatus getStatus(String orderId) { ... }
}

// Bad: Multiple responsibilities, unclear
public void doStuff(Object input) { ... }

Types of Classes

Type Purpose Example
Entity Represent domain objects User, Product, Order
Value Object Represent immutable values Money, Address, DateRange
Service Contain business logic PaymentService, AuthService
Repository Data access abstraction UserRepository, OrderRepository
DTO Transfer data between layers UserDTO, OrderRequest
Factory Create objects UserFactory, NotificationFactory

Object Creation

Objects are instances of classes. Understanding object creation is crucial for designing flexible and testable systems.

Object Lifecycle

Class Definition
       │
       ▼
   Construction ──▶ Initialization ──▶ Usage ──▶ Destruction
   (new keyword)   (constructor)     (methods)   (garbage collect)

Constructor Patterns

Default Constructor:

class User {
    private String id;
    private String name;
    
    // Default constructor
    public User() {
        this.id = UUID.randomUUID().toString();
        this.name = "Anonymous";
    }
}

Parameterized Constructor:

class User {
    private String id;
    private String name;
    private String email;
    
    public User(String name, String email) {
        this.id = UUID.randomUUID().toString();
        this.name = name;
        this.email = email;
    }
}

Builder Pattern (for complex objects):

User user = new User.Builder()
    .setName("John")
    .setEmail("john@example.com")
    .setRole(Role.ADMIN)
    .build();

Object Identity vs Equality

Identity (==): Same reference in memory
Equality (equals()): Same logical value

User a = new User("John");
User b = new User("John");
User c = a;

a == b  → false (different objects)
a == c  → true  (same object)
a.equals(b) → true (same values)

Object Immutability

Immutable objects cannot be modified after creation:

// Immutable class
class Money {
    private final double amount;
    private final String currency;
    
    public Money(double amount, String currency) {
        this.amount = amount;
        this.currency = currency;
    }
    
    public double getAmount() { return amount; }
    public String getCurrency() { return currency; }
    
    // Returns new object instead of modifying
    public Money add(Money other) {
        return new Money(this.amount + other.amount, this.currency);
    }
}

Factory Methods

public class UserFactory {
    public static User createRegularUser(String name, String email) {
        return new User(name, email, Role.REGULAR);
    }
    
    public static User createAdminUser(String name, String email) {
        return new User(name, email, Role.ADMIN);
    }
}

Properties and Methods

Properties (attributes) and methods define the state and behavior of objects. Proper design of these is essential for maintainable code.

Property Design

Types of Properties:

┌─────────────────────────────────────────────┐
│                 User                         │
├─────────────────────────────────────────────┤
│ Instance Properties (per object)            │
│  - id: String          (unique per user)    │
│  - name: String        (unique per user)    │
│  - email: String       (unique per user)    │
├─────────────────────────────────────────────┤
│ Static Properties (shared across all)       │
│  - totalCount: int     (all users combined) │
│  - MAX_NAME_LENGTH: 50 (constant)          │
└─────────────────────────────────────────────┘

Property Rules:

  1. Keep properties private (encapsulation)
  2. Use getters/setters for access control
  3. Prefer immutable properties when possible
  4. Validate in setters

Method Design Principles

Single Responsibility:

// Good: Each method does one thing
class Calculator {
    public int add(int a, int b) { return a + b; }
    public int subtract(int a, int b) { return a - b; }
    public double average(int[] numbers) { ... }
}

// Bad: One method does everything
public void doCalculation(String type, int a, int b) {
    if (type == "add") { ... }
    else if (type == "subtract") { ... }
}

Method Length:

  • Aim for 5-20 lines per method
  • If longer, break into helper methods
  • Each method should be understandable in isolation

Parameter Design:

// Good: Clear, limited parameters
public Order createOrder(String userId, List<OrderItem> items, 
                        PaymentMethod payment) { ... }

// Bad: Too many parameters
public Order createOrder(String userId, String address,
                        String city, String zip, String cardNum,
                        String expiry, double total, ...) { ... }

Return Types

Pattern Example When to Use
Value int getCount() Simple computations
Object User getUser(id) Fetching data
Boolean boolean validate() Validation checks
Optional Optional<User> find(id) May return nothing
void void save(user) Side effects only
Builder Builder setName(n) Fluent APIs

Method Visibility Strategy

public    → API of the class (used by external code)
protected → Extension points (used by subclasses)
package   → Internal collaboration (used by same package)
private   → Implementation details (used only internally)

Rule of thumb: Start with private, increase visibility only when needed.

Practice Problems

0/3solved
Design Classes and Objects System

Design a scalable Classes and Objects system. Cover high-level architecture, data model, and API design.

Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliability
Classes and Objects Scaling

How would you scale Classes and Objects to handle 10x the current load? Identify bottlenecks and solutions.

Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decomposition
Classes and Objects Failure Modes

Analyze potential failure modes for Classes and Objects and design mitigation strategies.

Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradation

Quiz

1. What is the relationship between a class and an object?

Question 1 options

2. Which naming convention is appropriate for class names?

Question 2 options

3. Why should class attributes typically be private?

Question 3 options

4. What is a value object?

Question 4 options

5. What is the purpose of a factory method?

Question 5 options

Flashcards

Question

What is a class?

Answer

A blueprint/template that defines attributes (data) and methods (behavior) for objects. Classes define the structure; objects are instances with actual values.

Question

What are the 6 main types of classes in LLD?

Answer

Entity (User), Value Object (Money), Service (PaymentService), Repository (UserRepository), DTO (UserDTO), Factory (UserFactory).

Question

What is the difference between == and equals()?

Answer

== checks reference identity (same object in memory). equals() checks logical equality (same attribute values).

Question

What is an immutable object?

Answer

An object whose state cannot be modified after creation. Achieved through final fields, no setters, and returning new objects for modifications.

Question

Why prefer fewer method parameters?

Answer

Too many parameters reduce readability, increase coupling, and suggest the method has too many responsibilities. Consider using parameter objects or builder patterns.

Revision Notes

Key Takeaways

  • 1.Classes are blueprints; objects are instances with actual state
  • 2.Use PascalCase for class names, camelCase for methods/variables
  • 3.Keep attributes private and control access through methods
  • 4.Immutable objects simplify reasoning and reduce bugs
  • 5.Factory methods encapsulate complex creation logic

Interview Tips

  • Name classes clearly to communicate their purpose immediately
  • Start with entity classes when designing a new system
  • Consider immutability for value objects and shared data
  • Use factories when object creation involves complex logic or multiple types

Cheat Sheet

Classes and Objects - Cheat Sheet

Class Naming:

  • PascalCase: UserProfile, OrderService
  • Nouns for entities, Verbs for services

Property Rules:

  1. Keep private (encapsulation)
  2. Use getters/setters
  3. Prefer immutable
  4. Validate in setters

Object Creation Patterns:

  • Constructor: new User(name, email)
  • Builder: new User.Builder().name(n).build()
  • Factory: UserFactory.createAdmin(name, email)

Class Types:

Type Purpose
Entity Domain objects
Value Object Immutable values
Service Business logic
Repository Data access
DTO Data transfer
Factory Object creation