I’m working on a project which I want to build up OO. Now I came with a function that checks or a value is valid.
private function valid(value:*, acceptedValues:Array):Boolean {
for(var i:uint = 0; i < acceptedValues.length; i++) {
if (value == acceptedValues[i]) {
return true;
}
}
return false;
}
As you can see, the function is very general and will be accessed across different classes.
Now my question is; where do I store it in a OO correct way?
Thanks in advance!
I’ll add some more input to the confusion and say this:
You won’t want a single method to validate your values. Today, just passing an array of valid values might be enough. But tomorrow, you’ll have something like an e-mail address to validate, and then you’ll need a method that validates against a RegEx. Maybe next week, you’ll need to validate against a set of values that derives from the context the value was taken from, and so on…
Using inheritance in this context, as one comment suggested, is not a good idea – you’ll tightly couple your validations to the rest of the code, and sooner or later you’ll find yourself changing a lot of things when only a simple validation call should have changed. Same goes for a utility class: You’ll find yourself using that class reference lots of times, and if you ever choose to change your validation method, you’ll have to accommodate for lots of changes in lots of places.
So, in good OO fashion, you best use an interface, let’s call it
Validatorand let all of your validating classes implement it:By the way, that’s also the ultimate reason not to use a static class: There are no static interfaces in ActionScript.
Now for some classes. Let’s start with your own validation method, based on an array of values:
…and the e-mail one:
Any time you need validation now, you can simply pass an instance of the interface to the class that needs it, for example:
If your requirements change, you can simply pass a different implementation, with out ever having to touch the code for
MyValidatingClassagain. Clean, simple, loosely coupled – and ready to be reused in the next program you write. And the one after that. And so on…