Is it a good practice to make some data processing/validation in getters and setters? In wikipedia here there are 2 examples:
Are these good examples or it is better to avoid it? If it is better to avoid it, how can I implement these 2 examples above in a better way?
UPDATE: Please, Do not take examples with date and etc serious. It is just an example, of course it can be stupid.
Real example which I had.
I have an external third party system and I have to make integration. This external system expect from me some data as class with getters and setters. I have to pass 2 fields there, id (something like 09df723987cd7 (let's say GUID)) and formattedID something like "objecttype/09df723987cd7". I cannot change this external system.
I want to implement it like
getId() {
return id
}
getFormattedId() {
return objectType + "/" + id;
}
objectType is another field in this class.
My Question: is it OK, or there is some more elegant way to implement it?
The examples you provided are not good fit, at least not in the form and with the names you mentioned.
I'll try with some better examples:
Setters
You might want to use them for validation mostly. As an example setDate(Date d)
could check the data is in a certain range, e.g. not more than 20 years into the future etc. (depends on your requirements).
Getters
If those contain more than simple logic they probably represent virtual properties, i.e. properties that don't have an underlying field but are calculated on the fly.
Let's take getAmount()
for example: there might not be any field amount
or the amount might be stored in cents (or smaller) for some reason (e.g. no precision issues). Thus getAmount()
might look like this:
public double getAmount() {
return amountInCents / 100.0;
}
Note that the name getAmount()
might be misleading though, so you might be better off using a name like getAmountInUSD()
or similar.
General
Using getters and setters in Java is adviceable in most cases since you'd be able to the following (list not complete):