# Abstraction

> Expose what a thing does, hide how it does it — callers work through the interface without knowing the implementation.

- **Category**: Oop Concepts
- **Subcategory**: principles
- **Canonical URL**: https://designpattern.fyi/patterns/abstraction/

---

## Description
**Intent**: Callers of a complex system should only need to understand the contract to use it correctly — not the implementation details underneath.

**Context**: Users of a DatabaseConnection class don't need to know connection pooling, timeout handling, or query parsing. They need connect() and query(). Without abstraction, every caller is coupled to implementation details that shouldn't matter to them.

**Solution**: Define an abstract class or interface that specifies available operations without specifying how they work. Concrete classes provide the real implementation hidden behind the interface. Callers code to the interface only — they're insulated from any implementation change or swap.



## Use Cases
Complex underlying implementations that callers shouldn't need to understand. Defining contracts for multiple interchangeable implementations (database drivers, payment processors, storage backends). Hiding complexity that would otherwise couple callers to internals.



## Implementation Example

```javascript
// Abstract class (conceptual in JavaScript)
class DatabaseConnection {
  constructor() {
    if (this.constructor === DatabaseConnection) {
      throw new Error('Abstract class cannot be instantiated');
    }
  }

  connect() {
    throw new Error('Must implement connect method');
  }

  query(sql) {
    throw new Error('Must implement query method');
  }
}

class MySQLConnection extends DatabaseConnection {
  constructor(config) {
    super();
    this.config = config;
  }

  connect() {
    console.log('Connecting to MySQL...');
  }

  query(sql) {
    console.log(`Executing MySQL query: ${sql}`);
  }
}
```



## Trade-offs


### Advantages

- Callers only need to understand the interface — implementation complexity is invisible to them

- Implementations can change or be swapped without callers knowing or caring

- Promotes modular, layered design where each layer only knows its neighbor's contract




### Considerations & Drawbacks

- Adds indirection — debugging requires tracing through the interface to find the implementation

- Abstract class design takes upfront thought — wrong abstractions are expensive to fix later

- Purely abstract hierarchies can be harder to navigate than equivalent concrete code







