Criando 在 Teste Técnico 印象中的例外

2025-05-24

Criando 在 Teste Técnico 印象中的例外

例外情况始终是关于东方物体和软件的常见问题!

目录

1. 序言

如果你想了解一个研究计划,请永远记住我会犯“错误”,或者与其他关系有关,但如果你想了解更多的频率,你可能会遇到一些错误或例外情况。 amigas do que inimigas。如果您想使用自己感兴趣的项目,请务必注意这一点。

没有 meu caso、acabava usando 或 trecho throw new Exception()pra 字面上的 qualquer coisa 和我在代码库中的便利,por conta de uma Exception espalhada no meio de tantas outras。没有任何问题,我们在观察时间时,请确认。

节奏很快,FODAS 的主要功能是让我能够出色地实现例外、原则Factory Pattern。正确的方法是让我感到惊奇simples e elegantes,因为这是错误的。

希望您能以最优雅的方式在 2 公里的路程中避免失误。

2. O que gostariamos de EVITAR

Vamos começar dando um pouco de contexto para esse教程:想象一下如何开发RPG系统并准确地创造出简单的专业角色。

src
├── Item
│   └── Item.php
└── Player
    ├── Inventory.php
    └── Player.php
Enter fullscreen mode Exit fullscreen mode

Dentro desse contexto,想象一下你的角色装备了某个物品。 Porém, é lógico que nos vamos colocar algumas regras de validação com suas devidas Exceptions.

namespace DanielHe4rt\Player;

use DanielHe4rt\Item\Item;

class Player {

    public function __construct(
        public string $username,
        public int $level,
        protected Inventory $inventory,
    ) {

    }

    public function equipItem(Item $item): void
    {

        if ($this->inventory->hasItem($item)) {
            throw new \Exception(
                'Você não possui o item "' . $item->name . '". '
            );
        }

        if ($item->minLevel > $this->level) {
            throw new \Exception(
                'Você não pode equipar o item ' . $item->name . 'pois o nível minimo é ' . $item->minLevel 
            );
        }

        $this->setupItem($item);
    }


    private function setupItem(Item $item): void 
    {
        // faça coisas iradas
    }
}
Enter fullscreen mode Exit fullscreen mode

游戏中存在两种验证方式,针对不同的客户。 E pasmem: isso funciona (num cenário que o código tá completinho) e cumpre o papel de validação... MASSSSS, depois que eu aprendi que em testes de emprego o que é visto é a QUALIDADE DA ENTREGA e não a agilidade que foi criado, meu mundo deu uma leve mudada para entender como transar coisas que parecem “estranhas e feias” em coisas “simples e优雅”。

Nesse caso, eu gostaria muito de evitar duas coisas:

  • 例外情况;
  • 例外情况包括在当地。

不存在错误,作为例外情况,如果继续存在,请尽快遵守法律。

3. 修改 1:Criando 例外情况

src
├── Item
│   └── Item.php
└── Player
    ├── Exceptions
    │   ├── PlayerException.php
    │   └── PlayerInventoryException.php
    ├── Inventory.php
    └── Player.php
Enter fullscreen mode Exit fullscreen mode

Exception贝莱扎,在我们的第一届“定制”会议上,我们讨论了新类别的例外情况。世界上没有任何事情,但我们已经了解了各种不同的情况下的法律和含义。

namespace DanielHe4rt\Player; 

class PlayerException extends \Exception
{}

class PlayerInventoryException extends \Exception
{}
Enter fullscreen mode Exit fullscreen mode

重新调整简单的功能equipItem(),将异常情况重新定位为新的异常情况。


namespace DanielHe4rt\Player;

use DanielHe4rt\Item\Item;
use DanielHe4rt\Player\PlayerException;
use DanielHe4rt\Player\PlayerInventoryException;

class Player {

    public function __construct(
        public string $username,
        public int $level,
        protected Inventory $inventory,
    ) {

    }

    public function equipItem(Item $item): void
    {
        if (!$this->inventory->hasItem($item)) {
            throw new PlayerInventoryException(
                'Você não possui o item "' . $item->name . '". '
            );
        }

        if ($item->minLevel > $this->level) {
            throw new PlayerException(
                'Você não pode equipar o item ' . $item->name . 'pois o nível minimo é ' . $item->minLevel 
            );
        }

        $this->setupItem($item);
    }


    private function setupItem(Item $item): void 
    {
        // faça coisas iradas
    }
}
Enter fullscreen mode Exit fullscreen mode

作为新的异常,Agora sabemos exatamente do que se trata e mainmente onde buscar na nossa codebase quando essa Exception estourar.字面上的CTRL + ALT + F意思“PlayerInventoryException”。便利生活,DevOps 的生活可以通过 NewRelic/DataDog 来生活并实现。

Porém algo ainda me incomoda muito... Por quê essas mensagens gigantes estão no meio da regra de negócio? Misturar pt-br com en desse jeito é triste d+ pra mim desculpa amigos!! Vamos aprender um jeito de por isso debaixo dos panos, porém antes precisamos passar num tópico de Design Pattern chamado Factory!

4.设计模式:工厂模式

您可以通过设计模式来解决这个问题,并最终解决这个问题。 Mas caso não,eu te explico!

“设计模式可以解决一般问题。” - Alguém por ai

解决通用问题的想法,是一种解决问题的软件设计原则,可以解决问题,并且可以快速解决问题。设计模式的分类如下:

  • Padrões Comportamentais;
  • 克里亚西奥奈斯神父;
  • 埃斯特鲁图赖斯牧师。

如果没有网站https://refactoring.guru,我们建议您尝试探索文档和自动解析器。好吧,mas vamos focar nele,o tal do Criacional de Fábrica(或工厂方法)

一个想法是通过不同类别的实例来创建对象,从字面意思上构建算法实例,以便重新获得简单的算法功能。没有Models::make()任何程序存在数百年的历史,因此无法Exception::create()获得ApiQualquer::factory()有关各个类别的构建方法。

示例 API 客户端、构建器模块化精确套管针和隔离 PORÉM 可能会快速制造或最终实现目标:


class GithubClient {

    public function __construct(string $clientId, string $clientSecret) 
    {
        $this->client = new Client([
            'clientId' => $clientId,
            'clientSecret' => $clientSecret,
        ]);
    }

    public static function make(): self
    {
        return new self(
            env('github.client_id'),
            env('github.client_secret'),
        );
    }

    public function getUserByUsername(string $username = 'danielhe4rt'): array 
    {
        // faça uma chamada pro github..
    }
}

// Chamando sem fabricar o objeto

$client = (new GithubClient('client-id-foda', 'client-secret-foda'))
    ->getUserByUsername('danielhe4rt');

// Chamando usando o Factory 

$client = GithubClient::make()
    ->getUserByUsername('danielhe4rt');

Enter fullscreen mode Exit fullscreen mode

我们将按照以下说明制作所有参数。任何“制造/工厂”或任何你想要解决的问题,都是一种广泛依赖的方法,因为它是一个问题。

从形式上来说,工厂模式的合法性是非常重要的,因为它是一种基本的功能。 Agora voltemos para nossas 例外!

5. Refatoração 2:Refinando 作为例外

展示,aprendemos um pouquinho sobre o 工厂,agora vamos aplicar。

Criaremos um 工厂的方法是我们的​​例外情况,它是一种感觉,并且是一个上下文。 Pois é, nada de usar “制造” 或 “创造” nesses 时刻。例外情况是关于我们的历史的最小内容,或者是关于未来的发展和未来的发展。

重新调整后的PlayerInventoryException效果、效果和结果:

class PlayerInventoryException extends \Exception 
{
    public static function itemNotFound(string $itemName): self
    {
        $message = sprintf('Você não possui o item "%s".', $itemName);
        return new self(
            message: $message,
            code: 403 // Forbidden
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

在我们的工厂里,我们可以看到美好的休闲时光,并以异常信息作为信息。

public function equipItem(Item $item): void
{

    if (!$this->inventory->hasItem($item)) {
        throw PlayerInventoryException::itemNotFound($item->name);
    }

    if ($item->minLevel > $this->level) {
        throw new PlayerException(
            'Você não pode equipar o item ' . $item->name . 'pois o nível minimo é ' . $item->minLevel 
        );
    }

    $this->setupItem($item);
}
Enter fullscreen mode Exit fullscreen mode

Agora refatorando a próxima, temos a mesma ideia de trocar a PlayerException.

class PlayerException extends \Exception 
{
    public static function lowLevelForThisEquipment(string $itemName, int $itemLevel): self
    {

        $message = sprintf(
            'Você não pode equipar o item %s pois o nível minimo é %s.',
            $itemName,
            $itemLevel
        );

        return new self(
            message: $message,
            code: 403 // Forbidden
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

e agora nossa equipItem()tá ó,uma maravilha!

public function equipItem(Item $item): void
{
    if (!$this->inventory->hasItem($item)) {
        throw PlayerInventoryException::itemNotFound($item->name);
    }

    if ($item->minLevel > $this->level) {
        throw PlayerException::lowLevelForThisEquipment($item->name, $item->minLevel);
    }

    $this->setupItem($item);
}
Enter fullscreen mode Exit fullscreen mode

Tá uma maravilha?塔。 Mas ainda tem algo me incomodando... Por quê passar os Tipos primitivos sendo que essas 例外 estão se “comunicando” com 类?

Ficaria bem mais limpo se passarmos a referenceência do object inteiro pra Exception e lá dentro ela resolve o que precisa usar.最后,我想告诉你未来的未来,我不想再为你做任何事了,不是吗?

namespace DanielHe4rt\Player;

use DanielHe4rt\Item\Item;

class PlayerException extends \Exception 
{
    public static function lowLevelForThisEquipment(Item $item): self
    {

        $message = sprintf(
            'Você não pode equipar o item %s pois o nível minimo é %s.',
            $item->name,
            $item->minLevel
        );

        return new self(
            message: $message,
            code: 403 // Forbidden
        );
    }
}

class PlayerInventoryException extends \Exception 
{
    public static function itemNotFound(Item $item): self
    {

        $message = sprintf('Você não possui o item "%s".', $item);

        return new self(
            message: $message,
            code: 403 // Forbidden
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

最终的结果是,我们的方法如此迷人,往往会出现例外情况,并且会在企业经营过程中反馈反馈信息。

namespace DanielHe4rt\Player;

use DanielHe4rt\Item\Item;
use DanielHe4rt\Player\PlayerException;
use DanielHe4rt\Player\PlayerInventoryException;

class Player {

    public function __construct(
        public string $username,
        public int $level,
        protected Inventory $inventory,
    ) {

    }

    public function equipItem(Item $item): void
    {
        if (!$this->inventory->hasItem($item)) {
            throw PlayerInventoryException::itemNotFound($item);
        }

        if ($item->minLevel > $this->level) {
            throw PlayerException::lowLevelForThisEquipment($item);
        }

        $this->setupItem($item);
    }


    private function setupItem(Item $item): void 
    {
        // faça coisas iradas
    }
}
Enter fullscreen mode Exit fullscreen mode

6. 结论

例外情况是激光雷达的“chatas”。最后,如果您在客户方面遇到了错误,那么我们将不遗余力地为您提供最准确的建议,并为您提供有关魅力的补充和帮助,并您提供积极的帮助和积极的态度。

Espero que vocês tenham curtido o conteúdo e não esqueça de me seguir nas redes sociais!

参考:格式化异常消息

文章来源:https://dev.to/he4rt/criando-exceptions-para-impressionar-no-teste-tecnico-2nie
PREV
开源软件 Livre:conheça 和 entenda de uma vez por todas o que cada umsignifica
NEXT
Compartilhando seu conhecimento com o mundo!科莫·埃斯克里弗·阿蒂戈斯