Let's say class Foo requires injection of class Bar. Should I typehint the method parameter because I know what Bar needs to be, or should I not typehint it, in case Bar changes in the future?
class Foo {
public function __construct( Bar $bar ) {
// do something
}
}
or:
class Foo {
public function __construct( $bar ) {
// do something
// the wrong class could be passed in here, but I'm also future-proof in case
// another class provides similar functionality to Bar
}
}
Presumably, the "best" answer is to make Bar implement an inte开发者_如何学运维rface, but I really feel silly creating an interface that will only have one extension class for the foreseeable future. What is the best practice?
The simple, easy solution: typehint to Bar
for now, and create an interface and change the typehint later. If you use refactoring practices properly and design your code well, the change should have no effect later on.
精彩评论