Skip to content

Chapter 37 of 37

Best Practices and Optimization

Write secure, testable, observable Java and optimize only from representative measurements.

44 minutes 10 quick checksBy Subha Prasad
Lesson 37 of 37Course navigation

Lesson content

Read, practise, then check your understanding

Favor immutable values, small cohesive APIs, constructor-established invariants, composition, dependency injection, and standard abstractions. Validate at trust boundaries, close resources, avoid global mutable state, and never log secrets.

Measure before changing

static double average(int[] values) {
    if (values.length == 0) return 0;
    long sum = 0;
    for (int value : values) sum = Math.addExact(sum, value);
    return (double) sum / values.length;
}

Automate formatting, static analysis, unit/integration tests, dependency scanning, and observability. Profile representative workloads with tools such as Java Flight Recorder; algorithm, allocation rate, data locality, I/O, contention, and database access usually matter more than micro-syntax. Benchmark with JMH so JIT warmup and dead-code elimination are handled. Set a supported Java baseline and document performance changes with reproducible evidence.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes immutability?
Which Java term matches this description: Design in which observable object state cannot change after construction.
Which statement best describes dependency injection?
Which Java term matches this description: Providing collaborators from outside rather than constructing hidden dependencies.
Which statement best describes profiling?
Which Java term matches this description: Measuring runtime behavior to identify real bottlenecks.
Which statement best describes defensive copying?
Which Java term matches this description: Copying mutable input or output to protect internal state.
Which statement best describes least privilege?
Which Java term matches this description: Granting code and APIs only the access they require.

0 of 10 checks passed

Your progress is saved on this device.

Best Practices and Optimization | Java Lesson | Subha Prasad