Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / SOLID Principles

    Two Ideas Behind Everything: Cohesion and Coupling

    Cohesion — how closely the parts inside one class belong together. Aim for high cohesion: every method and field serves one

    Chapter 1 of 83 min read

    Start With the Problem#

    StudyBuddy's first version has one class that does everything with quiz results:

    Java
    class QuizManager {
        void finishQuiz(String student, int points) {
            double pct = (100.0 * points) / 200; // maths
            String line = student + ": " + pct + "%"; // formatting
            // ... open a database connection and save the result ...         // storage
            // ... create an email client with a hard-coded password, send ... // notifications
            if (plan.equals("student")) credits += 50;
            // billing rules
            else if (plan.equals("pro")) credits += 200;
        }
    }

    It works. Then, in one month, the product team asks for: a CSV export, an exam-week double-credit promotion, WhatsApp notifications instead of email, a new "teacher" plan, and automated tests that don't send real emails. Every single request means editing QuizManager. Each edit risks breaking the other four jobs. Two developers editing it at once collide in Git (Git Ch 5). And you can't test it without a real database and real email server.

    Code isn't written once — it's changed hundreds of times. SOLID is five principles (collected by Robert C. Martin in the early 2000s) for arranging classes so that change is cheap and safe.

    The Plain Picture#

    • A toolbox where each drawer holds one kind of thing (screws in one, drill bits in another) is easy to use. A drawer holding screws, batteries, recipes and socks is not. That's cohesion.

    • A lamp with a plug can be moved to any socket. A lamp wired directly into the wall can't be moved without an electrician. That's coupling.

    The Real Names#

    • Cohesion = how closely the parts inside one class belong together. Aim for high cohesion: every method and field serves one purpose.

    • Coupling = how much one class depends on the details of another. Aim for low (loose) coupling: classes talk through small, stable interfaces (Object-Oriented Programming Ch 6), like a plug and socket.

    Every SOLID principle is a specific way to raise cohesion or lower coupling. Keep these two words in mind; they're what interviewers really want to hear you reason about.

    Check yourself

    2 questions
    1

    High or low cohesion is good? High or low coupling?

    Show answer

    High cohesion, low coupling.

    2

    Give a StudyBuddy example of tight coupling.

    Show answer

    QuizManager creating an EmailClient with a hard-coded password inside its method — it can't work with any other notifier or be tested without real email.