1

I'm looking at optimizing, formatting and styling a few largish files at the moment. Most of it seems to not be optimally written (probably airing on the side of caution rather than whats best).

One of the things I've specifically been trying to do is reduce cyclomatic complexity where many functions use if() statements that are redundant. More Booleans = more complexity, and while I'm sure it's not terrible (optimizations probably only milliseconds better) I've been seeing a lot of stuff like this:

if (isset($variable) && !is_null($variable) && is_object($variable) && isset($variable->property))

Now I'm fairly sure for example, that:

!is_null($variable) && is_object($variable)

can be shortened to:

is_object($variable)

because if $variable is null, then the is_object method will return false anyway - however I'm not 100% this is the case every time. Generally I just wanted to put see what people recommend in terms of lowering the complexity of statements like this, or any other rules for Boolean logic which could lower complexity.

Max Colledge
  • 287
  • 1
  • 3
  • 9
  • Are you optimising for performance or code simplicity - or both? – Tom Jul 20 '15 at 17:21
  • I'm not fully aware of your code, but you're checking a lot of things that the `$variable` must implement. Easy way out, at least in my opinion, is having a function that accepts an interface that `$variable` is an instance of -> `public function someFunction(RespectMyInterface $variable)`. If anything that's not the given interface is passed - it won't work, therefore the checks you mentioned are redundant won't be needed at all. The function signature contract will only be fulfilled if the variable passed implements the interface in the example. Then again, I might be completely wrong. – N.B. Jul 20 '15 at 19:56
  • Tom - Ideally both, but just any general optimisations for making boolean logic less bulky or more concise is the general aim – Max Colledge Jul 21 '15 at 09:17
  • N.B. - While this is a super neat suggestion, unfortunately its not necessarily going to always be the same checks that I'm making. Often it would be a relatively specific check for each object, and making an interface for each one seems more time consuming than beneficial (and potentially confusing for future devs who find the code!) – Max Colledge Jul 21 '15 at 09:20

0 Answers0