Defaults of Defaults?

Today’s snippet isn’t so much scary code as it is unnecessary and redundant. One of the things developer’s learn over time is how to be efficient and how to make things simpler, but this is not an example of simple or efficient.

WordPress has a function called wp_parse_args() that can be used for defining default variables (as an array) that will be used in the case some available options aren’t passed. It is a tremendously useful function that I find myself using a lot.

This little snippet has used wp_parse_args() to parse defaults within an array that has already been parsed for defaults, oh and then it parses args a third time too:

static function normalize_field( $field )
{
	$field = wp_parse_args( $field, array(
		'js_options' => array(),
	) );

	$field['js_options'] = wp_parse_args( $field['js_options'], array(
		'allowClear' => true,
		'width' => 'resolve',
		'placeholder' => "Select a Value"
	) );

	// Default query arguments for get_terms() function
	$default_args = array(
		'hide_empty' => false,
	);

	if ( ! isset( $field['options']['args'] ) )
		$field['options']['args'] = $default_args;
	else
		$field['options']['args'] = wp_parse_args( $field['options']['args'], $default_args );

	/*
	 * some code removed
	 */
	 
	return $field;
}

Why has this made the cut for crappy code submissions? Simply because it can be dramatically simplified. This is also one of those cases where the simplified (in terms of syntax) is also much easier to read and to follow.

This does the same thing:

static function normalize_field( $field )
{
	$field = wp_parse_args( $field, array(
		'js_options'      => array(
			'allowClear'  => true,
			'width'       => 'resolve',
			'placeholder' => 'Select a Value'
		),
		'options'         => array(
			'args'        => array(
				'hide_empty' => false,
			)
		),
	) );

	/*
	 * some code removed
	 */

	return $field;
}

Submitted by Franz Josef Kaiser.

2 thoughts on “Defaults of Defaults?

  1. Well, technically, it doesn’t do the same thing. In the first version, I can pass array( 'js_options' => array( 'allowClear' => false ) ) to the function and still get the defaults for width and placeholder. This is because wp_parse_args doesn’t run recursively.

Leave a comment