Joey's Mom is making lunch: a bit of meatloaf, with mashed potatoes, peas and a couple of carrot slices.
/* @author Mom */
public class Lunch {
public var pieces = Array;
private var nutrients = 0;
public function __construct(todaysLunchPieces) {
this.pieces = ArrayCopy(todaysLunchPieces);
this.nutrients = CalculateNutrients(todaysLunchPieces);
}
public function eat() {
return nutrients;
}
public function toString() {
return this.pieces;
}
...
}
JoeysLunch = new Lunch(['meatloaf', 'mashed potatoes', 'carrots', 'peas']);
Joey asks what's for lunch. Mom answers "Meatloaf, mashed potatoes, carrots, peas". Joey doesn't like peas. He starts picking them and surreptitiously giving them to the dog under the table.
Joey's Mom sees Joey's lunch hack, and says:
"OK, Joey... you don't have to eat the peas, if you don't want to. Gimme your plate."
Next day... Joey's Mom takes all the peas, carrots and leftover mashed potatoes, and grinds them into a nutritious and healthy soup...
Joey's Mom as refactored Lunch:
/* @author Mom */
public class Lunch {
private var pieces = Array;
private var nutrients = 0;
private var description = '';
public function __construct(todaysLunchPieces, description) {
this.pieces = ArrayCopy(todaysLunchPieces);
this.nutrients = CalculateNutrients(todaysLunchPieces);
this.description = description;
}
public function eat() {
return nutrients;
}
public function toString() {
return this.description;
}
...
}
JoeysLunch = new Lunch(['meatloaf', 'mashed potatoes', 'carrots', 'peas'], 'Soup');
Now Joey can't change the internal state of his Lunch.
He is only allowed to eat() and only has access to the output of eat() and to a general description of what Lunch is. He can't remove the peas from the soup because the peas are now encapsulated.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Encapsulation:
Joey's Mom is making lunch: a bit of meatloaf, with mashed potatoes, peas and a couple of carrot slices.
Joey asks what's for lunch. Mom answers "Meatloaf, mashed potatoes, carrots, peas". Joey doesn't like peas. He starts picking them and surreptitiously giving them to the dog under the table.
Joey's Mom sees Joey's lunch hack, and says:
"OK, Joey... you don't have to eat the peas, if you don't want to. Gimme your plate."
Next day... Joey's Mom takes all the peas, carrots and leftover mashed potatoes, and grinds them into a nutritious and healthy soup...
Joey's Mom as refactored Lunch:
Now Joey can't change the internal state of his Lunch.
He is only allowed to eat() and only has access to the output of eat() and to a general description of what Lunch is. He can't remove the peas from the soup because the peas are now encapsulated.