← All topics
Start ▶
OOP and SOLID
Encapsulation, inheritance, polymorphism and the SOLID principles.
200 questions
Level:
No questions match — try other words or turn a level back on.
1
What are the four pillars OOP rests on, and what does each one mean in a sentence?
Encapsulation (hiding data and managing it only through methods), inheritance (extending an existing class), polymorphism (one call, different behavior) and abstraction (hiding unneeded detail and showing only what matters).
2
What is the difference between a class and an object?
A class is a template or blueprint: it describes which fields and methods there will be. An object is a concrete instance created from that blueprint with new on the heap, and its fields hold its own values.
3
What is encapsulation and why do we make fields private?
Encapsulation means the state of an object can't be changed directly from outside: the state is touched only through the object's own methods. A private field protects the class invariants (for example, that a balance can't go negative).
4
Is it right to automatically write a getter and setter for every private field?
No. Adding setters blindly is the same as making the field public. Expose only what the outside really needs, and offer changes through meaningful methods (activate(), changeEmail()).
5
What is inheritance and how do you write it in Java?
Inheritance is when one class takes the fields and methods of another class and extends or changes them. In Java it is written with extends and expresses an "is-a" relationship: Dog extends Animal means a dog is an animal.
6
Why can't a class in Java inherit from two classes at the same time?
Because of the "diamond problem": if two parent classes have the same method or field, it is ambiguous which one is inherited. Java forbids multiple inheritance for classes to keep the language simple, but a class can implement several interfaces.
7
When is the super keyword used?
super refers to the parent class: super(...) calls the parent constructor (it must be the first line of the constructor), super.method() calls the overridden parent method, and super.field accesses a hidden parent field.
8
What does the following code print, and why in exactly this order?
First A konstruktori, then B konstruktori, and last C konstruktori. The first thing each constructor does is call super(), so the chain runs from the topmost parent downward.
9
What is polymorphism? Show it with a simple example.
Polymorphism means working with different objects through a single type (an interface or a parent class). Which version of a method runs is decided at runtime by the actual type of the object.
10
Explain the difference between overloading and overriding.
Overloading / Overriding — Where: Usually in one class / In a parent and a child class; Signature: The number/types of parameters differ / The signature is the same; Return type: Doesn't matter (if it's the only difference, it's an error) / The same or a narrower type (covariant); Resolved: At compile time / At…
11
The code works even without the @Override annotation. So why is it needed?
@Override tells the compiler "this method overrides a method of a parent class or interface". If there is a mistake in the signature (the name or a parameter type), the compiler gives an error immediately; otherwise a new method quietly appears and the bug stays hidden.
12
What do you understand by abstraction in programming?
Abstraction means showing only the part of a complex system that the user needs and hiding the internal details. In Java this is done mainly with interfaces and abstract classes: the caller knows "what is done", not "how".
13
What is an abstract class, and can you create an object from it directly?
An abstract class is an incomplete class marked abstract: it may contain abstract methods without a body. You can't create an object from it with new; objects come only from a concrete child class that extends it.
14
What is an interface and how does a class use it?
An interface is a contract a class must fulfill: a set of method signatures. A class adopts an interface through implements and must implement all of its abstract methods. A single class can implement several interfaces.
15
What do you base the choice on between an abstract class and an interface?
Abstract class / Interface — Inheritance: Only one extends / Many implements; State (instance fields): Yes / No, only constants; Constructor: Yes / No; Methods: Any access level / public (or a private helper); Meaning: "This is a ..." / "This can ..."
16
Why were default methods added to interfaces?
In Java 8, to add new methods to old interfaces without breaking the thousands of classes that implement them. A default method comes with a body, and classes can override it if they want.
17
What does final change when it is put on a class, a method and a variable?
A final class can't be inherited from (String). A final method can't be overridden by a child class. A final variable or field gets its value only once; if it is an object, the reference doesn't change, but the inside of the object can.
18
Compare the four access modifiers in Java by scope of visibility.
Inside the class / Inside the package / Child class (other package) / Everywhere — private: yes / no / no / no; (none): yes / yes / no / no; protected: yes / yes / yes / no; public: yes / yes / yes / yes
19
What is composition and how does it differ from inheritance?
Composition is when a class keeps another object in a field and hands part of its work to it ("has-a": a car has an engine). Inheritance is an "is-a" relationship: the child class remains a type of the parent class.
20
Where does the advice "favor composition over inheritance" come from?
Inheritance tightly binds the child class to the internal details of the parent and makes later changes harder. Composition relies only on the public interface, which makes swapping components and testing easier. The advice spread from the "Design Patterns" (GoF) book and Effective Java.
21
What happens if you "override" a static method in a child class?
A static method can't be overridden; it is hidden (method hiding). Which version is called is decided at compile time by the declared type of the variable, not by the actual type of the object.
22
How does converting an object to a parent type and back to a child type (upcast/downcast) work?
Assigning a child object to a parent-type variable is automatic and safe. The reverse needs an explicit cast like (Dog) animal, and if the object is actually a different type, a ClassCastException is thrown at runtime.
23
Which methods of the java.lang.Object class do you override most often, and why?
Most often equals(), hashCode() and toString(). The first two are so objects can be compared by content and work correctly in hash collections, and toString() is for a readable form in logs and debugging.
24
What is the this keyword used for?
this is a reference to the current object. You use it to tell a field apart from a parameter with the same name, to call another constructor of the same class with this(...), or to pass the object itself to another method.
25
Which principle does each letter of the SOLID acronym stand for?
S is Single Responsibility, O is Open/Closed, L is Liskov Substitution, I is Interface Segregation, D is Dependency Inversion. Robert Martin collected these five principles; the goal is code that is easy to change and not brittle.
26
How do you recognize a class that violates the Single Responsibility principle?
If a class has several independent reasons to change (say, a business rule, a database format and an email template all in one class), SRP is violated. Signs: a very long class, "Manager"/"Util" in the name, imports from different areas.
27
Explain the Open/Closed principle with a practical example.
Code should be open for extension and closed for modification: adding a new capability should mean adding a new class, without editing classes that already work and are tested. You usually do this with interfaces and polymorphism.
28
Explain the Liskov principle with the rectangle and square example.
In math a square is a rectangle, but in code, if you make Square extends Rectangle and setWidth changes both sides, code that expects a rectangle gets the wrong result. LSP says: a child class must not break the promises of the parent class.
29
What problem does the Interface Segregation principle solve?
A big "does everything" interface forces the implementing class to write methods it doesn't need and ties callers to changes that don't concern them. ISP says: split the interface into small pieces based on the clients.
30
Are the Dependency Inversion principle and Dependency Injection the same thing?
No. Dependency Inversion is a design principle: a high-level module should depend on an abstraction, not on a concrete low-level class. Dependency Injection is a technique for giving those dependencies to an object from outside (for example, through the constructor); it is one way to reach DIP.
31
What does the DRY principle require, and how does overdoing it cause harm?
DRY (Don't Repeat Yourself) means every piece of knowledge or rule should live in one place in the system, so a change happens in one place. But merging code that only looks similar by accident and means something different creates needless coupling.
32
How does the KISS principle show up in everyday backend code?
KISS (Keep It Simple, Stupid) means choosing the simplest solution that solves the problem. In practice: instead of needless patterns, extra layers and "clever" one-liners, write code the next developer understands quickly.
33
What is YAGNI, and when does it stop you from writing code "for the future"?
YAGNI (You Aren't Gonna Need It) means not writing a feature in advance that you don't need now because it "might come in handy later". Such code eats time, has to be tested and maintained, and often is never used, or the guess turns out wrong.
34
Explain the difference between coupling and cohesion. Which should be low and which high?
Coupling is how strongly modules depend on each other; it should be low. Cohesion is how well the things inside one module serve a single purpose; it should be high. The goal: "loose coupling, high cohesion".
35
What rules do you follow when choosing a good name (for a class, method or variable)?
A name should tell why it exists, what it does and how it is used, without a comment. Classes are nouns (InvoiceRepository), methods are verbs (calculateFee), booleans are phrased as questions (isActive, hasDiscount). Avoid abbreviations and single-letter names.
36
Why is a very long method a problem, and how do you break it into pieces?
A long method mixes several jobs: it is hard to read, test and change safely. Pull the logical pieces out into small methods with meaningful names ("Extract Method"), so the main method reads like a list of steps.
37
What is a "magic number" in code, and what do you write instead?
A magic number is a literal value written into the code without explanation, whose meaning only the author understands (if (status == 3), * 0.12). Instead you write a named constant, an enum or a configuration value.
38
What steps does writing an immutable class need, and which one is most often forgotten?
Make the class final, make all fields private final, don't add setters, set all the values in the constructor, and make copies of mutable objects (List, Date) both when they come in and when they go out. "Modifying" methods should return a new object.
39
What is the difference between an Entity and a Value Object in DDD?
An Entity has its own identifier and stays "the same object" even as its state changes over time (a customer, an order). A Value Object has no identifier, is defined only by its values, and is usually immutable (an amount of money, an address, a date range).
40
What is the "ubiquitous language" in DDD, and how does it affect the code?
The ubiquitous language is a single vocabulary that business experts and developers use together. One concept has the same name in conversation, in documents and in code, so "translation" errors go down.
41
What does this code print, and why is it dangerous to call an overridable method inside a constructor?
It prints null. When the Base constructor calls init(), polymorphism makes Derived.init() run, but at that moment Derived's field initializers haven't run yet, so prefix is still null.
42
Do fields behave polymorphically like methods? What happens if a parent and a child class have a field with the same name?
No, fields are not polymorphic. A field with the same name hides the parent's (field hiding), and which one is read is chosen at compile time by the declared type of the variable. Methods, on the other hand, are chosen by the actual type of the object.
43
A class implements two interfaces, and both have a default method with the same signature. What happens and how do you resolve it?
A compile error: the class has to resolve the conflict itself. You override the method in the class and, if needed, call a specific interface's version with InterfaceName.super.method().
44
When overriding a method, what restrictions apply to the return type, the access modifier and exceptions?
The signature must be the same; the return type can be the same or a subtype (covariant); the access modifier can't be narrowed, only widened; and checked exceptions can't be broader than those of the parent method.
45
How does overriding equals() separately in a parent and a child class break symmetry?
If Point.equals compares only x, y while ColorPoint.equals also compares the color, then point.equals(colorPoint) is true but colorPoint.equals(point) is false. That breaks the symmetry rule of the equals contract, and collections start behaving unexpectedly.
46
How does returning an internal List through a getter break encapsulation, and how do you fix it?
If a getter returns the private list itself, outside code can add or remove elements, bypassing the class's checks. The fix: return an unmodifiable view (Collections.unmodifiableList) or a copy (List.copyOf), and make changes through separate methods.
47
What problem do sealed classes in Java 17 solve?
A sealed class or interface states exactly which classes may extend it, using permits. This closes the hierarchy: the compiler knows all the variants, and a switch is checked for completeness without a default.
48
Which of these overloads gets called, and what is printed?
First Object, then String is printed. The overload is chosen at compile time by the declared type of the variable: obj is a variable of type Object, so it doesn't matter that it holds a String. print(null) picks the most specific type, the String version.
49
If you can't create an object from an abstract class, why does it need a constructor?
An abstract class has its own fields too, and the constructor is needed to fill them and check invariants. When a child class is created, the constructor is always called through super(...), so the shared initialization code lives in one place.
50
What does it mean when instanceof checks pile up in a row in your code, and how do you rewrite it?
Usually it means polymorphism isn't being used: the behavior lives in an outside if chain instead of in the objects themselves. Every time a new type is added, you have to find and edit all such chains. The fix is to move the method to the common type, or use a full switch over a sealed hierarchy.
51
Will this code compile, and what happens when it runs?
It compiles, because arrays in Java are covariant: String[] is a subtype of Object[]. But when it runs, an ArrayStoreException is thrown, because the array remembers its actual element type and won't accept an Integer.
52
If you write a `private` method of the parent class again in the child class, is that an override?
No. A private method is not visible to the child class, so a method with the same name in the child is a completely new, independent method. When called from inside the parent class, the parent's own private version always runs.
53
Does `this` inside an anonymous class mean the same thing as `this` inside a lambda?
No. In an anonymous class, this is the new object of that anonymous class. A lambda doesn't create a new scope: its this means the enclosing class's object.
54
What is the difference between aggregation and composition? How do they look in Java code?
Both are "has-a" relationships. In composition, the part can't live without its owner: it is created with it and disappears with it. In aggregation, the part is independent: others use it too, and it stays even if the owner is gone.
55
How do you correctly write a utility class made up only of static methods?
I make the class final and add a private constructor, so you can neither create an object from it nor extend it. Making it abstract is the wrong way: it looks like an invitation to extend it and doesn't fully block creating objects.
56
What is a covariant return type and when is it useful?
An overriding method can return a subtype of the type the parent method returns. This saves the caller an extra cast; for example, a copy() method returns the concrete class.
57
Why was the `String` class designed to be `final` and immutable?
For security, caching and thread-safety. String is used everywhere: as a key, a file path, a URL, a password. If it could be modified, or inherited from to break its behavior, the whole platform would be unreliable.
58
When is it appropriate to make a class or a method `final`?
A final class can't be inherited from, and a final method can't be overridden. They are used when the class isn't designed for inheritance, or when you need an immutability or security guarantee.
59
Why are `static` and `private` methods in an interface needed, and are they inherited by a class that implements the interface?
static methods (Java 8) are for helpers or factories that belong to the interface, and private methods (Java 9) are for hiding shared code between default methods. Neither is inherited by a class that implements the interface.
60
Who can actually see a `protected` member?
Child classes and all classes in the same package. Most people think it is "only for child classes", but any class in the same package can freely access a protected member.
61
What happens if request-specific data is stored in a field of a Spring singleton bean?
There is one bean, while requests arrive in parallel on many threads. The field becomes shared by all requests: one user's data "leaks" into another's. That is a race condition, and it only shows up under load.
62
Why shouldn't you return a JPA entity directly from a REST controller, and what does a DTO give you?
An entity is the internal model, while the API is an external contract. If you return the entity, internal refactoring breaks the API, unneeded or sensitive fields leak out, and lazy associations cause extra queries or errors during JSON serialization. A DTO separates these two worlds.
63
What signs in code tell you the Liskov principle has been violated?
The main sign is that code written against the parent type behaves differently when it gets a child type: instanceof checks, UnsupportedOperationException in an override, strengthened conditions or weakened guarantees.
64
Why is constructor injection better than field injection in Spring?
With constructor injection the dependencies are final, the object is never created half-ready, and in tests you can create it with new without Spring. Field injection hides the dependencies and makes it invisible that a class depends on too many things.
65
When is it fine to write a static helper method, and when should it be a bean with an instance method?
A function that is stateless, pure (the same input always gives the same output) and doesn't touch external resources can be static. If it depends on time, the DB, the network, configuration or randomness, it should be a bean, otherwise you can't replace it in a test.
66
Do you return expected business errors (for example "insufficient balance") with an exception or with a result type?
Both are used. If the error is an ordinary branch for the caller and it must always handle it, a result type (a sealed Result) is clearer. If the error should stop the flow and be turned into an HTTP response in one place higher up, an unchecked domain exception is more convenient.
67
Where do you do validation: in the controller with `@Valid`, in the service, or in the domain object itself?
Each layer checks what belongs at its level. The controller checks the request format (@Valid: not blank, length, format). The domain object checks business invariants, because wherever the object is created, it must never be in an invalid state. The service checks rules that depend on other data.
68
What is the Command-Query Separation (CQS) principle, and what bugs come from violating it?
A method either changes state (a command, void) or returns data (a query, without side effects), never both. A query should be safe to call again and again; a "getter" that makes a hidden change gives unexpected results in logs, in the debugger or on a second call.
69
When are comments in code useful, and when do they become a code smell?
A comment is useful when it answers "why": a business reason, a bug being worked around, a non-obvious decision. When the comment explains "what the code does", that usually means the code itself is unclear, and you should fix it with a name or by extracting a method.
70
How do you simplify a method with lots of nested `if`s using guard clauses?
You check the error and edge cases at the start of the method and immediately return or throw. That way the main logic doesn't get pushed inward; it stays flat on the left and is easier to read.
71
What does it mean when a method takes 6-7 parameters, and how do you fix it?
This is the "long parameter list" smell: at the call site the parameters are easy to mix up, and often several of them are really one concept. You need to gather them into a parameter object or a value object, or split the method.
72
What is an anemic domain model, and when does it become a problem?
It is a model where entities consist only of fields and getters/setters, and all the business logic lives in service classes. It is fine in plain CRUD, but as the rules multiply, invariants get scattered and it becomes easy to put an object into an invalid state.
73
What is the "boy scout rule", and how much refactoring do you do while working on a feature?
"Leave the code a little cleaner than you found it." Small improvements in the places you touch, like a name, extracting a method, deleting dead code, go along with the feature. A big refactoring should be in a separate PR, otherwise review and rollback get harder.
74
In code review, which OOP and design problems do you look at first?
First the logical boundaries: is the logic in the right class, is encapsulation intact (setters, exposed collections), does a new dependency break the layers. Then names, error handling and tests. I leave style issues to the linter.
75
What is wrong with a chain like `order.getCustomer().getAddress().getCity()`?
This is a Law of Demeter violation: the code talks not only to its direct "friends" but also to their internal structure. As a result, the caller becomes tied to a whole graph of objects, and any internal change breaks it.
76
Show the "Tell, don't ask" principle with a code example.
Instead of asking an object for its state and making the decision outside, you tell the object what to do, and it makes the decision itself. That way the rule sits next to the data.
77
What is wrong with giving a method a `boolean` flag argument, and how do you fix it?
A flag argument means the method really does two different things, and at the call site it isn't visible what true/false means. It is usually better to split it into two separate, clearly named methods or to use an enum.
78
What options are there instead of returning `null` when a method finds nothing?
Optional for a single value, an empty collection for a collection, a Null Object when you need "do-nothing" behavior, and a clear exception when it is a real error. Each has its place.
79
How do you identify and refactor the god class and feature envy code smells?
A god class is a huge class that knows and does too much. Feature envy is a method that works more with another class's data than with its own class. The first is fixed by splitting the class, the second by moving the method to the owner of the data.
80
Explain the DDD concepts of ubiquitous language and bounded context in plain words.
Ubiquitous language means the business and the developers use the same terms, and those terms are named exactly the same in code. A bounded context is the boundary within which those terms have a single meaning; in another context the same word may mean something else.
81
Why doesn't this `equals` work with `HashSet`?
This method doesn't override equals, it overloads it: the parameter type is Money, not Object. HashSet calls equals(Object), which uses the identity comparison inherited from Object. As a result, equal objects are treated as not equal.
82
What is the fragile base class problem, and how does it show up in production?
A harmless-looking internal change in a parent class breaks the classes that inherit from it, because the child classes have come to depend on how the parent's methods call each other. It happens especially when a library version is updated.
83
Do sealed interfaces and pattern matching `switch` replace classic polymorphism?
Not entirely; they extend along a different axis. With polymorphism, adding a new type is easy and a new operation is hard; with sealed + switch it is the reverse: a new operation is easy, and when a new type is added, every switch gives a compile error. This is the "expression problem".
84
What are an aggregate and an aggregate root? How do you draw their boundaries?
An aggregate is a group of objects that change together and together protect one set of invariants. It is accessed from outside only through the root. The boundary is drawn by asking "which rules must be immediately correct within a single transaction".
85
How do you preserve encapsulation in a JPA entity when Hibernate asks for setters and an empty constructor?
Hibernate doesn't require public setters: if you use field access, it fills the fields with reflection. A protected empty constructor is enough. Expose collections to the outside as unmodifiable and make changes through domain methods.
86
Why do you need domain events, and how do you publish them in a Spring application?
A domain event is an important fact that happened in the domain ("the order was paid"). It decouples the aggregate from other modules: Order knows nothing about email, the warehouse or analytics, it just publishes an event. In Spring this is done with ApplicationEventPublisher and @TransactionalEventListener.
87
What are a port and an adapter in hexagonal (ports and adapters) architecture? What principle is it based on?
A port is an interface declared by the domain or use-case layer, and an adapter is the implementation that connects it to a technology (HTTP, JPA, Kafka). The basis is Dependency Inversion: dependencies point from the outside in, and the domain knows no framework.
88
In Spring, do you need to write an interface for every service if it has only one implementation?
Not necessarily. Spring works with classes too, through CGLIB proxies, and Mockito can mock classes. An interface is useful at a real abstraction boundary, where you talk to another module or an external system; an XxxService + XxxServiceImpl pair for everything is often just noise.
89
If a circular dependency appears between classes or packages, how do you detect and break it?
A circular dependency is when A depends on B and B depends on A. Such modules can't be understood, tested or split apart on their own. You break it by moving the interface to the side that uses it, extracting the shared part into a third module, or using events.
90
What is primitive obsession, and what bugs does it lead to?
It means expressing domain concepts (email, amount, id, phone) with plain String, long and BigDecimal. As a result, arguments get swapped, validation is scattered, and the compiler can't catch the mistake.
91
How do you choose between a telescoping constructor, a static factory and a builder for an object with many parameters?
With up to 3-4 required parameters, a constructor or a named static factory. With many optional parameters, a builder. A static factory has a name, can cache, and can return a subtype; a builder assembles the object step by step in a readable way.
92
If an object is modified after being added to a `HashSet`, what does this code print?
It prints false and 1. After the object was added to the HashSet, a field used in hashCode changed, so it is now looked up in a different bucket and not found, yet it stays in the set.
93
What is the difference between the Template Method and Strategy patterns, and when do you choose each?
Both separate the varying part of an algorithm. Template Method does it through inheritance: the skeleton is in the parent class and the steps are in the child class. Strategy does it through composition: the varying part is a separate object that is swapped at runtime.
94
How do you add caching, logging or retry to an existing class with a Decorator, without changing it?
You write a wrapper class that implements the same interface and holds the original object inside. It passes the call on to the original and does extra work before or after. You can wrap several decorators one after another.
95
How is design by contract (precondition, postcondition, invariant) applied in Java, and how does it relate to LSP?
A precondition is a condition that must hold before a method is called, a postcondition is the result the method guarantees, and an invariant is a rule that is always true during the object's life. By LSP, a child class can't strengthen a precondition or weaken a postcondition.
96
What is an anti-corruption layer, and when do you build one when integrating with an external system?
It is a layer that translates the model of an external or legacy system into your own domain. It stops the external API's names, codes and odd rules from leaking into domain code, and if the external system changes, only this layer changes.
97
What is the difference between package-by-layer and package-by-feature structures? Which one improves cohesion?
Package-by-layer splits code by technical layer (controller, service, repository), while package-by-feature splits it by business capability (order, payment, course). The feature structure increases cohesion and lets you hide classes that don't need to be public.
98
If a class is hard to unit test, what design problems does that point to, and how do you fix them?
Usually hidden dependencies: services created with new inside the class, static calls, LocalDateTime.now(), singletons. If you turn them into dependencies passed through the constructor, testing gets easy and the design improves too.
99
Why are `Cloneable` and `clone()` called bad design, and what are better ways to copy an object?
Cloneable is a marker interface with no methods that quietly changes the behavior of Object.clone(). clone() bypasses constructors, makes a shallow copy, throws a checked exception, and doesn't work with final fields. Use a copy constructor or a static factory instead.
100
How can you get rid of `switch`es by adding behavior to an enum, and where is the limit?
Enum constants can have their own method implementations (a constant-specific body) or take a lambda/value through the constructor. Then each state's behavior sits next to the constant, and the switch isn't repeated. But putting infrastructure dependencies into an enum is a mistake.
101
Calling `add()` on a list returned by `List.of(...)` throws `UnsupportedOperationException`. Isn't that a Liskov violation?
Formally, yes, it contradicts LSP: the List contract promises add, but the implementation refuses it. The JDK documents this as an "optional operation", a deliberate trade-off.
102
Why do `HashSet` and `TreeSet` report different sizes in this code?
BigDecimal.equals compares the scale as well as the value, so 2.0 and 2.00 are not equal. HashSet relies on equals/hashCode and keeps two elements; TreeSet relies on compareTo and treats them as one.
103
Why is passing `this` out of a constructor ("this escape") dangerous?
Until the constructor finishes, the object is not fully built. If this is registered as a listener, handed to a thread or added to a static collection, other code (or another thread) can see it half-initialized, with final fields not yet written.
104
How can a non-static inner class cause a memory leak?
An instance of a non-static inner class keeps a hidden reference (Outer.this) to the outer object. If the inner object ends up somewhere long-lived (a cache, a static list, another thread), it keeps the outer object and all its fields from being garbage collected.
105
How do you write a Builder in an inheritance hierarchy so that the child builder's methods return the right type in a chain?
You use a generic "self type": Builder<T extends Builder<T>>, and every setter returns self(). The child builder passes itself as T, so child methods can still be called after a parent method.
106
Why don't these two overloads compile, and how do you fix them?
Generic types are erased: both methods become process(List) in bytecode. Two methods with the same erasure can't live in one class, so you get a "name clash" error. The fix is to give the methods different names or wrap the parameter in a concrete type.
107
Why can't you pass a `List<Dog>` to a method that expects a `List<Animal>`, and how do you make an API flexible with wildcards?
Generics are invariant: List<Dog> is not a subtype of List<Animal>, otherwise you could add a Cat to it. In APIs you apply the PECS rule: a parameter you only read from is ? extends T, one you only write to is ? super T.
108
How does Java serialization get around encapsulation and invariants?
When a Serializable class is deserialized, its constructor is not called: the fields are filled directly from the bytes. So the checks in the constructor don't run, and a forged byte stream can create an object in an invalid state.
109
What traps do Lombok's `@Data`, `@EqualsAndHashCode` and `@ToString` set in inheritance and in entities?
By default @EqualsAndHashCode ignores the parent class's fields (callSuper = false), so different objects come out equal. @Data opens a setter on everything and destroys encapsulation. @ToString and @EqualsAndHashCode cause infinite recursion and lazy loading with bidirectional relations.
110
How do you choose between a marker interface (`Serializable`, `RandomAccess`) and an annotation?
A marker interface creates a type: you can use it as a parameter type to catch mistakes at compile time and check it with instanceof. An annotation doesn't create a type, but it can go on methods, fields and packages, and it can take extra parameters. Need a type: interface. Need metadata: annotation.
111
How do you design an object that holds a resource (connection, file, lock)? Why is `finalize()` unusable?
You make the resource owner explicit, make the class AutoCloseable and close it with try-with-resources. finalize() has unknown timing (and may never run at all), is slow and is dangerous. It was deprecated in Java 9 and marked for removal in Java 18. Cleaner exists as a safety net.
112
How do you model order statuses and the transitions between them in OOP?
For a small, stable set of states, an enum with the allowed transitions and a single transitionTo method is enough. If behavior differs sharply per state, use the State pattern: each state is its own class and handles its own actions. The key point is that the transition rule lives in one place and isn't scattered across services as ifs.
113
What is "temporal coupling"? How do you fix a class that requires its methods to be called in a certain order?
If a class only works correctly when its methods are called in a strict order (init() → configure() → run()) and nothing enforces it, that is temporal coupling. Breaking the order only fails at runtime, often with an NPE. The fix is to enforce the order through types and the constructor.
114
What design risks come from passing context such as the user, tenant or trace ID through a `ThreadLocal`?
ThreadLocal is hidden global state: a dependency appears that isn't visible in the method signature. In a thread pool, if you don't clear it, the context "leaks" into the next request, and in async code it simply disappears. It's fine for small cross-cutting data (a trace ID), not for business data.
115
How do you build several validation or processing steps with Chain of Responsibility, and what does that look like in Spring?
Each step is a separate class implementing a common interface; the chain calls them in order, and each step decides whether to "stop" or "continue". In Spring you inject a List<Handler> and set the order with @Order: adding a new step is just adding a new bean.
116
What is a Service Locator and why is it worse than Dependency Injection?
With a Service Locator, a class asks a central registry for the dependency it needs (context.getBean(...)). It works, but the dependencies aren't visible in the constructor, tests have to set up the registry, and errors only show up at runtime.
117
How do you "translate" exceptions at layer boundaries? Why shouldn't `SQLException` or an HTTP client error leak into the domain?
Each layer should throw errors at its own level of abstraction. If an infrastructure error (SQLException, WebClientResponseException) leaks into the domain, the upper layers become tied to a concrete technology. The adapter catches it and wraps it in a domain-language error, keeping the cause.
118
How do you tell that a class has low cohesion? What signs and metrics are there?
If a class's fields split into groups and each method uses only one of those groups, cohesion is low. Signs: a name you can only describe with "and", lots of dependencies, code that changes for different reasons. LCOM is the usual metric.
119
What is the Composite pattern and how does it help model tree-like structures (categories, menus, org charts)?
In Composite, a single element and a group of elements implement the same interface. Client code then doesn't ask "is this a leaf or a branch?": it calls total() or render(), and the group passes the call down to its children recursively.
120
How do you deserialize polymorphic objects from JSON, and what security traps are there?
In Jackson you give a logical type name ("type": "card") with @JsonTypeInfo(use = Id.NAME) and @JsonSubTypes. Taking the class name from the JSON (Id.CLASS, global default typing) is dangerous: an attacker can instantiate any "gadget" class on the classpath.
121
What problems does a common `AbstractCrudService<T, ID>` base class for all services lead to?
At first duplication drops, but then every service starts overriding parent methods to add its own rules, and the base class bloats with flags and hooks. The same CRUD API gets exposed for every entity, even for ones that must never be deleted.
122
What is a value object in DDD, and how do you write one properly in Java with a record?
A value object is an immutable object with no identity, defined only by its value: Money, Email, DateRange. A record gives you equality and immutability, and you add validation and normalization yourself in the compact constructor.
123
How do you model the difference between an entity and a value object in JPA? When `@Embeddable`, when a separate table?
Something with its own lifecycle and identity is an entity with its own table. Something that is just a part of its owner and is compared by value is an @Embeddable, living as columns in the owner's table.
124
What happens when `toString()` or `hashCode()` is called on bidirectionally linked objects (`Order` ↔ `OrderLine`)?
If both classes build toString/hashCode from all their fields, Order calls its lines and each line calls its Order: infinite recursion and a StackOverflowError. You need to leave one side of the link (usually the parent reference) out of these methods.
125
Should you make a private method `public` or package-private in order to test it?
Usually no. A private method is tested through the public methods: tests should check behavior, not internal structure. If testing a private method on its own feels really necessary, it usually means it should be extracted into a separate class.
126
How can you keep a generic type at runtime? How does Jackson's `TypeReference` work?
Because of erasure, the Order in List<Order> doesn't exist at runtime. But generic information in a class declaration is kept: when you create the anonymous subclass new TypeReference<List<Order>>() {}, its supertype TypeReference<List<Order>> is written into the bytecode and can be read with reflection. This is the "super type token" pattern.
127
What is the difference between a Repository in DDD and a classic DAO?
A DAO faces the table: CRUD for every table, with methods close to SQL. A Repository faces the domain: it behaves like a collection of aggregates, exists only for roots, and its interface is written in domain language.
128
Why does a `static final SimpleDateFormat` field give strange dates on prod, and what design lesson comes out of it?
SimpleDateFormat has mutable state inside (a Calendar) and is not thread-safe. If one static instance is used by many threads, the results get mixed up or you get a NumberFormatException. The fix is the immutable, thread-safe DateTimeFormatter. The lesson: a shared object must be immutable.
129
What limits do records have from an OOP point of view, and is it right to add behavior (methods) to them?
A record is final, can't extend another class, can't add instance fields, and all its components are public. But you can add methods, static factories and interfaces, and you often should: a record is not just a "data box".
130
What is the "parallel inheritance hierarchies" code smell and how do you fix it?
Every time you add a class to one hierarchy, you are forced to add its pair to another: CardPayment → CardPaymentValidator → CardPaymentMapper. It means the two hierarchies are tightly coupled, and every new type requires changes in several places.
131
In Java 21, can a sealed interface and a pattern matching `switch` replace the Visitor pattern?
In many cases, yes. A sealed hierarchy and an exhaustive switch let you add a new operation without the accept/visit boilerplate, and when a new type is added the compiler points at every switch. If the hierarchy isn't closed, you still need Visitor.
132
What is the Null Object pattern and how does it differ from `Optional`?
A Null Object is an object that "does nothing" but fully matches the interface: instead of a null check, it supplies the behavior itself. Optional openly tells the caller that a value may be absent and leaves the decision to them.
133
Where should you check invariants in the Builder pattern, and what trap does Lombok's `@Builder` set here?
The check has to be in build() or in the constructor it calls, so an invalid object is never born. Lombok's @Builder checks nothing by default, and if you forget a required field it silently leaves null.
134
What happens if you use `==` or `synchronized` on value-based classes like `Integer`, `LocalDate` or `Optional`?
Relying on identity of value-based classes is wrong: == sometimes gives true and sometimes false (depending on a cache), and synchronized on them can end up sharing the same lock with other code. Since Java 16 the compiler warns about synchronizing on them.
135
How do package-private and JPMS modules give you encapsulation at a bigger level than `private`?
private only closes a class's insides. Package-private hides a package's internal classes from the outside, and JPMS closes packages that aren't exportsed from other modules, even against reflection: public no longer means "open to everyone".
136
Why are `java.util.Date` and `Calendar` called a bad OOP design example, and which mistakes did `java.time` fix?
Date is mutable, misnamed (it's a point in time, not a date), its months count from 0 and its years from 1900, and java.sql.Date inherits from it and breaks LSP. java.time brought immutable value types, clear concepts (LocalDate, Instant, ZonedDateTime) and a safe API.
137
If you make a Spring bean class or method `final`, why might `@Transactional` stop working?
When a class has no interface, Spring builds a subclass proxy with CGLIB. A final method can't be overridden, so the proxy passes it straight through to the real object and no transaction is opened. A final class can't be proxied at all.
138
What happens if a listener or observer is registered and never removed?
The event source holds a strong reference to the listener, so the listener and everything it holds escape the GC: a "lapsed listener" memory leak. On top of that, "dead" objects keep receiving events and work with stale state.
139
What is the difference between the "shotgun surgery" and "divergent change" code smells, and which principle do they violate?
Shotgun surgery means one change requires editing many classes (the logic is scattered). Divergent change means one class changes for many different reasons. Both are two sides of broken cohesion and the Single Responsibility principle.
140
How reasonable is it to use default methods in interfaces for code reuse (as a mixin)?
For small, stateless helper behavior it's fine: convenience methods built on top of the interface's other abstract methods. But an interface has no state (fields), so imitating an abstract class with default methods gives a confusing, brittle design.
141
In a modular monolith, how do you define module boundaries and protect them from "melting away" over time?
I draw boundaries by business capability rather than technical layer (package by feature), give each module a small public API, and enforce the rules in CI with ArchUnit or Spring Modulith tests. Documentation doesn't protect anything; only a test that fails does.
142
When does hexagonal (ports and adapters) architecture pay off, and when is it unnecessary complexity?
It pays off in a system with rich, long-lived business logic and several input/output channels (REST, Kafka, batch, different providers). In plain CRUD or a short-lived service it multiplies interfaces, mappers and DTO layers for every operation, with little benefit.
143
How do you safely break up a 5000-line "god class" in a legacy system with no tests?
First I pin down the behavior with characterization tests, then I separate responsibilities with small, mechanical refactoring steps (extract method/class, automated IDE refactorings). Each step is deployed on its own; I don't go for a big "rewrite".
144
When do you use inheritance hierarchies in JPA (SINGLE_TABLE, JOINED, TABLE_PER_CLASS), and when is composition better?
Inheritance mapping pays off when you really need polymorphic queries; SINGLE_TABLE is fast but gives nullable columns, JOINED is clean but slow because of the JOINs. Often a "type" column with @Embedded or composition with a JSON column is simpler and faster.
145
How do you design an extensible API that other teams write plugins for, so that you can change it later without breaking users?
I start with a small interface and immutable parameter objects, hide the implementation classes, and add new capabilities through default methods or new interfaces. On every release I check binary compatibility automatically (japicmp or revapi).
146
How do you notice in prod that an aggregate has grown too big, and how do you shrink it?
Optimistic lock conflicts go up, loading the whole graph to change one record, and lock wait times grow. The fix is to re-check the real invariants, split the aggregate, and make the consistency between the pieces eventual through events.
147
How do interfaces and polymorphism affect performance when there are many layers of abstraction? What does the JIT do here?
In most cases they have almost no effect: if the JIT sees one or two implementations at a call site, it inlines the call. The problem is a megamorphic call site: when three or more types are mixed, virtual dispatch and the lack of inlining become noticeable in a hot loop.
148
In a library or shared module, what is the difference between source compatibility and binary compatibility? Which changes silently break them?
Source compatibility means user code recompiles against the new version. Binary compatibility means a jar compiled against the old version keeps working without recompiling. Some changes keep one and break the other, and the error only shows up at runtime as NoSuchMethodError.
149
When designing the public API of an internal Java library used by many teams, which OOP decisions cause the most pain later?
Open, non-final classes (users inherit and bind to internal behavior), mutable return types, exposing implementation types in signatures, and leaking transitive dependencies into the API. These later turn into a contract you can't fix.
150
YAGNI and "design open for extension" seem to contradict each other. In practice, how do you decide how much to abstract up front?
I abstract only for the change points that are known now; for a guessed future I keep the code simple but easy to change. For irreversible decisions (API contracts, data schemas, module boundaries) I think much more up front.
151
Domain objects are stored as JSON in a database or in Kafka. When the class changes, how do you stay compatible with old data?
Stored JSON is not code, it's a contract: it outlives the class. So I only add fields, rename and remove them in stages, and for a sharp change I add a version field and an upcaster (code that converts the old shape into the new one on read).
152
How do you design a class that other teams will inherit from, so their code doesn't break in the next version?
I decide on inheritance deliberately: I expose the extension points as explicit protected hooks, make everything else final, and document self-use. Or I close inheritance entirely and offer an interface and composition.
153
How do you add cross-cutting concerns like audit, metrics and permission checks without polluting domain code?
A domain method should only deal with the business rule. I move cross-cutting concerns to the boundary: an application service, a decorator, an aspect or a domain event listener. Which one depends on how tied to the business the concern is: observability is an aspect, an audit with business meaning is an event.
154
The mapping layers between entity, domain model, DTO and event have multiplied. When is a separate model worth it, and how do you organize the mapping?
A separate model is worth it only for a boundary where things really change differently: an external API, an external event, a complex domain. Elsewhere I cut down the number of models. For mapping I use compile-time generation (MapStruct) or explicit hand-written code, not "magic" reflection-based mappers.
155
When is it right to split one big `Order` class into separate types by lifecycle stage (`DraftOrder`, `PlacedOrder`, `ShippedOrder`)?
When the fields present and the actions allowed differ sharply at each stage. Then the compiler stops an action in the wrong state: DraftOrder simply has no ship() method. The cost: working with several types in persistence and the API gets harder.
156
Which design rule does this code break, and what problem does it cause in production?
It breaks the Law of Demeter: the service reaches deep along a chain of objects and gets tied to a foreign structure. If any class in the chain changes, this code breaks, a null in the chain gives an NPE, and a test needs three mocks.
157
Which SOLID principle does this code break, and how would you fix the design?
It breaks Liskov: ReadOnlyRepository doesn't perform the save that the base contract promises and throws an exception at runtime. If we split the interface into read and write (ISP), the problem moves to compile time.
158
When an invariant depends on outside data (for example, "an email must be unique in the system"), how do you enforce it in the domain model?
A single object can't check a rule like this on its own: it doesn't know about other objects. I give the check to a domain service or a factory, but the final guarantee is a unique constraint in the database, because two parallel requests can both pass both checks.
159
When designing an immutable object, how do you choose between a builder, a wither and a defensive copy?
For an object with 3–4 fields, a plain constructor or a record is enough. A builder when there are many optional fields, a wither when you need a new copy with one field changed. And I always make a defensive copy of mutable inputs (List, Date, arrays).
160
How do you design an exception hierarchy for a large project?
One base unchecked exception for domain errors and a few meaningful subtypes: "not found", "rule violated", "access denied". Each is mapped to an HTTP status in one place; technical errors stay separate.
161
How do you identify bounded context boundaries in a new large system?
I draw the boundaries by language and business process, not by technical layer: where one word starts to mean two different things is usually a boundary. Event storming, team structure and rate of change confirm the decision.
162
What is a context map in DDD? When do you choose shared kernel, customer-supplier, conformist and open host service relationships?
A context map is a map of the relationships between bounded contexts: who depends on whose model, and how. The type of relationship reflects power and agreements between teams more than technology; if you name it up front, half of the integration problems never appear.
163
If two services or modules read and write the same database tables, what hidden coupling does that create, and how do you get out of it?
A shared table is the strongest and most invisible contract: column names, types, even status values become the API of both sides. If one team runs a migration, the other breaks in prod. The way out is for each piece of data to have one owner, and for the others to get it through an API, an event or a read-only view.
164
Why does sharing a common "common-model" jar (with DTOs and entities) between several services often become a problem?
A shared model library couples services at compile time: if one field changes, all services are forced to release together. That's a sign of a "distributed monolith". Sharing is only appropriate for things that are stable, small and versioned.
165
What is the difference between a domain event and an integration event, and why is it dangerous to express them with one class?
Domain event / Integration event — Who listens: handlers inside the same module / other services, other teams; Transport: in-memory (ApplicationEventPublisher) / Kafka, RabbitMQ; Content: domain objects, IDs / only what's needed, flat data; Change: free, along with refactoring / follows schema evolution rules
166
How do you organize hexagonal architecture (ports and adapters) at the package level in a Spring Boot project?
In the center are the domain and use cases, free of framework dependencies, with their ports (interfaces) right there. Outside are the adapters: REST controller, JPA repository, Kafka listener. Dependencies only point inward.
167
How do you protect architecture rules (layers, package dependencies) automatically, without trusting code review?
With ArchUnit tests: I write the allowed directions between layers, the absence of cycles and naming rules as ordinary JUnit tests. They run in CI, and when a rule is broken the build fails.
168
For APIs between services, how do you choose between contract-first (generating code from OpenAPI/Protobuf) and code-first (generating the schema from Java classes)?
For APIs with many consumers, between teams and long-lived, contract-first: the contract is a separate artifact, easy to review and to check for compatibility automatically. For a fast-changing internal API inside one team, code-first is quicker. The main thing is that the generated classes must not turn into your domain model.
169
When splitting a monolith into services, how do you measure coupling and cohesion, and how is the decision made?
I look at static dependencies (the class/package graph), change frequency together (git history) and runtime calls (tracing) at the same time. A cluster with high internal cohesion and low external coupling is a good candidate; splitting things that change together is a mistake.
170
The same validation or calculation code is duplicated in three services. Do you make a shared library or leave the duplication?
If it's one business rule that must change together, I give it a single owner (a library or a service). If it just looks similar but changes for different reasons, I leave the duplication.
171
The business split one concept into two (for example, "customer" is now "payer" and "user"). How do you evolve a model that many services use?
First I define the new concepts clearly in domain language and introduce them as new types side by side, without deleting the old model right away. Then expand–migrate–contract: add the new model, move consumers over step by step, deprecate the old model and finally remove it.
172
You need to add a new method to an interface in a Java library used by many teams. How do you do it without breaking users?
I add a default method to the interface or create a new small interface. I check binary and source compatibility separately (with japicmp or revapi), mark what will be removed @Deprecated(forRemoval = true) first, and remove it in a major version under semver.
173
How does the choice between a monorepo and a polyrepo affect coupling between modules?
A monorepo makes atomic changes easy (you can change an API and all its consumers in one PR), but for exactly that reason boundaries erode. A polyrepo enforces boundaries, but versioning and coordination cost a lot. Coupling is controlled by extra rules, not by the repo.
174
How do you plan moving a deep inheritance hierarchy that has grown over the years to composition in a large codebase?
First I find which axes the hierarchy varies along, pull each axis out into its own strategy object, write new classes through those, and move the old subclasses to an adapter one at a time. I don't do everything in one PR.
175
Business rules change every week (discounts, limits). In code, do you choose the strategy pattern, configuration, a feature flag or a rules engine?
It depends on which part of the rule changes: if only numbers change, configuration/DB; if the structure of the logic changes, code (a strategy); if you need to roll it out gradually to certain users, a feature flag. I only take a rules engine when the business itself must write rules.
176
Use JPA entities directly as the domain model, or make a separate persistence model: what are the trade-offs?
Using the JPA entity as the domain halves the code, but the domain has to obey Hibernate's rules (a no-arg constructor, proxies, lazy loading). A separate model keeps the domain clean, but adds mapping at every boundary and an extra source of bugs.
177
When is introducing CQRS justified, and when is it just unnecessary complexity?
CQRS is useful when the read and write load or shape differ sharply, or when report queries are wrecking a complex domain model. In plain CRUD, and with a strict "I wrote it, I read it right away" requirement, it only adds eventual consistency problems.
178
In event sourcing, aggregate state is rebuilt from events. How does this affect OOP design, and what are the traps?
Aggregate methods don't change state directly: they check the rule and create an event, and the state only changes by "applying" the event. The traps: the event schema stays forever, long event streams need snapshots, and it's easy to put a side effect inside apply.
179
When a business rule spans several aggregates or services (for example, stock in the warehouse and an order), how do you enforce the invariant?
First I question the rule itself: does it really have to be consistent instantly, or is eventual consistency with compensation enough? Usually a saga: each step is a local transaction in its own aggregate, with a compensating action on failure.
180
The business understands "active customer" as one thing, the code as `isEnabled` and the reports as a third. How do you introduce ubiquitous language in practice?
I write a glossary of key terms together with the business, rename the code (classes, methods, events, tables) to match it, and when a term is used with two meanings, I treat it as a sign of a missing bounded context.
181
How do you justify time for refactoring and clean-code work to business leadership?
Not with "the code is ugly", but with numbers: feature delivery time, the number of incidents in that module, onboarding time. I propose refactoring not as a separate project but as an investment tied to an upcoming business task.
182
Of the code quality metrics (cyclomatic complexity, LCOM, afferent/efferent coupling, instability), which are useful in practice and which mislead?
Metrics are useful for finding trends and hotspots, and harmful as absolute targets. Complexity plus change frequency, coupling between packages and cycles give the most value; coverage percentage and LOC mislead the most.
183
Explain connascence. What does it add about coupling beyond "low coupling, high cohesion"?
Connascence means two components are related so that if you change one, you must change the other. It splits coupling into kinds (name, type, position, meaning, algorithm, timing...) and says exactly which is stronger and how it relates to distance.
184
How does Conway's law affect design decisions, and what is the "inverse Conway maneuver"?
A system's architecture copies the communication structure of the organization that built it. The inverse Conway maneuver is changing the team structure first, to get the architecture you want. If you don't align the two, code boundaries keep drifting toward team boundaries.
185
How does the Interface Segregation principle show up at the API level between services? Is one big endpoint/DTO for all consumers bad?
Yes, ISP applies to network APIs too: any fields and operations beyond what a consumer needs bring it dependencies and security risk. I publish separate, small contracts (or a BFF) for different groups of consumers.
186
How does the Liskov principle apply to API versioning? What do you need to follow so that a new version of an API can "substitute" for the old one?
The new version must be a substitute for old consumers in the Liskov sense: don't strengthen requirements on input, don't weaken promises on output. Adding a field is fine; adding a required parameter or changing a meaning is a breaking change.
187
A new provider is added to the payment system every quarter. How do you build a design that follows the Open/Closed principle at the service and code level?
The domain only knows the PaymentProvider port; each provider is a separate adapter, registered automatically through Spring. The provider selection rule lives in configuration. Adding a provider means a new class and configuration, and the old code isn't touched.
188
You need to recalculate 10 million rows overnight. When is it right to give up rich domain objects and the ORM?
A domain model is built for decisions about one or a few objects. In bulk processing (batch, migration, reporting), loading every row into an object, calling a method and saving is very expensive in both memory and time. For that, set-level SQL or streaming is right, but the business rule must not end up duplicated in two places.
189
A team wants to write an internal "universal framework": generic CRUD for any entity, dynamic forms, business processes defined in configuration. What do you think of it?
With caution: this often leads to the "inner-platform effect", where a worse copy of Java and Spring gets built on top of Java and Spring. It speeds up the simple cases, but every non-standard requirement makes the framework more complex, and you end up with a system nobody understands.
190
In a multi-threaded, high-load system, how do you design objects: shared mutable state, immutable objects, or a "single owner" model?
The default is immutable objects and giving the state to a single owner (thread confinement, actor/queue). Shared mutable state only when necessary, as small as possible and encapsulated inside one class, with concurrent collections or an explicit lock.
191
In a reactive (WebFlux) project, should domain methods return `Mono`/`Flux`? What happens when framework types leak into the domain?
Usually no. Domain decisions should be pure and synchronous: values in, a result or an event out. Mono/Flux belong only where there's I/O: in the application service and adapters. If Reactor gets into the domain, business rules become much harder to read, to test and to move to virtual threads later.
192
Records, sealed types and pattern matching in Java 21 give you a "data-oriented programming" style. How do you balance it with classic OOP in one codebase?
The data-oriented style for types that carry data and results (DTOs, events, commands, errors, protocol messages); classic encapsulation for domain objects with rich behavior that protect their own state and invariants. The boundary is between "what this object knows" and "what this object does".
193
As a platform team, when do you agree to "magic" mechanisms based on annotations and reflection (custom annotations, aspects, automatic registration)?
For repeatable, cross-cutting tasks with a clear contract: audit, metrics, tracing, permission checks. Not for "magic" that changes the business flow or makes a decision that isn't visible when you read the code: explicit code is better there.
194
The unit tests written for domain code each need 6–8 mocks. What does that say about the design, and how do you change the testing strategy?
This is usually a design signal: the class is tied to too many collaborators, the logic is scattered across services, and the domain objects are anemic. I move the logic into pure domain objects and test them without mocks, and cover the external boundaries with a small number of integration tests.
195
In an engineering department of 60 people, how do you introduce clean code and design standards so they don't stay on paper?
I give everything that can be automated (formatting, static analysis, architecture rules) to CI, and I show the remaining decisions through ADRs and a sample project. We write the standards together with the teams and keep them few but mandatory.
196
In a multi-tenant SaaS, every customer (tenant) needs slightly different business rules. How do you design it without burying the code in ifs?
I split the differences into three categories: parameters (tenant settings), swappable behavior (a strategy picked per tenant) and truly custom extensions. The tenant context is determined in one place, and the code doesn't know if (tenant == "X").
197
When do you use the Specification pattern to express complex search and filtering rules in domain language, and what are its limits?
When the same business condition is used both in an in-memory check and in a DB query, or when conditions are combined dynamically, Specification is useful. But it tries to join two worlds (Java predicates and SQL), and in complex queries the abstraction leaks.
198
You need to move a 10-year-old monolith to a new design. How do you plan the strangler fig approach, and where does it most often fail?
I put a routing layer in front of the monolith and move functions to a new module/service one at a time; each step is verified in prod and the old code is deleted. It most often gets hard at data migration, at the "two systems" left unfinished, and when the business doesn't stop new features.
199
When is removing an abstraction layer the right decision? How do you spot needless indirection and a "leaky abstraction"?
If an abstraction wraps only one implementation, if every caller still has to know the technology details inside, or if it makes errors harder to understand, it doesn't earn its cost. I inline such a layer and simplify the code.
200
How do you manage "hidden" dependencies like system time, ID generation and random numbers in a design, and why are they an architecture issue?
I inject them as explicit dependencies: Clock, IdGenerator, RandomGenerator. Then the code can be tested deterministically, and the time zone and ID format are controlled in one place and consistent across services.
Sign up — studied questions get marked and your progress is saved.