Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 12 | class Comment_Meta_Container extends Container { |
||
| 13 | protected $comment_id; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * Create a new container |
||
| 17 | * |
||
| 18 | * @param string $unique_id Unique id of the container |
||
| 19 | * @param string $title title of the container |
||
| 20 | * @param string $type Type of the container |
||
| 21 | **/ |
||
| 22 | View Code Duplication | public function __construct( $unique_id, $title, $type ) { |
|
| 29 | |||
| 30 | /** |
||
| 31 | * Perform instance initialization |
||
| 32 | **/ |
||
| 33 | public function init() { |
||
| 41 | |||
| 42 | /** |
||
| 43 | * Checks whether the current request is valid |
||
| 44 | * |
||
| 45 | * @return bool |
||
| 46 | **/ |
||
| 47 | public function is_valid_save() { |
||
| 50 | |||
| 51 | /** |
||
| 52 | * Perform save operation after successful is_valid_save() check. |
||
| 53 | * The call is propagated to all fields in the container. |
||
| 54 | * |
||
| 55 | * @param int $comment_id ID of the comment against which save() is ran |
||
| 56 | **/ |
||
| 57 | public function save( $comment_id ) { |
||
| 69 | |||
| 70 | /** |
||
| 71 | * Check container attachment rules against current page request (in admin) |
||
| 72 | * |
||
| 73 | * @return bool |
||
| 74 | **/ |
||
| 75 | public function is_valid_attach_for_request() { |
||
| 80 | |||
| 81 | /** |
||
| 82 | * Check container attachment rules against object id |
||
| 83 | * |
||
| 84 | * @return bool |
||
| 85 | **/ |
||
| 86 | public function is_valid_attach_for_object( $object_id = null ) { |
||
| 89 | |||
| 90 | /** |
||
| 91 | * Add meta box to the comment |
||
| 92 | **/ |
||
| 93 | public function attach() { |
||
| 103 | |||
| 104 | /** |
||
| 105 | * Output the container markup |
||
| 106 | **/ |
||
| 107 | public function render() { |
||
| 110 | |||
| 111 | /** |
||
| 112 | * Set the comment ID the container will operate with. |
||
| 113 | * |
||
| 114 | * @param int $comment_id |
||
| 115 | **/ |
||
| 116 | public function set_comment_id( $comment_id ) { |
||
| 120 | } |
||
| 121 |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: