Skip to content
BytePatterns

Designing a File System

Low-Level Design: lesson 11 of 15

One contract answered by both a leaf and a whole subtree.

Lesson 11 of 15 · 6 min

Designing a File System

Step 1 of 9

One contract: an Entry is anything that can report its own size.

The Idea

Name one contract — an entry that can report its size. A File answers from its own bytes; a Folder answers by asking everything it holds and adding up.

Nesting then costs nothing: a folder of folders is just a folder whose children answer the same question.

Real-World Example

A shipping dock. A pallet's weight is the sum of the crates on it, and a crate may itself be a loaded pallet. The scale asks one question and never cares which it got.

The Code

class File:
    def __init__(self, name, size): self.name, self._size = name, size
    def size(self): return self._size

class Folder:
    def __init__(self, name): self.name, self.items = name, []
    def add(self, entry): self.items.append(entry); return self
    def size(self): return sum(e.size() for e in self.items)   # ask, do not test

root = Folder("/").add(File("a.txt", 12)).add(Folder("logs").add(File("x.log", 30)))
print(root.size(), len(root.items))       # 42 2

Python

The Tradeoff

Uniformity is bought with traversal: every size read walks the whole subtree, and a leaf-only operation needs a type test after all. A flat path-to-record table inverts both costs.

Your turn

Put the steps in the right order.

  1. Each entry answers for itself, and the folder adds the answers up
  2. size() is called on the root folder
  3. The folder asks every entry it holds for its own size
  4. An entry that is itself a folder repeats the question on its children

Mini quiz

1 / 3

File and Folder share one contract so that:

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.