Skip to content

Instantly share code, notes, and snippets.

@felixgirault
Last active September 26, 2016 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felixgirault/1662b5e9f3244d958410 to your computer and use it in GitHub Desktop.
Save felixgirault/1662b5e9f3244d958410 to your computer and use it in GitHub Desktop.
Refactoring 1

Separation of concerns

Instead of making huge functions that makes a lot of things given a set of options, prefer splitting them into small atoms.

Bad

<?php

/** 
 *	A huge function that does processing and formatting.
 */
function getValues($arg, array $options) {
	$values = [];
	$options + [
		'implode' => false,
		'separator' => ', '
	];
	
	// processing...
	
	if ($options['implode']) {
		$values = implode($options['separator'], $values);
	}
	
	return $values;
}

/**
 *  Getting values as an array
 */
echo getValues('arg');

// => [1, 2]

/**
 *  Getting values as a string
 */
echo getValues('arg', [
	'implode' => true, 
	'separator' => ' / '
]); 

// => "1 / 2"

Better

<?php

/**
 *	A simple function for processing.
 */
function getValues($arg) {
	$values = [];
	
	// processing
	
	return $values;
}

/**
 *	A simple function for formatting.
 */
function inlineValues($arg, $separator = ', ') {
	return implode($separator, values($arg)):
}

/**
 *  Getting values as an array.
 */
getValues('arg'); 

// => [1, 2]

/**
 *  Getting values as a string.
 */
inlineValues(
	getValues('arg'), 
	' / '
); 

// => "1 / 2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment