Development

Hard-coded parts and create constants (how to use them)

Hardcoded Parts

Constants

Have you ever met something like this:

We have a few code smells here. I’ve talked about a few of these in previous articles, which are nested if statements and the intent of these conditions is unclear. What else should be done to improve it? 
Answer is: avoid the hard-coded definitions of values, simply use CONST objects instead. Let’s start.

Firstly, create const classes. We should have two – 1st for admin roles and 2nd for order states.

Secondly, add functions into the classes, which will replace the conditions parts that use these values.
Instead of: “If ($user->roles === “ADMIN”), create something like:

For “if ($state in[“CREATED”, “INPROGRESS”, “CANCELED”, “WAITING”]”, which is checking if the provided state  is in the allowed states, therefore we can add a function like:

Another unclear condition is “if ( in_array($order->state, [“NEW INPROGRESS”]) )”. I’m sure you don’t know what is the intention of it, but since i’m the creator of this code, i know that I simply wanted to check if order, in which is in state, is allowed to be changed.

Lets add method in the class

As a result, both classes will look like that:

It’s time for the initial code reflector with using new classes and other knowing rules. The result of that will be:

I think it looks much better now, but there’s still one thing to improve. Lets consider – who is the owner of the order state data? I think it’s the $order object, because the rule is, that the owner of the data should decide if it can be changed and is able to change it. Therefore we should move it to the “owner” class.

Finally

The code should look like that:

Subsequent articles

  • Static Factory Methods aka Named Constructors: Read more…
  • Improving conditions clauses – few small things with hudge impact: Read more…