PHP Refactoring - Lez. 3: Methods of a class
As regards the methods of a class, also applies in this case the naming convention previously exposed to the properties of the class itself. We repeat them below for convenience:
- If consists of a single word, all lowercase, for example, currency ();
- If made of many words the first letter of each, starting from the second, in uppercase, all lowercase other, for example, addElement ();
- The method name should be self explanatory.
In addition to these rules we also consider the following:
- If the method name is composed of several actions split it in many ways as there are actions;
- The length of the body of the method should not exceed 40 lines;
- The number of parameters must not exceed a maximum of 4;
Method name consists of several actions
Put the case that in writing the code of a class have a method with the following signature:
public function controllaImmagazzina ($ product)
The code of the method is as follows:
class Warehouse { public function controllaImmagazzina ($ product) { if ($ product == null) { return "product set"; } Else if (substr ($ product-> getCodice (), 0, 3) == "CAT") { return "made with old catalog"; } Else if ($ product-> getIngombro ()> 10) { return "product too cumbersome"; } $ Db = new Db ("mysql"); $ Db-> update ($ product); } ............................................. } |
As you can see, we introduced a single method that could return useful actions individually, which is why we have to split each share into a new method and if we really need to use them together we create an additional method that calls in sequence.
Following the directions just given, the above code should appear as follows:
class Warehouse { ................................................ public function check ($ product) { if ($ product == null) { return "product set"; } Else if (substr ($ product-> getCodice (), 0, 3) == "CAT") { return "made with old catalog"; } Else if ($ product-> getIngombro ()> 10) { return "product too cumbersome"; } return ""; } public function store ($ product) { $ Db = new Db ("mysql"); $ Db-> update ($ product); } public prendeInCarico ($ product) { $ Msg = $ this-> check ($ product); if ($ msg! == "") { echo $ msg; Else {} $ This-> store ($ product); echo "Taking charge successful"; } } } $ ObjProdotto = new Product (); $ Obj = new Warehouse Warehouse (); $ Msg = $ obj Warehouse -> prendeInCarico ($ objProdotto) echo $ msg; |
Rewriting the code we have made it more readable and reusable, in the case we want to control a product only within another method, or only store a product that does not require control.
We now analyze the other requirements.











Действительно классная темка.
спасибо Вам за комментарий
Nicola