Where should I write codes for checking validity of class’ properties? (For examples: “amount” should be a positive integer, “email” should be a string with correct e-mail formatting) At the setter methods, At somewhere I use that (using try/catch), or others.
If I check validity at setter methods, it may be looked ugly (like type checking). But if I check it when using it, duplicated code may appeared when it is used many times.
(Sorry for my poor English.)
Definitely do it in the setter, if you need to do it at all.
First, the setter is probably called less often than the getters, so you’re doing less work.
Second, you catch the problem earlier.
Third, it keeps the internal state of the object consistent. Keeping out bad data means you know that your object is “right”.