4 ms·
In JavaScript it is possible to define getter and setter method of an object. So this behaviour can be emulated by adding a validation in the setter method. ht
by hasperdi 6y ago
In JavaScript it is possible to define getter and setter method of an object. So this behaviour can be emulated by adding a validation in the setter method.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
In Java too, don’t know about other languages though...
- n30phyte 6y agoBasically any language with objects and methods can do this
- nradov 6y agoSure, although in languages like Java that lack operator overloading the syntax gets messy.
- Jtsummers 6y agoRight, it's emulated but not universal or built-in. Nothing in JavaScript will enforce using getters/setters, it's 100% up to programmer discipline or adding a linter (if any linter has this as an option) to ensure both the creation of the accessors and their use. The benefit of this in Ada is that it is universal, and it requires the programmer to do nothing special later on except to not turn off the runtime checks. Using that above example, this would be a runtime error: Reading : Integer := Get_A_Reading(...); -- In some run Reading gets 0 for some reason Temperature : OperatingTemp; ... Temperature := OperatingTemp'Value(Reading); -- runtime error in Ada if Reading is invalid And because OperatingTemp is a distinct type, you never even have the option to do: Temperature := Reading; -- doesn't compile Also, in most OO languages where you'd make temperature an internal, private variable you can prevent external users of the class from interacting with it incorrectly, but you can't control internal users. Consider this Java-ish example: class Thermostat { private int temperature; // should only be in [33,90] public void SetTemperature(int value) { // check range and set } public void AnotherMethod(int value) { // good discipline would be: SetTemperature(f(value)); // but it's not strictly required so this is also allowed temperature = f(value); } }
- goatinaboat 6y agoIn JavaScript it is possible to define getter and setter method of an object If a civil engineer had access to concrete but he chose to build with mashed potato instead he would be considered insane. Yet programmers with access to Ada choose JavaScript and it's considered perfectly normal.