נבנה על ידיBuilt by Ariel Yohimovich

חזרה למפגשBack
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.

מה נעשה היום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
נושאTopic 1

מונחיםTerms

המונחים של המפגש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:
נושא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.
נושא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.
נושא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.
נושאTopic 5

טעויות נפוצותCommon mistakes

טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

  • balance has private access in Account:balance has private access in Account:
נושאTopic 6

פרויקט מדףShelf project

הצעד של היום בפרויקט מדףToday's step in the Shelf project

  • מדף, צעד 15: דירוג תמיד בין 1 ל-5Shelf, step 15: a rating always 1–5

כימוס: העצם שומר על הנתונים שלו בעצמו: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:

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.

ניסיון לכתוב לשדה 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.

בזיכרון רואים שתי נקודות: 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.

balance has private access in Account:balance has private access in Account:

מדף, צעד 15: דירוג תמיד בין 1 ל-5Shelf, step 15: a rating always 1–5

מי יכול לקרוא שדה 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

רק קוד בתוך BookOnly code inside Book

מה הדרך הנכונה לשנות נקודה בלתי משתנה?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

p = p.moveBy(1, 0);p = p.moveBy(1, 0);

ל-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

זורקים IllegalArgumentException עם הודעה ברורהThrow an IllegalArgumentException with a clear message

מדחום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.

צייד באגים: מיליונר בקיצור דרךBug hunter: a shortcut millionaire

  • main מנסה לשים מיליון ישירות ביתרה, ו-javac עוצר.main tries to put a million straight into the balance, and javac stops it.

חשבון מוגןA protected account

  • Account עם private final String owner (מהבנאי), private int balance, ו:Account with private final String owner (from the constructor), private int balance, and:

נקודה שלא זזה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).

טווח חוקי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.

מדף, צעד 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.

כסף בלי שגיאות עיגולMoney without rounding errors

  • מחלקה בלתי משתנה Money ששומרת long cents (ולא double, שמעגל).An immutable class Money storing long cents (not a double, which rounds).

רשימה שאי אפשר לשנות מבחוץA list nobody changes from outside

  • Playlist מחזיקה private final List<String> songs.Playlist holds private final List<String> songs.

מה למדנו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

עכשיו לתרגולNow, practice

6 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית6 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

נבנה על ידיBuilt by Ariel Yohimovich