abstract classes and validation methods
Introductory OOP question for you:
Situation: I want an abstract class with a public setter and abstract validator, since each child will validate that property in a unique way.
Code:
abstract class Parent {
public function setName($name) {
if (validateName($name)) {
$this->_name = $name;
} else {
// error msg
}
}
abstract public function validateName($name);
}
class Child extends Parent {
public function validateName($name) {
// ensure name gits this child's requirements
}
}
Question: is this a "legal" 开发者_如何学Cdesign approach? I figured since the setName
method will be the same for every child class, it should be a public method in the parent class, but the validator should be abstract to force child classes to implement it.
I'm just sketching this out on paper conceptually...
Yes, that's a valid approach, although your syntax in imperfect:
if (validateName($name)) {
should be this:
if ($this->validateName($name)) {
But if this is the scope of the architecture, why not just define abstract setName()
that validates and sets it? Like this:
interface Parent {
public function setName($name);
}
class Child implements Parent {
public function setName($name) {
if (/* $name is valid */) {
$this->_name = $name;
} else {
// error message
}
}
}
Of course I use an interface here, because there's no code in Parent.
But please realize, this depends on how you're program is structured. I'd have to see at least a diagram of the program's architecture to say definitely either way.
精彩评论