Stack Overflow: low-level design

Design a Q&A site like Stack Overflow. Members post questions with tags, answer them, comment, vote, and earn reputation. The asker can accept one answer.

Stage 1: Members and posts

Give questions and answers one shared base.

Questions and answers share author, body, time and a score. Copying those fields invites drift. An abstract `Post` holds the shared fields. `Question` adds a title, tags and the accepted answer; `Answer` points to its question. Anything that can be voted on or commented on is a `Post`, so votes and comments are written once. Inheritance fits because both really are posts. Keep it to one level.

Stage 2: Comments, tags and votes

Let members react to posts.

There is no way to react to a post, and nothing prevents double voting. A `Vote` links one voter to one post with +1 or -1. A vote is stored once per (voter, post), so a second vote is rejected or changes the first. Because votes are their own records, they can be audited and reversed. `score` on the post is a cached sum. Recompute it from votes if it is ever in doubt.

Stage 3: The service and search

Give posting, voting and search an entry point.

Rules (no self-vote, asker accepts) and search need an owner. `QAService` enforces the rules, and `SearchIndex` answers text and tag queries from an index that is updated when questions are posted. Rules are in one class and search is replaceable (a database index or a search engine). The index is updated alongside the write; if it lags, results are briefly stale.

Stage 4: Reputation: Observer

React to votes and acceptance.

Reputation (and later badges) should change when votes happen, without `vote` knowing about them. `ReputationService` listens to votes and acceptances and records a `ReputationEvent` each time. A member's reputation is the sum of their events. A badge service is one more listener (**Observer**), and a reversed vote just adds an opposite event. Summing events on every read is slow at scale. Keep a cached total and fix it from the events when needed.