teleren/devto huggingface dataset:
Don't Use Service Classes with Static Methods
Tags: laravel, php, oop, webdev
Published: 2022-03-28 16:22:42

A service class in the context of this post is a class used to encapsulate domain logic. When creating an endpoint to create a new blog post, for example, many will opt to put the core logic of creating that new post inside of a service class method rather than operate directly in the controller.

The reason developers choose to encapsulate that logic is usually to be able to reuse it in other places within the project. For instance, when creating a blog post may be possible through their front-end implementation or their API.

# Why static methods are used in the first place

It's hard to determine exactly why this pattern is used, but my guess would be this: It resembles a clean design (like a Facade pattern could provide) without the overhead. Instead of writing out the boilerplate to turn the class into a usable facade, it's easier to drop a `static` keyword in front of the method. And just like a facade, it looks clean. You don't have to do any ugly dependency injection.

```php
class PostService
{
  public static function create()
  {
    // do some creating...
  }
}

class PostController
{
  public function store(Request $request)
  {
    // validate and whatever else...
    PostService::create($request->all());

    return back();
  }
}
```
Doesn't that look awesome?

# Why you shouldn't do it

Testing.

You are going to have a hell of a time trying to test anything that utilizes these service classes. Let's say you're testing a controller method that uses a service. That service does a lot of complex logic behind the scenes. You'll have to arrange everything that the service needs to execute without failure from within your test. All just to test this other unrelated thing.

There are ways (sorta) to [mock a static method](https://docs.mockery.io/en/latest/reference/public_static_properties.html#mocking-public-static-methods), but is not recommended, which is even stated directly in the Mockery documentation.

The moral of the story is, save yourself a lot of headaches down the road and stick with good, old-fashioned dependency injection. With Laravel, using the container to auto-resolve all of your dependencies is a cinch anyway.

# The easiest alternative

```php
class PostController
{
  public function store(Request $request, PostService $service)
  {
    // validate and whatever else...
    $service->create($request->all());

    return back();
  }
}
```

Let's be honest, the code block above isn't much worse, especially when you think about how much easier testing will be.

# How to test

Laravel leverages the container to auto-resolve your dependencies, so they've provided [a way to hijack that and sub in a mocked version](https://laravel.com/docs/9.x/mocking#mocking-objects).

```php
$this->mock(PostService::class, function (MockInterface $mock) {
    $mock->shouldReceive('create')->once();
});
```
Write Tests Early and Often
Tags: testing, beginners, tdd, codequality
Published: 2022-03-28 16:20:05

I have a project that I've worked with on and off for the last few years. Writing tests was not a part of my work flow when I started it back then. As the project has grown to have more functionality, I have found that the tests I didn't write are causing my development speed and my trust in the code to plummet.

Writing tests is important, but writing them early is even more important. A young project is not going to have established or well-defined code. You will want to change the way it works and you'll end up breaking things. The only way you're going to know that is with tests. I can't tell you how many times I've decided I didn't like an implementation and changed it. Every time I've done it, some part of the functionality was left unaccounted for and broken. 

You end up in a circular situation where, with every change you make, you're forced to click around your project and make sure everything still works. With tests, all you have to do is trigger the test suite. That makes for the best argument against those that believe writing tests is a waste of time. When compared to all of the manual testing that must be done, tests improve your development speed immensely, and that speed increases non-linearly as the project grows.

When you're building some little to-do app, of course testing feels like a pointless endeavor. The bigger the project gets, the more you're going to resist going back and writing all those tests. The problem is, eventually, the drain of having to check your project after every change will outweigh your desire to make those changes, and you will end up abandoning the project.

Once you're working on something significant, you'll see the benefit testing provides. I've worked at companies with large projects that both did no testing at all and encouraged writing tests. 

The non-testing company's code-base was always riddled with bugs. We had a full-time QA person, and boy were they busy. Every bug fix had a chance to introduce new bugs, so we were constantly forced to spend a ton of time clicking around to make sure things worked (but the bugs always showed up). Our developers all had to have a mental checklist of things to watch out for that would constantly cause bugs. Imagine we just wrote that checklist out with tests. We would no longer have the cognitive load of keeping those things in mind. We'd never have to worry about that bug cropping up. It would just be tested to ensure correctness.

In contrast, at my current company that encourages writing tests, the user-base is much larger by, I'd guess, at least 100x and we see bugs much less regularly. And when we fix bugs, we add a test and never see it again.

So write those tests early, and write them often!
Advice for Aspiring Developers
Tags: beginners, webdev, career, codenewbie
Published: 2022-03-28 16:19:37

I recently received a message from someone looking to become a developer, who wanted general advice on the road ahead with no degree. This is what I said.

***

Everyone is going to have a different path, so I suggest getting your mind right and the rest will follow.

1. Don't give up, this stuff is hard. But if you keep coming back you'll make it far.
2. Once you find a direction, stick with it and don't let other people shake you. For example, I am a back-end dev working in Laravel/PHP and if I listened to people who said PHP was a stupid, dead language I'd have switched to another framework and put myself further back relearning things.
3. Don't get suck in tutorial hell. It's easy to watch videos all day and have nothing stick. Make yourself build things and learn to fail. When you hit a wall, do research to find out how to do it, then keep going. Practice is the fastest way to really learn.
4. Focus on the fundamentals. Read books about Clean Code, SOLID principles, refactoring, OOP/functional programming, design patterns, architecture, etc. Those are the skills that transfer beyond this new framework or that hot new library. The concepts transfer everywhere and will allow you to learn new skills much much faster because you'll see the patterns underneath.
Shakeeb's Algorithm to reverse a number. Crisp and very logical. Dont memorise 😂😂😁
Published: 2022-03-28 15:54:42

`#include<bits/stdc++.h>
using namespace std;
int reverse(int n)
{
	//Count numbers first
	int count = 0;
	int orig = n;
	while(n>0)
	{
		count++;
		n=n/10;
	}
	//REVERSE USING PLACE VALUES;
	//Input: 345
	//3 becomes unit, 4 becomes 10 and 5 becomes 100th
	//Basically reversing the place value;
	int pv = count;
	int rem =0;
	int newPlaceValue;
	int rev= 0;
	while(pv>=0 && orig>=0)
	{	
		rem = orig%10; 
		rev = rev  + (rem*pow(10, pv));
		orig=orig/10;
		pv--;	
	}
	return rev=rev/10;

}
int main()
{
	int n;
	cin>>n;
	int answer = reverse(n);
	cout << answer;
}

> Okay, so you might be wondering why this big chunk of code just to reverse a number... why not the regular conservative way to do it... Basically I want to show that mugging up and writting/copying things is a waste of time..Enuf of the pep talk lets get into the solution description......
You need to have knowledge about place values of a given number....if you see all you are doing is reversing the place values backwards therefore do so.......
`
#66 Days of Data
Tags: python, datascience, 100daysofcode, ankitgupta
Published: 2022-03-28 15:46:15

## **Learning Python**  👨‍💻

D 43 of #66daysofdata 📈

Today I have learnt Exception Handling & File Handling in Python

Checkout 👉 [My #66 Days of Data timeline on Github](https://github.com/mrankitgupta/66DaysOfData)

Say me Hi! 
I'll be glad to connect on 
👇

**Twitter** @ [Mr_AnkitGupta01](https://twitter.com/Mr_AnkitGupta01)

**Github** @ [MrAnkitGupta](https://github.com/mrankitgupta)

**LinkedIn** @ [Mr_AnkitGupta](https://www.linkedin.com/in/mrankitgupta)

**Socials** @ [Ankit Gupta](http://ankitgupta.bio.link)
Hide WooCommerce Cart Icon When Empty
Published: 2022-03-28 15:43:33

**Step #1** – Find your cart icon CSS class name
In order to make the cart icon appear or not appear you will need to track down the name of the CSS class that is assigned to it.

Please take a look at the short video below to show you exactly how to find the CSS class name of your shopping cart icon.

**Step #2** – Place CSS class name in a custom function
Now that we have the name of our CSS element for our shopping cart icon we are going to want to create a custom function and use this name to trigger the option of being visible or being invisible.

Your CSS class name will be placed inside the snippet below where it says CLASS_NAME.

```
// Hide WooCommerce Cart Icon When Empty
add_action( 'wp_footer', function() {
    if ( WC()->cart->is_empty() ) {
        echo '<style type="text/css">CLASS_NAME{ display: none; }</style>';
    }
});
```

**Step #3** – Place custom function into your site
We now have everything that we need in order to implement this custom functionality into our website.

You will take the custom function that you created in Step #2 and place this inside of the functions.php file of your active theme.
#Day 9 of Solving 450 Questions[30/450]
Tags: programming
Published: 2022-03-28 15:37:10

📅Day 9 : March 28,2022
Problems solved today :
[Triplet Sum in Array ](https://practice.geeksforgeeks.org/problems/triplet-sum-in-array-1587115621/1)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eappqnymlvwni66m2x1u.png)


[second-highest-salary](https://leetcode.com/problems/second-highest-salary/submissions/)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l5y05mpyxqsz8vm7z5ag.png)
C++ dagi maxsus belgilar
Tags: beginners, cpp, programming, uzbek
Published: 2022-03-28 15:36:29

##`\n`
\n - backslash n
Ushbu belgi `string` ichiga yoziladi. Bu belgi bor joydan yangi qatorga yoziladi. Masalan  ⬇️
```cpp
    cout << "Salom\n dunyo." << endl;

Salom
  dunyo.
```
##`\t`
**Backslash tab**
Bu ham `string` ichida yoziladi va  bu bo'lgan joy tab tugmasi bosilgada chiqadigan masofada joy bo'sh qoldirib ketiladi. ⬇️
```cpp
cout << "olma\tbehi\tanor"

olma   behi   anor
```
##`\b` 
**backslash b**
```cpp
cout << "olma\b bexi" << endl;

olm bexi
```
Bu *`\b`* oldingi 1 dona belgini o'chirib yuboradi.
What is Postman?!
Tags: softwareengineering, frontend, bac, javascript
Published: 2022-03-28 15:36:05

Hello beautiful people! It's me again coming to tell you about Postman. So first, what is postman? Well, Postman is an application where an user can send requests to a JSON server (a Node package that turns a JSON file on your computer into data storage) and find out if the request works or not.

For example, let's say you are building a project using Ruby and JavaScript. Ruby being backend and JavaScript being frontend of course. You are going to want to send data that you create in the backend, to the frontend. You know, so that you can see what is happening on your web application. Postman is a fantastic way to do that!

Let's say in our backend we create a todo list that has multiple users. You may want to perform a few CRUD (Create Read Update, Delete) operations. To start you want to download postman from their website.

https://www.postman.com/downloads/

Make sure you set it up properly. Just so you know, you don't have to sign in, you are able to say 'skip and go to the app'. Then you just click 'Get Started', 'Create a request'. After that you figure out which CRUD operation you want to use, make sure the URL that you are typing matches with the one you created in the backend, and voila you have successfully used postman!

Now you are able to 'get', 'patch', 'post', 'delete', etc., through postman. Go crazy, really play around with it until you fully understand what it does. I will also recommend you pay close attention to what you type in the 'Body' portion. You want to make sure that the object you type has the exact parameters you laid out in the backend. Otherwise you are really going to confuse yourself. 

I hope this helps, remember, don't be afraid to try multiple requests, after all this is your project and you want to make sure you know everything inside and out.
Easiest way to truncate a string in Groovy
Tags: groovy
Published: 2022-03-28 15:25:27

---
title: Easiest way to truncate a string in Groovy
published: true
description: 
tags: #groovy
//cover_image: https://direct_url_to_image.jpg
---
The fastest way to truncate a string to a certain length:

`assert "abcdefghij".take(5) == "abcde"`
Get Started Part 2: Take control of your multiple boards.
Tags: devops, vscode, python, luos
Published: 2022-03-28 15:25:14

Following our last part that allows you to set up your dev environment, you will control your boards in several lines. 
We will power a led and define a blinking state/rapidity quickly.

{% embed https://www.youtube.com/embed/KKrzyR-Op9c %}

P.S: no cat was used during this experiment 🙀
Active Record manipulation (column, table. Belongs)
Published: 2022-03-28 15:24:23

This blog will guide you on how to create a table change column name, change the datatype, link tables, and rake utilization. First, make sure the rake gem is linked through the Gemfile, once ready use bundle install to get the library to your code. Gemfile is produced with the terminal command bundle init. In javascript, they packages instead of gems, and instead of bundle, you will use npm.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8k35sdyo3vnztda3w7na.png)


Use rake -T this will produce all the tools available thanks to the tool library. Next to each command, there will be a little description of what they preform, below I highlighted the most frequently used,


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c1rnso9lbwaawwvblfzm.png)

From here you can create tables, seed information, and drop tables. Below is an example of how to create a table and name it. If you look closely EVA is named WRONG, the right wat would have been """""create_eva"""""".


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b71a8ub2f1wk9tnnuxla.png)

The below example is what occurred if create migration is run without a name. Also when creating a table be sure to make the table plural and the links singler. The user of reference to link the table to eva and keanu table. Below picture show example of WRONG USE, observe the double """s""", be careful it is a common mistake especially with code editor suggestions. the CORRECT WAY TO WRITE IT """ references :class_name""""".


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ib5y7hpwnltgisiqk6s.png)


Here is a list of helpful migration tools

 create_table :table creation
rename_column :table, :orginal_name, :new_name 
change_column :table_name, :column_name, :new_datatype( string, boolean, number)


Next, the data table needs to be filled with information. When a table is filled with information the linking can be helpful and beneficial. For this, we need the seeds.rb file to seed our data.

Producing it is very simple to use the format below as a framework.

ClassName.create(name_key: desrice_valuie)

If a key is not filled with a value it will have nil with searched in the database. Once the table is populated with data the next step will be to link them if there is the desired association. The adam table has a reference to both Keanu and Eva, so the adam table will be linked to those two through the class association and vice versa.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/63y1nuwmvgtn84wt3xf2.png)
Easiest way to find out if today is a weekday in Groovy
Tags: groovy
Published: 2022-03-28 15:22:26

---
title: Easiest way to find out if today is a weekday in Groovy
published: true
description: 
tags: #groovy
//cover_image: https://direct_url_to_image.jpg
---
This is a very easy way to find out if today is a weekday:

`['Mon', 'Tue', 'Wed', 'Thu', 'Fri'].contains(new Date().format("E"))`
Slow and steady
Published: 2022-03-28 15:11:26

This past Friday we released version 2.9 of [Telescope](https://github.com/Seneca-CDOT/telescope) and we are now closer and closer to the big final 3.0 release.

## Breaking things down

I received feedback on my [PR](https://github.com/Seneca-CDOT/telescope/pull/3237) from the previous week about sharing a single Nginx container for all static sites. The restructuring of the directories made the PR too big with hundreds of file changes (although most just renaming). To make it easier for reviewer (and for myself!) I decided to split the [work](https://github.com/Seneca-CDOT/telescope/issues/2993) into multiple PRs. I started with moving the `src/web` directory to `src/web/app`.

I searched again through the whole project for paths that needed to be updated. This more narrow focus on a smaller task helped me find some relative paths that I missed in the original PR. This really shows the benefits of splitting a big task into smaller pieces to make it more manageable.

Before merging this [PR](https://github.com/Seneca-CDOT/telescope/pull/3287) we needed to update the path on [Vercel](https://vercel.com/) and give a heads-up to other students working on frontend issues that they needed to rebase their branch before moving forward.

I still have to do the same with the `docusaurus` and `test-web-content` directories and then make the necessary Docker and Nginx changes.

## Frontend changes

The other [issue](https://github.com/Seneca-CDOT/telescope/issues/2923) I worked on this week was adding a copy button for code snippets. I had to revisit a lot of Web APIs features so I spent a lot of time on [MDN](https://developer.mozilla.org/en-US/) (I love this website, there's always something new to learn on it). I originally used `MouseEvent` to capture the mouse movement and add a copy button to the DOM. [Tue](https://github.com/TueeNguyen) helped out by suggesting to use `mouseenter` and `mouseleave` so I made the appropriate changes.

As of Friday the copy button was working but the code was not great and it used the text 'copy' instead of an icon. Because of this it did not make it into the 2.9 release.

Busy with an endless Android assignment that took over my weekend, I did not manage to continue to work on it. To my surprise, [Duc](https://github.com/DukeManh) took over the [PR](https://github.com/Seneca-CDOT/telescope/pull/3281) and made it truly great! His final version turned the button into a React component that feels a lot more at home on Telescope than my original version.

Working on this reminded me that Open Source is a team sport and we really shouldn't be afraid to get help from others that might have more experience.

Tue and I got the ball rolling and then Duc scored the goal. In the end we all win! 🔭
Generic em Typescript
Tags: typescript, generic, beginners
Published: 2022-03-28 15:09:01

> Neste post eu vou dar uma introdução sobre o que é e como usar generic em typescript. 

Generic é um funcionalidade que permite criar:

- componentes
- funções
- interfaces
- classes 

que aceitam  uma variedade de tipos de dados ao invés de um.

Com o uso de generic damos a possibilidade da nossa função poder ser usada em diferentes situações, e removendo a duplicidade de código.

Generic aparecem em typescript dentro de colchetes angulares, no formato **<T>** onde **T** vai representar o tipo de dado.
E **<T>** é lido como generic do tipo **T**, e este tipo **T** pode ser usado como tipo de dado para qualquer parâmetro  ou variável dentro da **função**, **classe** ou **interface**.

Exemplo:

```
function info(value: string) {
  return value
}
```

Aqui temos um função normal que aceita um valor do tipo string e retorna, mas tem casos pretendemos usar a nossa função em cenários onde o **value** pode ser outro tipo de dado, ai chega o ponto em pensar em generic.

```
function info<T>(value: T) {
  return value
}
```
Com a adição de info**<T>** tornamos a nossa função generic, possibilitando assim que ela receba diferentes tipos de dados para a variável value.

Em typescript generic pode ser usado com **função**, **classe** ou **interface**

**Generics com função**
Para usar generic com função basta adicionar **<>** depois do nome da função, e dentro de **<>** colocar a lista dos tipos de dados que a função vai receber

```
function info<T>(...) { ... }

function pickValue<T, K>(...) {...}
```

Nota que os tipos de dados do generic não são usados apenas para os parâmetros da função, eles podem ser usados como tipo de dados para todo e qualquer componente dentro da função.

```
async function fetchApi<ResultType>(path: string): Promise<ResultType> {
  const response = await fetch(`https://api.joelmbengui${path}`);
  return response.json();
}

type Info = {
  name: string
}
const data = await fetchApi<Info>('/info');
```


**Generics com Interfaces, Classes**

Na criação de interfaces ou classes, temos muita vantagem ao usar generic, pois conseguimos cobrir uma grande variedade de situação para a nossa interface ou classe

**Interface**
Para criar um interface ou classe generic, adicionamos a lista de tipos depois do nome da interface ou classe

```
interface GenericInterface<T> {
  value: T
}
```

Aqui declaramos uma interface que tem uma propriedade value e onde o tipo vai ser determinado quando passarmos o valor de **T**.

**Class**

```
class Queue<T> {
  private data = []
  push = (item: T) => this.data.push(item)
  pop = (): T => this.shift();
}

const queue = new Queue<number>();
queue.push(0)
queue.push("1") // ERROR: can push string 
```

Aqui criamos uma pilha que pode ser usada para diferentes cenários, seja ele quando precisamos de um pilha de números, string, alunos, etc.


**Conclusão**
Neste pequeno tutorial falamos sobre generic, como usá-la em funções , interface e classes.

E podemos notar que o bom uso de generic, vai nos ajudar a evitar repetir código e deixar as nossas funções, interfaces e classes mais flexíveis.