Categories
Uncategorized

Clean Code

One thing I would like to start considering more while I write code is creating code that is more readable. For a lot of my coding career, I have written code that was only meant for me to engage with and understand. This would usually only be for a short term as well, such as an assignment where I would never have to see that code again. Though I would try my best to write code that was clean and readable, it wasn’t usually a priority. I would usually focus on meeting requirements and creating functional code.

When writing code for larger projects, especially ones involving other team members, the importance of creating clean code increases substantially. The short-term gain of creating messy code quickly will cost even more development time down the road. This is also true for solo projects, where you need to understand your own code at a later date.

// Bad Code
class CarouselRightArrow extends Component{render(){return (<a href="" className="carousel__arrow carousel__arrow--left" onClick={this.props.onClick}> <span className="fa fa-2x fa-angle-left"/> </a> );}};

// Good Code
class CarouselRightArrow extends Component {
render() {
return (
<a
href="#"
className="carousel__arrow carousel__arrow--left"
onClick={this.props.onClick}>
<span className="fa fa-2x fa-angle-left" />
</a>
);
}
};

https://www.geeksforgeeks.org/tips-to-write-clean-and-better-code/#

This code snippet was taken from the link above and shows the difference in code that provides the same functionality but varies in readability. As you can notice, the second class is far easier to understand.

One thing I want to avoid when coding is creating methods that are too long. Methods should achieve one function and should try to be constrained to 10 lines of code if possible. It’s easy to start expanding methods by a few lines at a time, but usually this means that a new method should be created to contain this new code. I have always tended to create longer methods, so this is something I definitely want to work on for future projects.

https://refactoring.guru/smells/long-method

Problem

void printOwing() {
printBanner();

// Print details.
System.out.println("name: " + name);
System.out.println("amount: " + getOutstanding());
}
Solution

void printOwing() {
printBanner();
printDetails(getOutstanding());
}

void printDetails(double outstanding) {
System.out.println("name: " + name);
System.out.println("amount: " + outstanding);
}

https://refactoring.guru/extract-method

Here is some example code from the link above, showing the separation of two functionalities into separate methods.

Leave a Reply

Your email address will not be published. Required fields are marked *