Is this bad coding practice? I feel like there is repetition and redundancy [closed]

2 days ago 2
ARTICLE AD BOX

Bear in mind that DRY is a guideline, not some absolute rule you must follow. Aim for correctness, simplicity, readability, self-documentation, and maintainability of code. Following DRY is only useful to the extent that it helps meet those aims.

There is no virtue in encoded function names like CtoF - there are many possible things that C or F could be, and no need to force someone reading your code to resort to guesswork (or to read through comments or other documentation to work our what they are).

Be explicit, and do CelciusToFahrenheit. Readability for someone coming later (and maintaining the code) trumps the initial saving of typing. And the code should be self-documenting - minimise (ideally eliminate) any need for comments to explain any of it (e.g. the meaning of CtoF).

In this case, I would do something like

const double MultiplierCelciusToFahrenheit = 1.8; const double ShiftCelciusToFahrenheit = 32.0 const double ShiftCelciusToKelvin = -273.15; double CelsiusToFahrenheit(double celcius) { return celcius * MultiplierCelciusToFahrenheit + ShiftCelciusToFahrenheit; } double FahrenheitToCelcius{double fahrenheit) { return (fahrenheit - ShiftCelciusToFahrenheit) / MultiplierCelciusToFahrenheit; } double CelciusToKelvin(double celcius) { return celcius + ShiftCelciusToKelvin; } double KelvinToCelcius(double kelvin) { return kelvin - ShiftCelciusToKelvin; } double FahrenheitToKelvin(double fahrenheit) { return CelciusToKelvin(FahrenheitToCelcius(fahrenheit)); } double KelvinToFahrenheit(double kelvin) { return CelciusToFahrenheit(KelvinToCelcius(kelvin)); }

Notes

The functions only have one argument, not two. If converting a celcius temperature c to fahrenheit, do f = CelciusToFahrenheit(c). No need to pass a second argument (in fact, passing a second argument would be a diagnosable error).

No repeated or replicated magic numbers. There are named constants instead. This reduces potential concerns due to typos (e.g. typing 18 by accident somewhere rather than 1.8.

All the caller needs visibility of is declarations of the functions. The named constants do not need to be visible to the callers.

One could go further and place the functions in a namespace named (something like) TemperatureConversion but I have not bothered.

Read Entire Article