I'm wondering if it's a good idea to make verifications in getters and setters, or elsewhere in the code.
This might surprise you be when it comes to optimizations and speeding up the code, I think you should not make verifications in getters and setters, but in the code where you're updating your files or database. Am I wrong?
It depends.
Generally, code should fail fast. If the value can be set by multiple points in the code and you validate only on after retrieving the value, the bug appears to be in the code that does the update. If the setters validate the input, you know what code is trying to set invalid values.
@Terrapin, re:
Properties have other advantages over fields. They're a more explicit contract, they're serialized, they can be debugged later, they're a nice place for extension through inheritance. The clunkier syntax is an accidental complexity -- .net 3.5 for example overcomes this.
A common (and flawed) practice is to start with public fields, and turn them into properties later, on an 'as needed' basis. This breaks your contract with anyone who consumes your class, so it's best to start with properties.
From the perspective of having the most maintainable code, I think you should do as much validation as you can in the setter of a property. This way you won't be caching or otherwise dealing with invalid data.
After all, this is what properties are meant for. If all you have is a bunch of properties like...
... they might as well be fields
You might wanna check out Domain Driven Design, by Eric Evans. DDD has this notion of a Specification:
I think failing fast is one thing, the other is where to keep the logic for validation. The domain is the right place to keep the logic and I think a Specification Object or a validate method on your Domain objects would be a good place.
Validation should be captured separately from getters or setters in a validation method. That way if the validation needs to be reused across multiple components, it is available.
When the setter is called, such a validation service should be utilized to sanitize input into the object. That way you know all information stored in an object is valid at all times.
You don't need any kind of validation for the getter, because information on the object is already trusted to be valid.
Don't save your validation until a database update!! It is better to fail fast.
I like to implement IDataErrorInfo and put my validation logic in its Error and this[columnName] properties. That way if you want to check programmatically whether there's an error you can simply test either of those properties in code, or you can hand the validation off to the data binding in Web Forms, Windows Forms or WPF.
WPF's "ValidatesOnDataError" Binding property makes this particularly easy.