How to Program? None of the Tutorials Taught You This

How to Program? None of the Tutorials Taught You This

Are you tired of programming tutorials that leave out a crucial piece of the puzzle? You've likely spent hours diving into coding exercises, mastering programming languages, and crafting projects, only to find that something crucial is missing. It's the vital practice that turns good code into great software: writing tests before programming.

In the vast landscape of software development education, the emphasis is often placed on writing code that produces the desired output. We learn about variables, loops, functions, and data structures, honing our skills to solve problems and build applications. However, nestled within this journey, there's a critical aspect that's frequently overlooked – testing.

As aspiring developers, we're equipped with syntax knowledge and programming concepts, yet often lack the understanding of how to verify the correctness of our code. We might craft solutions that work seamlessly under ideal conditions but crumble when faced with edge cases or unexpected inputs.

The Habit of Writing Tests First

Enter the transformative habit of writing tests before writing code. While Test-Driven Development (TDD) provides a structured framework for this approach, simply adopting the habit of writing tests upfront – even if not strictly adhering to TDD principles – can yield tremendous benefits.

Here's how you can integrate this habit into your workflow using JavaScript, PHP, and Python:

JavaScript Example:

  1. Understanding the Problem:

    • Before diving into code, let's understand the problem: how do we determine whether a number is prime or composite?
  2. Writing Tests:

    • Let's start by writing tests using a popular testing framework like Jest:
    const isPrime = require('./isPrime');

    test('Check if 7 is prime', () => {
        expect(isPrime(7)).toBe(true);
    });

    test('Check if 10 is composite', () => {
        expect(isPrime(10)).toBe(false);
    });
  1. Implementing the Code:

    • With failing tests in place, let's implement the isPrime function:
    function isPrime(num) {
        if (num <= 1) return false;
        for (let i = 2; i <= Math.sqrt(num); i++) {
            if (num % i === 0) return false;
        }
        return true;
    }
    module.exports = isPrime;
  1. Refactoring:

    • Once the tests pass, refactor the code to improve readability and efficiency.

PHP Example:

  1. Understanding the Problem:

    • Similarly, let's understand the problem in PHP: how do we determine whether a number is prime or composite?
  2. Writing Tests:

    • Using PHPUnit, we can write tests to check if our function correctly identifies prime and composite numbers:
    require 'isPrime.php';

    class IsPrimeTest extends PHPUnit\Framework\TestCase
    {
        public function testIsPrime()
        {
            $this->assertTrue(isPrime(7));
        }

        public function testIsComposite()
        {
            $this->assertFalse(isPrime(10));
        }
    }
  1. Implementing the Code:

    • Implement the isPrime function based on the tests:
    function isPrime($num)
    {
        if ($num <= 1) return false;
        for ($i = 2; $i <= sqrt($num); $i++) {
            if ($num % $i === 0) return false;
        }
        return true;
    }
  1. Refactoring:

    • Refactor the code to improve maintainability and performance.

Python Example:

  1. Understanding the Problem:

    • Let's approach the problem in Python: how do we determine whether a number is prime or composite?
  2. Writing Tests:

    • Using the built-in unittest framework, we can write tests to validate our prime number function:
    import unittest
    from is_prime import is_prime

    class TestIsPrime(unittest.TestCase):
        def test_is_prime(self):
            self.assertTrue(is_prime(7))

        def test_is_composite(self):
            self.assertFalse(is_prime(10))
  1. Implementing the Code:

    • Implement the is_prime function based on the tests:
    def is_prime(num):
        if num <= 1:
            return False
        for i in range(2, int(num ** 0.5) + 1):
            if num % i == 0:
                return False
        return True
  1. Refactoring:

    • Refactor the code for clarity and efficiency.

By making this habit a cornerstone of your development process in JavaScript, PHP, Python, or any other language, you'll reap a myriad of benefits:

  • Clearer Understanding of Requirements: Writing tests upfront forces you to clarify the requirements and behavior of your code before diving into implementation.

  • Improved Code Quality: By focusing on writing testable code, you inherently write code that's modular, reusable, and easier to maintain.

  • Reduced Debugging Time: Catching bugs early in the development process significantly reduces the time spent debugging and troubleshooting later on.

  • Increased Confidence in Code Changes: With a robust test suite in place, you can confidently make changes to your codebase, knowing that any regressions will be quickly caught.

Conclusion

In conclusion, the habit of writing tests before programming is a transformative practice that can elevate your software development journey in any programming language. Whether you strictly adhere to Test-Driven Development principles or simply adopt the habit of writing tests upfront, the benefits are undeniable.

So, the next time you embark on a coding adventure, start with the tests. Remember: before you start coding, start testing.

Have you incorporated the habit of writing tests before programming into your workflow? Share your experiences and insights in the comments below! And don't forget to subscribe for more tips and best practices in software development. Happy coding!

Did you find this article valuable?

Support Shital Mainali by becoming a sponsor. Any amount is appreciated!