A class has 3 methods and 4 fields. The methods use 2, 1 and 1 of the fields. Find its cohesion ratio to two decimal places.
Answer and solution
Answer: (accepted range )
.
.
, which is 0.33.
FOR CORE AND IT JOBS · CHAPTER 7 OF 7
Some Java classes are easy to change; others break when touched. Cohesion, coupling, SOLID, four patterns, refactoring and unit tests show why, so you can change working code safely.
Updated 30 Oct 2026
You will judge a class by its focus and its dependencies. You will spot and fix a broken SOLID principle. You will write Singleton, Factory, Strategy and Observer and say when each helps. You will split a long method and test a class.
Chapter 1, Classes and objects in Java
Chapter 2, Encapsulation and immutability
Chapter 3, Inheritance
Chapter 4, Polymorphism, abstract classes and interfaces
Chapter 5, Exceptions
Chapter 6, Collections and generics
Ratios and fractions
A class is cohesive when its methods work on the same fields, so it does one job. It is coupled to each class it names: a change there can break it. Aim for high cohesion, low coupling. All code here is Java 17: classes in PascalCase, methods and fields in camelCase.
COHESION RATIO
For , ; a rough measure from 0 to 1, no unit. , = numbers of methods and fields; = number of (method, field) pairs where the method reads or writes the field. A low value suggests several jobs in one class.
COUPLING COUNT
Counts the concrete classes of your own program, other than , that names: as a type, after new, or in a static call. Interfaces (many classes can stand behind one) and Java's own classes such as String do not count.
WORKED EXAMPLE
Invoice has fields items and printerName. addItem and total use items, print uses both, connectPrinter uses printerName. Find , split the class, and find again.
Count the pairs, because is the number of (method, field) uses: addItem 1, total 1, print 2, connectPrinter 1, so .
Here and , so and .
Only print uses both fields, and it needs printerName just to reach the printer, so the class does two jobs: keeping items and driving a printer.
Split into Invoice (items; addItem, total) and Printer (printerName; connectPrinter, and print(String text), which is given the text instead of reading items).
Invoice: , , , so . Printer: both methods use printerName, so again , , and .
Answer: The class scores 0.625, and the two classes after the split each score 1.
S, single responsibility. A class should have one reason to change. Broken: Report builds text and writes the file, so a format change and a storage change both edit it.
class Report {
String build(int total) { return "Total " + total; }
void save(String text) { /* writes text to r.txt */ }
}Fix: keep build in Report and move save, unchanged, into a new class ReportStore.
SINGLE RESPONSIBILITY
is a class. A reason to change is a separate decision that would force an edit to , such as the text format or where files go.
O, open for extension, closed for modification. Broken: each new shape edits old, working code.
class Geometry {
double area(String kind, double x) {
return kind.equals("square") ? x * x : Math.PI * x * x; // a triangle edits this line
}
}Fix: one interface and one class per shape (a record is a short class whose fixed fields are set by its constructor).
interface Shape { double area(); }
record Square(double side) implements Shape { public double area() { return side * side; } }
record Circle(double r) implements Shape { public double area() { return Math.PI * r * r; } }OPEN AND CLOSED
Holds when callers use the interface Shape and never test the kind themselves.
L, Liskov substitution. A subclass must work wherever its parent is used. Broken: Penguin extends Bird but fly throws, so a loop calling fly on each bird crashes.
class Bird { void fly() { System.out.println("flying"); } }
class Penguin extends Bird {
@Override void fly() { throw new UnsupportedOperationException(); }
}Fix: take fly out of Bird into interface Flyer { void fly(); }, which only flying birds implement. Penguin extends Bird and has no fly. Below, pre is what a method needs from its caller, post what it promises, and means " implies ".
SUBSTITUTION RULE
For each overridden method: the child accepts at least what the parent accepts and promises at least as much. Bird.fly promises to return normally; a fly that always throws breaks the second rule.
I, interface segregation. No class should have to write methods it does not use. Broken: interface Worker { void work(); void eat(); } forces a Robot to write an empty public void eat() { }. Fix: split it into interface Workable { void work(); } and interface Eatable { void eat(); }; Robot implements only Workable.
D, dependency inversion. Depend on interfaces, not concrete classes. Broken: Notifier builds its own helper.
class Notifier {
private final SmsSender sender = new SmsSender();
}Fix: receive it through the constructor as an interface.
interface Sender { void send(String m); }
class Notifier {
private final Sender sender;
Notifier(Sender sender) { this.sender = sender; }
void alert(String m) { sender.send(m); }
}DEPENDENCY INVERSION
An arrow points from a class to the interface it uses or implements. Both point at Sender, so falls from 1 to 0.
A pattern is a named fix for a recurring problem. Singleton keeps exactly one instance. A thread is one line of execution, and a program can run several at once. This lazy version is not thread-safe: a second thread can run between the test and the assignment.
class Config {
private static Config instance;
private Config() {}
static Config get() {
if (instance == null) instance = new Config(); // check, then act
return instance;
}
}Fix: write static synchronized Config get(). The keyword synchronized lets only one thread at a time run get(), so the test and the assignment act as one step.
WORKED EXAMPLE
Two threads T1 and T2 call the lazy Config.get() for the first time, with instance null. Show how two objects get built.
T1 runs the test: instance is null, so it enters the if. It is paused before the assignment.
T2 runs the test: instance is still null, because T1 has not assigned yet, so T2 also enters the if.
T2 builds object A, stores it and returns A. T1 resumes, builds object B, overwrites instance and returns B.
The two callers now hold different objects, so the class is no longer a singleton. With synchronized, T2 waits until T1 has stored its object, then finds instance not null and returns it.
Answer: Check-then-act is two steps, so two objects can exist. The synchronized version builds one.
Factory puts the choice of class in one place: callers name the interface and the factory, not the classes it builds. Strategy passes behaviour in as an object, so the behaviour changes without editing the class that uses it: the Sender handed to the fixed Notifier is one, and so is a Comparator (Chapter 6).
class SmsSender implements Sender { public void send(String m) { System.out.println("SMS: " + m); } }
class EmailSender implements Sender { public void send(String m) { System.out.println("Mail: " + m); } }
class SenderFactory {
static Sender create(String kind) {
return switch (kind) {
case "sms" -> new SmsSender();
case "email" -> new EmailSender();
default -> throw new IllegalArgumentException(kind);
};
}
}
// new Notifier(SenderFactory.create("email")).alert("hi"); prints Mail: hiObserver lets one object tell many others that it changed without knowing who they are: it keeps a list of listeners (objects that want to hear of a change) and calls each. v -> ... is a lambda: a short way to write an object of a one-method interface.
interface Listener { void onChange(int v); }
class Sensor {
private final java.util.List<Listener> ls = new java.util.ArrayList<>();
void subscribe(Listener l) { ls.add(l); }
void set(int v) { for (Listener l : ls) l.onChange(v); }
}
// Sensor s = new Sensor(); s.subscribe(v -> System.out.println("got " + v)); s.set(7); prints got 7Pattern | Helps when |
|---|---|
Singleton | Exactly one shared object is needed |
Factory | The class to build depends on input |
Strategy | Several algorithms can swap in |
Observer | Many parts react to one change |
WATCH OUT FOR
Factory and Strategy look alike: both work through an interface. Test: Factory decides which object to create; Strategy decides which behaviour to run.
Refactoring changes the structure of code without changing what it does. A common first step: cut a long method into small, named ones, rerunning the tests after each step. Before, total held the summing loop and the tax in one body, ending return s + s * rate;. After:
import java.util.List;
class Billing {
double total(List<Double> prices, double rate) {
double s = sum(prices);
return s + tax(s, rate);
}
private double sum(List<Double> prices) {
double s = 0;
for (double p : prices) s += p;
return s;
}
private double tax(double s, double rate) { return s * rate; }
}A unit test runs one small piece of code and checks the result: arrange, act, assert. This outline uses JUnit 5: @Test labels a method for JUnit to run. BillingTest sits in Billing's package (a named group of classes), so it can call total, which has default access.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class BillingTest {
@Test
void totalAddsTax() {
Billing b = new Billing(); // arrange
double t = b.total(java.util.List.of(10.0, 30.0), 0.5); // act: 40 + 20
assertEquals(60.0, t, 1e-9); // assert: passes
}
}Passing before and after shows the refactoring kept this result. assertThrows checks that a method throws (Chapter 5).
A class has 3 methods and 4 fields. The methods use 2, 1 and 1 of the fields. Find its cohesion ratio to two decimal places.
Answer: (accepted range )
.
.
, which is 0.33.
Penguin extends Bird, and Penguin.fly() always throws UnsupportedOperationException. Which principle does this break?
Single responsibility
Open for extension, closed for modification
Liskov substitution
Dependency inversion
Answer: (C)
Code that works with any Bird calls fly and now crashes for a Penguin.
The child does not keep the parent's promise, so it cannot replace the parent.
That is Liskov substitution.
Which statements about the lazy Config.get() shown earlier are true? Select all that apply.
A second thread can pass the null test before the first assigns
Declaring it static synchronized makes it build one object
The private constructor stops two threads from building two objects
Static fields are copied for each thread
Answer: (A), (B)
A is true: check-then-act is two steps, so both threads can see instance as null.
B is true: synchronized lets one thread at a time run get(), so the second finds the stored object.
C is false: the private constructor only stops other classes calling new; get() itself calls it twice.
D is false: one static field is shared by all threads.
Alert names five concrete classes of its own program: SmsSender, EmailSender, FileLogger, OrderDatabase and Scheduler. It now takes a Sender and a Logger (both interfaces) in its constructor and no longer names the first three. Find .
Answer:
Before the change .
Sender and Logger are interfaces, which do not count, and the three concrete classes they replace are no longer named.
OrderDatabase and Scheduler remain, so .