fabiochiu/medium-articles huggingface dataset:
Knot-of-nots: Avoiding negative names for boolean methods
By: Thameena S
Tags: Boolean, Naming Conventions, Object Oriented, Code Readability, Clean Code

Knot-of-nots: Avoiding negative names for boolean methods

The usual convention to name methods that return boolean is to prefix verbs such as ‘is’ or ‘has’ to the predicate as a question, or use the predicate as an assertion. For example, to check if a user is active, you would say user.isActive() or to check if the user exists, you would say user.exists().

But when the intention is to check if the user is not active, I've come across code that is written as user.isNotActive() or user.isInactive(). The problem with having negative method names is that it becomes harder to understand when you try to reuse the same method for the positive use-case.

Consider the following scenario. We need a list of users that does not have a prime subscription. The method that has this logic might be named as user.doesNotHavePrimeSubscription() or user.hasNoPrimeSubscription().

Works well for this use case. However, it is highly likely that we might need to get the list of users that has a prime subscription in the future. To re-use the existing method, the if statement will have to be written in this format:

!user.doesNotHavePrimeSubscription, being a double negative statement, makes it confusing to understand such a simple use-case, especially when it comes to complicated methods. To make your code easily readable, change negative verbs to affirmative ones.

Rather than ending up in a knot of nots, it's always a better practice to construct the method name using the positive form of the verb and prefix

a ‘!’ (not) only for the negative use-case. A very simple convention, if followed, that will help in better code readability and reusability.
Must know Java Commands using Lambda Expressions
By: Shreya Singh
Tags: Lambda Expressions, Clean Code, Java

Lambda expressions in Java are effective ways using which we can write shorter, cleaner and more understandable Java code. They significantly reduce the lines of code as well. Here are the top 10 of my most used Java commands using lambda expressions.

Printing the elements:

Suppose you have an ArrayList of numbers. You want to print these numbers using lambda expressions.

numbers.forEach((num) -> {

System.out.println(num);

}); Filtering elements based on a condition:

Given an array of numbers filter some number based on some given condition say num > 5

numbers.stream().filter(num -> num > 5).collect(Collectors.toList()); Grouping Elements of Same Type:

Given an Arraylist of Java object Book with authorName and price, we want to group the book by Author name.

Map<String, List<Book>> booksByAuthorName = books.stream().collect(Collectors.groupingBy(book -> Book::getAuthorName)); Sorting an ArrayList of numbers:

In ascending order:

Collections.sort(numbers);

In Descending Order:

Collections.sort(numbers, Collections.reverseOrder()); Sorting an ArrayList of Strings lexicographically:

Given: myStrings = [Java, C++, Python]

Output: myStrings = [C++, Java, Python]

Collections.sort(myStrings); Getting Maximum and Minimum in Custom Objects:

User user1 = users

.stream()

.min(Comparator.comparingInt(User::getAge))

.get();

User user2 = users

.stream()

.max(Comparator.comparingInt(User::getAge))

.get(); Streaming over Hashmap using Lambda:

myMap.forEach((key, value) -> System.out.println(key + “ :” + value)); Filtering in HashMap:

Map<String, Integer> mp = new HashMap<>();

mp.put(“ABC”, 1000);

mp.put(“BCD”, 500);

mp.put(“FGH”, 1300);

mp.put(“ADF”, 200);

Map<String, Integer> result = mp.entrySet()

.stream()

.filter(v -> v.getKey().startsWith(“A”))

.filter(p -> p.getValue().intValue() <= 1000)

.collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); Getting value by key in a map or else default value provided if key doesn’t exist:

int n1 = map.getOrDefault(“a”, 0);

int n2 = map.getOrDefault(“b”, 10); Using findAny() and findFirst()

findAny:

List<Integer> getNumbersGreaterThanX(List<Integer> numbers) {

Optional<Integer> ans = numbers.stream().parallel().filter(num -> num > X).findAny();

if (ans.isPresent()){

return ans.get();

} else {

return Optional.isEmpty();

}

}

findFirst:

Integer getFirstElementFromList(List<Integer> numbers){

Optional<Integer> ans = numbers.stream().filter(num -> num > X).findFirst();

if (ans.isPresent()){

System.out.println(ans.get());

} else {

System.out.println(“No Number greater than X”);

}

}
Writing clean Cypress tests 🔧
By: Klaidas Lekavicius
Tags: Testing, Cypress, Clean Code, Quality Assurance, React

While writing Cypress tests at Revel, we try to ensure the same level of readability as in the actual source code of the project. Along with the flexibility to easily extend and refactor tests, the goal is to make Cypress tests easy to understand for new joiners as well as extend suites with new cases. To properly do that, we invested some time into preparing a developer-friendly solution to write code that can be extended with test identifiers built by reusable utility functions. Also, because most of the Cypress tests need to execute some common actions, we try to ensure the possibility to reuse most of them between tests, promoting DRY.

Test identifiers

As with most of the modern web applications, our project is created using reusable components, which ensure a similar look and feel for the consumer. To interact with HTML DOM elements from our Cypress tests, we decided to target elements with unique tracing properties that a testing framework can reference:

Because reusable elements can appear in multiple places of the application, it was easy for Cypress to fail while trying to find them without any additional querying of parent elements. For that reason, we decided that each component can inherit an identifier from a parent component and add its own value to construct the tracing path.

This reusable identifiers structure gives us the following benefits:

An identifier in an application can be built of multiple other identifiers, yet it will be always unique because it also contains a value from a parent component that’s rendering a child

When we want to inspect a particular element, we can easily search it in the DOM by using the identifier value. No need to fiddle around by identifying parent components that contain a needed element

When the UI is being changed, we don’t need much effort to maintain the tests. Even if a button to Login the user changed its position from header to footer, at most we will need to update the identifier, and a test will pass!

Finally, writing a Cypress test is as simple as using predefined identifiers:

Making tests DRY

Readability and ability to reuse code is one of the most important values that we have while writing code, and things are no different with tests. If there’s some piece of code that can be common in testing, we make it a reusable utility:

This effort gives a tremendous reliability boost. Cypress tests are easy to read, almost like a true specifications document!

Cypress also provides an ability to create your own custom commands which are specific to your application and can be used everywhere. Cypress suggests not to make everything a custom command, although our approach of taking certain elements out of the DOM gets way easier by having a custom getId command which can accept an identifier value:

Conclusion

Investing in time to make Cypress tests pretty and readable pays a lot in the long term. Newly joined team members usually can pick up work way faster, and the effort needed to add additional tests becomes much smaller! ❤️
What a blast we had yesterday –pikkujoulu edition
By: Tuulikki Rautiainen
Tags: Clean Code, Holiday Season

Our whole team of 17 got together to celebrate the year coming to an end and the approaching holiday season. We had a remote party that started with a beer tasting by our CBO Erkki Heino, followed by a really great, home delivered dinner from makumatka.fi and then some fun and games. I guess you could say we’re a gaming company, and having a party online does provide a natural platform party games (Drawful and Among Us). Also eating together by the screen made it feel like having a really great reach to hear the discussion and talk with everyone, as in a restaurant you usually end up talking mostly with people next to you. It was kind of inspiring to see what kind of activities can also be enhanced when doing remotely! Next spring we’ll try a remote cooking evening.

Our Valuemotive team in December 2020

Putting together a pikkujoulu was easy and fun, but starting to do it took some effort to be honest. I personally have been so tired of sitting by the screen so much and not connecting with people face to face. But the overall feeling yesterday and today was that boy that really energized me and the whole team. At times I completely forgot we were remote, it more felt like just hanging out with your best work buds.

One of the highlights of the evening was to crack the christmas present riddle. We had a special Nicaragua blend coffee from our loved coffee supplier Helsingin Kahvipaahtimo and a special key to open the mystery of it all. This did take some peer coding and pi desimals, but we got there. Sort of. Meta levels mentioned.

Kuumaa koodia

We’re so grateful to celebrate the ending of the year with great company and work to be done next year too. This year more than ever it’s not a given. We also acknowledge people around us that might need some help, so as a small gesture we matched our dinner budget and donated that sum to Hurstin Apu.



From all of us at Valuemotive, have a relaxing and whatever you might feel you need kind of holiday and see you on the flip side!

PS We had so much fun. And we do enjoy our time together otherwise too, as our fresh Great Place to Work score of 90 showed us in this December survey results. Wanna join us? We’re hiring!
Find unused classes in Android codebase
By: Eric N
Tags: Sonarqube, Static Code Analysis, Proguard, Android App Development, Clean Code

Photo by Ed Leszczynskl on Unsplash

Problem

Even though Proguard and R8 removed the unused code for you at release time, you should still make effort to remove dead code to reduce confusion, increase productivity of your everyday work and onboarding.

Solution

For starter, none of the static code analysis tools (SonarQube, CheckStyle, Pmd, Findbugs, Android Lint) I know does the job.

Since Proguard and R8 removed unused classes, I followed the instructions here and generated and generated an usage.txt file

Add -printusage to your proguard.pro file

to your proguard.pro file Run ./gradlew app:minifyReleaseWithProguard or ./gradlew app:minifyReleaseWithR8

But the usage.txt file is big and I can clearly see some classed that are used, not dead code.

My interpretation is that usage.txt lists both removed and obsfucated classes.

So I came up with the following algorithm

Go through usage.txt line by line, filter out noises

See if the class name is found in mapping.txt, if it’s not, the class is removed by Proguard/ R8

To make the search for class name in mapping.txt, I stored mapping.txt’s record in a binary tree.

Give M lines of text in usage.txt and N lines of text in mapping.txt (N is pretty big; it’s 214543 lines in my small dating app; M is minuscule compared to N), the time complexity of my algorithm is M * logN

Update Dec 17 2020

Java Set data structure could have been used here instead Binary Search Tree since I have no desire to sort the classes.

Insert and search time complexity would both be O(1) while space complexity would remain only O(N).

Conclusion

There is a chance the tree is skewed and the time complexity will be close M*N. To avoid that, the tree should be kept balance during insertion.
I will definetly pick on variable names, imagine a variable name like act for account and c for…
By: Ali Mohammed
Tags: Coding, Clean Code, Developer

I will definetly pick on variable names, imagine a variable name like act for account and c for case, oli for opportunityLineItem. I ask the question what is the intent of this variable, why is it that the developer treating variables as a third class citizion. Variables should have an intent and be assured I will be the first person to pick on this anytime everytime. Reference https://www.amazon.co.uk/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073/ref=pd_lpo_14_img_0/261-2864096-1128422?_encoding=UTF8&pd_rd_i=0137081073&pd_rd_r=fae84bde-f508-43d9-9330-744cc7119228&pd_rd_w=I7p18&pd_rd_wg=OQHyd&pf_rd_p=7b8e3b03-1439-4489-abd4-4a138cf4eca6&pf_rd_r=TECKEAYT1YVFS6JK8S6H&psc=1&refRID=TECKEAYT1YVFS6JK8S6H
How clean code impacts hiring, productivity and cash flow ?!
By: Freddy Mounir
Tags: Cash, Productivity, Reflections, Development, Clean Code

Most business owners, think about code as the cheapest / least important part of a product.

We talk business, we build up the idea. Then Code comes last. Which is partially true, Code really comes last after product ideation, usability, business model, feasibility study and revenue stream. BUT it shouldn’t come LEAST.

Uncle Bob talked about this a lot , and the coming part is a mixture of what i learned from him and what i experienced in my practical life.

During my career, I saw a lot of projects/products with unclean/clean code. I saw how “Unclean” ones requires very high maintenance, cost and requires hiring extensively.

For example: if you have a module that requires integration with multiple providers, you have two options, either to design it clean and write a generic code , that requires adding couple of configuration lines to add a new provider. Or Hire a new developer to work on this “Integration Project” . This can be the variance from just a couple of lines task to hiring developer , adding to your cash flow , expenses , taking months to accomplish the same end result.

The below Graphs will show you how unclean code impacts all business decisions :

The above chart, Uncle Bob talked about once. It simply says that, in the first of any product , you hire couple of Developers, their output and productivity are very high. The accomplish and finish a lot of features, very fast. Mean while you don’t pay them a lot , because they are only couple of developers.

By time, due to their unclean code, adding new features, fixing bugs, began to take longer time. So they became less productive by time.

As a business owner you think that its time to burn some money in order to get the productivity curve back to your expansion plans you built on the very early readings of productivity and deliverables the team did.

So you start hiring, you spend more money to hire better calibers.

At this point of time , you cash flow curve increases, while the productivity of the team actually is down than the norm, because adding new resources slows down the whole team in order to onboard the new members, inject them into the process, so the result the whole team become slower.

Then after the storming — norming, then performing phase , the whole team starts to be more productive, the curve the above the norm for a very small time, but at the end whole team performance will decrease to be norm or even below it, because of maintaining the legacy, unclean code.

The Gap between the business goals, team productivity and business expenses become higher and higher.

So Clean code can make your company survive, Design time is an important one, Thinking is 60% of the Task, so prevent your developers just hopping in writing whatever they want. Because the pain and loss is huge on the long run.
ASP.NET Web API & Angular 10 Clean Architecture
By: Fullstack Hub
Tags: Aspnetcore, Clean Architecture, Cqrs, Clean Code, Angular

I recently implemented an application using Jason Taylor Clean Architecture with a .NET Core article and thought it would be a good idea to write another article to break it down into steps so that it would be easy to follow for beginners. Obisvoulsy, there would be some differences e.g. I will be using Dapper micro ORM, repository, and unit of work design pattern instead of Entity Framework .NET Core and will use a separate database for integration testing instead of an in-memory database and also if time permits, I will add more detailed Angular unit and integration tests.

We will be developing one of my favorite applications called User Management where you would be able to add, update, delete and view the users, currently, I am going to skip user authentication, you can find it in Jason’s Github repository.

Learning Path: https://fullstackhub.io/category/learning-path/asp-net-web-api-angular-10-clean-architecture/

Github: https://github.com/fullstackhub-io/UserManagement/
Code Smell 50 — Object Keys. Primary keys, IDs, references. The…
By: Maximiliano Contieri
Tags: Code Smells, Clean Code, Software Development, Software Engineering, Programming

Primary keys, IDs, references. The first attribute we add to our objects. They don’t exist in the real world.

Photo by Maurice Williams on Unsplash

Problems

Coupling

Accidental Implementation

Bijection Principle Violation.

Solutions

Reference object to objects. Build a MAPPER. Only use keys if you need to provide an external (accidental) reference. Databases, APIs, Serializations. Use dark keys or GUIDs when possible. If you are afraid of getting a big relation graph use proxies or lazy loading. Don’t use DTOs.

Sample Code

Wrong

Right

Detection

This is a design policy.

We can enforce business objects to warn us if we define an attribute or function including the sequence id.

Tags

Accidental

Conclusion

Ids are not necessary for OOP. You reference objects (essential) and never ids (accidental).

In case you need to provide a reference out of your system’s scope (APIs, interfaces, Serializations) use dark and meaningless IDs (GUIDs).

Relations

More info
Phases of Naming
By: Sarib Mahmood
Tags: Life Lessons, Clean Code, Software Engineering, Technology, Developer

Phases of Naming

Photo by Florian Olivo on Unsplash

As a young programmer coming out of College with “no experience but abundance of enthusiasm” I was always focused on getting things done. The idea of making sure that my code was clean and readable for anyone else other than me never crossed my mind.

Clean code, a book by Robert C. Martin (Uncle Bob), was something that got started me on the journey to look back at my practices and try to better them one way or another. But one principle in particular that I’m still struggling to get better at is the Convention of Naming.

This article is not intended to provide instructions/solutions as to how one should go about Naming Conventions in code, but rather my own struggles with it. I’m not even sure whether everyone goes through this struggle when it comes to programming or was it just me. Though I would like to believe that everyone out there at some point in the career faced the same dilemma which is

What are the proper etiquettes for naming variables/functions?

Now if you go about Uncle Bob’s book, you’ll find instructions like

“Focus on whether the code reads like paragraphs and sentences, or at least tables and data structure.”

(I would suggest everyone to go read the book at least once)

What follows below is a progression of approach towards naming conventions in my career as a programmer.
Chapter 10 : Classes
Tags: Clean Code

從原文得到的說明是:

Dependency should be on abstractions not concretions

High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g., interfaces).

Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.
Code Smell 48 — Code Without Standards
By: Maximiliano Contieri
Tags: Code Smells, Clean Code, Software Development, Standards, Programming

Code Smell 48 — Code Without Standards

Working on a solo project is easy. Unless you go back to it after some months. Working with many other developers requires some agreements. Maximiliano Contieri Follow Dec 10, 2020 · 2 min read

Photo by De Jesus de Blas — Russia

Problems

Maintainability

Readability

Solutions

Automate your styles and indentation. Enforce agreed policies.

Sample Code

Wrong

Correct sample taken from Sandro Mancuso’s bank kata

Right

The right example has several other smells, but we keep it loyal to its GIT version in order to show only code standardization issues.

Detection

Linters and IDEs should test coding standards before a merge request is approved.

We can add our own naming conventions related to Objects, Classes, Interfaces, Modules etc.

Examples

Tags

Standardization

Conclusion

Use coding standards in your projects.

A well-written clean code always follows standards about naming conventions, formatting and code style.

Such standards are helpful because they make things clear and deterministic for the ones who read your code, including yourself.

Code styling should be automatic and mandatory on large organizations to enforce Collective Ownership.

Relations

More info
5 Steps to Cleaner Code
By: Chris Smith
Tags: Coding, Clean Code, Coding Style

2: Use Meaningful Names

As with the replacement of magic number, the use of meaningful names is to ensure the code is easy to understand both for the person writing it and others picking it up further down the line. This applies to variables, method names, class names and any other items that require naming within your project.

Take the two lines below, both perform the same function, however the second example is much more descriptive and reduces the need for a comment.

decimal x = 3.99m; // postage cost

decimal postageCost = 3.99m;

Here is another example, this time where the method name isn’t describing the task the method is performing. What does the name TotalCost mean? Is it retrieving, updating or doing some other task with total cost? To understand this you would need to read the code within the method. A better name would be GetTotalCost as this indicates exactly what the method is doing.

private decimal TotalCost(decimal subTotal)

{

decimal postageCost = 3.99m;

return Decimal.Add(subTotal, postageCost);

}

3: Return Early

Returning early from methods is a way of exiting when certain conditions have been met as early as possible. It helps cut down on nested conditions blocks and else statements which in turn improve the code quality/readability.

Using the GetTotalCost method, we may want to return a total cost only when the subTotal parameter is greater than 0. This first example below provides one way of performing this task, however there is a lot of code for what is required and we only return at the end of the method.

private decimal GetTotalCost(decimal subTotal)

{

decimal totalCost;

decimal postageCost = 3.99m; if (subTotal > 0)

{

totalCost = Decimal.Add(subTotal, postageCost);

}

else

{

totalCost = 0;

}



return totalCost;

}

We can refactor this the above method to return early if the condition is met or carry on if it isn’t. As you can see we have cut down on lines of code and at the same time made the method much more readable and easier to follow.

private decimal GetTotalCost(decimal subTotal)

{

decimal postageCost = 3.99m; if (subTotal > 0)

return Decimal.Add(subTotal, postageCost);



return 0;

}

This is a very simple example but I’m sure you can see the benefit especially if the code contains a greater level of nesting and if/else statements.
Clean code — Name matters. A good naming convention is one of the…
By: Marcin Worwa
Tags: Clean Code, Software Development, Technology, PHP, Programming

1. Give your names intentions

Name of class, function, variable should inform why was created, what do and how is used. If you need to add a comment above your variable you probably didn’t precise your intentions enough. Choosing the right name is a good investment so take your time. Asking your colleagues for help is a good idea. Remember you are not the only one who will be working with this code.

Bad:

public int $f_cnt; // friends count

Good:

public int $friendsCount;

Variable name f_cnt don’t inform us strictly what kind of information keeps inside. We have to guess or dig deeper into code to find the information we are looking for.

Bad:

public function process(array $u, $a = 18): array

{

$results = [];

foreach ($u as $i) {

if ($i['a'] >= $a) {

$results[] = $i['id'];

}

}



return $results;

}

As you see this code isn’t complicated. It has only one array iteration and one conditional statement but can you deduce what this code does? The problem here is not code complexity but its secretiveness. Names of variables, array keys, and function properties are hiding important information from us. Let’s see at refactored code.

Good:

public function getAdultUsersIds(array $usersList, $adultAge = 18): array

{

$adultUsersIds = [];

foreach ($usersList as $user) {

if ($user['age'] >= $adultAge) {

$adultUsersIds[] = $user['id'];

}

}



return $adultUsersIds;

}

Better immediately. We can now deduce what method does just by reading the name.
Code Smell 47 — Diagrams. Diagrams are not code. They cannot be a…
By: Maximiliano Contieri
Tags: Software Design, Code Smells, Case, Uml, Clean Code

Code Smell 47 — Diagrams

Photo by Nick Seagrave on Unsplash

Problems

Maintainability

Trash code

Code Duplication

Diagrams focus only on structure (accidental) and not behavior (essential).

Solutions

Use diagrams only to communicate ideas with other humans. Program on your favorite IDE. Thrash all diagrams. Even the ones generated from the source code. Trust your tests. They are alive and well maintained. Use Domain Driven Design technique.

Sample Code

Wrong

Right

Detection

We can remove all code annotations and forbid them by policy.

Examples

Conclusion

Designing is a contact sport. We need to prototype and learn from our running models.

Papers and JPGs don’t run. They live in the utopic world where everything works smoothly.

CASE was a very hot trend back in the 90s. No good system was developed with these tools.

Relations

More info
Code Smell 46 — Repeated Code. DRY is our mantra. Teachers tell us to…
By: Maximiliano Contieri
Tags: Code Smells, Clean Code, Software Development, Refactoring, Programming

Code Smell 46 — Repeated Code

Photo by Sid Balachandran on Unsplash

Problems

Code Duplication

Maintainability

Don’t Repeat Yourself

Solutions

Find repeated patterns (not repeated code). Create an abstraction. Parametrize abstraction calls. Use composition and never inheritance. Unit test new abstraction.

Sample Code

Wrong

Right

Detection

Linters can find repeated code.

There are not very good finding similar patterns.

Maybe soon machine learning will help us find such abstractions automatically.

For now, it is up to us, humans.

Examples

Tags

Duplication

Conclusion

Repeated code is always a smell.

Copying and pasting code is always a shame.

With our refactoring tools, we need to accept the duplication remove challenge trusting our tests as a safety net.

Relations

More info
Dependency Injection Containers in Swift — Part 2
By: Ronen Michael Harati
Tags: Dependency Injection, Decoupling, Clean Code, Swift, iOS

Dependency Injection Containers in Swift — Part 2

In the previous article Dependency Injection Containers in Swift we explored what a Dependency Injection Container(DIC) is, and how to create a simple one. In this article, we will explore how to pass parameters to the DIC.

Currently, when resolving an object from the DIC, we don’t pass any parameters, we just use the default configuration. This may be good enough for some cases, but many times we want to configure the object being resolved. Let’s take a look at an example and what issue rises when using a DIC.

ServiceThree depends on ServiceOneProtocol and some parameters. This is perfectly fine, however if we try to register this class with our DIC we won’t be able to set the parameters from the caller. Let’s see why.
Chapter 8 : Boundaries
Tags: Clean Code

有良好的軟體設計，將無須花費巨大時間投入和重寫程式碼，在使用我們控制不了的程式碼時，必須加倍小心使用，確保未來需要修改程式碼時，不用投入太多時間成本。

邊界上的程式碼需要乾淨的分離，和定義期望的測試。我們應該避免讓太多的程式碼知道第三方的細節。

It’s better to depend on something you control than on something you don’t control, lest it end up controlling you.

最好使用我們控制的程式碼，而不要讓程式碼控制我們。
Escribiendo código mantenible con el Principio de Responsibilidad Única
Tags: Solid Principles, Typescript, Español, Clean Code, Software Development

calvinespinoza/single-responsibility

Code demonstrating Single Responsibility Principle. GitHub is home to over 50 million developers working together to…
Code Smell 45 — Not Polymorphic. Methods should be interchangeable if…
By: Maximiliano Contieri
Tags: Polymorphism, Code Smells, Clean Code, Software Development, Programming

Code Smell 45 — Not Polymorphic

Problems

Missed Polymorphism

Coupling

IFs / Type check Polluting

Names coupled to types.

Favor polymorphism.

Solutions

Rename methods after what they do.

Sample Code

Wrong

Right

Detection

This is a semantic mistake. We could add a warning for similar method names on Polymorphic classes.

Tags

Polymorphic

Conclusion

Naming is very important. We need to name after concepts and not after accidental types,

Relations

More info
Implementing State Machines In Java
By: Balaji Srinivasan
Tags: Fsm, Clean Code, Enum, Java, Enumeration

What is a State Machine ?

Wikipedia defines a finite-state machine (FSM)() as:

an abstract machine that can be in exactly one of a finite number of states at any given time. The FSM can change from one state to another in response to some external inputs; the change from one state to another is called a transition. An FSM is defined by a list of its states, its initial state, and the conditions for each transition.

It is a way to program a model so that it is at one particular state at any moment.

The world is filled with state machines which we can see anywhere in our daily usage. Below are few

Road Traffic Signal Red -> Yellow -> Green

Coffee Vending Machine

E-commerce Portal Ordering

Online Trip Booking

Many Jobs

Implementing State Machines In Java

There are many ways in which we can implement state machines. In the Java world itself, we have many libraries using which we can model these states

* [Spring State Machine](https://projects.spring.io/spring-statemachine/)

* [Squirrel](https://github.com/hekailiang/squirrel)

We can also implement them using a standard `State Design pattern` [example] https://www.journaldev.com/1751/state-design-pattern-java)

What if we don’t want to add any external dependencies?

What if we want to have a simple state machine and control it via our own logic?

State Machines Using Enums in Java

Many of us would have used Uber or Ola at-least once. Let’s try implementing the trip booking state machine using Java Enums

What are the ideal states in trip booking?

Trip Booked

Driver Assigned

Driver Reached

Trip Started

Trip Ended

The above enum can be used across our application for maintaining the state of the trip. Even in a database, this can be used by using the string value of the enum. Example TripStates.TRIPCREATED.name()

Now we have implemented the state machine but how to ensure proper state transition happens. One simple way is to include a function within the enum and check it across whenever we are trying to change the state of a trip

The above function needs to be called wherever state changes need to happen. This helps in moving states in a forward manner.

But there is a problem with this. We will be able to move a trip from a trip created to a trip started. The above implementation might not solve the real constraint we would like to introduce like a trip cannot be marked as started without marking as reached.

How can we achieve this with just enum?

Java Enums can have additional fields to it. We can leverage that to solve this.

If you look we are maintaining validFromStates in order to easily expand this to other cases where a trip can end even from different states. Example: CustomerNotReachable etc..

The above is a simple implementation that can be used. But if we wanted to have more logic within these state transitions we can still leverage but we need to hook the above model with other design patterns.

Cross Posted from Personal Blog
Componentes de React: añadir CSS con código limpio
By: Eduardo Ortega Naranjo
Tags: Clean Code, CSS, Tips, React

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
React components: add CSS with clean code
By: The Agile Crafter
Tags: Clean Code, CSS, Tips, React

Read this post in Spanish here.

When it comes to designing applications with React, there are many ways to add style to components. The ones I knew so far were the following:

Import a CSS file with the necessary classes and use the JSX property “className” to add them to the component. Use the “style” property to add inline style.

The disadvantage of the first option is that you have to create an additional file to create a component and it complicates the maintenance of the code a bit. Also, you have to manually avoid class name collision between components.

On the other hand, the main drawback of the second option is that you cannot copy CSS from the browser inspector and paste it into our code, or vice versa, because the “style” property of our component receives an object and the properties of the objects cannot have the “-” character in the name, so the properties must be rewritten. Also, the property value must be quoted to convert it to text. All of this slows down development because you have to retype what you test in the browser. For example, to add the following CSS snippet to a component:

element.style {

min-height: 626px;

border: 1px solid red;

background-color: white;

}

We would have to create the following object in our code:

const style = {

minHeight: '626px',

border: '1px solid red',

backgroundColor: 'white'

};

In this post I share a clean way to style components using “styled-components”.

Styled-components is a library that creates React components with embedded styles using template literals.

Some of the advantages of this library are the following:

Creates class names automatically to avoid collisions.

Templates use CSS syntax.

Allows conditional rendering based on properties.

Adds vendor prefixes automatically.

Example of use

To install the library, you have to execute the following command (the types can be omitted if TypeScript is not used, but in this case I use it):

npm install styled-components @types/styled-components

Imagine you want to create a list of elements and that the color of each element, as well as the cursor, changes when it is clicked on.

If the library is not used, this can be achieved by writing the following code, where I use a function to get the style using the component’s state (I write it directly in the index.tsx file for simplicity):

And the result, after clicking on the “Three” element, would be the following image:

If we used the library, you could replace the style function with a component that can interpolate a CSS fragment depending on the value of the “selected” property. The resulting code is as follows:

And the result, after clicking on the “Three” element, would be the following image:

The extension “vscode-styled-components” for Visual Studio Code is very useful to work with this library, because it adds syntax highlighting for templates and allows CSS autocompletion.

References:
Notes — Clean Code : (2) Meaningful Names
By: Yi Jyun
Tags: Note, Clean Code

這邊可以歸納為概念以及 Code 兩個方面

這邊比較屬於通用的概念，不會特別針對 language 的特性做建議。

把意圖作為變數的名稱。

避免使用錯誤資訊(disinformation)去誤導別人的理解

2. 名稱與型態不符合

在定義 constant 或命名變數名稱，使用比較容易搜尋到的命名

use the name from the prob- lem domain. At least the programmer who maintains your code can ask a domain expert what it means.
Code Smell 43 — Concrete Classes Subclassified
By: Maximiliano Contieri
Tags: Software Design, Code Smells, Clean Code, Software Development, Programming

Code Smell 43 — Concrete Classes Subclassified

Problems

Bad Models

Coupling

Liskov Substitution Violation

Method overriding

Mapper fault

Solutions

Subclasses should be specializations. Refactor Hierarchies. Favor Composition. Leaf classes should be concrete. Not leaf classes should be abstract.

Sample Code

Wrong

Right

Detection

Overriding a concrete method is a clear smell. We can enforce these policies on most linters.

Abstract classes should have just a few concrete methods. We can check against a predefined threshold for offenders.

Tags

Composition

Conclusion

Accidental sub-classification is the first obvious advantage for junior developers.

More mature ones find composition opportunities instead.

Composition is dynamic, multiple, pluggable, more testable, more maintainable and less coupled than inheritance.

Only sub-classify an entity if it follows the relationships behaves like.

After sub-classing the parent class should be abstract.

Relations

More info
Code Smell 43 — Concrete Classes Subclassified
Tags: Software Design, Code Smells, Clean Code, Software Development, Programming

Inheritance. Concrete classes. Reuse. A fantastic mix up.

Problems

Solutions

Subclasses should be specializations. Refactor Hierarchies. Favor Composition. Leaf classes should be concrete. Not leaf classes should be abstract.

Sample Code

Wrong

Right

Detection

Overriding a concrete method is a clear smell. We can enforce these policies on most linters.

Abstract classes should have just a few concrete methods. We can check against a predefined threshold for offenders.

Tags

Composition

Conclusion

Accidental sub-classification is the first obvious advantage for junior developers.

More mature ones find composition opportunities instead.

Composition is dynamic, multiple, pluggable, more testable, more maintainable and less coupled than inheritance.

Only sub-classify an entity if it follows the relationships behaves like.

After sub-classing the parent class should be abstract.
Code Smell 42 — Warnings/Strict Mode Off
By: Maximiliano Contieri
Tags: Code Smells, Clean Code, Software Development, Software Engineering, Programming

Code Smell 42 — Warnings/Strict Mode Off

Photo by Noah Dominic Silvio on Unsplash

Problems

Missed Errors

Ripple Effect

Fail Fast

Solutions

Enable all warnings Enable preconditions and assertions in production. Fail fast Design by contract

Sample Code

Wrong

Right

Detection

Most languages have warning levels. We should turn most of them ON.

We should run linters to statically analyze our code for potential problems.

Tags

Fail Fast

Conclusion

If we ignore warnings and code moves on sooner or later it will fail.

If the software fails later it will be very difficult for us to find root cause.

Defect will likely be near first warning and far away from the crash.

If we follow the Broken Windows Theory, we should not tolerate any warnings, so a new issue will not pass unnoticed on a sea of tolerated warnings.

Relations

More info
Chapter 3: Functions | 函式
Tags: Clean Code

Funcitons should do one thing. They should do it well. They should do it only.
3 Organization Tips For Your Spaghetti Code
By: Li-Hsuan Lung
Tags: Self Improvement, Konmari, Clean Code, Refactoring, Programming

The life-changing magic of tidying up legacy code.

Photo by Sheila Joy on Unsplash

Do you have a junk drawer at home? You know, the one where you store all the miscellaneous and occasionally useful objects. When you open the drawer, you see multiple sets of scissors, safety pins, thumbtacks, rubber bands, receipts, spare changes, and batteries you keep buying in case of a blackout.

If you are not organized, you likely have a junk drawer in your codebase, too.

It starts with a couple of one-off and uncategorized functions. You are unsure where these functions should go, so you dump them in a folder named utils or helpers. You could never find what you need in these folders, so you end up implementing the same functions over and over again. Eventually, your folder of junks turns into this huge ball of mess that takes over your entire project.

Fear not — Marie Kondo is here to tidy up your spaghetti code with her positive attitude and organizing tips.

Discard with Gratitude

Before organizing your junk folder, search and delete any unused code. Unused code takes up mental space and will distract you when you start shuffling things around.

Use an automated tool like Vulture or the Coverage tab in Chrome’s DevTools to help you detect unused code more efficiently. Build a robust test suite with good code coverage if you want to feel confident when you hit the backspace key.

Celebrate the code you are about to delete for having fulfilled their purpose. Appreciate their authors for moving the project forward at one point. However, now is time for the unused code to depart from your codebase and recede into the shadow of your version control history.

Tidy by Category — Not by Location

When you walk into a house and find dirty laundry lying around in every room, Marie Kondo would advise you to gather them in one big pile first instead of trying to organize them room by room.

Photo by NordWood Themes on Unsplash

Similarly, when you open a project and find string format methods littered around the codebase — move them to one location. You will be able to spot any duplicated code or reusable pattern more quickly.

You can organize your classes and functions by the categories presented in the Clean Architecture. Start with an easy category to warm up your refactoring muscles, and tackle one category at a time. Feel free to create your own categories, but otherwise, this is the order I recommend:

Presenters

Controllers

Services

Use Cases

Adapters

Give Everything A Home

Spaghetti code is caused by the fact that they do not belong anywhere. Give them a home, and they will start falling into place like puzzle pieces. A hallmark of Marie Kondo’s method is to store items vertically. She uses dividers, clear containers, and even folds clothes vertically to increase their visibility.

Photo by Gareth Hubbard on Unsplash

As you carve out a new home for your code, spend a few extra minutes on coming up with a plain and easy-to-understand name, and pay attention to the overall cohesion.

Ask yourself:
Angular SonarQube Integration
By: Mete Demirtas
Tags: Test, Angular, Sonarqube, Clean Code

Install SonarQube

You can either download sonarqube zip package on website or use sonarqube docker image.

On Webiste download link :

Extract file and run ‘startsonar.bat’. You can see that, works on http://localhost:9000

Following two commands you can run SonarQube on Docker :

docker pull sonarqube docker run -d --name sonarqube -p 9000:9000 -p 9092:9092 sonarqube

Now, you can browse to http://localhost:9000, and you’ll be looking at the SonarQube Web GUI.

If system ask username and password, both are ‘admin’
Code Smell 41 — Regular Expression Abusers
By: Maximiliano Contieri
Tags: Code Smells, Clean Code, Software Development, Software Engineering, Programming

Code Smell 41 — Regular Expression Abusers

Photo by John Jennings on Unsplash

Problems

Readability

Maintainability

Testability

Intention Revealing

Solutions

Use regular expression just for string validation. If you need to manipulate objects, don’t make them strings.

Sample Code

Wrong

Right

Detection

Regular expressions are a valid tool. There’s not much automated way of checking for possible abusers. A whitelist might be of help.

Tags

Primitive Obsession

Abusers

Conclusion

Regular expressions are a great tool for string validation. We must use them in a declarative way and just for strings.

Names are very important to understand pattern meanings.

If we need to manipulate objects or hierarchies, we should do it in an object way.

Unless we have a conclusive benchmark of impressive performance improvement.

Relations

More info
Maven Project SonarQube Integration
By: Mete Demirtas
Tags: Sonarqube, Maven, Clean Code, Angular, Java

Install SonarQube

You can either download sonarqube zip package on website or use sonarqube docker image.

On Webiste download link :

Extract file and run ‘startsonar.bat’. You can see that, works on http://localhost:9000

Following two commands you can run SonarQube on Docker :

docker pull sonarqube docker run -d --name sonarqube -p 9000:9000 -p 9092:9092 sonarqube

Now, you can browse to http://localhost:9000, and you’ll be looking at the SonarQube Web GUI.

If system ask username and password, both are ‘admin’
Code Smell 40 — DTOs. DTOs are widely used and the ‘solve’…
By: Maximiliano Contieri
Tags: Code Smells, Anemic, Dto, Clean Code, Programming

Code Smell 40 — DTOs

Problems

Anemic Object

Inconsistent Data

Duplicated logic

Duplicated structure

Class Polluting

Information Hiding Violation

Code repeated among mutators, accessors, serializers, parsers

Ripple Effect

Data integrity

Solutions

Transfer anemic data on arrays. Use real business objects. If we want to transfer partial objects: use proxies or null objects to break the reference graph.

Sample Code

Wrong

Right

Detection

We can use the same anemic object detectors.

We can check for anemic classes with no business object behavior (removing serializes, constructors, mutators etc).

Tags

Anemic

Conclusion

DTOs are a tool and an established practice in some languages. We should use them with care and responsibility.

If we need to disassemble our objects in order to send them away from our realms, we need to be extremely cautioned. Since dismembered objects have no integrity considerations.

His author warns us about its actual abuse.

Relations

More info
“It is heasier to recognize ugly, than to recognize beauty in code” , according to Bjarne Strousrup (inventor of C++)
By: Michael Manga
Tags: Clean Code, Code, Programming

While invented to talk on the podcast of Lex Fridman ,

Bjarne Strousrup presented the idea that “it is heasier to recognize ugly from beauty , in code”.

He develops this idea by explainging that “sometimes, beauty comes from something that is innovative and unusual , and that you sometimes need to think reasonably hard to recognize that”.

However, he believes that bad code can be quite easily identified , with experience :

“On the other hand, Messes have things in common. You can catch a lot of sloppiness mecanically.”

“I think we will see much more static annalysis in the comming decade” -Bjarne Stroustrup

He concludes this argumentation by explaining, that for that use, he is a “great fan” of statitic analysis, allowing to “not only check for the language rules, but for the usage of language rules.”

He offers a brief definition of what is static annalysis to him :

Static analysis is about “representing a piece of code, so that you can write a program that go over that representation, and look for things that are right and not right”.
Code Smell 39 — new Date(). 70s first tutorial: getCurrentDate()…
By: Maximiliano Contieri
Tags: Code Smells, Clean Code, Software, Refactoring, Programming

Code Smell 39 — new Date()

Problems

Coupling

Fragile Tests

Timezone Problems

Solutions

Use Dependency injection to decouple time source.

Sample Code

Wrong

Right

Detection

We should forbid global functions policies. We need to couple to accidental and pluggable time sources.

Conclusion

Date.today() , Time.now() , and other global system calls are coupling smell.

Since tests must be in full environmental control. We should easily set up time, moved it back and forth etc.

Date and Time classes should only create immutable instances. It is not their responsibility to give the actual time. This violates Single Responsibility Principle.

The passage of time is always scorned by programmers. This makes objects mutable and designs poor and coupled.

Relations

More info

Tags