I have the existing code provided below:
if (!$existing_records && !$has_required_field) {
return 'Skip Update, no records found';
} elseif (!$existing_records && $has_required_field) {
syslog(LOG_ERR, "some field is required but no regulatory records found. id=$id");
return 'Error some field is required but no records found';
} elseif ($client_records == $existing_records) {
syslog(LOG_INFO, "skipped, the record is unchanged. id=$id");
return 'Skip Update record, the record is unchanged';
} elseif ($unfilled_required_fields) {
syslog(LOG_ERR, " one of required fields is not filled id=$id");
$additional_message = ' but not all required field is filled';
}
//bla bla bla (logic to saving the record)
The above code contains conditions with logging and return statements but no actual logic inside them, just exactly like above.
My senior pointed out that the above code contains multiple conditions, which can make it burdensome for readers to understand each condition. As a suggestion, they provided a similar code change, shown below:
$update = determine_to_skip_update($id, $existing_records, $has_required_field, $client_records, $unfilled_required_fields);
if($update['is_skipped']){
return $update['message'];
}else {
$additional_message = $update['message'];
}
function determine_to_skip_update(int $id, array $existing_records, bool $has_required_field, array $client_records, array $unfilled_required_fields)
{
$result = ['is_skipped'=>false, 'message'=>''];
if (!$existing_records && !$has_required_field) {
$result['message'] = ' Skip Update, no records found';
} elseif (!$existing_records && $has_required_field) {
syslog(LOG_ERR, "field is required but no regulatory records found. id=$id");
$result['message'] = ' | Error some field is required but no records found';
} elseif ($client_records == $existing_records) {
syslog(LOG_INFO, "skipped, the record is unchanged. id=$id");
$result['message'] = ' | Skip Update record, the record is unchanged';
} elseif ($unfilled_required_fields) {
syslog(LOG_ERR, " one of required fields is not filled. id=$id");
$result['message'] = ' not all required field is filled';
}
return $result;
}
Is the suggested code change truly an improvement? I feel it is more maintainable, but somehow it seems a bit more complicated to understand than my initial code.
Are there any other better alternatives to improve it further? Alternatively, should I consider using a new class to handle this simple logic?