Search code examples
javaoopinformation-hiding

OOD - Setting value once so that it cannot be changed


I am trying to understand the principle of information hiding. Suppose that I have a vehicle class with methods such as getSpeed, setSpeed, getEngine, setEngine, getVIN, setVIN, etc. To enforce info hiding, I wouldn't want to give client classes the ability to setVIN since a vehicle only has one VIN (I might be wrong). I am kind of confused on how to make this class apply info hiding. I wouldn't want to make setVIN to private. But how do you set the VIN once and not allow it to be set again afterwards? Or should I even do it that way?


Solution

  • Information hiding means you're not exposing the internal VIN field for direct modification from the outside. Having a setter does not violate the hiding principle, because you have the control over the fields modification.

    In your case, if you want to make sure the VIN is only set once, best way to do it is by setting it in the constructor, and removing the setVIN.

    BTW, although this is a general question (which is fine), if you have a specific language in mind, it might be worth mentioning. Some languages do not allow non-default constructors, for instance. In that kind of language, I'd leave the setVIN, but have it check whether the VIN has already been set when called. If it had, either ignore the call, or throw an exception.