Skip to main content

Easy Tips for Writing Cleaner Code

· 6 min read
Rajiv Karthik Yanamandra
Senior Software Engineer @ Compare The Market, Australia

10 Simple refactoring hacks for cleaner, better code!

Hey there, fellow coders! Have you ever looked at your code and thought, "Wow, this is messier than a toddler's art project!"? Well, you're not alone.

Today, we're delving into the enchanting world of refactoring. It's akin to spring-cleaning for your code, but much more gratifying!

thumbnail post

TL;DR - version

challenges

Alright, let’s get into it. Refactoring involves enhancing your code without altering its functionality. Think of it as renovating a house: you’re not relocating but simply improving the living space.

info

Remember, this is not an exhaustive list. There are many other practices and principles to consider when writing clean code. These tips are a great starting point!

Tip-1: Extract Method

Got a chunk of code that performs a specific task? Extract it into its own method! This enhances the readability of your main code and makes your methods more reusable.

   // Before
double total = 0;
foreach (var item in cart.Items)
{
total += item.Price * 0.9; // applying discount
}

// After
double total = CalculateTotal(cart.Items);

private double CalculateTotal(List<Item> items)
{
double total = 0;
foreach (var item in items)
{
total += item.Price * 0.9; // applying discount
}

return total;
}

Tip-2: Rename Variable

Naming can be challenging, but using descriptive names for variables, such as customerDiscount or currentBalance, is worth the effort. This small change can make your code much more understandable.

   // Before
double x = total * 0.1;

// After
double customerDiscount = total * 0.1;

Tip-3: Replace Magic Numbers

If you encounter numbers like 7 or 42 directly in your code, substitute them with named constants. const int MAXUSERS = 42; tells you much more than just using 42 in your code.

   // Before
if (users.Count > 42) {
// Do something
}

// After
const int MAXUSERS = 42;
if (users.Count > MAXUSERS) {
// Do something
}

Tip-4: Inline Method

Sometimes, instead of extracting, you may need the opposite. For instance, if you have a method that returns a constant value, you should consider inlining it. It can make your code easier to follow by reducing unnecessary indirection.

    // Before
public double GetPiValue() {
return 3.14;
}

double area = GetPiValue() * radius * radius;

// After
double area = 3.14 * radius * radius;

Tip-5: Simplify Conditionals

Nested if-else statements can quickly get out of hand. Use guard clauses to handle simple cases upfront and reduce the nesting. This will make your logic cleaner and more approachable.

   // Before
if (condition) {
if (anotherCondition) {
// Do something
}
}

// After
if (!condition) return;
if (!anotherCondition) return;
// Do something

Tip-6: Decompose Conditional

Break down complex conditional logic into smaller methods. This not only enhances the readability of your code but also simplifies testing.

   // Before
if (isHoliday && isWeekend && isSunny) {
// Go for a picnic
}

// After
if (ShouldGoForPicnic()) {
// Go for a picnic
}

private bool ShouldGoForPicnic() {
return isHoliday && isWeekend && isSunny;
}

Tip-7: Replace Temp with Query

If you’re using a temporary variable to store a value that can be derived through a method, get rid of the temp and call the method directly. This reduces the risk of errors and makes your code more concise.

   // Before
double basePrice = GetBasePrice();
if (basePrice > 100) {
// Apply discount
}

// After
if (GetBasePrice() > 100) {
// Apply discount
}

Tip-8: Introduce Parameter Object

If your method has too many parameters, wrap them in a single object. This makes your method calls cleaner and your code easier to read.

   // Before
public void CreateOrder(string productId, int quantity, double price, string customerName) {
// Implementation
}

// After
public void CreateOrder(OrderDetails orderDetails) {
// Implementation
}

public class OrderDetails {
public string ProductId { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
public string CustomerName { get; set; }
}

Tip-9: Encapsulate Collection

If you're working with a collection, incorporate methods to manipulate the collection within the class. This maintains data integrity and enhances the usability of your class.

  // Before
public class Order {
public List<Item> Items;

public void AddItem(Item item) {
Items.Add(item);
}
}

// After
public class Order {
private List<Item> items = new List<Item>();

public void AddItem(Item item) {
items.Add(item);
}

public IReadOnlyList<Item> Items => items.AsReadOnly();
}

Tip-10: Remove Dead Code

Make sure to delete any code that you're not using. Unused code is unnecessary clutter that can confuse anyone trying to understand your codebase.

   // Before
public void ProcessOrder() {
// Some processing
}

private void UnusedMethod() {
// This method is never called
}

// After
public void ProcessOrder() {
// Some processing
}

Bonus: Tip-11 : Adopt the Single Responsibility Principle

Each class or function should have one reason to change, and only one reason. This means every class and function should do just one thing.

   public class User
{
public string Name { get; set; }
public string Email { get; set; }

public void SaveToDatabase()
{
// Code to save user to database
}

public void SendEmail()
{
// Code to send email to user
}
}

// Refactored
public class User
{
public string Name { get; set; }
public string Email { get; set; }
}

public class UserRepository
{
public void Save(User user)
{
// Code to save user to database
}
}

public class EmailService
{
public void SendEmail(User user)
{
// Code to send email to user
}
}

Conclusion

So, next time you’re coding, take a moment to consider how you can refactor and make your code a little cleaner. Trust me, your future self and your team will thank you!

You know the drill: chai ☕ and biscuits 🍪 for focus, and clean code for brilliance 💻.

🎉Happy coding!!🎉

☕ Fuel the Journey!

Every coffee ☕ (or chai 🍵) you buy fuels another idea, another post, and another smile. Thank you for supporting my work!