Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Created January 19, 2023 10:27
Show Gist options
  • Save webdevilopers/2c37b7343974774affb2cba2ba1caf56 to your computer and use it in GitHub Desktop.
Save webdevilopers/2c37b7343974774affb2cba2ba1caf56 to your computer and use it in GitHub Desktop.
Early Return Developer vs. OpenAI ChatGTP vs. PHPStorm PHP Inspections
<?php declare(strict_types=1);
final class DocumentFormatValidator
{
private function validatePrefix(Filename $filename, DocumentFormat $format): void
{
$detectedPrefix = $this->detectPrefix($filename);
if ($detectedPrefix === null) {
if (!$format->requiresPrefix()) {
return;
}
throw new DomainException('Missing prefix.');
}
if (!$format->requiresPrefix()) {
throw new DomainException('Non required prefix detected.');
}
if (in_array($detectedPrefix->toString(), $format->prefixes, true)) {
return;
}
throw new DomainException('Invalid prefix.');
}
}
<?php declare(strict_types=1);
final class DocumentFormatValidator
{
private function validatePrefix(Filename $filename, DocumentFormat $format): void
{
$detectedPrefix = $this->detectPrefix($filename);
if ($format->requiresPrefix()) {
if ($detectedPrefix === null) {
throw new DomainException('Missing prefix.');
}
if (!in_array($detectedPrefix->toString(), $format->prefixes, true)) {
throw new DomainException('Invalid prefix.');
}
} else if ($detectedPrefix !== null) {
throw new DomainException('Non required prefix detected.');
}
}
}
<?php declare(strict_types=1);
final class DocumentFormatValidator
{
private function validatePrefix(Filename $filename, DocumentFormat $format): void
{
$detectedPrefix = $this->detectPrefix($filename);
if ($format->requiresPrefix()) {
if ($detectedPrefix === null) {
throw new DomainException('Missing prefix.');
}
if (!in_array($detectedPrefix->toString(), $format->prefixes, true)) {
throw new DomainException('Invalid prefix.');
}
} else {
if ($detectedPrefix !== null) {
throw new DomainException('Non required prefix detected.');
}
}
}
@webdevilopers
Copy link
Author

webdevilopers commented Jan 19, 2023

Original:

Originally my version looked similar to the others. But since I prefer "early returns" I removed any else-construct.

developer

OpenAI:

This version of the code avoids unnecessary checks and throws exceptions only when necessary.

openai

PHPStorm PHP Inspection:

ide-ea

ide

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment