נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
Encapsulation, getters, setters ו-immutabilityEncapsulation, getters, setters & immutability
מפגש 15: private ו-public, שמירה על מצב תקין, getters ו-setters במידה, ועצמים שלא משתנים.Session 15: private and public, keeping state valid, getters and setters in moderation, and objects that never change.
private ו-public, שמירה על מצב תקין, getters ו-setters במידה, ועצמים שלא משתנים. בסוף המפגש מוסיפים צעד לפרויקט המלווה.private and public, keeping state valid, getters and setters in moderation, and objects that never change. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- setter ששומר על הכלליםA setter that guards the rules
- מבחוץ אי אפשר לגעתYou can't touch it from outside
- עצם שלא משתנהAn object that never changes
- טעויות נפוצותCommon mistakes
- פרויקט מדףShelf project
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגשThis session's terms
- כימוס: העצם שומר על הנתונים שלו בעצמו:encapsulation: The object guards its own data:
- private: שדה או מתודה שנגישים רק מתוך המחלקה עצמה.private: A field or method reachable only inside its own class.
- getter ו-setter:
getRating() מחזירה ערך, ו-setRating(int) משנה אותו (עם בדיקה).getter and setter: getRating() returns a value, and setRating(int) changes it (with a check). - אינווריאנט: כלל שתמיד נכון על העצם, למשל "הדירוג בין 1 ל-5".invariant: A rule that's always true about the object, e.g.
- עצם בלתי משתנה: עצם שלא משתנה אחרי שנוצר:immutable object: An object that never changes after it's made:
- העתקה מגינה: מחזירים עותק (או תצוגה לקריאה בלבד) של אוסף פנימי, כדי שאיש לא ישנה אותו מבחוץ:defensive copy: Return a copy (or a read-only view) of an inner collection, so nobody changes it from outside:
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושאTopic 2
setter ששומר על הכלליםA setter that guards the rules
setter ששומר על הכלליםA setter that guards the rules
rating הוא private, ולכן הדרך היחידה לשנות אותו היא setRating, שזורקת חריגה על ערך לא חוקי.rating is private, so the only way to change it is setRating, which throws on an illegal value.- הכלל "בין 1 ל-5" לא נשבר אף פעם.The rule "between 1 and 5" is never broken.
- ל-
title אין setter בכלל: הוא final.title has no setter at all: it's final.
rating הוא private, ולכן הדרך היחידה לשנות אותו היא setRating, שזורקת חריגה על ערך לא חוקי. הכלל "בין 1 ל-5" לא נשבר אף פעם. ל-title אין setter בכלל: הוא final.rating is private, so the only way to change it is setRating, which throws on an illegal value. The rule "between 1 and 5" is never broken. title has no setter at all: it's final.נושאTopic 3
מבחוץ אי אפשר לגעתYou can't touch it from outside
מבחוץ אי אפשר לגעתYou can't touch it from outside
- ניסיון לכתוב לשדה private ממחלקה אחרת נעצר כבר בקומפילציה.Trying to write a private field from another class is stopped at compile time.
ניסיון לכתוב לשדה private ממחלקה אחרת נעצר כבר בקומפילציה.Trying to write a private field from another class is stopped at compile time.נושאTopic 4
עצם שלא משתנהAn object that never changes
עצם שלא משתנהAn object that never changes
- בעצם בלתי משתנה "הזזה" יוצרת נקודה חדשה.In an immutable object a "move" creates a new point.
- בזיכרון רואים שתי נקודות:
p נשארה (1, 2).In memory you see two points: p stayed (1, 2). final class אומר שאי אפשר לרשת ממנה ולשנות את ההתנהגות.final class means nobody can extend it and change the behaviour.
בעצם בלתי משתנה "הזזה" יוצרת נקודה חדשה. בזיכרון רואים שתי נקודות: p נשארה (1, 2). final class אומר שאי אפשר לרשת ממנה ולשנות את ההתנהגות.In an immutable object a "move" creates a new point. In memory you see two points: p stayed (1, 2). final class means nobody can extend it and change the behaviour.נושאTopic 5
טעויות נפוצותCommon mistakes
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
balance has private access in Account:balance has private access in Account:
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.נושאTopic 6
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- מדף, צעד 15: דירוג תמיד בין 1 ל-5Shelf, step 15: a rating always 1–5
ל-Book יש private final String title ו-private int rating = 3, getters, ו-setRating שזורקת Rating must be 1-5, got 7. קבעו 4, נסו 7 (הדפיסו את ההודעה), והדפיסו Dune 4.Book has private final String title and private int rating = 3, getters, and setRating throwing Rating must be 1-5, got 7. Set 4, try 7 (print the message), and print Dune 4.כימוס: העצם שומר על הנתונים שלו בעצמו:encapsulation: The object guards its own data:
המונחים של המפגשThis session's termsprivate: שדה או מתודה שנגישים רק מתוך המחלקה עצמה.private: A field or method reachable only inside its own class.
המונחים של המפגשThis session's termsgetter ו-setter: getRating() מחזירה ערך, ו-setRating(int) משנה אותו (עם בדיקה).getter and setter: getRating() returns a value, and setRating(int) changes it (with a check).
המונחים של המפגשThis session's termsאינווריאנט: כלל שתמיד נכון על העצם, למשל "הדירוג בין 1 ל-5".invariant: A rule that's always true about the object, e.g.
המונחים של המפגשThis session's termsעצם בלתי משתנה: עצם שלא משתנה אחרי שנוצר:immutable object: An object that never changes after it's made:
המונחים של המפגשThis session's termsהעתקה מגינה: מחזירים עותק (או תצוגה לקריאה בלבד) של אוסף פנימי, כדי שאיש לא ישנה אותו מבחוץ:defensive copy: Return a copy (or a read-only view) of an inner collection, so nobody changes it from outside:
המונחים של המפגשThis session's termsrating הוא private, ולכן הדרך היחידה לשנות אותו היא setRating, שזורקת חריגה על ערך לא חוקי.rating is private, so the only way to change it is setRating, which throws on an illegal value.
setter ששומר על הכלליםA setter that guards the rulesהכלל "בין 1 ל-5" לא נשבר אף פעם.The rule "between 1 and 5" is never broken.
setter ששומר על הכלליםA setter that guards the rulesל-title אין setter בכלל: הוא final.title has no setter at all: it's final.
setter ששומר על הכלליםA setter that guards the rulesניסיון לכתוב לשדה private ממחלקה אחרת נעצר כבר בקומפילציה.Trying to write a private field from another class is stopped at compile time.
מבחוץ אי אפשר לגעתYou can't touch it from outsideבזיכרון רואים שתי נקודות: p נשארה (1, 2).In memory you see two points: p stayed (1, 2).
עצם שלא משתנהAn object that never changesfinal class אומר שאי אפשר לרשת ממנה ולשנות את ההתנהגות.final class means nobody can extend it and change the behaviour.
עצם שלא משתנהAn object that never changesbalance has private access in Account:balance has private access in Account:
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java saysמדף, צעד 15: דירוג תמיד בין 1 ל-5Shelf, step 15: a rating always 1–5
הצעד של היום בפרויקט מדףToday's step in the Shelf projectמי יכול לקרוא שדה private int rating של Book?Who can read a private int rating field of Book?
- כל מחלקה באותו קובץAny class in the same file
- רק קוד בתוך
BookOnly code inside Book - רק
mainOnly main - אף אחדNobody
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.רק קוד בתוך BookOnly code inside Book
נכון.Right.מה הדרך הנכונה לשנות נקודה בלתי משתנה?What's the right way to change an immutable point?
p.x = 5;p.x = 5;p.setX(5);p.setX(5);p = p.moveBy(1, 0);p = p.moveBy(1, 0);- אי אפשר בכללIt's impossible
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.p = p.moveBy(1, 0);p = p.moveBy(1, 0);
נכון: מקבלים עצם חדש ושמים אותו במשתנה.Right: you get a new object and store it in the variable.ל-setRating(int r) יש בדיקה. מה עושים כש-r הוא 9?setRating(int r) has a check. What happens when r is 9?
- שומרים 9Store 9
- שומרים 5 בשקטQuietly store 5
- זורקים
IllegalArgumentException עם הודעה ברורהThrow an IllegalArgumentException with a clear message - מדפיסים אזהרה וממשיכיםPrint a warning and go on
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.זורקים IllegalArgumentException עם הודעה ברורהThrow an IllegalArgumentException with a clear message
נכון: מי שקרא יודע מיד מה לא בסדר.Right: the caller knows at once what's wrong.מדחוםA thermometer
- מחלקה
Thermometer עם private double celsius, getCelsius(), getFahrenheit() (מחושב, בלי שדה), ו-setCelsius שזורקת IllegalArgumentException מתחת ל-273.15-.A class Thermometer with private double celsius, getCelsius(), getFahrenheit() (computed, no field), and setCelsius throwing IllegalArgumentException below -273.15.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: מיליונר בקיצור דרךBug hunter: a shortcut millionaire
- main מנסה לשים מיליון ישירות ביתרה, ו-javac עוצר.main tries to put a million straight into the balance, and javac stops it.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.חשבון מוגןA protected account
Account עם private final String owner (מהבנאי), private int balance, ו:Account with private final String owner (from the constructor), private int balance, and:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.נקודה שלא זזהA point that doesn't move
- כתבו את
Point הבלתי משתנה מהתזכורת (שדות private final, x(), y(), moveBy).Write the immutable Point from the refresher (private final fields, x(), y(), moveBy).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.טווח חוקיA valid range
- מחלקה בלתי משתנה
Range(int min, int max) שהבנאי שלה זורק min 5 > max 1 כשהסדר הפוך.An immutable class Range(int min, int max) whose constructor throws min 5 > max 1 when the order is reversed.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מדף, צעד 15: דירוג תמיד בין 1 ל-5Shelf, step 15: a rating always 1–5
- ל-
Book יש private final String title ו-private int rating = 3, getters, ו-setRating שזורקת Rating must be 1-5, got 7.Book has private final String title and private int rating = 3, getters, and setRating throwing Rating must be 1-5, got 7.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.כסף בלי שגיאות עיגולMoney without rounding errors
- מחלקה בלתי משתנה
Money ששומרת long cents (ולא double, שמעגל).An immutable class Money storing long cents (not a double, which rounds).
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.רשימה שאי אפשר לשנות מבחוץA list nobody changes from outside
Playlist מחזיקה private final List<String> songs.Playlist holds private final List<String> songs.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.מה למדנוWhat we learned
- כימוס: העצם שומר על הנתונים שלו בעצמו:encapsulation: The object guards its own data:
rating הוא private, ולכן הדרך היחידה לשנות אותו היא setRating, שזורקת חריגה על ערך לא חוקי.rating is private, so the only way to change it is setRating, which throws on an illegal value.- ניסיון לכתוב לשדה private ממחלקה אחרת נעצר כבר בקומפילציה.Trying to write a private field from another class is stopped at compile time.
- בעצם בלתי משתנה "הזזה" יוצרת נקודה חדשה.In an immutable object a "move" creates a new point.
balance has private access in Account:balance has private access in Account:- מדף, צעד 15: דירוג תמיד בין 1 ל-5Shelf, step 15: a rating always 1–5
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.