This program demonstrates how to use getters and setters in a JavaScript object to manage a restaurant menu. It allows setting a meal and its price, ensures that the inputs are valid, and provides a formatted output for the day’s special. The approach showcases encapsulation and basic data validation within an object.
-
Private Properties Convention
- The properties
_mealand_priceare prefixed with an underscore to indicate they are intended as private, following common JavaScript conventions.
- The properties
-
Setters with Validation
- The
mealsetter ensures that only non-empty strings can be assigned as a meal. - The
pricesetter ensures that a price is only set after a meal has been specified, and that the price is a positive number. - Warnings are logged if validation fails, helping to prevent incorrect data entry.
- The
-
Getter for Derived Output
- The
todaysSpecialgetter returns a formatted string describing the special of the day, only if both meal and price have been set correctly. - If either value is missing or invalid, it provides a helpful message indicating the issue.
- The
-
Encapsulation and Data Integrity
- By using getters and setters, the object controls how its internal properties are modified and accessed, ensuring data consistency.
-
Readable Output
- The final message clearly communicates the daily special in a user-friendly format.
Today's Special is noodles for $21!
-
Setting a price before a meal: Set a meal first before setting the price
-
Setting an empty meal: Meal must be a non-empty string
-
Setting a non-positive price: Price must be a positive number
This programme illustrates how to use object-oriented techniques in JavaScript to manage and validate data. It highlights the benefits of getters and setters, encapsulation, and data integrity, while providing clear, user-friendly feedback through console messages. It is a practical example of controlling access to an object’s properties while producing dynamic outputs based on valid inputs.