teleren/devto huggingface dataset:
Our way: Enums
Tags: laravel, php, codestyle
Published: 2023-10-19 22:38:35

👉 Go to [Summary](https://dev.to/robsontenorio/or-way-laravel-code-guidelines-7p0)

> There is no wrong or right way, there is our way.
>
> -- Someone 


.
.
.


## Why not Enums?

Don't get me wrong: Enums are **useful**, but it is pretty **"hardcoded"**.

We can do it better!


## Better approach: use Models

Consider this migrations.

```php
Schema::create('status', function (Blueprint $table) {
   $table->id();
   $table->string('name');
   $table->string('description');
   $table->string('color');
}

Schema::create('orders', function (Blueprint $table) {
   $table->id();
   $table->foreignId('status_id')->constrained();
   $table->decimal('amount');
}

```

Consider this Models.

```php
class Status extends Model 
{
   public const PENDING = 1;
   public const APPROVED = 2;
   public const DONE = 3;
}

class Order extends Model 
{
   public function status() 
   {
      return $this->belongsTo(Status::class);
   }
}
```


It is done!

```php
$orders = Order::with('status')->get();
```


```html
@foreach($orders as $order)
 
   <div>
       Order: {{ $order->id }} , {{ $order->amount }} 
   
       <span class="{{ $order->status->color }}">
           {{ $order->status->name }}
       </span>

       <div class="text-sm">
           {{ $order->status->description }}
       </div>
   </div>

@endforeach

```


## Benefits

Making `status` as a Model:

- Dynamic config.
- No extra helpers or `IFs` to show status details.
- It is easy to query.
Day 11: #100DaysOfCode - Built a Balance Sheet
Tags: webdev, html, programming, css
Published: 2023-10-19 22:21:49

Hello Guys,

Another fulfilled day for me, I am pleased to share the code of my completed project with you guys, the thought of writing on this platform, gives me the motivation to keep pushing every day.

Today, I was tasked to build a balance sheet, which I did with the help of freecodecamp, they gave me the task and also assisted me in doing it. I learned some new HTML tags and CSS selectors. It was an interesting one and I'm glad to share it with you guys.

Check out my code below:

https://github.com/Duke411/Balance-Sheet
Discussion of the Week - v7
Tags: bestofdev, discuss
Published: 2023-10-19 20:50:38

In this weekly roundup, we highlight what we believe to be the most thoughtful, helpful, and/or interesting discussion over the past week! Though we are strong believers in healthy and respectful debate, we typically try to choose discussions that are positive in nature and avoid those that are overly contentious.

Any folks whose articles we feature here will be rewarded with our Discussion of the Week badge. ✨

![The Discussion of the Week badge. It includes a roll of thread inside a speech bubble. The thread is a reference to comment threads.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yvizv31dpchucxic2lxc.png)

Now that y'all understand the flow, let's go! 🏃💨

## The Discussion of the Week

Give it up for Jordan (@jordantylerburchett) for getting folks talking about their fave OSes with "[What is your favorite operating system?](https://dev.to/jordantylerburchett/what-is-your-favorite-operating-system-1048)":

{% embed https://dev.to/jordantylerburchett/what-is-your-favorite-operating-system-1048 %}

Classic question! Hey, oftentimes, it's the straightforward discussion topics like this one that really gets folks talking.

Take a look through the comments section and you'll see a whole plethora of operating systems being shouted out: MacOS Snow Leopard, Arch Linux, Alpine Linux, Ubuntu, openSUSE, Windows 10, Windows XP, AmigaOS, TempleOS... the list goes on and on. But don't just listen to me list off the OSes — where's the fun in that? Ya gotta hop into the post and check out the comments section to hear folks' reasonings and preferences for different situations.

Also, since Jordan was being humble and [only mentioned the OS they created once in the comments](https://dev.to/jordantylerburchett/comment/2a3ml), I figured I'd toot the horn for them and point y'all to [RefreshOS](http://www.egotech.company/download_refreshos_1-23.html). Gotta respect an OS creator doing their community research! ✊

## What are your picks?

The DEV Community is particularly special because of the kind, thoughtful, helpful, and entertaining discussions happening between community members. As such, we want to encourage folks to participate in discussions and reward those who are initiating or taking part in conversations across the community. After all, a community is made possible by the people interacting inside it.

There are loads of great discussions floating about in this community. This is just the one we chose to highlight. 🙂

I urge you all to share your favorite discussion of the past week below in the comments. And if you're up for it, give the author an @mention — it'll probably make 'em feel good. 💚
Sintaxe da linguagem C#
Tags: beginners, csharp, dotnet, braziliandevs
Published: 2023-10-19 20:46:04

Quando falamos em sintaxe de uma linguagem de programação, estamos nos referindo a um conjunto de regras que determinam como devemos escrever as coisas nessa linguagem.

Assim como o idioma português e inglês possuem regras gramaticais, algo parecido acontece quando estamos programando.

Para que tudo funcione adequadamente é preciso obedecer essas regras, ou seja a sintaxe da linguagem que estamos utilizando.

Programar nada mais é do que instruir o computador a fazer algo, neste sentido as linguagens são compostas por, comandos, variáveis, expressões e estruturas de controle.

Entre as diversas linguagens de programação existentes, cada uma possui sua sintaxe, algumas são semelhantes, como Java e C# por exemplo, mas no geral elas possuem muitas diferenças.

Dito isso, vamos conhecer a sintaxe da linguagem c#.

## Ponto e vírgula
É usado para marcar o final de uma instrução ou comando e separar várias instruções em um programa

```csharp
string NomeDoAluno = "leojs";
Console.WriteLine($"Olá, {NomeDoAluno}");
```

## Par de chaves {}
Delimita o corpo de uma classe ou método, ou seja o que está dentro das chaves é o que de fato vai acontecer.

```csharp
  // Classe
    public class Calculadora
    {
        // Método
        public int Somar(int a, int b)
        {
            return a + b;
        }
    }
```

## Variáveis
Para declarar variáveis em C# devemos especificar primeiro o tipo de dados e na sequencia o seu nome.

```csharp
int IdadeDoFuncionario = 20;
```
## Atribuição de valor a variáveis
Utilizamos o operador = (igual) para atribuir valor a uma variável.

```csharp
string MinhaVariavel = “valor da minha variável”;
```

## Case-Sensitive
Isso significa que o c# diferencia letras maiúsculas e minúsculas.

```csharp
string NomeDoAluno = “leojs”;
```
é diferente de

```csharp
string nomeDoAluno = “leojs”;
```
## Comentários
São usados para explicar o que o nosso código está fazendo.
Eles não afetam o funcionamento do sistema, e devem ser utilizados para ajudar outras pessoas que estão trabalhando no mesmo projeto.
No c# podemos utilizar 
// (barra-barra ou 2 barras) para comentários de uma linha
ou
/* (barra-asterisco) e */ (asterisco-barra) para comentários de varias linhas

```csharp

//Comentário de uma linha

/* 
Comentário
de 
várias
linhas
*/
```

Este foi um resumo básico e introdutório para você que começando com c#.

Espero que tenha gostado e nos vemos no próximo artigo.
Our way: Tests
Tags: laravel, php, codestyle
Published: 2023-10-19 20:43:38

👉 Go to [Summary](https://dev.to/robsontenorio/or-way-laravel-code-guidelines-7p0)

> There is no wrong or right way, there is our way.
>
> -- Someone 


.
.
.


## The coverage test trap

1. The 100% coverage **does not** mean anything by itself.
1. You have to be confident.
1. You have to be confident.
1. You have to be confident.
1. Yes, 3 times.
1. Are you really testing what matters? **Double check it.**




## Test what matters

1. Test only your business rule.
1. You don't need to test what is backed by Laravel.
1. Rule of thumb: if you mutated data you need to test it!

```php
// There is nothing to test here
// Laravel assures everything will be saved properly 

public function save(Request $request) 
{
    $data = $request->validate(...);
   
    // Don't need test, this is a CRUD
    User::create($data);

}
```


```php
// You have a business rule here to test
// You must assure that aged people need assistance, by default!


public function save(Request $request) 
{    

    $data = $request->validate(...);

    
    if ($data['age'] > 60) {
        $data['need_assistance'] = true;
    }
   
    User::create($data);

}
```


```php
// You have a business rule here to test
// After creating an user, you have insert data in another table


public function save(Request $request) 
{    

    $data = $request->validate(...);
   
    // No test here
    User::create($data);

    // But here yes! 
    Invite::create([something will be created here])

}
```

## Basics


1. Get green is not enough, **get confident**. 
1. Test **behavior** (input/output), not implementation details (mocks).
1. Test’s **name** is important.
1. Write comments before writing test (GIVEN, WHEN, THEN). 
1. Complex features can have more than one test class.

```php

// I don't give a shit how avatar was generated!
// I just wanna see the avatar !

class CreateAvatarTest extends TestCase{
    public function test_create_online_user_avatar()
    {
        // GIVEN there is a user
        $user = UserFactory::new()->create();

        // WHEN I request to make an avatar
        $response = $this->get("/avatar-maker?for={$user->id}")

        // THEN I get avatar's URL
        $response->assertJsonFragment(['url' => 'https://...']);
        
    }    
}
```
Our way: Classes and Methods
Tags: laravel, php, codestyle
Published: 2023-10-19 20:43:23

👉 Go to [Summary](https://dev.to/robsontenorio/or-way-laravel-code-guidelines-7p0)

> There is no wrong or right way, there is our way.
>
> -- Someone 

.
.
.

### Class attributes types


**WTF!?**

```php
class Customer
{
    public $points;
    public $available;
}

```


**Nice!**

```php
class Customer
{
    public int $points;
    public bool $available;
}
```


.
.
.

### Constructor property promotion


**WTF!?**

```php
class Customer
{
    public string $name;
    public string $email;
    public Date $birth_date;

    public function __construct(
        string $name, 
        string $email, 
        Date $birth_date
    ) {
        $this->name = $name;
        $this->email = $email;
        $this->birth_date = $birth_date;
    }
}
```


**Nice!**

```php
class Customer
{
    public function __construct(
        public string $name, 
        public string $email, 
        public Date $birth_date,
    ) { }
}

```

.
.
.

### Methods types


**WTF!?**

```php
public function($points, $available)
{
   ...

   return $score;
}

```


**Nice!**

```php
public function(int $points, bool $available): float
{
   ...

   return $score;
}
```

.
.
.

### Fluent sintaxe


**WTF!?**

```php
$mary = User::first();

$payment = new Payment(12.98, '2023-01-09', $mary, 4.76);
$payment->process();
```


**Nice!**

```php
$mary = User::first();

(new Payment)
   ->for($mary)
   ->amount(12.98)
   ->discount(4.78)
   ->due('2023-01-09')
   ->process();

```

.
.
.

### Encapsulate contexts


**WTF!?**

```php

public function makeAvatar(string $gender, int $age, string $hairColor)
{
   ...   
   return 'https://...';
}

$user = User::first();

makeAvatar($user->gender, $user->age, $user->hairColor);
```


**Nice!**

```php
public function makeAvatarFor(User $user): string
{
   ...
   return 'https://...';
}

$user = User::first();

makeAvatarFor($user);
```
Our way: Actions vs Services
Published: 2023-10-19 20:42:58

👉 Go to [Summary](https://dev.to/robsontenorio/or-way-laravel-code-guidelines-7p0)

> There is no wrong or right way, there is our way.
>
> -- Someone 


.
.
.

### Actions

1. It represents an **internal** app use case.
1. Each `action` must contain **one** use case.
1. Naming is important.
1. An `action` can call another `action` or `service` in complex scenarios.


```php

class MakeUserAvatarAction {

    function __construct(){ 
        // ... 
    }

    function execute(){
        // It does only 1 thing
    }    
}

``` 

### Services

1. It represents **external** integrations, commonly through **API**.
1. You can have many methods.

```php
class KeycloakService{
    
    function __construct(){ 
        // ... 
    }

    function createUser() { }

    function syncRoles() { }

    ...
}
```



## Actions vs Services

1. An `action` has **one** method, that solves **one internal**  use case.
1. An `service` can have more methods, that represents an **external** integration.

```bash
app/
    |
    |__ Actions/    
    |   |   
    |   |__ post/
    |   |   |
    |   |   |__ DeletePostAction.php
    |   |   |__ PromotePostAction.php
    |   |
    |   |__ users/
    |       |
    |       |__ MakeAvatarAction.php
    |
    |__ Services/
        |
        |__ PaymentService.php
        |__ KeycloackService.php
    
```
Our way: Naming
Tags: laravel, php, codestyle
Published: 2023-10-19 20:42:53

👉 Go to [Summary](https://dev.to/robsontenorio/or-way-laravel-code-guidelines-7p0)

> There is no wrong or right way, there is our way.
>
> -- Someone 


.
.
.

### Naming is hard #1


**WTF!?**

```php

$value = $this->getLoggedUser();

// ... after 50 lines of code you forget what `$value` is.

```


**Nice!**

```php
$user = $this->getLoggedUser();

// Ok, got it. It is `$user`
```

.
.
.


### Naming is hard #2


**WTF!?**

```php
$user1 = User::where('name', 'Mary')->first();
$user2 = User::where('name', 'Joe')->first();

// 50 lines of code here ...

if ($user1->age > $user2->age) {

    // WTF are $user1 and $user2 ?
}


```


**Nice!**

```php
$mary = User::where('name', 'Mary')->first();
$joe = User::where('name', 'Joe')->first();

... // 50 lines of code here

if ($mary->age > $joe->age) {

    // Ok, Mary is older than Joe
}
```
Our way: Constants
Tags: laravel, php, codestyle
Published: 2023-10-19 20:42:48

👉 Go to [Summary](https://dev.to/robsontenorio/or-way-laravel-code-guidelines-7p0)

> There is no wrong or right way, there is our way.
>
> -- Someone 


.
.
.


### Magic number


**WTF!?**

```php
class Costumer 
{
   public float $amount;
   
   public function something() 
   {
       // Ok, and WTF means 98.45 ?
       if ($this->amount > 98.45) {
          ...
       }

   }

}

```


**Nice!**

```php
class Costumer 
{
   public float $amount;

   public const LIMIT = 98.45
   
   public function something() 
   {
       if ($this->amount > self::LIMIT) {
          ...
       }

   }

}
```

**Nice!**

```php
// If LIMIT is used across codebase put it on `.env`
LIMIT = 98.45


public function something() 
{
    if ($this->amount > config("app.limit")) {
          ...
    }
}
```
You may need a Ref not a State.
Tags: react, webdev
Published: 2023-10-19 18:14:49



When you build React Apps, you may come to a conclusion that all mutations can be done with `useState` in functional components, but you would see that a lot of enterprise, or other seniors that would use more different ingredients, that would increase the complexity, you may wonder that all of that complexity is unneeded and things can be way simpler, just by using `useState`, this article will show you one aspect why we may need to complicate things a little.


> Based on React docs a ref is used when you want a component to “remember” some information, but you don’t want that information to trigger new renders, you can use a ref.

With that being said, we need to play around the APIs

## Use case 

Let's say that we have a UI component that would take a `state` then it makes an API call to get a value, but instead of using this value for presentation, we need to use this `value` for another `API`.

We have two options when it comes to storing the first API `value`:

1. using the `useState`: this would not make sense, since `useState` would do `mutate` + `rerender`, and we don't want a rerender.

2. using the `useRef`, this is making sense because we only want to store a value that would be used later in an API call


## to make it short:

### state => `Mutate` + Rerender
### ref => `Mutate` # only

## Is it worth it to take it into consideration?

In the micro-level, you won't feel the difference, but when application grows and with any action you're taking that into consideration, you will have the UX and performance you would like to accomplish to your users.


## Another Aspect

In using `ref`, you are mutating the value directly as if it is a normal `var` value, unlike the `useState` where you need to mutate indirectly by passing the value or its callback into the `setState` funciton, but why?

> State needs to be updated indirectly because it is not just an update to a value, it does:

1. Checks the effects that dependent on the value itself
2. Rerender job
3. Mutate the Value itself

But in Refs, when you change the `ref.current` property, React does not re-render your component. React is not aware of when you change it because a ref is a plain JavaScript object.


## Code:


{% replit https://replit.com/@IbrahimShamma99/Ref-state-app#src/App.tsx %}
Our way: Models, Migrations, Factories and Seeders.
Tags: laravel, php, codestyle
Published: 2023-10-19 20:42:24

👉 Go to [Summary](https://dev.to/robsontenorio/or-way-laravel-code-guidelines-7p0)

> There is no wrong or right way, there is our way.
>
> -- Someone 


.
.
.


### Models

1. It should represent **primarily** ORM mapping.
1. Must have **not** contain use cases, see [actions](https://dev.to/robsontenorio/our-way-actions-vs-services-1kda).
1. It can have small helper methods, computed properties, or `scopes` to make it easy to query data.

```php
class User extends Model{

    // Relationships
    function country(): BelongsTo { ... }

    // Helper method
    function isAdmin(): bool { ... }    

    // Query scope
    function scopeActive(Builder $query) { ... }

    // Computed attribute
    function getShortNameAttribute(): string { ... }
}
```


## Migrations

1. Use normalized modeling.
1. Stick with convention `xxxx_id`  for `FKs`.
1. Comment edge case columns.
1. Remember`indexes` (performance).

```php

Schema::create('users', function (Blueprint $table) {
   $table->id();
   $table->foreignId('country_id')->constrained();
   $table->string('name')->index();
   $table->string('cpf')->comment('Brazilian social number');
   
});
```

## Seeders

1. Must contain all default values to bootstrap app first time.
1. Mostly it represents domain business value that should be mapped into model constants.
1. Remember seeders can run many times, so put a `IF`.

```php
class PaymentTypesSeeder extends Seeder
{   
    public function run()
    {
        // Avoid run twice
        if (PaymentType::count()) {
            return;
        }
        
        // Insert initial data when app bootstraps
        PaymentType::insert([...])
    }
}
```


## Factories    


1. If it matters use a pre-seeded value. 
1. If it does not matter call a factory.

```php
class UserFactory extends Factory
{
   public function definition()
   {       
      return [            
            // It is a well known value, should be one from seeder 
            'prefered_payment_type_id' => PaymentType::inRandomOrder()->first(),
            // does not matter who is the parent user
            'parent_id' => User::factory(), 
            'name' => $this->faker->name(),
             // ....
        ];
    }

```
Our way: Let the code breath
Tags: laravel, php, codestyle
Published: 2023-10-19 20:42:08

👉 Go to [Summary](https://dev.to/robsontenorio/or-way-laravel-code-guidelines-7p0)

> There is no wrong or right way, there is our way.
>
> -- Someone 

.
.
.

### Separate contexts


**WTF!?**

```php
$post = Helper::sanitize($post);
$post = Helper::validation($post);
$post->notify($user);
$comments = Helper::crazy('hello');
$comments->gosh();
```


**Nice!**

```php
$post = Helper::sanitize($post);
$post = Helper::validation($post);
$post->notify($user);

$comments = Helper::crazy('hello');
$comments->gosh();
```

.
.
.

### Please, line breaks!


**WTF!?**

```php
$hello = 'Mary';
if(...) {

}
foreach(...) {

}
if(...) {

}
$go = 'Paul';

```


**Nice!**

```php
$hello = 'Mary'; 
// <---here
if (...) {

}

foreach(...) {

}

if(...) {

}
// <---here
$go = 'Paul';
```

.
.
.

### Cleaner `IF`


**WTF!?**

```php
if (User::where('name', 'Joe')->first() && 
   Product::where('name', 'xbox')->count() == 0) {
   throw new Exception("I'm sorry Joe. We don't have Xbox");
}

```


**Nice!**

```php
$isJoe = User::where('name', 'Joe')->first();
$hasXbox = Product::where('name', 'xbox')->count() == 0;

if ($isJoe && ! $hasXbox) {
   throw new Exception("I'm sorry Joe. We don't have Xbox");
}
```


.
.
.

### Early return


**WTF!?**

```php
// You can buy a toy ONLY:
//  - If you have money 
//  - If it is weekend
//  - If it is NOT snowing

if($haveMoney) {
   if(! $isWeekend) {
       throw new Exception("It is not weekend!")
   } else {
      if($isSnowing) {
          throw new Exception("It is snowing!")
      } else {
          return 'Yes! I can buy!';
      }
   }
} else {
   throw new Exception("I don't have money!")
}

// Oh my... who did this!?
```


**Nice!**

```php
// No need to read rules, I can read the code.

if (! $haveMoney) {
   throw new Exception("I don't have money!")   
}

if (! $isWeekend) {
    throw new Exception("It is not weekend!")
}

if ($isSnowing) {
    throw new Exception("It is snowing!")
} 

return 'Yes! I can buy!';
```
Our way: Laravel Code Guidelines
Tags: laravel, php, codestyle
Published: 2023-10-19 20:39:44


> There is no wrong or right way, there is our way.
>
> -- Someone 



## Summary

- [Naming](https://dev.to/robsontenorio/our-way-naming-3556)
- [Constants](https://dev.to/robsontenorio/our-way-constants-2i75)
- [Classes and Methods](https://dev.to/robsontenorio/our-way-classes-and-methods-1e14)
- [Let the code breath](https://dev.to/robsontenorio/our-way-let-the-code-breath-1a77)
- [Eloquent](https://dev.to/robsontenorio/our-rules-eloquent-4im7)
- [Actions vs Services](https://dev.to/robsontenorio/our-way-actions-vs-services-1kda)
- [Models, Migrations, Factories and Seeders](https://dev.to/robsontenorio/our-way-models-migrations-factories-and-seeders-n1d)
- [Tests](https://dev.to/robsontenorio/our-way-tests-4jd6)
- [Enums](https://dev.to/robsontenorio/our-way-enums-3hkl)