teleren/devto huggingface dataset:
Code Smell 181 - Nested Classes
Tags: webdev, beginners, programming, php
Published: 2022-11-22 22:00:35

*Nested or Pseudo-Private Classes seem great for hiding implementation details.*

> TL;DR: Don't use nested classes

# Problems

- [Bijection](https://dev.to/mcsee/the-one-and-only-software-design-principle-3086) fault to real world concepts.

- Lack of testability

- Lack of reuse

- Scopes and [namespaces complexity](https://stackoverflow.com/questions/47452783/code-style-and-smells-nested-classes)

# Solutions

1. Make the class public

2. Keep the public class under your own namespace/module.

3. Use a Facade to the external world to hide it.

# Context

Some languages allow us to create private concepts that only live inside a more significant idea. 

These classes are harder to test, harder to debug, and reuse.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/836b485a9a9bb29e8292f9e79b867cbb)
```java
class Address {
  String description = "Address: ";

  public class City {
    String name = "Doha";
  }
}

public class Main {
  public static void main(String[] args) {
    Address homeAddress = new Address();
    Address.City homeCity = homeAddress.new City();
    System.out.println(homeAddress.description + homeCity.name);
  }
}

// The output is "Adress: Doha"
//
// If we change privacy to 'private class City' 
//
// We get an error " Address.City has private access in Address"
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/abcc622d9f0f27c40fd94202535dcced)
```java
class Address {
  String description = "Address: ";
}
 
class City {
  String name = "Doha";
}

public class Main {
  public static void main(String[] args) {
    Address homeAddress = new Address();
    City homeCity = new City();
    System.out.println(homeAddress.description + homeCity.name);
  }
}

// The output is "Adress: Doha"
//
// Now we can reuse and test City concept
```

# Detection

[X] Automatic 

Since this is a language feature, we can detect it and avoid its usage.

# Tags

- Hierarchies

# Conclusion

Many features are bloated with complex features.

We seldom need these new pop culture features.

We need to keep a [minimal](https://dev.to/mcsee/what-is-wrong-with-software-5pa) set of concepts.

# More Info

- [W3 schools](https://www.w3schools.com/java/java_inner_classes.asp)

# Disclaimer

Code Smells are just my [opinion](https://dev.to/mcsee/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned-1n3a).

# Credits

Photo by [Dana Ward](https://unsplash.com/@danaward) on [Unsplash](https://unsplash.com/s/photos/spiral)  
 
* * *

> Developers are drawn to complexity like moths to a flame, frequently with the same result.

_Neal Ford_
 
{% 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 %}
Update book library: Slowing down development
Published: 2022-11-22 22:00:00

This short post, as the title and subtitle, says is to inform you that I'll slow down the development of my book library and what I'll be doing. The past Saturday I pushed some commits that I didn't think were worth pushing into GH, but given that I will slow down the development, I want  anyone visiting the repository knows what I was doing with the code base, the last time I wrote it.

{% embed https://github.com/UlisesAlexanderAM/book %}

## Why
After realizing I'm still need more experience to get a job, I switched the focus of my effords.

## Now what

Starting today, I'll resume solving exercises in [Exercism](https://exercism.org/profiles/UlisesAlexanderAM), focusing on my [Python](https://exercism.org/tracks/python) and [Haskell](https://exercism.org/tracks/haskell) tracks.

I'm considering building small projects in Python and Haskell, but I'm not sure if I develop them in both languages in parallel or one for each project.

The projects I'm considering doing are:

- Translating and expand my [fish shell](https://fishshell.com/) script into either Python, Haskell or both. 

- Continue working on the project ["A cat facts list"](https://uaam.hashnode.dev/a-cat-facts-list) which I talk in my original blog.

{% embed https://uaam.hashnode.dev/a-cat-facts-list %}

- Create something with the wakatime API, probably to use in my GH profile

{% embed https://github.com/UlisesAlexanderAM/ %}

- An API to get some of my favorites quotes from [readwise](https://readwise.io/i/ulises_alexander)

## Other endeavors

I'm also writing a newsletter about things I found in the week that I think are worth sharing. This newsletter is general, but I'm condering making one for topics related to software engineering, one like the current one but in spanish, my native language, and one related to my hobbies (music, anime, manga, webtoons, webcomics). 

Given that I created a medium account to sync my highlights to readwise, I'll post there, software unrelated content.

**Note: the readwise link is a referral link**
Need help on ReactJS chart library...
Tags: react, javascript, webdev, beginners
Published: 2022-11-22 21:41:39


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jdzwqnwy3ecvg2ah5kcg.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/opccnfm151kefwcj27g0.jpg)

Need suggestion on which library to use to get the above variants of graphs ?

I need to use this for a project, which was designed in figma and since it would show live data from backend I can't just make it static. I tried recharts but couldn't get it to display like this, probably am not using the right parameters.
Apprendre à coder en 2022 et au-delà
Tags: french, html, css, javascript
Published: 2022-11-22 21:37:50

Bienvenue dans ma série gratuite sur l'apprentissage a coder. Grâce à cette série gratuite , tu passeras de zéro expérience a être capable de déployer ta première application web , ta premiere page web (t'inquite je vais t`expliquer ces terminologies dans cette serie , reste juste concentré(e) ). En cours de route, je vais t'enseigner les concepts essentiels du développement web nécessaires en 2022 et au delà , a la fin de cette serie tu seras un ***software engineer*** - un ingénieur en informatique.

Partage juste cette serie , ainsi tu pourras m'aider a toucher  plus de personne.

## À qui cette serie s'adresse-t-il ?

Deja tu dois comprendre un truc tres important:

> 
Tout le monde peut apprendre à coder 
L'un des meilleurs aspects du coding est que tout le monde peut apprendre à le faire. Quel que soit ton âge, ton sexe ou ton origine, le coding est une compétence que tout le monde peut acquérir.

- Tu n'as ***jamais écrit une ligne de code de toute ta vie***, et tu aimerais apprendre a coder , alors cette serie est pour toi.

- Tu veux être en mesure de créer tes propres applications et sites web, alors cette serie est pour toi.

- Apprendre à coder , t'aideras à comprendre comment les choses fonctionnent dans le monde numérique d'aujourd'hui.

- Apprendre à coder , t'aideras à penser de manière analytique et à résoudre des problèmes.

- Apprendre à coder , pourra t'aider à gagner plus d'argent. Sur le marché du travail actuel, les employeurs sont constamment à la recherche d'employés ayant des compétences en codage.

- Apprendre à coder , pourra t'aider a faire partir d'une communauté en pleine expansion.
Et la liste est longue.

## Que vas-tu apprendre dans cette série ?

Dans cette série, tu apprendras :

**Premiere partie : Initiation au developpement web**

- HTML

- CSS
   - Css flexbox
   - Css grid
   - Css media query
   - Saas

- Git et Github

**Deuxieme partie : La programmation informatique**

- Javascript

- React-Js

**Troisieme partie : Projets**.

***

Avec le temps il y'aura des ajouts dans le programme de la  serie...

De toi , j'attend juste de la volonté , aussi de la patience  pour pouvoir apprendre a coder . Partage pour que cette serie puisse toucher le plus de personne possible.

Si tu as lu jusqu'ici, je l'apprécie vraiment!

Prend soin de toi et a la prochaine.

Tu peux me contacter sur : [Twitter](https://twitter.com/RaneNjimsDev) | [github](https://github.com/NjimsRane)

coding_is_sexy :heart:
RUST: How to test println!() ?
Tags: rust, testing, programming
Published: 2022-11-22 21:07:02

Let's say we want to test that a function is correctly outputting something.

Our function may looks like this simple example: print n times the name given in parameter.

```rust
fn greeting(nb: i32, name: &str) {
    for _ in 0..nb {
        println!("hi {}", name);
    }   
}
```

How to test it? 🤔 It looks hard.

One easy way is to refactor our code using a `Trait`.
You can see Traits as interfaces.

```rust
trait Logger {
    fn log(&mut self, value: String);
}
```

Then, let's define a `struct` which implements this `trait`.

```rust
struct ConsoleLogger;

impl Logger for ConsoleLogger {
    fn log(&mut self, value: String) {
        println!("{}", value);
    }
}
``` 

Great! Now we can refactor our `greeting` function to use this `trait`.

```rust
fn greeting(nb: i32, name: &str, logger: &mut dyn Logger) {
    for _ in 0..nb {
        logger.log(format!("hi {}", name));
    }
}
```

Ok but how this is helpful for testing?

Well, now, in tests, we could define a new struct with a different implementation for our trait. 

Here, instead of outputting our strings using `println!` we will store those in a `Vec<String>`
This way, it will be super easy to assert that our values are valid.

```rust
struct TestLogger(Vec<String>);

impl Logger for TestLogger {
        fn log(&mut self, value: String) {
            self.0.push(value);
        }
}
```

And we can finally test:

```rust
#[test]
fn greeting_test() {
    let mut test_logger = TestLogger::default();
    greeting(2, "maxday", &mut test_logger);
    assert_eq!(2, test_logger.0.len());
    assert_eq!("hi maxday", test_logger.0[0]);
    assert_eq!("hi maxday", test_logger.0[1]);
}
```

Voila! 🎉

Full code here: https://gist.github.com/maxday/ae3c9f219c35c228dadd5359def5a833

 🚀 🚀 🚀 If you want more Rust, feel free to check my new YouTube channel here: https://youtube.com/@maxday_coding
How to customize/add logic in Strapi CMS Relation-Ship
Tags: javascript, react, stripe, help
Published: 2022-11-22 20:57:54



Hello developers.

I need your help in Strapi CMS. 
my case is simple. 


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

Here i made on collection type. that is called **Center** and next one is post.


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

here Center has many Posts relation.

## all centers title
- ind_chennai
- ind_goa
- ksi_mumbai

## some post content_title
- POST 1
- POST 2


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

When I add/edit a post, I want to show only any **center** title starting with **ind_** in the dropdown.

My problem is if I have to write the logic for this, where do I write it? if you know that way please tell me guys.

Details:

- strapi v4
- sqlite / psql
How I keep xDebug in php.ini.hbs in LocalWP consistent
Tags: php, localwp, wordpress
Published: 2022-11-22 20:57:28

When you setup LocalWP and switch PHP versions it re-creates various `php.ini.hbs` files for each version (and the currently running) of PHP.

The problem is that it resets the xDebug config to use port `9003` every time. Furthermore it always turns off autostart in xDebug v3.

I want my port to be `9021` in every PHP version, and I want autostart on by default. But when I switch PHP versions my configuration isn't retained.

So, I wrote a small script to help me keep my `php.ini.hbs` files consistent if it's ever de-configured my PHP version switching.

- Check it out [here](https://github.com/aubreypwd/code/blob/master/PHP/LocalWP/xdebug-consistent-config.php) &rarr;
Enhancing Windows Terminal
Tags: terminal, programming
Published: 2022-11-22 20:56:56

![terminal example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j32pdhdsyizc9mwj0h49.png)

What you need: 
- Latest version of windows terminal
- Latest version of powershell 

`Install-Module -Name PackageManagement -Repository PSGallery -Force`
`Install-Module -Name PowerShellGet -Repository PSGallery -Force`
`Install-Module PSReadLine -AllowPrerelease -Force`
`Install-Module posh-git -Scope CurrentUser`
`Install-Module -Name Terminal-Icons -Repository PSGallery`

Now install oh-my-posh from [here](https://ohmyposh.dev/docs/installation/windows)

Now install a nerd font so you can get all the nice symbols and stuff [detailed here](https://ohmyposh.dev/docs/installation/fonts)

Open your powershell profile by typing `code $PROFILE` in the terminal. Add the following config

```
Import-Module -Name Terminal-Icons

Import-Module posh-git

oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/star.omp.json" | Invoke-Expression

Import-Module PSReadLine

Set-PSReadLineOption -PredictionSource History

Set-PSReadLineOption -PredictionViewStyle ListView

Set-PSReadLineOption -EditMode Windows
```

Extra: if you want to be able to open terminal at set locations, hit `CTRL + SHIFT ,` then add a line called startupActions like this

```
 "startupActions": "new-tab --tabColor #3B78FF -p \"Windows.Terminal.PowershellCore\" -d C:\\GIT\\Proj1 ; new-tab --tabColor #C19C00 -p \"Windows.Terminal.PowershellCore\" -d C:\\GIT\\Proj1",
```
Another one - if you want the folder names to show up in the tabs do this:

`code "$env:POSH_THEMES_PATH/star.omp.json"` (replace the file name with the theme you are using)

add   `"console_title_template": "{{.Folder}}{{if .Root}} :: root{{end}}",` to the root anywhere
My Final dev.to post!
Tags: django, webdev, beginners
Published: 2022-11-22 20:41:59

I have decided to focus solely on maintaining my own site rather than depending on dev.to as a platform for technical blogging because of various reasons.

It has been a pleasure writing here on dev.to, and it has proven to be an extremely valuable platform for sharing my knowledge on Django web development and AWS Cloud Computing.

I will not remove the content already on dev.to.

Thank you all for the support, it’s been a blast!

Here we go! Goodbye dev.to!

**All of my future posts, will be available on my new blogging website below:**


{% embed https://www.cloudwithdjango.com/ %}
Top 7 Featured DEV Posts from the Past Week
Tags: top7
Published: 2022-11-22 20:25:13

---
title: Top 7 Featured DEV Posts from the Past Week
published: true
description: A round up of the most-read and most-loved contributions from the community this past week
tags: icymi 
cover_image: https://thepracticaldev.s3.amazonaws.com/i/sfwcvweirpf2qka2lg2b.png
---

_Every Tuesday we round up the previous week's top posts based on traffic, engagement, and a hint of editorial curation. The typical week starts on Monday and ends on Sunday, but don't worry, we take into account posts that are published later in the week._ 

## Is dev.to for Web Devs and Beginners?

Have you noticed a lot of web dev and beginner content on DEV? @derlin has the data to prove that that’s our bread and butter!

{% embed https://dev.to/derlin/devto-is-for-webdevs-and-beginners-i-have-data-to-prove-it-54c4 %}


## ✨Today I Learned: The Subtle Art of Code Reviews 💡✨

Code-reviewing is tough! As a first-timer, you might find yourself staring blankly at the code wondering what is and isn't appropriate to suggest. Learn from @saminarp's experience and check out these best practices to master the subtle art of code reviews.

{% embed https://dev.to/saminarp/today-i-learned-the-subtle-art-of-code-reviews-3pef %}


## Build and Deploy a Node.js Microservices Application

When it comes to modern software development, microservices are one of the hottest trends. In this article, @pavanbelagatti will show the benefits of building a microservices app!

{% embed https://dev.to/pavanbelagatti/build-and-deploy-a-nodejs-microservices-application-2966 %}


## Fun with console.log() 💿

Run console.log(console), and you'll see that there's much more to the console object. @lissy93 briefly outlines the top 10 neat tricks you can use to level up your logging experience.

{% embed https://dev.to/lissy93/fun-with-consolelog-3i59 %}


## Mock an API in One Minute

Great news: you can mock an API in only one minute and you don't need to write any scripts. @manikbajaj will show you how!

{% embed https://dev.to/ismailkamil/how-to-mock-an-api-in-one-minute-eip %}


## Writing Your First Conference Proposal

Maybe you’ve been thinking about speaking at a conference, but you’re nervous. Hopefully, this blog post from @bekahhw will help you discover an idea and/or overcome the fear of submitting. 

{% embed https://dev.to/bekahhw/writing-your-first-conference-proposal-4jei %}


## Spring Modulith: Have We Reached Modularity Maturity?

Many folks flock to microservices because the application they work on resembles a messy plate of spaghetti. 🍝 @nfrankel contends that if ya have a well-designed application, the pull of microservices isn't so strong.

{% embed https://dev.to/nfrankel/spring-modulith-have-we-reached-modularity-maturity-2id0 %}


_That's it for our weekly Top 7 for this Tuesday! Keep an eye on dev.to this week for daily content and discussions...and be sure to keep an eye on this series in the future. You might just be in it!_
Best discord bot to make custom commands
Tags: customcomma, customcommandsdiscordbo
Published: 2022-11-22 20:11:48

Building your own server or community and you want to have your own customised commands for your server without needing to write codes/programmes and pay to keep them live forever? Then you can try the Custom Commands discord bot. Its both free and easy to use for an absolute beginner discord user
Lets see how we can use the Custom Commands Discord bot

## Invite the bot
You can find the bot in various places but the best one is https://makeown.cc/. Its the official website link where you can just click invite and start making your own custom commands

## Create Commands
First invite the bot and click on this link https://makeown.cc/dashboard this will take you to a login page. Log in and then you will see server list where you are joined. Click on the server you have invited the bot and you can see a interface Like this

![Custom Commands discord bot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/85ib333xyn0bpd5g1fim.png)


On the left side, Sidebar, you can see the Create button click that and you will see a variety of commands you can create with this bot.
Click the one you want. But lets see the text option. Click Text and you will see a interface like this

![Custom Commands discord bot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0uvustksn1ri400w6y2b.png)

Here you can see a few things.

- Command name

Command name is the name of the custom command. Which will trigger the command and show you the content

- Arguments

If you want to pass dynamic argument to the command, Something like a context, you can use arguments, But for now keep it blank, and fill the content with some content you want.
For example a command name youtube and the content might be something like https://youtube.com so whenever someone type **youtube it will send the content.

Its that simple.

Note: For commands the default prefix is ** but you can change it on the settings with whatever you like.

> Now its your turn to try different features of this bot and have fun.

{% embed https://github.com/shahriyardx/shahriyardx %}
Going serverless using Cloudflare Workers
Tags: beginners, programming, opensource, javascript
Published: 2022-11-22 19:48:59

Over the last two weeks, I have worked with my peers on a project called [My Photohub](https://github.com/humphd/my-photohub). A project being put together by student developers at [Seneca College](https://www.senecacollege.ca/home.html).

## Initial Design 
Initially, we had an Express backend for my [PR](https://github.com/humphd/my-photohub/pull/9) to process form submissions. However, we wanted to eliminate the need for maintaining and configuring the backend on our own. Therefore, we decided to go [serverless](https://developers.cloudflare.com/workers/), using [Cloudflare Workers](https://developers.cloudflare.com/workers/).

## Going Serverless
Using a serverless approach could be problematic for someone who has been used to setting up a server for the backend. However, I challenged myself to get familiar with Cloudflare Workers to the point that I could have a serverless backend demo to present to my team members.

### Doing Research

The first step was to do my research.

I first read the documentation on the Cloudflare website and learned what precisely _serverless computing_ is. I learned that serverless computing does not mean that there would be no servers involved. We, as developers, would not have to worry about maintaining the servers since Cloudflare would manage them for us.

#### But why Cloudflare Workers? 

One may still wonder why Cloudflare Workers when I can easily create a server using Node.js.

Top three reasons to use Cloudflare Workers:
- Reduced costs *(you only pay for what you use)*
- Eliminates the need to manage server 
- Easily scalable

### Writing the Code

It took me a couple of days to figure out how to rewrite the current code using syntax for a service worker. I tried several approaches, some worked, and some did not. The [tutorials](https://developers.cloudflare.com/workers/tutorials/) and [examples](https://developers.cloudflare.com/workers/examples/) sections of the Cloudflare website are regularly updated to help newcomers get started, and I found them very helpful. The tutorials are well-crafted and can be filtered based on experience level. The beginner tutorials seemed appropriate, as I needed to gain experience with Cloudflare Workers.

### Problem Encountered
 I overlooked some problems in my implementation, but my teammates caught them. For example, running the service worker through ESLint with incorrect configuration yields errors. 
We have to add the following to `eslintrc.json` file:
```node
  "env": {
    "serviceworker": true
  },
```

### Improving the Code
[David](https://github.com/humphd) immensely helped me improve my code through his constructive feedback on the PR. His comments helped me remove redundancies and restructure the code so it's cleaner. 

## Final Thoughts
Technology is an ever-evolving thing. As developers, we have to keep up with it by expanding our skills and knowledge portfolio. I also learned that with every revision, I improved my code.