Abstraction and Program Design
Big idea: Abstraction means hiding details so you can think about the big picture. Good design names the data (attributes) and the actions (methods) before any code is written.
- Represent the design of a program by using natural language or creating diagrams that indicate the classes in the program and the data and procedural abstractions found in each class by including all attributes and behaviors.
Two kinds of abstraction
Data abstraction gives data a name without exposing how it is stored. A String is "some text"; you don't need to know how the characters sit in memory.
Procedural abstraction gives a process a name. You call Math.sqrt without knowing how it computes the root. Because callers only depend on the name, parameters, and behavior, you can rewrite a method's insides later without breaking anyone.
Designing a class
Before coding, list each class's attributes (the data it needs) and behaviors (what it does). A simple diagram works well:
| LibraryBook | |
|---|---|
| Attributes | title: String, author: String, checkedOut: boolean |
| Behaviors | checkOut(), returnBook(), isAvailable(): boolean |
Method decomposition
Break a large behavior into smaller helper methods, each with one job. This removes duplicate code and makes each piece easier to test. Parameters make a method general, so the same method can be reused with different inputs.
Methodsstatic double average(int a, int b) { return (a + b) / 2.0; }
static String letter(double avg) {
if (avg >= 90) return "A";
if (avg >= 80) return "B";
return "C";
}
static String fullReport(String name, int t1, int t2) {
double avg = average(t1, t2);
return name + ": " + avg + " (" + letter(avg) + ")";
}Using themSystem.out.println(fullReport("Ana", 88, 94));OutputAna: 91.0 (A)- Abstraction reduces complexity by hiding details.
- Data abstraction names data; procedural abstraction names a process.
- An attribute is declared in a class outside any method. An instance variable is unique to each object; a class variable is shared by all.
- Method decomposition breaks large behaviors into smaller methods and reduces duplicate code.
- Design classes (attributes and behaviors) in words or a diagram before coding.
- Repeated code is a sign a helper method should be extracted.