teleren/devto huggingface dataset:
Code Smell 147 - Too Many Methods
Tags: webdev, beginners, programming, java
Published: 2022-07-06 21:23:24

*Util classes are great to gather protocol*

> TL;DR: Don't add an accidental protocol to your classes

# Problems

- Readability

- Single Responsibility Violation

- Bad Cohesion

- High Coupling

- Low Reusability

# Solutions

1. Break your class

2. [Extract Class](https://dev.to/mcsee/refactoring-007-extract-class-18ei)

# Related Refactorings

{% post https://dev.to/mcsee/refactoring-007-extract-class-18ei %}

# Context

We tend to put a protocol in the first class we find.

That's not a problem.

We just need to refactor.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/d1c326e90aa2feba4746c6e019999312)
```java
public class MyHelperClass {
  public void print() { }
  public void format() { }
  // ... many methods more

  // ... even more methods 
  public void persist() { }
  public void solveFermiParadox() { }      
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/c64e13c3ea97620ce02dab73ffc517b2)
```java
public class Printer {
  public void print() { }
}

public class DateToStringFormater {
  public void format() { }
}

public class Database {
  public void persist() { }
}

public class RadioTelescope {
  public void solveFermiParadox() { }
}   
```

# Detection

[X] Automatic 

Most linters count methods and warn us.

# Relations

{% post https://dev.to/mcsee/code-smell-124-divergent-change-ddl %}

{% post https://dev.to/mcsee/code-smell-143-data-clumps-52f6 %}

{% post https://dev.to/mcsee/code-smell-90-implementative-callback-events-13l %}

{% post https://dev.to/mcsee/code-smell-22-helpers-2j6j %}

{% post https://dev.to/mcsee/code-smell-34-too-many-attributes-584p %}

# More info

[Refactoring Guru](https://refactoring.guru/smells/large-class)

# Tags

- Cohesion

- Bloaters

# Conclusion

Splitting classes and protocol is a good practice to favor small and reusable objects.

# Credits

Photo by [Marcin Simonides](https://unsplash.com/@cinusek) on [Unsplash](https://unsplash.com/s/photos/full)  

* * *

There is no code so big, twisted, or complex that maintenance can't make it worse.

Gerald M. Weinberg
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
The Gadget manifesto
Tags: webdev, productivity, serverless
Published: 2022-07-06 21:21:14

**Hello ~~world~~ dev.to**, this is a message from the [Gadget](https://www.gadget.dev?utm_source=devto&utm_medium=social&utm_campaign=manifesto) founders.

We’re tired of boilerplate work. We’re sick of abstractions that miss the mark. We’re done building auth for the thousandth time. We want to work on fun and novel challenges.

> At Gadget, we believe that most software is built on common, low-level patterns that we’ve all been following and have collectively established. We’ve repeatedly built the world’s most powerful applications, garage startups, and everything in between using these best practices. Yet, we continue to build from scratch every single time. As self-proclaimed stewards of efficiency, we admit, we’re some of the worst offenders. <br>
> In our defence, the tools we use to build software do little to help us get there quickly. We’re faced with endless options for tools and libraries that take more effort to integrate than they’re worth, and heaps of documentation to sift through. And we’re meant to stitch it all together from the ground up. For the first time. For the thousandth time.<br>
> And so that’s what we do. We spend days containerizing the same old infrastructure, deploying a database, setting up logging tools and more, before we can even begin writing the first line of useful code related to our project. We rebuild the endless stream of table-stakes features: auth, payments, search, permissions management ... Nothing unique or novel, not enough to make a compelling product, but still required every time. Then, we finally get to the good stuff, the business logic that makes our app special, only to find that much more of our focus goes to operating and scaling our apps. Our days involve repetitive tasks that just need to get done: running schema migrations, tuning config knobs, improving pagination, adding sortable tables... <br>
> We deserve better.  <br>
> And that’s what Gadget promises. A better development stack. <br>
> The Gadget stack makes development fun again. We’ve taken the repetitive work of building a backend out of the equation. We’ve provided the infrastructure to support you as you scale. We don’t prescribe how you should build your app, but we do provide the best defaults for the low-level primitives so that you don’t ever have to think about the basics again, unless you want to. And if you ever outgrow our defaults, you have complete control of the stack, to replace and extend as you need, with built-in escape hatches everywhere. <br>
> Gadget is the solution to needless repetition, frustration and inefficiency. It’s a way to become the stewards of efficiency again. Gadget is a new dev stack that works for you, made by people like you.<br>
> We can’t wait to see what you build with it.

Gadget co-founders, [Harry](https://twitter.com/harrybrundage) & [Mo](https://twitter.com/hashemito)
Bun - Ya esta aqui.
Tags: javascript, typescript, spanish, webdev
Published: 2022-07-06 21:05:40

[**Bun**](https://bun.sh/) es el nuevo runtime de JavaScript, escrito en [Zig](https://ziglang.org/). Bundler nativo, transpilador, task runner y cliente npm. Todo en uno.

![Benchmark](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rlybyig3oqmy4odd1elu.png)

## Baterías incluidas
- APIs Web como **fetch**, **WebSocket** y **ReadableStream**.
- **node_modules** bun implementa un algoritmo de resolución de módulos de Node.js, por lo que puedes usar paquetes npm en bun.js. ESM y CommonJS son compatibles, pero Bun utiliza internamente ESM.
- Transpilador de **Typescript** y **JSX**.
- Soporta **paths**, **jsxImportSource** y más desde los archivos **tsconfig.json**.
- Utiliza las llamadas al sistema más rápidas disponibles con **Bun.write** para write, copy, pipe, send y clone files.
- Cargado automatico de **.env** sin `require("dotenv").load()`
- Cliente SQLite3 integrado con **bun:sqlite**
- **bun:ffi** Para codigo iteroperable con JavaScript
- **node:fs** **node:path** Bun soporta de manera nativa la mayoria de modulos del core de Node.js
- **wiptest** para test de JavaScript y TypeScript

## Que tal si vemos un poco de codigo? 👨‍💻
Levantemos un servidor HTTP sencillito.
```js
// http.js
export default {
  port: 3000,
  fetch(request) {
    return new Response("Welcome to Bun!");
  },
};

```
Echémoslo a volar con:
```sh
bun run http.js
```

Y ya lo tenemos.

![server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cb7egvjjq87942xif96.png)

Pero que tal si hacemos un app de Next.js?
`bun create next ./app`

Que tal algo con React?
`bun create react ./app`
 
## Bun CLI

- Bun ejecuta package.json scripts hasta x30 más rápido que NPM.
- Bun instala paquetes NPM hasta x20 más rápido que yarn.

Ve, echale un ojo a su [repositorio](https://github.com/Jarred-Sumner/bun). Si puedes pruébalo y cuéntame en los comentarios como te fue.

Y Happy Hacking 🎉👨‍💻.
Hire ethical developers
Tags: hiring, career, community, leadership
Published: 2022-07-06 17:47:30

_Imagine you are running a small shop in your city. One day you catch a few people stealing something in your shop. After arguing, they ask to join your shop crew because they know some security points that could be improved._

**Is that the kind of people you would want to work with?** Probably not. They know that you're losing your money when they steal something. However, that's not a reason for them to stop doing it.

What's happening in the developer's world?

## Professional ethics

Some time ago, I read [this article](https://medium.com/@timotheejeannin/i-built-a-screenshot-api-and-some-guy-was-mining-cryptocurrencies-with-it-cd188dfae773) about a man that was using a screenshot API to earn money mining cryptocurrencies. The article talks about how the company managed the situation and stopped him.

The conversation was respectful and finally, the man stopped minning crypto using that service. I don't want to discuss how the company managed the situation, but I'd like to highlight some parts of the conversation:

> C: are we the first company you attacked?
>
> M: no..
>
> M: this is my hobby
>
> M: for fun and profit
>
> [...]
>
> M: i am sorry if you had any loss
>
> C: It's ok we haven't lost anything.
>
> [...]
>
> M: can i be a part of your team ?
>
> C: i'm sorry but we already have a developer in house.

We're at the same point as the shop example. **A person without professional ethics that knows the damage he or she might cause to your company is asking to join your team**. He knows how to use your service illicitly, so he knows how to protect you.

Based on the comments of the [article](https://medium.com/@timotheejeannin/i-built-a-screenshot-api-and-some-guy-was-mining-cryptocurrencies-with-it-cd188dfae773), it seems the company was wrong. But, were they really wrong ignoring his offering?

**No**.

Ethics in general ought to be integrated in all your hiring decisions. **Surround yourself with people that help you to grow as a professional, but even more importantly, as a person**. Please, don't reward bad people because they are good programmers.

## Mentors and idols

The same principle applies to your mentors and idols. Remember, ethics matter and are essential. If you know that your idols are good professionals but completely awful people, don't promote their work.

You may think that it doesn't matter because their opinions are not relevant for their work. **However, increasing their popularity has a dangerous consequence**. Their ideas will become more popular too.

**Please, create a better community by promoting good people, not just developers**.
Reduct Storage Client SDK for JavaScript 0.5 was released
Tags: javascript, news, database, node
Published: 2022-07-06 20:59:00

Few days ago I released the [next version](https://github.com/reduct-storage/reduct-js/releases/tag/v0.5.0) of the SDK. Traditionally, we update our SDKs after we have introduced new changes in [Reduct Storage HTTP API](https://docs.reduct-storage.dev/http-api). But this release is a bit special because we added streaming data to there. Let'see how we can use it.

If you're new to Reduct Storage, you can have a look at [this tutorial](https://dev.to/reduct-storage/how-to-use-reduct-storage-with-typescript-c74) before we start. 

## Reading Data

This example shows the easiest way to read a record from the storage engine and write it into a file:

```js
const {Client} = require("reduct-js");
const fs = require("fs");

client = new Client("https://play.reduct-storage.dev");
const bucket = await client.getBucket("bucket");

const readStream = await bucket.readStream("entry-name");
const fileStream = fs.createWriteStream("somefile.txt");
readStream.pipe(fileStream);
```

As you can see, we created a stream from the file and piped it with the record, which is read as a stream. Then we downloaded the record and wrote it to the file asynchronously in little chunks.

## Writing Data

You can write data to the storage engine with streams as well. However, you must provide the content length at the beginning of the write operation. It means you have to know the size of the record in advance. Let's see in code:


```js
const bucket = await client.getBucket("bucket");

const fileStream = fs.createReadStream("somefile.txt");
const {size} = fs.statSync("somefile.txt");

await bucket.writeStream("entry-name", fileStream, size);
```

Here we read the same file as a stream and uploaded it to the storage engine. The syntax is a bit different, but essentially, it works like `pipe()`.
Building a next app with Prisma.
Published: 2022-07-06 20:48:48


Create your next application

`npx create-next-app@latest`

Install Prisma

`npm install prisma --save-dev`

Initialize Prisma project

`npx prisma init`

Add your postgres link to your .env file. Make sure that everything is on the same line. 

`DATABASE_URL="postgresql:blahblahblah"`

Create your database schema in the prisma.schema file

```
// schema.prisma
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Post {
  id        String     @default(cuid()) @id
  title     String
  content   String?
  published Boolean @default(false)
  author    User?   @relation(fields: [authorId], references: [id])
  authorId  String?
}

model User {
  id            String       @default(cuid()) @id
  name          String?
  email         String?   @unique
  createdAt     DateTime  @default(now()) @map(name: "created_at")
  updatedAt     DateTime  @updatedAt @map(name: "updated_at")
  posts         Post[]
  @@map(name: "users")
}
```
Push the schema to your database 

`npx prisma db push`

Install prisma client

`npm install @prisma/client'

Updata your prisma client

`npx prisma generate'

Create a new directory called lib and a prisma.js file in it. 

In the prisma.js file you have to create an instance of the Prisma client. 

Then you can import your instance of the Prisma client into any file you need. Then you create a getServerSideProps function to query the data. Then you can display those props however you want. 

```
import prisma from '../lib/prisma';
import React from "react"

export const getServerSideProps = async () => {
  const feed = await prisma.post.findMany({
    where: { published: true },
    include: {
      author: {
        select: { name: true },
      },
    },
  });
  return { props: { feed } };
}


const Blog = ({feed}) => {
  console.log(feed)
  return (
    <div>
      {feed[0].title}
    </div>
  )
}

export default Blog
```
My next post might be on creating a REST API with Prisma.
Sistemas comunes de codificación y decodificación
Tags: webdev, spanish
Published: 2022-07-06 20:20:08

Es común en informática no poder presentar o almacenar datos en texto plano por motivos de seguridad. Para ello, es muy común utilizar sistemas de codificación; esto consiste en tomar un dato como una letra o palabra y convertirlo en símbolos que parecen ilegibles. La decodificación es el proceso opuesto, tomar los símbolos codificados y convertirlos en algo que sea legible por humanos. Veamos algunos de los sistemas de codificación y decodificación más comunes utilizados en la actualidad.

Base64
======

La idea detrás de esta codificación es usar 64 caracteres que son comunes en todos los sistemas de codificación y también se puedan imprimir, las variaciones base64 más comunes usan caracteres alfanuméricos (`A-Z`, `a-z`, `0-9`) para los primeros 62 valores y alguna combinación de un signo más (`+`), una barra diagonal (`/`) para los últimos 2 caracteres y quizás un signo igual (`=`) para el relleno.

Ejemplo
-------

Original: `hola mundo`

Base64: `aGVsbG8gd29ybGQ=`

Hexadecimal (Base 16)
=====================

En este sistema, los datos se codifican en secuencias de 4 bits utilizando 16 símbolos del juego de caracteres ASCII, los caracteres más utilizados son las letras `A` a `F` (a veces minúsculas `a-f`) y los números arábigos o dígitos `0-9`.

Ejemplo
-------

Original: `hola mundo`

Hexadecimal (Base16): `68656c6c6f20776f726c640a`

ROT13 (Cifrado César)
=====================

Mejor definido como un cambio de sustitución simple que consiste en tomar una letra del alfabeto y reemplazarla con una letra 13 posiciones hacia abajo en el alfabeto (se pueden usar otros números de posiciones); esto también se conoce como el Cifrado César, ya que fue utilizado por Julio César en su correspondencia privada en la antigua Roma.

Ejemplo
-------

Original: `hola mundo`

ROT13: `uryyb jbeyq`

Estas codificaciones se usan comúnmente en desarrollo web, criptografía y encriptación de correo electrónico. Esperamos que esta publicación pueda proporcionar una comprensión básica de estas codificaciones y cómo transforman los datos.

Mira esta publicación en Art of Code: https://es.artofcode.tech/sistemas-comunes-de-codificacion-y-decodificacion/
Pycraft v0.9.5-4 is now live!
Tags: programming, python, opensource, gamedev
Published: 2022-07-06 20:09:22

Pycraft v0.9.5-4 is now live on GitHub, it features many generational improvements and starts to introduce and mess with the concept of clouds, weather and Perlin noise in Pycraft! Check out all the details and give it a try here: https://github.com/PycraftDeveloper/Pycraft/tree/Pycraft-v0.9.5-4

Full change-log:
* Feature: The game now includes the start of a weather implementation, including procedurally generated clouds that move around the player. The clouds and weather will change randomly through the day/night, based on the rough relative probabilities of that respective weather in the UK. They also employ the fog effect we added to the terrain last time and have variable height based on the weather. Additionally the fog throughout the game now varies based on the current weather, so on a rainy day there will be more fog.
* Feature: The entire project has started to undergo restructuring to bring it in line with some of the PEP-8 standards.
* Bug-Fix: Numerous issues and bugs have been fixed regarding the benchmark functionality and exiting the benchmark now is much friendlier and any errors that used to be raised have now been fixed.
* Bug-Fix: More work has been done on the installer to improve its functionality, expect more improvements and eventual Linux compatibility there.
* Identified-Bugs: After toggling between full screen in the 2D engine of Pycraft (which uses Pygame) the window cannot be resized on some systems, even with the correct flags.
* Identified-Bugs: The installer will render incorrectly if the user has chosen to scale their displays.
Identified-Bugs: The cloud noise file for Pycraft (Rand_noise.png) is only generated once and the file is never re-written unless it's deleted.
* Bug-Fix: we are improving compatibility with non-Nvidia GPUs as the GLSL programmes can occasionally incur errors due to minor changes to how different GPUs accept syntaxes.
Common Encoding and Decoding systems
Tags: webdev
Published: 2022-07-06 20:05:57

Sometimes data cannot be stored or presented in plain text due to security reasons. For this, it is very common to use encoding systems; this consists of taking a piece of data like a letter or word and converting it into symbols that looks unreadable. Decoding is the opposite process, taking the encoded symbols and converting them back into something that's human readable. Let's see some of the most common encoding and decoding systems used nowadays.

Base64
======

The idea behind this encoding is to use 64 characters that are common across encoding systems and are also printable, most common base64 variations use alphanumeric characters (`A-Z`, `a-z`, `0-9`) for the first 62 values and some combination of a plus sign (`+`), a forward slash (`/`)for the last 2 characters and perhaps an equal sign (`=`) for padding.

Example
-------

Original: `hello world`

Base64: `aGVsbG8gd29ybGQ=`

Hex (Base 16)
=============

In this system, data is encoded in 4-bit sequences using 16 symbols from the ASCII character set, most commonly used characters are letters `A` to `F` (sometimes lowercase `a-f`) and the Arabic numerals or digits `0-9`.

Example
-------

Original: `hello world`

Hex (Base16): `68656c6c6f20776f726c640a`

ROT13 (Caesar Cypher)
=====================

More of a simple substitution shift that consists of taking an alphabet letter and replacing it with a letter 13 positions down the alphabet (other numbers of positions can be used); this is also known as the Caesar Cypher since it was used by Julius Caesar in his private correspondence in ancient Rome.

Example
-------

Original: `hello world`

ROT13: `uryyb jbeyq`

These encodings are commonly used in web development, cryptography, and email encryption. We hope this post can provide a basic understanding of these encodings and how they transform data.

Check out this post on Art of Code: https://artofcode.tech/common-encoding-and-decoding-systems/
Code Snippets: Das praktische Plugin für eine Snippet-Verwaltung in WordPress
Tags: wordpress, code, wordpressplugins
Published: 2022-07-07 12:09:00

---
title: Code Snippets: Das praktische Plugin für eine Snippet-Verwaltung in WordPress
published: true
date: 2022-07-06 20:04:18 UTC
tags: WordPress,code,WordPressPlugins
canonical_url: https://bloggerpilot.com/code-snippets/
---

![Code Snippets Plugin](https://bloggerpilot.com/wp-content/uploads/2022/07/code-snippets.png)

<!-- wp:heading -->
<h2>What exactly are WordPress code snippets?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Now, before I take a look at the WordPress plugin itself, I'd like to start by briefly clarifying what the Code Snippets are all about. After all, I can't just expect you to already know what exactly WordPress Code Snippets are and how they might help you and your blog. Don't worry, this thing is basically quite simple.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>WordPress Code Snippets are PHP snippets, which are small fragments of code meant for functions.php in your <a href="https://bloggerpilot.com/en/wordpress-themes/">WordPress theme</a>. Through functions.php, you usually add smaller functions that don't necessarily require a separate plugin. Such snippets can be cosmetic, for example to hide the admin bar in the WordPress backend, or for practical purposes to change all file names to lowercase when uploading.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":40196,"sizeSlug":"full","linkDestination":"none"} -->
<figure class="wp-block-image size-full"><img src="https://bloggerpilot.com/wp-content/uploads/2022/07/code-snippets-editor.png" alt="The Code Snippets Pro Editor" class="wp-image-40196"/><figcaption>The Code Snippets Pro Editor</figcaption></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Basically, the snippets are simply PHP code and are always used when no extra plugin should be developed or installed. So for relatively small functions. Theoretically, you can fill the functions.php with extensive code because there is no real limit. But it is generally used for small code snippets. So much for that.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In the actual use of the code snippets, there is then the idea, as for actually all changes to the theme, to add them only via a child theme. This is done so that the snippets persist and the theme doesn't overwrite everything during an update. Nevertheless, the administration is of course a bit more complicated and you keep the overview in the functions.php only with appropriate comments in the code itself.</p>
<!-- /wp:paragraph -->

Der Original-Artikel erschien auf [Code Snippets: Das praktische Plugin für eine Snippet-Verwaltung in WordPress](https://bloggerpilot.com/code-snippets/).