Scrivio Interview library
DesignIntermediate8 min read · updated 12 November 2026

An AbstractImporter base class has 12 subclasses, each overriding between two and five hook methods. Changes to the base class often break subclasses. How would you refactor it?

Changes break subclasses because this is the fragile base class problem: each subclass depends on the base class's internal call order and on which hooks it calls when. We refactor by naming the variable steps, such as read, validate, transform and write, turning each into a small interface, and composing an Importer from implementations passed in as constructor parameters, the way Spring Batch builds steps from ItemReader, ItemProcessor and ItemWriter. We migrate one subclass at a time with tests that compare output before and after, and keep a template method only where the steps are truly fixed and few.

Why this question is asked

Inheritance-based frameworks inside a codebase usually start well. Two importers share a loop, someone extracts AbstractImporter, and for a while every new importer is twenty lines. By the time there are 12 subclasses, each overriding a different mix of hooks, nobody can change the base class without breaking an importer they have never seen. Interviewers ask this because it tests whether we can name the problem, choose a composition design that removes it, and move a working system to it without a risky rewrite. In this answer, we will see why the base class became fragile, identify the steps, design small interfaces, compose importers from them, look at Spring Batch as a reference, and plan the migration.

1Why Changes Break the Subclasses

The base class has a template method, run(), that calls hook methods in a certain order. Subclasses override some of those hooks, and over time they start relying on details that were never part of a stated contract: that beforeRow() is called before validate(), that validate() is not called for header lines, that a field set in open() is available in transform(). Some subclasses even call super.transform() and change its result.

So when someone changes the base class, for example to validate rows in batches for speed, the call order changes, and a subclass that set up state in beforeRow() suddenly sees nulls. Nothing in the compiler or the types expressed the dependency, which is why it is called the fragile base class problem: the base class cannot change without knowing all its subclasses.

Java
abstract class AbstractImporter {
public void run(Path file) {
open(file);
for (String line : lines(file)) {
if (skip(line)) continue;
beforeRow(line); // CustomerImporter sets 'current' here
Row r = parse(line);
if (validate(r)) write(transform(r)); // ... and reads 'current' here
}
close();
}
protected void open(Path f) {}
protected boolean skip(String line) { return line.isBlank(); }
protected void beforeRow(String line) {}
protected abstract Row parse(String line);
protected boolean validate(Row r) { return true; }
protected Object transform(Row r) { return r; }
protected abstract void write(Object o);
protected void close() {}
}
// Changing run() to validate all rows first, then transform, breaks CustomerImporter:
// transform() now sees the 'current' of the last row -> wrong customer ids

Notice that the state lives in subclass fields, and the hooks talk to each other through that state. That hidden coupling to the base class's call order is what makes every change risky.

2Naming the Steps

The first step is reading all 12 subclasses and listing what they actually vary. In importers this usually falls into four steps: reading records from a source, validating a record, transforming it into the target model, and writing the result. Hooks such as beforeRow, skip and open are usually ways of doing one of those four things, or of keeping state between them, and they map onto the steps once we look closely.

Each step becomes a small interface with one method and an explicit input and output, so that no step needs to share hidden fields with another.

Java
interface RecordReader<I> extends AutoCloseable { Optional<I> next(); } // empty at the end
interface Validator<I> { List<String> errors(I record); } // empty list means valid
interface Transformer<I, O> { O transform(I record); }
interface Writer<O> { void write(List<O> batch); }

3Composing an Importer

The importer is now a final class with one fixed loop, which takes its four collaborators in the constructor. It owns batching, error collection and counting; the collaborators own only their step. Because the class is final and the steps have explicit inputs and outputs, changing the loop, for example to write in batches of 500, cannot depend on any subclass's hidden state.

Java
public final class Importer<I, O> {
private final RecordReader<I> reader; private final Validator<I> validator;
private final Transformer<I, O> transformer; private final Writer<O> writer;
public Importer(RecordReader<I> r, Validator<I> v, Transformer<I, O> t, Writer<O> w) {
reader = r; validator = v; transformer = t; writer = w;
}
public ImportResult run() throws Exception {
List<O> batch = new ArrayList<>(); int ok = 0, rejected = 0;
try (reader) {
for (Optional<I> rec = reader.next(); rec.isPresent(); rec = reader.next()) {
if (!validator.errors(rec.get()).isEmpty()) { rejected++; continue; }
batch.add(transformer.transform(rec.get())); ok++;
if (batch.size() == 500) { writer.write(batch); batch.clear(); }
}
if (!batch.isEmpty()) writer.write(batch);
}
return new ImportResult(ok, rejected);
}
}
Importer<CsvLine, Customer> customers = new Importer<>(
new CsvReader(path), new CustomerValidator(), new CustomerMapper(), new JdbcCustomerWriter(jdbc));
customers.run(); // ImportResult[ok=9812, rejected=17]
Step throughAn importer built from parts
  1. Importer (final)Fixed loop, batching, counting, error handling
  2. RecordReaderCSV, fixed-width, Excel: shared across importers
  3. ValidatorPer domain, testable with one record
  4. TransformerMaps the source record to the target model
  5. WriterJDBC batch, REST call, file: shared

5 layers, from the top down. Step through them one at a time.

Notice what we gained. The CSV reader can be shared by the eight importers that read CSV, where before each subclass had its own parse. The customer validator can be unit tested with one record, without a file. Importers that differed only in their writer now differ only in one constructor argument. And a step that needed state, such as the current customer, now passes it explicitly in the record or keeps it inside its own object.

4Spring Batch as a Reference Design

Spring Batch made the same choice years ago. A chunk-oriented step is built from an ItemReader, an optional ItemProcessor and an ItemWriter, each a small interface, and the framework owns the loop, the chunking, transactions per chunk, skip and retry policies, and restart after failure. If our importers are growing towards needs like restarting a failed 2 million row file at row 1.5 million, adopting Spring Batch directly may be better than growing our own Importer. If they are simple, our own small composition is enough and keeps the dependency out. Either way, the shape is the same, which makes a later move to Spring Batch straightforward.

5Migrating Subclass by Subclass

We do not rewrite all 12 at once. First, we build golden tests: for each importer, a set of realistic input files and the exact output they produce today, captured as database rows or as a file the fake writer records. These tests describe current behaviour, including quirks, so we know when we change it.

Then we migrate the simplest importer, run its golden test against the new composition, and ship it, keeping AbstractImporter in place for the rest. Each later migration often reuses readers and writers from earlier ones, so they get quicker. When the last subclass has moved, we delete the base class. Where a difference in output appears, we decide with the owners whether it was a bug to fix or behaviour to keep, rather than letting the refactoring change it silently.

Step throughMigration plan for 12 importers
  1. Capture golden input and outputPer importer, current behaviour
  2. Pick the simplest remaining subclassReuse existing readers and writers
  3. Compose it from step implementationsNew class, old one still present
  4. Golden test passes?Same rows, same rejects
    YesSwitch traffic and remove the subclassNoInvestigate: bug or behaviour to keep
  5. Last one migrated?12 to go at the start
    YesDelete AbstractImporterNoPick the next subclass

5 steps in order. Play them, or step through them one at a time.

6When a Template Method Is Still Right

Composition is not always better. If an algorithm has two or three steps that are truly fixed, a handful of subclasses, and a base class that rarely changes, a template method is simpler to read and has no fragility problem in practice. AbstractList is a good example: its contract of get and size has not changed in decades. The trouble starts when hooks multiply, subclasses start sharing state between hooks, and the base class keeps changing. Those three signs together are the signal to switch.

7Follow-up questions

Could we just document the call order of the hooks instead?

Documentation helps, but it does not stop the base class from needing to change, and every subclass would still depend on that order. Making the steps explicit interfaces with inputs and outputs removes the dependency instead of describing it.

How do you handle a subclass that overrides the whole run() method?

That subclass is really a different algorithm. We look at what it does differently, often a different loop such as parallel reading, and either add that capability to the importer, for example a configurable batch size, or leave it as its own class that does not pretend to share the template.

Does composition make the code harder to follow?

It adds a few small types, but each is simple and named after a step, and the loop exists in one place. Many teams use a small builder or a Spring configuration class per importer that lists its four parts, which reads like a description of the importer.

8Conclusion

In this answer, we saw that AbstractImporter's subclasses break because they depend on the base class's internal call order and share hidden state between hooks, the fragile base class problem. We named the variable steps, turned them into small reader, validator, transformer and writer interfaces, composed a final Importer from them through its constructor, like Spring Batch's ItemReader, ItemProcessor and ItemWriter, and migrated one subclass at a time with golden tests, keeping template methods only where steps are fixed and few.

What to say in the interviewAbout 100 seconds aloud

Open with

This is the fragile base class problem. The base class's run method calls hooks in a particular order, and over the years the subclasses have come to depend on that order and on state they set in one hook and read in another.

Then, if they want more

Nothing in the types expresses that, so any change to run, like batching validation, breaks some importer nobody was looking at. I would refactor towards composition. First I read all 12 subclasses and name what really varies, which for importers is almost always reading records, validating them, transforming them and writing them.

Each of those becomes a small interface with explicit inputs and outputs, so steps do not share hidden fields. Then the importer becomes a final class that takes a reader, a validator, a transformer and a writer in its constructor and owns the fixed loop, batching and error counting.

That way readers and writers can be shared, each step can be unit tested in isolation, and the loop can change without breaking anyone. Spring Batch's ItemReader, ItemProcessor and ItemWriter are exactly this design, and if we need restartability or skip policies I would consider moving to it.

For the migration, I would capture golden tests per importer, real input files and the exact output they produce today, then migrate one subclass at a time, compare outputs, and delete the base class at the end. I would keep a template method only where the steps are truly fixed and few, like AbstractList.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "An AbstractImporter base class has 12 subclasses, each overriding between two and five...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/19dd19980b/