teleren/devto huggingface dataset:
Kotlin Code Smell 5 - Too Clever For Your own Good
Tags: kotlin, codesmell, cleancode, programming
Published: 2022-12-05 12:17:42

---
title: Kotlin Code Smell 5 - Too Clever For Your own Good
published: true
date: 2022-12-05 07:30:42 UTC
tags: kotlin,codesmell,cleancode,programming
canonical_url: https://yonatankarp.com/kotlin-code-smell-5-too-clever-for-your-own-good
---

> **TL;DR:** Don't pretend you are too smart. Clean code requires readability and simplicity.

## Problems

* Readability
    
* Maintainability
    
* Code quality
    
* Premature optimization
    

## Solutions

* Refactor the code
    
* Use [**better names**](https://maximilianocontieri.com/what-exactly-is-a-name-part-i-the-quest)
    

## Examples

* Optimized loops
    

## Exceptions

* Optimized code for low-level operations.
    
* 1-liner code functions
    

## Sample Code

### Wrong

```kotlin
fun primeFactors(n: Int): ArrayList<Int> {
    val f = ArrayList<Int>()
    var d = 2
    var nn = n

    while (nn >= 2) {
        if (nn % d == 0) {
            f.add(d)
            nn /= d
        } else {
            d++
        }
    }

    return f
}
```

### Right

```kotlin
fun primeFactors(numberToFactor: Int): ArrayList<Int> {
    val factors = ArrayList<Int>()
    var divisor = 2
    var remainder = numberToFactor

    while (remainder >= 2) {
        if (remainder % divisor == 0) {
            factors.add(divisor)
            remainder /= divisor
        } else {
            divisor++
        }
    }
    return factors
}
```

## Conclusion

Developers who are too clever for their own good write cryptic code to brag. Smart developers write clean code. Clear beats clever!

---

Stay updated with my latest thoughts and ideas by registering for my [**newsletter**](https://yonatankarp.com/newsletter). Connect with me on [**LinkedIn**](https://www.linkedin.com/in/yonatankarp/) or [**Twitter**](https://twitter.com/yonatan_karp). Let's stay connected and keep the conversation going!

---

## Credits

* [Code Smell 06 - Too Clever Programmer](https://maximilianocontieri.com/code-smell-06-too-clever-programmer) by @[Maxi Contieri⭐⭐⭐](@mcsee)
Benefits of Custom Mobile App UI UX Design for Businesses
Tags: mobileappuidesign, appuiuxdesign, mobileappdesignservice, programming
Published: 2022-12-05 06:21:20

Custom mobile apps are more popular and in demand than ever before. These mobile apps can be fully customized to suit your business needs to help you save more time, which can be used to focus on other important responsibilities.

There are many reasons why more and more businesses are using customer apps every day. This article will go over the benefits of custom apps and why you should consider using them.

The two most important aspects of developing a mobile app are the user interface (UI) and the user experience (UX). It has different roles, but they work together to give users the best possible experience. An app with a customized UI and UX is one that was created for a particular business with the goal of increasing productivity and efficiency.



![Benefits of Custom Mobile App UI UX Design for Businesses](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9nj0wx5vv9ls1hj9t10p.png)
**Benefits of Custom Mobile App UI/UX Design for Businesses**

Whenever the UI and UX of a custom app are well thought out and executed, they become a powerful tool to increase user satisfaction, conversions, revenue, and user retention. Here we will talk about the main benefits of custom mobile app UI UX design.

- **High User Satisfaction:**

Focusing on your users and making sure they have the most incredible experience possible when using your mobile app. You want to retain customers, build brand and business loyalty, and keep them coming back for more.

To do this, you need to know your users first and foremost. To fully understand the expectations and preferences of your target audience, research their profiles.

- **Better Design Stability:**

It is essential to make sure that the design of your app is completely consistent. It is important to plan the design of the app before starting its development. Custom mobile [app UI UX design](https://webkul.design/mobile-app-design-services/) offers wonderful, individualized user experiences that meet the needs of both the company and its users.

- **Enhanced Conversion:**

A strong custom UI/UX mobile app design creates more user engagement and retention. It will boost conversion rates and boost sales for the company. The conversion rates will be higher as the app becomes more popular. The app's custom UI/UX is optimized so that it functions quickly, doesn't waste users' time, and provides them with the information they require. It also increases the chances of the app being successful.

###Conclusion
UI and UX have important roles in app development, and they cannot be ignored. Mobile app development needs to be planned before it starts. Hiring app design firms to help you create a great custom UI and UX is how you can ensure that your mobile app has the highest chance of success.
Handling negative or no response in AWS EventBridge
Published: 2022-12-05 06:13:44

Hey Guys,

I am new to AWS Eventbridge and I am currently dealing with how to handle negative scenarios in EventBridge. I am currently dealing with microservices architecture, and I am in need of solutions for the following questions:

1. How to handle negative or no response from Event Bridge

2. When there is no response from a a service when event bridge tries to notify should the service owner take responsibility or should we use single or multi lambda

3. Creating a queue named DL Queue with a lambda is something I found when googled, but is there any better cost effective solution ( Lambda seems to be more costlier as far as I explored )

4. If an event is triggered and if the request body is itself improper & it keeps trying for 24 hours, is there anyway we can manually clear the events in event bridge

It would be very helpful if some insights were given on these
Weekly 0039
Tags: weeklyretro
Published: 2022-12-05 06:10:58

### Monday

Sad Day.
The day started with a bad news. We need to suppress one of our dog because she is very sick and it’s better for her.
I have tried to work to stay focused on something else. Not really achieve the goal.
It doesn’t matter.

In the afternoon I published a post about changing the GitHub account on Windows.

![https://res.cloudinary.com/practicaldev/image/fetch/s--UAHxK5xX--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/01t5i83n879v4rh4ql3v.png](https://res.cloudinary.com/practicaldev/image/fetch/s--UAHxK5xX--/c_imagga_scale,f_auto,fl_progressive,h_420,q_auto,w_1000/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/01t5i83n879v4rh4ql3v.png)

[https://dev.to/kasuken/change-github-account-on-windows-2b91](https://dev.to/kasuken/change-github-account-on-windows-2b91)

**Mood:** 😢

### Tuesday

In the morning I had a meeting with Brandplane team about the status of the project and the roadmap.
I achieved a lot of things recently.

**Mood**: 🙂

### Wednesday

Annoying day. I spent a lot of time to add activities to one of the tool that I need to use for the awards programs.
It’s a very time consuming activity and every time I do it the last day. I need to add to my habits, at the end of every week, adding my community activities to these tools.

Or I can automate somehow this task, at least, as much as I can.

For the rest of the day, I work on Red Origin, on the Wizard feature to create App Registrations directly from Red Origin.

**Mood: 🙂**

### Thursday

Finally I found the focus again after the loss of this week. I felt motivated again.
I worked a lot on Red Origin, especially on the Calendar management for the strategist in the backend and in the application for customers.
It’s not perfect but it’s a good starting point. We will need to debug that part. I think I will publish everything next week in the test environment to start testing everything.
We are also start to collect some volunteers for the platform. It’s free for the first 50 strategist that want to test the platform.
We are just overbooked the first 50 😀

**Mood: 🧑‍💻**

### Friday

Day Off. 🙂

---

Thanks for reading this post, I hope you found it interesting!

Feel free to follow me to get notified when new articles are out 🙂

{% embed https://dev.to/kasuken %}

**Mood: 🤪**
876. Leetcode Solution in cpp
Tags: cpp
Published: 2022-12-05 06:09:04

```cpp
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */


class Solution {
 public:
  ListNode* middleNode(ListNode* head) {
    ListNode* slow = head;
    ListNode* fast = head;

    while (fast && fast->next) {
      slow = slow->next;
      fast = fast->next->next;
    }

    return slow;
  }
};
```
#leetcode
#solution
#challenge
Here is the link for the problem:
https://leetcode.com/problems/middle-of-the-linked-list/
Setup Error Middleware and async Handler in Node.js
Tags: node, javascript, beginners
Published: 2022-12-05 06:00:00

The express framework has a default error handler, that catches and processes errors that occur synchronously and asynchronously.

But the express default error handler returns an error in the HTML page. To fix this, I'll add an error middleware in my app.

> *For this series, I'm following an excellent video tutorial from [Traversy Media](https://www.youtube.com/playlist?list=PLillGF-RfqbbQeVSccR9PGKHzPJSWqcsm)*

## Table Of Contents
  * [Implement errorMiddleware](#error-middleware)
  * [Implement asyncHandler](#async-handler)

### Implement errorMiddleware <a name="error-middleware"></a>
Create a file named as `errorMiddleware.js` in `/backend/middleware` folder and add this code.
```javascript
const errorHandler = (err, req, res, next) => {
  const statusCode = res.statusCode ? res.statusCode : 500;

  res.status(statusCode);

  res.json({
    message: err.message,
    stack: err.stack,
  });
};

module.exports = {
  errorHandler,
};
```
and now I'll add it into `server.js` file.
```javascript
const { errorHandler } = require('./middleware/errorMiddleware');
...

app.use(errorHandler);
...
```
Make sure to define error-handling middleware in the last, after other app.use().
You can read more about it [here](https://expressjs.com/en/guide/error-handling.html)

Now I'll test the errorMiddleware in my setTodo POST call
```javascript
const setTodo = (req, res) => {
  if (!req.body.text) {
    res.status(400);
    throw new Error('Please add text field');
  }
  res.status(200).json({message: 'Set todo'})
}
```
and I'll get this error response 

![error-handling](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jezc0k709tw2ei0s4grt.png)

### Implement asyncHandler <a name="async-handler"></a>
As I am going to use `mongoose` in my next blog to interact with the database, which returns a promise in response. So to handle this I'll use `async/await` in all of the `todosController` functions.

For `async/await` we have to use a `try/catch` method but as I already have an error handler so I'll use `express-async-handler` package. 
This package will **handle the exceptions inside of async express routes and pass them to my express error handlers**.

Install async handler with this command 
```javascript
npm i express-async-handler
```
Now use it like this for all functions in `todosController.js`
```javascript
const asyncHanlder = require('express-async-handler');

const getTodos = asyncHanlder(async (req, res) => {
  res.status(200).json({message: 'Get todos'})
});

...
```

In the next blog, I'll create a database in MongoDB and connect it with Mongoose.

Thank you for reading!
Feel free to connect on [Twitter](https://twitter.com/Aneeqa_Khan25)
Advent of Code Day 5
Tags: adventofcode, elixir
Published: 2022-12-05 05:57:18


### Links

- [Intro](https://dev.to/sethcalebweeks/advent-of-code-2022-in-elixir-34i8)
- [Problem Statement](https://adventofcode.com/2022/day/5)
- [Code](https://github.com/sethcalebweeks/advent-of-code-2022/blob/main/lib/Day05.ex)

### Highlights

- Today's problem involved pretty standard stack manipulation. I used a recursive function to move each crate one at a time for part one. Part two was more straightforward since you could move all the crates at once.
- I didn't bother with parsing the initial state and manually entered it. The parsing of the instructions uses regex named captures with a bit of juggling to get the count to be an integer.

```elixir
defmodule Day05 do
  use AOC

  @stacks %{
    "1" => ["W", "B", "G", "Z", "R", "D", "C", "V"],
    "2" => ["V", "T", "S", "B", "C", "F", "W", "G"],
    "3" => ["W", "N", "S", "B", "C"],
    "4" => ["P", "C", "V", "J", "N", "M", "G", "Q"],
    "5" => ["B", "H", "D", "F", "L", "S", "T"],
    "6" => ["N", "M", "W", "T", "V", "J"],
    "7" => ["G", "T", "S", "C", "L", "F", "P"],
    "8" => ["Z", "D", "B"],
    "9" => ["W", "Z", "N", "M"]
  }

  def move_by_1(stacks, %{"count" => 1, "from" => from, "to" => to}) do
    {item, new_from} = stacks[from] |> List.pop_at(0)
    stacks |> Map.merge(%{
      from => new_from,
      to => [item | stacks[to]]
    })
  end
  def move_by_1(stacks, %{"count" => count, "from" => from, "to" => to}) do
    {item, new_from} = stacks[from] |> List.pop_at(0)
    stacks
    |> Map.merge(%{
      from => new_from,
      to => [item | stacks[to]]
    })
    |> move_by_1(%{"count" => count - 1, "from" => from, "to" => to})
  end

  def move_by_count(stacks, %{"count" => count, "from" => from, "to" => to}) do
    {items, new_from} = stacks[from] |> Enum.split(count)
    stacks |> Map.merge(%{
      from => new_from,
      to => items ++ stacks[to]
    })
  end

  def parse_instructions(fun) do
    [_, instructions] = input(5) ~> String.split("\n\n")

    instructions
    |> String.split("\n")
    |> Enum.reduce(@stacks, fn instruction, stacks ->
      %{"count" => count, "from" => from, "to" => to} = Regex.named_captures(~r/move (?<count>.*) from (?<from>.*) to (?<to>.*)/, instruction)
      fun.(stacks,  %{"count" => String.to_integer(count), "from" => from, "to" => to})
    end)
    |> Enum.reduce("", fn {_, stack}, str -> str <> hd(stack) end)
  end

  def part1, do: parse_instructions(&move_by_1/2)

  def part2, do: parse_instructions(&move_by_count/2)

end
```
How to set a default memory Requests and limits for a namespace
Tags: kubernetes, beginners, tutorial, devops
Published: 2022-12-05 05:56:10

## Introduction
Hi, I am Akshay Rao. 

- The kubernetes cluster is composed of namespaces. These namespaces can be given a default memory limits which can help the developers to create pods with out worrying about memory and the request limits and even need not to specify it in the deployment yaml file . 
- When a pod is created the namespace’s memory will be attached automatically.
- In this blog we will set the memory request and limit at 250MB and 125Mb.
- I am using minikube but this can be done on multiple nodes also.

**Create a namespace**

Start the minikube with `minikube start`
`kubectl create namespace mem-space-250mb`
verify with `kubectl get namespace`
![Image 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kv4494xwty4d88ti38n.png)

**Create a LimitRange and a Pod**
create a yaml file to define the Limitrange `vi default-memory.yml` 
```
apiVersion: v1
kind: LimitRange
metadata:
 name: mem-limit-range
spec:
 limits:
  - default:
     memory: 250Mi
    defaultRequest:
     memory: 125Mi
    type: Container
```
`esc->:wq` to write the file and quit
 attach this file to our "mem-space-250mb" namespace
`kubectl apply -f default-memory.yml --namespace=mem-space-250mb`
to create a pod will write a file with `vi pod-deployment.yml`
```
apiVersion: v1
kind: Pod
metadata: 
 name: pod-for-250mb-space
spec:
 containers:
 - name: ctr-mem-250mb
   image: nginx
```
i have not specified the memory request and limit in the file.
apply the deployment `kubectl apply -f pod-deployment.yml --namespce=mem-space-250mb `

![Image 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jeav5p898ghzzcm6nrz.png)
**Verifying**

verify the memory allocated automatically `kubectl get pod pod-for-250mb-space --output=yaml --namespace=mem-space-250mb`

![Image 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0l4kynppwsy7j9qw34ns.png)
the namespace's default memory is been allocated automatically to the pod.

## Other combinations
**What if the container limit is specifed but not the request**
The request will match the memory limit of the pod.
**What if the container request is specifed but no the limit**
the namespace's default limit will be taken in to consideration.

## Conclusion
Suggest in the comments on which kubernetes topic should i write blog.
Thank you
Top 5 best web series download: best web series of all time you should watch
Tags: webdev, beginners, news, movies
Published: 2022-12-05 05:29:49

Back in 2016 when Jio launched its 1 year offer of free data and free calls, it was the time when internet industry boomed in India. So many content creator became overnight sensations because of their unique style of content presentation. that time was also the game changer for the online streaming platforms and they jumped into it. And when Jio launched in Indian market there came a tsunami of content creators and digital streaming platforms.

With the rise of increasing internet users amazon launched its digital streaming platform in India Amazon Prime Video along with amazon prime Netflix also get launched in the same year. With their unique content and increasing internet users they get enough recognition only in a small period of time. they gave features which allowed user to [watch online web series](https://ndekho.com/5-best-web-series-download-best-web-series-of-all-time/) download and watch later. But their game changes when coronavirus breakout around the world and everyone was in complete lockdown, theatre’s were shut, when people around the world started streaming content online from these platforms.

With in no time those audience who were consuming online content became fan of their content and started watching almost every movie and web series from online streaming platforms. That is why when any movie can not do well on box office becomes hit on online streaming platforms.

Web series became more prominent from early 2000s and are generally in episodic form

[Vegamovies download free Bollywood, Hollywood Tamil, Telugu movies 2022](https://ndekho.com/vegamovies-fyi-bollywood-hollywood-telugu-movies-2022/)
Tips To Become A Productive Developer
Tags: webdev, javascript, beginners, tutorial
Published: 2022-12-05 05:07:53

1. Maintain a few side projects at all times to keep your mind active. Spend extra time on your side projects on the weekends and after work when your workload at work isn't keeping you too busy or pushing you. Utilize your side projects to expand your toolkit of abilities and experiment with new technologies and methodologies, a luxury you might not have at work given the need to deliver functionality as quickly as feasible.

2. Keep refactoring your code. With 20/20 hindsight, you can almost always think of a better way to create the same code as soon as you get something to work. Spend some time rewriting the code so that it makes more sense. Consider using a library to complete the task you were previously performing on your own. The more at ease you are with the finished product, the more likely it is that you will continue to develop it and add new features to it so that it becomes a part of your portfolio (put it on GitHub).

3. Get more used to your development environment and tools. Have a thorough understanding of your editor. What's the easiest way to refactor a function or identify a class? How quickly can a text file be modified? (learn regex).Never reinvent the wheel. Understand how to use every library that is offered in the language(s) of your choosing. Make an effort to provide an example for every library. Keep such instances close at hand so you may refer to them whenever necessary. When you are sufficiently familiar with a library, you are more likely to remember to utilize it when the occasion arises and to be aware of how to use it, making it easier to resist the need to create your own.

4. Read other people's code. It's a great way to learn. If you encounter idioms, libraries, patterns or techniques that seem unfamiliar, explore them further until you feel ready to try them in your own code. Being comfortable with reading code written by others is very important for doing code reviews within your team or across teams, working on open source projects, or troubleshooting open source libraries you're using in your own projects.

5. Develop what I call a "pixel to metal" perspective. Eliminate blind spots in your understanding of the entire scope of your application and its execution environment, whether it's the front end, the back end, the data store, the hardware, supported operating systems, virtualization layers, the network, the data center, or something else.

6. Automate. Automate. Automate. Including command line (bash profile), text manipulation and log mining (Perl), refactoring (Eclipse), building, deploying, integrating (Grunt, Ant, Maven, Gradle, Jenkins), and testing, automate anything you do often (xUnit, SoapUI, Selenium, Postman).


Connect me on [facebook](https://web.facebook.com/profile.php?id=100083195016286) and [LinkedIn](https://www.linkedin.com/in/christopherglikpo/)
5 famous websites - built in JAMstack
Tags: webdev, javascript, jamstack, serverless
Published: 2022-12-05 04:50:50

5 famous websites - built in JAMstack

JAMstack stands for JavaScript, APIs, and Markup. 

JAMstack architecture represents a modern web development architecture that allows devs to rely on the advantages of a static website, which include better [web performance and security] (https://thebcms.com/blog/headless-cms-secure-cms) benefits, while still retaining the dynamic attributes of a database-oriented CMS without the database. 

We might even say it’s the perfect answer to modern-day web development problems. Sound speed is one of the top-ranking benefits of modern design, security, and a [Headless CMS] (https://thebcms.com/) - that's a powerful combination for today’s successful websites. 

Check out how these few JAMstack projects did it. 

Here are 5 famous websites built in JAMstack.

PayPal

PayPal has been one of the biggest names in the fintech world for well over a decade. It lets users pay and shop online using a secure internet account. But we believe you already knew that.

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

What you didn’t know is that as one of the most popular payment options, PayPal is one of the prime targets for phishing and scams. Let me remind you again of the top three [benefits of JAMstack](https://thebcms.com/blog/5-superpowers-jamstack):

- Better performance
- Higher Security
- Better experience

When having a website or an app that processes payments, one of those benefits targets you in particular. PayPal is using JAMstack primarily because of its good security. With JAMstack, server-side processes are abstracted into microservice APIs, reducing the surface areas for the attack.

Ok, PayPal uses Jamstack to improve their security, but others, why Jasmstack was their choice? Find out at our blog:
(https://thebcms.com/blog/5-famous-websites-built-jamstack)