A brief show-and-tell about one pattern to use for refactoring. The LLM produced this, and I’m explaining it. I generally let the LLM pick names, coding style, and how to chop up the code.
My big goals:
- Reduce code file size, so it more easily fits in small contexts.
- Define more boundaries, inputs, and outputs, so you can reason more easily about the code, and find duplicated code, opportunities to create a library, and maybe eliminate code.
- Make the code more testable, and make tests.
Refactoring Long Functions
I remembered lots of long scripts with long, complicated logic. One of the challenges was figuring out where one part ended, and another started.
I asked it to refactor the code into a “flow”, using a small framework to run the parts. I should have said “pipeline”, because it created a class called Pipeline.
It works like unix pipes, sort of.
The upper part creates the pipeline. The lower part creates an array, and passes it through the pipeline. more explanation below.
public static function create(Request $request, bool $isComment): \Api\Response
{
$payload = \LAACTIVE\Pipeline::of(
PublishFlowStages::restoreRawPost(...),
PublishFlowStages::normalizeFileCount(...),
PublishFlowStages::resolveParent(...),
PublishFlowStages::validateCsrf(...),
Stage::on('post', PublishFlowStages::defaultLanguage(...), 'response'),
PublishFlowStages::checkForm(...),
PublishFlowStages::receiveUploads(...),
Stage::derive('fields', ['post', 'files', 'received'], PublishFlowStages::storyFieldsFrom(...), 'response'),
PublishFlowStages::createStory(...),
PublishFlowStages::createComment(...),
PublishFlowStages::createAttachments(...),
PublishFlowStages::regenerateListings(...),
)->process([
'request' => $request,
'files' => $request->files(),
'isComment' => $isComment,
'post' => [],
'topId' => 0,
'received' => null,
'fields' => null,
'id' => 0,
'parentConstant' => '',
'response' => null,
]);
return $payload['response'] ?? \Api\Response::redirect(
'/publish2/success?id=' . rawurlencode((string) $payload['parentConstant'])
. '&type=' . ($payload['isComment'] ? 'comment' : 'story')
);
}The … is new in PHP8.1, and it turns the static method into a closure (an anonymous function). So Pipeline::of() takes a list of closures, and then passes the array into the first one, takes the output of it, and passes it to the second one, and so on. The output is a transformation of the input, usually.
(It reminds me a little of PowerShell as much as Unix pipes.)
Functional Programming Style
Stage::derive() is a helper to make the functions more general-purpose. Notice that the array has specific key names. Each function needs to use these key names. That violates the principle of encapsulation — but for this app, we generally tolerate it.
I suspected there might be some functions that could be reused. So I asked for a feature to make the function more generic, and to specify which keys to use. Thaura created bind(), and then derive(). Here are their signatures and comments:
/**
* The one stage body: halt when the payload already carries the
* short-circuit state; otherwise gather the read keys' values in
* order, call the filter with them, and write the returned values
* back to the write keys in order. Every binding above is this
* with different key lists.
*
* @param list<string> $read
* @param list<string> $write
*/
private static function bind(array $read, array $write, callable $filter, string $haltKey): callable
{
...
/**
* Bind a pure derivation: the filter receives the values of the
* source keys, in the order given, and returns the value written
* to the destination key. The source keys are read-only. A single
* source key is the one-key-into-another-key map.
*/
public static function derive(string $to, array $from, callable $filter, string $haltKey = 'errors'): callable
{
return self::bind($from, [$to], static fn (...$args): array => [$filter(...$args)], $haltKey);
}derive() is a little like array_reduce(), where you take multiple array elements, run a function on them, and then produce a single output. The difference here is you specify the input keys and output key.
Stage::derive('fields', ['post', 'files', 'received'], PublishFlowStages::storyFieldsFrom(...), 'response'),The output key is ‘fields’, and the input keys are [‘post’, ‘files’, ‘received’].
In English, the code means “derive ‘fields’ from the inputs ‘post’, ‘files,’ and ‘received’, using the function storyFieldsFrom(), and the pass-through output is ‘response’”.
This is a nice technique to manipulate arrays. You can see there’s some potential code smell.
The ‘response’ is the $haltKey.
Normally, it’s called ‘error’, and holds a return value. If it indicates an error, the normal thing is to pass the array through, unchanged. This causes the error to reach the end of the pipeline, and be treated as an error.
In this case, the haltKey is ‘response’, and can hold the PSR-7-like Response object. If you have a Response, it gets passed down to the end of the pipeline, and can become the output, a redirect, or an error.
Conclusions
This helped to clean up the code a bit, however, I saw some problems immediately.
I didn’t like restoreRawPost() being called at the top, when a regular function could have done the same thing by initializing the ‘post’ key, in fewer lines, with less ceremony.
It also obscures some of the logic differentiating between stories, comments, and attachments. So it wasn’t a complete win.
That said, breaking pipeline into parts, and applying logic outside of the pipeline, seems straightforward.
I was hoping for more code reuse, but even a small win is a victory. The Pipeline and Stage classes are nice.
The lines of code didn’t really decrease, because lots of comments were added, but it was easy to reduce the code size, per file, by moving functions into a helper class.