3

Not So Stupid Question 329 What Are Explaining Variables

 2 months ago
source link: https://www.irisclasson.com/2024/02/23/not-so-stupid-question-329-what-are-explaining-variables/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Not So Stupid Question 329 What Are Explaining Variables

I find it quite amusing that one of the hardest things in programming is naming, what like the same time we seem to have a name for everything in terms of design patterns, methodologies, and so on. I honestly don’t mind as it makes it easier to communicate intent. today I came across the term I haven’t heard before for something that I use quite often.

Explaining Variables Refactoring

“Explaining Variables Refactoring” is a programming technique used to make code more readable and it’s probably something you’ve used before. As the name in implies, it means you introduce a new variable with a descriptive name to hold the result of a complex expression or condition. This technique is particularly useful in cases where the expression or condition is hard to understand at first glance. And to be honest, I used to use these a whole lot more a few years back, but I overdid it and it just cluttered the code. See some good and bad examples below.

Here is an example:

var maxAmount = 50;
if (order.getTotal() - order.getDiscounts() + shipping.cost() > 50)

// Refactored to:

var baseOrderAmount = order.getTotal() - order.getDiscounts()
var totalAmount = baseOrderAmount + shipping.cost()
if (totalAmount > maxAmount)

// Or:
Var totalAmount = order.getTotal() - order.getDiscounts() + shipping.cost()
if (totalAmount > maxAmount)

I prefer the latter :)

Bad usage/ unnecessary (in my opinion):

var amountOverMax = totalAmount > maxAmount
if (amountOverMax)

Comments

Leave a comment (via email)

Last modified on 2024-02-23


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK