4 questions to ask in interviews to assess codebase health

We all love good, quality code – and if we don’t, we should. Code that is consistent, clean, and easy to understand is essential to a healthy codebase. A healthy codebase is one that’s optimized for testability, maintainability, and scalability. It helps programmers code more efficiently and makes engineering teams more productive.

The health of a company’s codebase plays a large role in employee satisfaction. Unfortunately, the pressure to quickly add new features imposes harsh deadlines on programmers. The trade-off is a decrease in code quality. This is the reality of the software development world. We can expect a level of imperfection in any company’s codebase, but the important thing is how responsible a company is about resolving or preventing the damage that results from pushing rapid development.

When interviewing to find a developer job you love, there are questions you can ask to get a sense of their codebase health. By asking these questions, you can feel more confident about your interest in the company and the long-term sustainability of your work there.

We’ll cover:



Nursing healthy code and managing technical debt

To help foster a healthy codebase, companies need to have a regular cadence and strategy with which they manage technical debt. Technical debt refers to the time, money, and resources that are lost in exchange for hasty development. This can consist of code debt, design debt, and documentation debt. By asking their engineering teams to churn out functionalities at a rapid pace, any company can expect to incur technical debt. What’s important is that companies take measures to prevent and pay it off.

A developer-centric company must prioritize managing technical debt, not only for their financial gain but for employee satisfaction and retention as well. An unhealthy codebase is a thorn in the side of many programmers and software engineers. In a 2021 study by Stepsize, 51% of developers confirmed that they had left or considered leaving a company because of technical debt.



4 questions to ask in interviews to assess codebase health

There are questions you can ask in your interview to get a sense for the health of the company’s codebase. Many companies have room for improvement, and these answers don’t have to make or break your decision. While they may not have all the best practices in place, many interviewers would be impressed to have a candidate who is concerned and knowledgeable about matters concerning technical debt.

Note: Be mindful of your tone when asking questions. Come from a place of curiosity rather than judgment. You never know where a company or startup is in their growth.



1. What is your strategy for dealing with technical debt?

This is a high-level question that can give you a sense for how robust a company’s strategy is for managing technical debt. At the very least, your interviewer’s answer shouldn’t deny that their company incurs technical debt. At most, it should show that that leadership balances adding new features with repaying technical debt. We hope you’ll hear a well-rounded strategy ranging from code reviews to communication pipelines and incentivizing programmers to clear debt.



2. Do you conduct code reviews?

Despite being a best practice for maintaining code quality and scalability, not every company conducts code reviews. We hope you’ll hear a yes. Code reviews reduce bugs, facilitate optimization, and helps peers share knowledge and skills.

If they conduct code reviews, you can ask additional questions:

  • What does your approach look like? Some do formal line-by-line reviews, others do informal “check-in buddies,” while others leverage Git to do a code review for all pull requests. It’s worth clarifying if they review code for all projects, as some only prioritize the most “critical” ones.
  • How are priorities determined? Ideally, the code review’s priorities are informed by a knowledge of the technical debt they’ve recently incurred. The best code reviews will prioritize code quality and coding best practices such as commenting, rather than simple adherence to company or team coding standards.
  • Who is reviewing the code? Gold stars can be given if code is given a most objective review by peers who aren’t involved in the project. If not, that’s okay too. Again, we have an ideal world, and a realistic one.



3. Do you have CI/CD pipelines?

Not all companies have CI/CD pipelines, but the most successful software development companies do. In a perfect world, CI/CD pipelines should be consistent across all projects and tech stacks. CI/CD pipelines helps teams ship new features faster, increases visibility and collaboration, and helps ensure continuous reliability. A CI/CD pipeline automates CI/CD, which frees up developers’ time to focus on, well, development.



4. How much time is spent refactoring code?

Refactoring code reduces code complexity and supports the maintainability, security, and scalability of an application. Refactoring is an ongoing part of the development process. In addition to writing and testing, refactoring is likely to take a good amount of your time. Ask this question to get a sense for how frequently it’s done and how it’s built into the development process.



Wrapping up and next steps

The better the code health of a company, the more productive you and your team members will be. How a company balances adding new features with managing technical debt will be crucial to fostering a healthy codebase. It allows for effective long-term development – and happier and more productive engineering teams.

To help developers level up in their careers, we’ve gathered all our interview prep resources in one place at Interview Prep with Educative. You can find company-specific interview guides, coding interview tutorials, advice from industry experts and more.

Happy learning!



Continue learning about interview prep



Start a discussion

What questions would you ask to get a feel for a company’s codebase health? How have your employers managed technical debt? Let us know in the comments below!


Source link

Thumb Rules of Unit Testing

My ideas on writing meaningful unit tests were crystallized when I read “The Practical Test Pyramid” today.

As a novice programmer, I went in mindlessly, not knowing how to test my code.

The Practical Test Pyramid is an excellent guide, but I want to emphasize unit testing today.



Why Write Unit Tests?

As the name suggests – you test a “unit” of your code.

Unit tests are beneficial in ensuring the code works as intended – it is the first step towards being confident about the logic.

Unit tests have the narrowest scope of all the tests in your test suite.

A service accesses a database to perform a set of computations; the unit tests will cover all edge cases for the performed computations. The access to the database is “assumed”.



How to Write Good Unit Tests?



Cover Non-Trivial Cases

Test for all edge cases in the code.

Typically, you won’t test if input deserialization works unless you’ve written the library itself.

When it comes to unit testing, aim for confidence coverage and not code coverage.



Test for Observable Behavior

Loosely couple tests and code. Refactoring code is a common practice, but refactoring unit tests is stressful.

Unit tests should always answer two questions –

What is the input?
Is the output expected?



Structure

Tests, like your code, should be easy to read and understand.

Most supporters of TDD derive code from tests. Hence, a readable structure goes a long way in translating behaviour into code.

Use “Given, When, Then”

  • Given an input X
  • When function Y executes
  • Then the outcome is Z

Ensure you maintain a delicate balance between DRY(Don’t Repeat Yourself) and DAMP(Descriptive and Meaningful Phrases).

Read more about why repetition is acceptable in tests.



TestDoubles

We can use various TestDoubles to replace production objects for testing purposes.

  • Use stubs in cases where branching logic doesn’t matter.
    We don’t care if the database write fails.
  • Use mocks when the order and the output matter.
    We care if the database write fails the second time.

More at Mocks aren’t Stubs.

Let me know how you write unit tests in the comments!


Source link

1 line of code: How to convert tabs to spaces

const tabsToSpaces = (str, tabsize = 4) => str.replaceAll("t", " ".repeat(tabsize));

Returns the string and replaces a series of spaces (tab size) with a tab.



The repository & npm package

You can find the all the utility functions from this series at github.com/martinkr/onelinecode
The library is also published to npm as @onelinecode for your convenience.

The code and the npm package will be updated every time I publish a new article.

Follow me on Twitter: @martinkr and consider to buy me a coffee

Photo by zoo_monkey on Unsplash

Subscribe to the weekly modern frontend development newsletter




Source link

Write Better Python Code



Introduction

This article has the collection python coding practices that I have learned over last few months for writing more idiomatic python code.



1. Multiple Assignment

Initialise same value for different variables.

# Instead of this
x = 10
y = 10
z = 10

# Use this
x = y = z = 10



2. Variable Unpacking

x, y = [1, 2]
# x = 1, y = 2

x, *y = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4, 5]

x, *y, z = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4], z = 5



3. Swapping Variables

# Instead of this
temp = x
x = y
y = temp

# Use this
x, y = y, x



4. Name Casing

In python snake_case is preferred over camelCase for variables and functions names.

# Instead of this
def isEven(num):
    pass

# Use this
def is_even(num):
    pass



5. Conditional Expressions

# Instead of this
def is_even(num):
    if num % 2 == 0:
        print("Even")
    else:
        print("Odd")

# Use this
def is_even(num):
    print("Even") if num % 2 == 0 else print("Odd")

# Or this
def is_even(num):
    print("Even" if num % 2 == 0 else "Odd")



6. String Formatting

name = "Dumbledore"
item = "Socks"

# Instead of this
print("%s likes %s." %(name, item))

# Or this
print(" likes ".format(name, item))

# Use this
print(f"name likes item.")



7. Comparison Operator

# Instead of this
if 0 < x and x < 1000:
    print("x is a 3 digit number")

# Use this
if 0 < x < 1000:
    print("x is a 3 digit number")



8. Iterating over a list or tuple

We don’t need to use indices to access list elements. Instead we can do this.

collection = [1, 2, 3, 4, 5, 6]

# Instead of this
for i in range(len(collection)):
    print(collection[i])

# Use this
for number in collection:
    print(number)

# Both of these yields the same output



9. Using enumerate()

When you need both indices and values, we can use enumerate().

names = ['Harry', 'Ron', 'Hermione', 'Ginny', 'Neville']

for index, value in enumerate(names):
    print(index, value)



10. Using Set for searching

Searching in a set is faster(O(1)) compared to list(O(n)).

# Instead of this 
l = ['a', 'e', 'i', 'o', 'u']

def is_vowel(char):
    if char in l:
        print("Vowel")

# Use this
s = 'a', 'e', 'i', 'o', 'u']

def is_vowel(char):
    if char in s:
        print("Vowel")



11. List comprehension

Consider the following program to multiply the elements of the list into 2 if they are even.

arr = [1, 2, 3, 4, 5, 6]
res = []

# Instead of this
for num in arr:
    if num % 2 == 0:
        res.append(num * 2)
    else:
        res.append(num)

# Use this
res = [(num * 2 if num % 2 == 0 else num) for num in arr]



12. Iterating Dictionary

Using dict.items() to iterate through a dictionary.

roll_name = 
    315: "Dharan",
    705: "Priya"


# Instead of this
for key in roll_name:
    print(key, roll_name[key])

# Do this
for key, value in roll_name.items():
    print(key, value)



Sources


Source link

Why is Technical Debt Bad?



What Is Technical Debt?

There are many ways to define technical debt, but to put it into simple words, it’s the interest you have to pay when you choose the effortless short-ranged development choice instead of the challenging and elaborate one. Typically, this debt arises from using code that works perfectly fine for a short period of time but causes trouble in the long run. These kinds of quick and easy decisions lead to the cost of reworking the code in your program, leading to technical debt.



Causes Of Technical Debt

There are various reasons you can fall into the spiral of technical debt, the most common one amongst them being the lack of attention to long-term planning. Developers pay more attention to getting the software on the market rather than its long-term wearability. Often, creators can make the simple mistake of overseeing a harmful code which then results in technical issues. Similar to this, a faulty code or an easier one can also cause run time errors later. These practices later pile up in the form of technical debt, which not only deteriorates the quality of the product but can also cause delays in its delivery.



Why Is Technical Debt Bad?

Although technical debt works pretty well for some time, it causes trouble both to the software and the developer if not paid off within due time. Even if you do put up your software on the market, by having technical debt, the developer may be unable to keep the system up to date and may start getting complaints about its faulty nature. If this problem is not paid attention to at the right time, then the software may get signals of system failure. Moreover, the developer will have to spend more time solving this problem rather than working on updates.

This also causes a lot of issues in the team that is working on the software as well as the software itself because you have to make sure that the old interface and the new updated interfaces work together seamlessly. Even the slightest mistake may affect the workability of the software. Technical debt might seem like an easy solution in the initial developmental stages of a software, but it is very troublesome to both the creators and the clients after a short while.



Tips And Tricks To Avoid Technical Debt

There are several strategies that you can use to avoid technical debt. Some of these are listed below.



Fixing code

The real reason behind technical debt is a weak code which can be fixed even after the damage. The faster you fix your code and find a good alternative for it, the better your software will advance according to the needs of your customers. If you don’t fix the code when you come to know about it, it may not work properly and will bound developers to work on old iterations rather than new ones.



Focusing on the code quality

When creating a software, it’s important to focus on the structural integrity and code quality. It is important to give your time to each part of the project properly and finding things that will make it work even more smoothly. Instead of one person working on the project, a team with different perspectives can help develop a software even better.



Paying off your debt

It is imperitive to pay off your debt in a timely manner as it can cause a lot of problems in the future for the users. It is necessary for you and your team to work and fix the code so that it does not cause any more trouble than it already has. You should set a maximum threshold for the debt you can afford. Once it crosses that level, you should work on paying it off first.



Is All Technical Debt Bad?

Surprisingly not all technical debt is bad. Just like a financial loan, a technical debt can help in reaching your goals faster. However, if you don’t plan to deal with the debt later, you might run into some problems. If you fail to address the debt when it is required to be, then it might come in the way of innovation and advancements that you may want to make in the software.

Like everything else in this world, technical debt also has its pros and cons. It may help you to get your software on the market faster, but at the same time, it may cause trouble if you don’t take care of it on time. Therefore, it is best to start with a code that would do good in the long run. Even if you do manage to fix the code later, you still have to spend time in paying off the technical debt. So, it is best to start with a code that is beneficial to you and the software.



How To Reduce Technical Debt?

There are many ways through which you can avoid technical debts. Treating this debt like any other loan is the best approach for reducing it. You can set up upper limits for the tax debt you can afford. Similarly, you can also set deadlines for paying it off. This way, there is no excessive pile up of technical debt, and you can stay in control of the quality of your software. Overall, realistically, technical debt can never be zero, however, you should be able to manage it efficiently to guarantee the smooth running of your software.


Source link

Pizza flavoured Strategy pattern

Strategy pattern is a design pattern that allows you to define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.

This is useful when you have a large number of similar algorithms and you want to use them in different ways. It is one of the most common design patterns and is simple to understand and implement.

Strategy pattern is closely related to the Factory pattern – the main difference is that Factory pattern is more useful for deciding the implementation at runtime whereas Strategy pattern is more useful for deciding the implementation while designing the application.

Let’s start with some terminology.

  1. Strategy – A strategy is an interface which defines a family of algorithms.
  2. Context – A context is an object that uses a strategy to perform an operation.
  3. Concrete Strategy – A concrete strategy is a class that implements an algorithm.
  4. Client – A client is a class that tells the Context which strategy to use.



A real world example

Let’s think about an example of this in the real world. It is as simple as ordering a pizza.

  • We have an oven which can cook a pizza. Consider it a context.
  • The pizza is an abstraction. There can be many type of pizzas. So it is a strategy.
  • The actual pizza that a customer selects is a concrete strategy.
  • When the customer(the client) orders a specific pizza, the contents of the actual pizza are put into the oven, the oven starts to cook and the pizza is ready.



Let’s code this up



The Strategy

Let’s create a pizza interface.

public interface Pizza 
    void prepare();



The Concrete Strategy

Let’s create multiple concrete strategies.

Our first strategy is a NY Style pizza.

public class NYStyleCheesePizza implements Pizza 
    @Override
    public void prepare() 
        System.out.println("Preparing NY Style Sauce and Cheese Pizza");
    

The other is a Pineapple pizza.

public class PineapplePizza implements Pizza 
    @Override
    public void prepare() 
        System.out.println("Preparing Pineapple Pizza even though it is not a real pizza");
    



The Context

Let’s create a context class for our Oven.

public class Oven 
    private Pizza pizza;
    public Oven(Pizza pizza) 
        this.pizza = pizza;
    
    public void bake() 
        pizza.prepare();
    



The Client

Now, let’s create a client class.

public class Client 
    public static void main(String[] args) 
        Oven oven = new Oven(new NYStyleCheesePizza());
        oven.bake();
    

Considering the customer orders a NY Style pizza, the oven will start to cook the NY Style pizza.



Advantages of using Strategy Pattern

  1. Flexible context – You can change the strategy at runtime or even at design time but the context code doesnt have to change.
  2. Easy to extend – You can add more strategies without having to change the context code.
  3. Easier to test – You can test the code easily. All you have to do is pass in a mock strategy object to the context.

Strategy pattern is something you might be using already without even knowing it. It is intuitive and easy to understand.

If we talk about modern Java, the most popular occurrence of Strategy pattern is through Spring Qualifiers

Thanks for reading! This should help you understand the concept of strategy pattern. Stay tuned for more design patterns.
If you want to connect with me, you can find me on Twitter @abh1navv




Source link

4 Ways To Be Constantly Improving Your Code

A Follow Helps Everyone

No Really if you follow now, more and better quality content will be published. Also follow medium so you don’t miss out.
See more amazing content here: https://theoverpoweredpc.medium.com
Not much of world’s population is made up of programmers. In fact, only 22.1% of the population are programmers. This might make you think, “How is that possible? How can there be so little programmers but so many programs and apps?,” well at least it got me thinking. If there are so little programmers what could 1 programmer do to make their code be like a team of 100 programmers. There are 4 simple ways to easily improve your code.

  1. Stay Organized

There is no way to describe how important keeping your code in an organized manner is. The organization of your code will give you a much more readable piece of software and it will also be a lot easier to fix bugs and or improve performance. Not only will it be easier to read but it will also be easier to spot out something that seems of or unwanted. When you have more organized code people are more willing to pitch in some ideas too because they will be able to understand what is going on and be able to help if they want to.

Keeping your code organized will also improve the development of your program because it will be easier to find things to edit, add, remove, change, etc. I am not just talking about the code but also the files and the directory’s because that will also help you out when you are trying to find a script that is external that you need to link to your current script.

  1. Read Documentation

I know that reading documentation may not be the funnest thing to do but it can really help you out with a problem or struggle. Say you are trying to connect to a database for say Mongo DB, you are not going to know how to do it instantly by heart. You need to learn how to use the SDK and how to integrate it into your code for your program to work. It also really helps you out when you need help with something for say a tutorial, in our case, on how to connect to Mongo DB and read and write data to it.

  1. Stack Overflow

This may sound ridiculous, but it is not. Stack overflow is a site where people can share information on software and programs of all kinds, and you can also ask a question about a problem that you have and get an answer speedy fast. It may also seem like people do not know what they are doing there but plenty of people out there that got their jobs on stack overflow.

  1. Tools

Using simple tools to help your code is another fantastic way to improve your code. The tools that are out there can help you find and solve bugs, organize, script, lower lines of code for better performance, etc. Tools are also another wonderful way to find some code library’s that you may have never heard of before. For example, the site replit they have a smart code ide which I consider a tool that helped me out and I discovered jQuery and I accessed a whole new level of programming.
Find the article also on my medium site: https://theoverpoweredpc.medium.com/4-ways-to-be-constantly-improving-your-code-f5b05ddac433


Source link

When are microservices appropriate?

Lately, I’ve been tending to lean more towards employing a monolithic approach in system architecture. On paper, using micro-services seems like an ideal solution. The fact that you can decouple a project into smaller manageable bits is good. However, from experience and a couple of blog posts and videos I’ve watched, they do introduce a lot of complexities. Just to mention a few would be; giving database access to a microservice poses major security risks if not properly implemented, error handling, and especially if the said microservice is down would essentially make the system fail, connection error, read timeout, resource not found…you have to deal with many error scenarios.

I’m not completely against them, for example I believe a microservice should do one thing and do it really well. A good example would be sending sms notifications. This wouldn’t really need to interact with any database. Just accept a list of phone numbers and send out the messages.

So my question is; when are my microservices appropriate and do we really need them as much as folks preach?


Source link

Why Has React Js Become So Popular Among Specialists?

React Js is a popular open-source JavaScript library that allows you to create stunning web apps with little effort and coding. React Js’ main goal is to create engaging User Interfaces (UI) while also increasing the speed of apps. A Facebook giant of social media has discovered the React Js programming language for the developer to make the tasks easy. Furthermore, React Js can use Node to render on the server. Developers can also use React Native to create native apps. So, to develop your web application, get in touch with the React Js web development company who will help you in the growth of your business.

The flexibility of the React Js comes from the fact that it uses single components, allowing the developer to break down complex UI components into smaller pieces. React Js is honored to be affiliated with top-tier companies such as Yahoo, BBC, Instagram, Netflix, PayPal, and many more. Perhaps to build similar web applications for your brand, you will need to hire React js developer who is expertise in the specific industry.

Boon of React Js for the Web Development Process

According to the statistics, the United States is the most prevalent use of React js followed by other developed countries like Russia, China, the United Kingdom, and Japan. It depicts that most people are using React Js for their websites. React Js is a feasible option for professionals who are trying to find a simple programming language beyond Angular.

When the specialists were working with the other frameworks, they were obliged to do a lot of sophisticated coding when creating individual comments. React Js has fixed a lot of this problem, thanks to Facebook. The developers also have the option of reusing the code that speeds up the project execution. However, we have mentioned the traits of the React Js.

Easier to make adaptive Web applications with React Js

With the help of the React js web development company, you can get your dynamic online application. In fact, we know that it is awkward to develop an app with HTML strings and a difficult task that necessitates extensive coding. So, with React Js the problem is solved. React Js uses JSX syntax that further allows HTML quotes and HTML tag syntax to render the subcomponents. Moreover, it allows the mixing of the various components into a single time variable file.

Professionals can reuse the components

Reusing the components is a significant asset for web application development developers. The developer can repurpose the elements used to create other applications with the same functionality. Otherwise, you can hire react js developer to build an application with all the functionalities. It will not only save the efforts but also the time consumption to complete the project.

However, the react js involves less coding so, there are fewer chances of getting errors. Furthermore, it will enhance the speed of the application and will get more customer retention.

Easy to learn

With the inception of the React Js, it is definitely a plus point for the developers. If you are new to this field and want to learn about the development process, then we think React Js is the one that is very easy to grasp as compared to the other frameworks. Once you start using the React Js, you will become familiar with the features and easily develop web applications. Otherwise, you can approach React Js web development company to get your web application developed in the ReactJs framework.

However, it is not full-featured but, it is an open-source javascript script library with which you can easily execute every task. With the help of reactjs, you can easily build a high-responsive web application in a short period.

Growth of Community

Over time, the community of React js has grown widely and making it easier for novice developers to find a library for any task. The developer does not have to build on their own. Moreover, if you want to develop apps with React js and find problems, You can get extended support from Facebook.

Use of Practical Tools

Although, react js has earned a great reputation for having a useful collection of tools that makes the job of the developers easier. However, you will find React developer tools as a chrome developer add-on. You can easily examine the reactive component hierarchies along with the components of the present state and props.

Wind-Up

React Js has become so popular that it allows developers to create extremely engaging web apps and user interfaces in a short period. Also, it enables the specialist to reuse the components and build SPA with less coding. Hence, you can contact React js web development company to create large-scale web apps. By collaborating with a leading agency, you can hire Reactjs developers to establish your full-featured web application at a very cost-effective price.


Source link

Favor values over variables

Favoring values over variables makes code easier to read, write, and maintain.

A variable is a container for a value. Over time, you put new values in the container, overwriting the old. For example in TypeScript:

interface Todo 
    title: string;
    completed: boolean;
    importance: number;


function getRankedIncompleteTodos(allTodos: Todo[], pinnedTodos: Todo[]): Todo[] 
    const result = []; // 1. result = Empty array

    for (let todo of allTodos) 
        if (!todo.completed) 
            result.push(todo);
        
    
    // 2. result = An array of incomplete todos

    // sort by importance
    result.sort((a, b) => 
        if (a.importance < b.importance) 
            return 1;
        
        if (a.importance > b.importance) 
            return -1;
        
        return 0;
    );
    // 3. result = A sorted array of incomplete todos

    // pinned TODOs always at top
    for (let todo of pinnedTodos) 
        result.unshift(todo);
    
    // 4. result = An array of pinned todos followed by sorted incomplete todos

    return result;

Here result contains different values at different points in time. The sequence of values goes like this:

  1. Empty array
  2. An array of incomplete todos
  3. A sorted array of incomplete todos
  4. An array of pinned todos followed by sorted incomplete todos

For this sequence of values we have given a single label, result. To understand what result contains at a line of code, we have to trace through the code up to that point. In other words, we have to include the dimension of time in our understanding.

A variable acts like a sequence of values through time. That sequence can get complex and hard to predict, modulated by conditionals, loops, side effects, and other nested contexts.

Here’s the code refactored to favor values over variables:

import orderBy from "lodash";

function getRankedIncompleteTodos(allTodos: Todo[], pinnedTodos: Todo[]): Todo[] 
    const incompleteMatchingTodos = allTodos.filter(todo => !todo.completed);
    const sortedTodos = orderBy(incompleteMatchingTodos, todo => todo.importance, "desc");
    return [...pinnedTodos, ...sortedTodos];

In this code, I’ve given intermediate values their own descriptive labels. Each label stands for a single value and doesn’t change. So to understand what incompleteMatchingTodos or sortedTodos contains at a line, we need only look at their declarations. We don’t need to take time into account. It reduces cognitive burden.

Which would you rather read, write, and maintain? Take some code written with variables and convert it to values. See the difference for yourself. Then multiply the difference over a whole codebase.

This rule of thumb applies across many (imperative) programming languages. And some languages have ways of (partially) enforcing it. In JavaScript we would say “favor const over let.” In Java, “use final for local variables and parameters”. In functional languages, immutability is enforced by default 😎.

As usual, a rule of thumb has exceptions. In my experience, the majority of code in mainstream, high-level languages benefits from favoring values over variables. But I don’t argue for trying to shoehorn it. Sometimes performance-sensitive/low-level/library code fits variables better, or if you’re writing some unusual imperative algorithm. Most of the time though, especially in web apps and CRUD, we’re just taking some data, map/filter/reducing it in some way, and shuffling it on to the next step.


Source link