פרויקט קטן: המדף כמערכת מחלקותMini project: the shelf as classes
מתכננים ובונים יחד את Shelf, Book ו-Author: אחריות לכל מחלקה, ממשק נקי ובדיקה ידנית.
Designing and building Shelf, Book and Author together: one job per class, a clean interface and manual testing.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- אחריות אחת: לכל מחלקה תפקיד אחד ברור:
Authorיודעת על סופר,Bookעל ספר, ו-Shelfמנהלת אוסף. כשמשהו משתנה, ברור איפה לתקן.single responsibility: Each class has one clear job:Authorknows about an author,Bookabout a book, andShelfmanages a collection. When something changes, it's clear where to fix it. - הרכבה (has-a): עצם שמחזיק עצמים אחרים בשדות:
BookמחזיקAuthor. כמה ספרים יכולים להצביע על אותו סופר.composition (has-a): An object holding other objects in its fields:Bookholds anAuthor. Several books can point to the same author. - ממשק ציבורי: המתודות שמחלקה מציעה לעולם (
add,find,report). כל השאר פרטי, ואפשר לשנות אותו בלי לשבור את מי שמשתמש במחלקה.public interface: The methods a class offers the world (add,find,report). Everything else is private, and can change without breaking whoever uses the class. - האצלה: מתודה שמעבירה את העבודה לעצם אחר:
Shelf.size()מחזירהbooks.size().delegation: A method handing the work to another object:Shelf.size()returnsbooks.size(). - בדיקה ידנית: קוד קטן שמריץ את המחלקות ובודק תוצאות צפויות, ומדפיס PASS או FAIL. במפגש 29 נעבור ל-JUnit, שעושה את זה בצורה מסודרת.manual test: Small code that runs the classes and checks expected results, printing PASS or FAIL. In session 29 we move to JUnit, which does this properly.
02גרף של עצמיםA graph of objects
הרכבה: שני ספרים מצביעים על אותו עצם Author. בזיכרון רואים את הרשימה, שני ספרים, וחץ משותף לסופר. שינוי בסופר (למשל שם מתוקן) היה נראה דרך שני הספרים.
Composition: two books point to the same Author object. In memory you see the list, two books, and a shared arrow to the author. A change to the author (say, a corrected name) would show through both books.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Author austen = new Author("Austen");
List<Book> shelf = new ArrayList<>();
shelf.add(new Book("Emma", austen));
shelf.add(new Book("Persuasion", austen));
System.out.println(shelf.size() + " books, same author: " + (shelf.get(0).author == shelf.get(1).author));
}
}
class Author {
final String name;
Author(String name) {
this.name = name;
}
}
class Book {
final String title;
final Author author;
Book(String title, Author author) {
this.title = title;
this.author = author;
}
}2 books, same author: true
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מה קורה עכשיוWhat happens now
פלטOutput
Stack: משתנים בכל מתודהStack: each method's variables
Heap: העצמיםHeap: the objects
03המדף כמערכת: מי עושה מהThe shelf as a system: who does what
Author ו-Book הם עצמים קטנים ובלתי משתנים. Shelf מחזיקה רשימה פרטית ומציעה ממשק: add (שמסרבת לכפולים) ו-report. main רק משתמש בממשק, ולא נוגע ברשימה.
Author and Book are small immutable objects. Shelf holds a private list and offers an interface: add (which refuses duplicates) and report. main only uses the interface, never touching the list.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Shelf s = new Shelf();
Author austen = new Author("Austen");
s.add(new Book("Emma", austen, 4));
s.add(new Book("Dune", new Author("Herbert"), 5));
s.add(new Book("Persuasion", austen, 3));
s.add(new Book("Emma", austen, 4));
s.report();
}
}
class Shelf {
private final List<Book> books = new ArrayList<>();
boolean add(Book b) {
for (Book x : books) {
if (x.getTitle().equals(b.getTitle()) && x.getAuthor().equals(b.getAuthor())) {
return false;
}
}
books.add(b);
return true;
}
int size() {
return books.size();
}
void report() {
System.out.println("Shelf: " + books.size() + " books");
Map<Author, List<String>> groups = new LinkedHashMap<>();
Book best = null;
for (Book b : books) {
groups.computeIfAbsent(b.getAuthor(), k -> new ArrayList<>()).add(b.getTitle());
if (best == null || b.getRating() > best.getRating()) {
best = b;
}
}
for (Map.Entry<Author, List<String>> e : groups.entrySet()) {
System.out.println(e.getKey() + ": " + String.join(", ", e.getValue()));
}
System.out.println("Best: " + best);
}
}
class Book {
private final String title;
private final Author author;
private final int rating;
Book(String title, Author author, int rating) {
this.title = title;
this.author = author;
this.rating = rating;
}
String getTitle() {
return title;
}
Author getAuthor() {
return author;
}
int getRating() {
return rating;
}
@Override
public String toString() {
return title + " (" + rating + ")";
}
}
class Author {
private final String name;
Author(String name) {
this.name = name;
}
String getName() {
return name;
}
@Override
public boolean equals(Object o) {
return o instanceof Author a && name.equals(a.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
}Shelf: 3 books Austen: Emma, Persuasion Herbert: Dune Best: Dune (5)
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04הצעד של היום בפרויקט מדףToday's step in the Shelf project
חברו הכול: Shelf.add (בלי כפולים) ו-Shelf.report() שמדפיסה את מספר הספרים, את הכותרים לפי סופר (לפי סדר ההופעה), ואת הספר עם הדירוג הגבוה. עם Emma, Dune, Persuasion ושוב Emma, הדוח הוא:
Shelf: 3 books / Austen: Emma, Persuasion / Herbert: Dune / Best: Dune (5).
Put it all together: Shelf.add (no duplicates) and Shelf.report() printing the number of books, the titles per author (in order of appearance), and the top-rated book. With Emma, Dune, Persuasion and Emma again, the report is:
Shelf: 3 books / Austen: Emma, Persuasion / Herbert: Dune / Best: Dune (5).
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.