How to solve the code duplication problem?

Asked

Viewed 77 times

5

In Wordpress I am creating a custom screen in the administration area.

That’s why I’m extending my class customProductsListTable the class WP_List_Table:

class customProductsListTable extends WP_List_Table

I have another class for another custom screen that extends the same class WP_List_Table:

class customReviewsListTable extends WP_List_Table

The problem is that in the classes customProductsListTable and customReviewsListTable created some methods that are common and that do not exist in the class WP_List_Table.

So we have the following scenario:

  • The classes customReviewsListTable and customProductsListTable do overwrite of some class methods WP_List_Table, but the code behaves differently in each class.

  • The classes customReviewsListTable and customProductsListTable have new methods but with the same behavior.

Clearly I am duplicating code in both classes, but we cannot in PHP inherit more than one class.

How to solve the code duplication problem?

1 answer

4


Create an intermediate class, something like that:

class CustomListTable extends WP_List_Table

In it overwrite the methods you want and create new ones that will be common. Then inherit like this:

class CustomProductsListTable extends CustomListTable

class CustomReviewsListTable extends CustomListTable

I put in the Github for future reference.

In these classes you can overwrite and create new methods that are specific to them.

I kept your nomenclature, but note that it diverges from the one used in Wordpress. This is confusing. Although it is confusing for all of PHP.

I have the impression that this intermediate class may be abstract, but without seeing the whole context.

  • Thank you. Yes, the intermediate class can be abstract with the abstract methods in the cases that have different behavior and the others that have equal behavior, will not be signed as abstract. I don’t want the middle class to be instantiated either.

  • another way to solve would be to create one or more interfaces for these methods.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.