I have a function whose job is to look through a string that is a post's content and find certain pieces:
public static function findInsidePostContent( $post = Null )
{
//post_content comes from a WP_Post object.
$post_blocks = \parse_blocks( $post->post_content );
//Look inside, do some things.
}
The function has an absolute truth that we can always rely on: it only and solely works with a WP_Post
object.
But, naturally, since the parameter is Null
, there is a clear contradiction here, so, let's try to solve it by adding a specific line right at the start of the function:
$post = Utils::getPostObject( $post ); if( \is_wp_error( $post ) ) return $post;
Great, that function is always supposed to return a WP_Post
object, unless something wrong happened.
But what we just did was heavily couple two seemingly unconnected pieces of code and, usually, that's bad. We also hid a dependency. But what if we can predict that in all the cases, you will always work with a WP_Post
object? You'll always have to work resolve that WP_Post
object somewhere before:
$post = Utils::getPostObject( 21 );
Utils::findInsidePostContent( '', [], $post );
This "call path" will never, ever change.
Wouldn't the coupling be justified?
findInsidePostContent
must always receive aWP_Post
object, why does the$post
parameter have aNull
default value?findInsidePostContent
by auto-resolving thatWP_Post
object inside.