Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    JavaScript

    Build Real-World React Native App #5: Single Post Screen and Bookmark

    Flutter

    Understanding Flutter Bloc Pattern

    LinkedIn

    Strategic LinkedIn Tactics for E-Commerce Lead Generation

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Sunday, September 28
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / Follow These Guidelines to Write Testable Code That Can Scale | with Examples
    Programming

    Follow These Guidelines to Write Testable Code That Can Scale | with Examples

    Ranvir SinghBy Ranvir SinghNovember 25, 2019Updated:May 26, 2024No Comments13 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    Follow These Guidelines to Write Testable Code That Can Scale | with Examples
    Testing Tips
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link
    Testable Code
    Testable Code

    The responsibility of a Software Engineer is not only to deliver the software that works, but also to deliver the software which is testable and maintainable. By maintainable, I mean any new person can come in and start writing the code from day one.

    Most people don’t like to test the code they write. There can be multiple reasons for that but almost 90% of the time it happens because the code is highly coupled with one another and programmers don’t really know what should they check for in the tests.

    The first time I was introduced to test-driven development when I was writing code for my Google Summer of Code Project. My first impression of the TDD( Test-driven development) was not a very pleasant one. I would write the software with a great sense of pride but when it came to testing, I tried ways to escape it.

    Why would someone write tests that were so dumb was the question in my mind. But as soon as I realized the importance of these test suite, I have never written any piece of code which is not tested( Scripts excluded).

    The first step toward writing clean code, you need to write code that is differentiable on the basis of there usage. And the first step toward writing differentiable code is to think in terms of writing code that can be tested.

    If we take a simple example of the library management system, the user module should not know anything about the book module and the book module should not know what is the time span for which the book is issued for.

    Why most of the MVC( Model View Controller) frameworks win in this case is because they allow you to differentiate your code on the basis of what they do.

    For example: If we take an example of the directory structure that a Python-based web framework, Django follows the following guidelines,

    • You can write all your database related stuff in models.py files.
    • You can write all URL related stuff in urls.py.
    • You can write your app-specific logic in the views.py.

    Although you can divide them further( and you should) according to the size of your application, this type of structure gives you a starting point and help you to choose which part of the code should go where.

    If you want to write a pre-save hook for one of your tables which will add something to your table following some guidelines before the actual write happens in the database, you can simply argue that this part of code will definitely go to the model file.

    Some important terms

    Software testing

    Software testing is a procedure in which software is tested for bugs and off behaviors that were not inserted intentionally.

    For a given library management software we can check for the following test cases.

    1. At any time admin should be able to find which books are issued to which users.
    2. At any time admin should be able to find which books are present in which part of the library hall.
    3. At a given time, admin should be able to find the fine payable by a given user.
    4. At a given time, the admin should be able to issue a book to the user.
    5. At a given time, a user should be able to return the book to the library.

    These are a few test cases that will be generated and shared among the stack holders who are working on the project.

    Now, there are a few ways to test the software once it is done.

    1. Use TDD.
    2. Use the help of a tester.
    3. Write a test as you write the code.

    Using TDD

    TDD or test-driven development is the type of testing in which you write test cases prior to writing any code for the software or according to Uncle Bob, no incoming code should be merged into the main code before at least one failing test is written for that incoming part of code.

    Although this is an awesome way of writing software leading to code without obvious errors, this significantly slows down the development time when you are starting out.

    Using the help of a tester

    Tester's help
    Tester’s help

    A tester is a person for whom the software is a black box and most of the time, he/she doesn’t know about how the software works internally.

    He/She is given a set of conditions each time any change is made to the code. Only after a tester gives a go through to the changes, the changes are merged.

    Although you should always have one tester, you should not be solely dependent on this person.

    Writing tests as you go forward

    Write code for something and write test cases to verify the changes that you have made taking into account the various conditions given by the business is one of the best and most widely used ways to verify that your software works.

    All you need is to use any of the Continuous integration tools. You can use any of the tools out there. I personally have used Travis CI and Circle CI. Both of them work pretty well.

    Read More:  React Lesson 5: React Devtools and Reusable Open-Source Components

    Unit testing

    Unit testing is a way to test a single unit of software. For example, testing a utility function that changes the Array/List of characters to a string. Unit testing is the best way to be sure that your functions work as expected.

    Integration testing

    Integration testing is a type of testing where you test a few units together. For example testing login, buying a product and checking out, the whole process in a single test.

    A lot of people prefer a combination of both unit and integration tests for there codebase and its preferred to have at least API level integration testing.

    What do we test for?

    In the testing suite, we give a sample input to a given function and check if the function returns something which is expected or return something which is not expected.

    test_create_string.py

    def create_string(char_list):
        return ''.join(char_list)
    
    def test_create_string():
        abc = ['a', 'b', 'c']
        assert 'abc' == create_string(abc)

    Run the command py.test to find if the test passes or fails. (By the way, you will have to install pytest before running this, use the command pip install pytest)

    1 passed in 0.02s – I got this response. This means the test passed for me. You can also do negative assertions that can tell you that output is not a bad one.

    Or in JavaScript,

    const assert = require('assert');
    
    const createString = (charList) => {
        return charList.join('');
    }
    
    describe("createString", function() {
    
        it("Checks if the createString appends the characters properly.", function() {
            assert.equal(createString(['x', 'y', 'z']), 'xyz');
        });
    
    });

    You will have to install mocha for this. Mocha is used for testing code in JavaScript.

    Install it using npm install mocha. Then run the command to test the file.

    mocha test_create_string.js

    You will get the following output if your test passes.

    createString
    ✓ Checks if the createString appends the characters properly.
    
    1 passing (17ms)
    Running a command in mocha
    Running a command in mocha

    Why Test your code

    Testing your code has a lot of advantages few of them are discussed here. Testing always gives you confidence in the code that you write. These silly tests will be helpful in the later stages of development when you want to change something in the code.

    Become future proof

    Writing test make your code future proof. Each code change will go through a test suite which will make sure that everything is working perfectly.

    Let’s say you want to add the functionality in the earlier function.

    You want the function to return the parameter if the type of the parameter is not List/Array.

    In Python

    def create_string(char_list):
        if type(char_list) == list:
            return ''.join(char_list)
        return char_list

    or JavaScript

    const createString = (charList) => {
        if (Array.isArray(charList)) {
            return charList.join('');
        } else {
            return charList;
        }
    }

    All you have to do is add new tests to check if the new functionality is working or not. You will not have to worry about the earlier features.

    Allow new joiners to write the code as quickly as they join

    The new joiners can start working on your software as quickly as they join in. They can run the test suite to know more about the codebase.

    Test suite can work as the documentation of the codebase.

    The new people don’t have to worry about breaking something by the change they make.

    Make changes quickly

    When you are backed by a lot of tests, you can start making changes quickly. All you have to do is to write tests for the new thing that you are trying to build.

    You can go back to the module for which you will change the codebase and quickly check the current behavior by running the tests, write your changes with new tests and boom! You are done.

    Feel more confident in the changes that you make

    This is the biggest achievement that tests give you as a developer. I myself have used the term like, This module is thoroughly tested, we don’t have to worry about it breaking.

    This much confidence can only come if your code is backed by a lot of good quality tests.

    What makes your code testable

    Writing testable code is an art. Differentiating the testable code from a non-testable one is very important. Mixing them up leads to a mix up of code which you can’t test.

    Write cleaner functions

    Well, the first and foremost thing that you can start doing is to start writing cleaner functions. I have written an article on How to write clean function. Hope this article will help you to write cleaner functions.

    When you start writing a function that does only one thing, you will end up with the codebase which is entirely testable. You can simply write unit tests for all the functions separately.

    SOLID principles

    Uncle Bob’s SOLID principles teach us a lot about writing clean code that is testable.

    According to SOLID principles, your code should follow the following guidelines.

    Read More:  The Concept of Scope in JavaScript

    Single Responsibility Principle

    A class should have one and only one reason to change.

    The Open closed Principle

    You should be able to extend a classes behavior, without modifying it.

    The Liskov Substitution Principle

    Derived classes must be substitutable for their base classes. This means that functions that use references to base class must be able to use objects of derived class without knowing it.

    The Interface Segregation Principle

    Interfaces( A class which is only declared but the functionality is not defined, Functionality is defined in every extended class separately) must be fine-grained and should be client-specific.

    The Dependency Inversion Principle

    Depend on abstractions, not on concretions. That is, the modules that encapsulate high-level policy should not depend upon modules that implement details. For example, Your user module should not know, how the login is implemented.

    Make third party calls in separate modules

    Third-party calls the main things which make your testing life a little bit difficult. You always have to mock these third party calls unless you really are performance testing something.

    I have seen people writing a separate module for all these third-party calls. All you have to pass is the endpoint and credentials to use for making the call. It will spit out the response without worrying about the details.

    Using Factories/ Faker for object initialization

    A lot of your time while testing can go in initializing objects for testing. You can generate random objects using these factories in Python.

    Faker is the javascript module that can do the same thing in JavaScript.

    Stop circular dependencies

    Circular dependency
    Circular dependency

    Circular dependency is a state in which module 1 is required by module 2 and module 2 is required by module 1. This is a very bad state to be in and is against the Dependency Inversion Principle.

    Almost all of the languages are pretty hard on disallowing circular dependencies from happening but still, you can use different techniques to do circular dependency.

    You have to think about the structure of code again and preferably refactor some of your code.

    Minimize global declarations

    Minimize the number of variables you define globally. After some time, it becomes pretty hard to find where the variable was initialized and how the value is set to what it is being set to.

    Debugging anything related to a global variable is a real pain.

    Replace conditional statements with polymorphism

    It’s pretty hard to follow the conditional statements after some time. You can have different actions for the same class if the user belongs to a separate category. You can use Polymorphism to solve this problem.

    Following up on the example of a library management system if the user is admin, he/she can see the book details and if the user is a simple one he/she won’t be able to see the details.

    A simple function which when passed with the object of admin user should return back the details whereas when passed with a simple user should raise an error.

    How to test your Software properly

    There is a definite guideline on how you should build the CI pipeline for your project and encourage everyone in the team to write more tests. Let’s discuss this pipeline.

    Write unit as well as integration tests

    It’s always good to have a combination of both unit tests and integration tests. Whenever you write a new feature write the test cases along with the code.

    What I prefer is to write all the test cases in simple words and ask them to be verified by the stakeholders. Once all of them are verified, I write code to solve the problem.

    Once this is done, I pick up all the test cases and write them down in the code to check if they are passing or not. A lot of times, tests tell you a lot of places where the code can break which you might not have thought of.

    Use a CI tool (Continuous Integration)

    Once you write down the test cases, you need to integrate a CI tool that can run your tests whenever you create a Pull Request Merge Request.

    CI tool
    CI tool

    The CI tool should be able to run your tests. GitHub allows you to stop someone from pushing the code if the tests fail. You can add such checks in the code to avoid any occurrences of accidentally pushing of code.

    Add total coverage checks

    Add a total coverage check to find the total coverage of your test cases. Coverage is the percent of code that is covered under your test cases.

    Adjust the amount of coverage to be increased each time you add new code to your codebase and never try to fudge with this number. Make it a habit not to push untestable code.

    Checks
    Checks

    Hope you understood the purpose of the post and will write more and more test against your code. Please leave your comments below and share your views with us.

    JavaScript python software testing test testing
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Ranvir Singh

      Related Posts

      Mastering REST APIs: Essential Techniques for Programmers

      December 18, 2024

      Crafting Interactive User Interfaces Using JavaScript Techniques

      December 17, 2024

      Effective Strategies for Utilizing Frameworks in Web Development

      December 16, 2024
      Leave A Reply Cancel Reply

      You must be logged in to post a comment.

      Stay In Touch
      • Facebook
      • Twitter
      • Pinterest
      • Instagram
      • YouTube
      • Vimeo
      Don't Miss
      PHP February 3, 2020

      Top 6 Features of PHP 7.4 – Explained with Examples

      PHP 7.4 is a minor version, but it includes plenty of new features. Here I show you the top 6 of them with examples. They can make a significant effect on your PHP development process.

      Mapping the World: Creating Beautiful Maps and Populating them with Data using D3.js 

      January 21, 2020

      Operating Systems Showdown: Windows vs. macOS vs. Linux for Web Development

      July 10, 2019

      Visualizing Logs from a Dockerized Node Application Using the Elastic Stack

      January 30, 2020

      Categories

      • AI & Automation
      • Angular
      • ASP.NET
      • AWS
      • B2B Leads
      • Beginners
      • Blogs
      • Business Growth
      • Case Studies
      • Comics
      • Consultation
      • Content & Leadership
      • CSS
      • Development
      • Django
      • E-commerce & Retail
      • Entrepreneurs
      • Entrepreneurship
      • Events
      • Express.js
      • Facebook Ads
      • Finance & Fintech
      • Flask
      • Flutter
      • Franchising
      • Funnel Strategy
      • Git
      • GraphQL
      • Home Services Marketing
      • Influencer & Community
      • Interview
      • Java
      • Java Spring
      • JavaScript
      • Job
      • Laravel
      • Lead Generation
      • Legal & Compliance
      • LinkedIn
      • Machine Learning
      • Marketing Trends
      • Medical Marketing
      • MSP Lead Generation
      • MSP Marketing
      • NestJS
      • Next.js
      • Node.js
      • Node.js Lessons
      • Paid Advertising
      • PHP
      • Podcasts
      • POS Tutorial
      • Programming
      • Programming
      • Python
      • React
      • React Lessons
      • React Native
      • React Native Lessons
      • Recruitment
      • Remote Job
      • SaaS & Tech
      • SEO & Analytics
      • Soshace
      • Startups
      • Swarm Intelligence
      • Tips
      • Trends
      • Vue
      • Wiki
      • WordPress
      Top Posts

      Comprehension in Python

      Programming February 5, 2020

      Уроки React. Урок 14.

      Programming November 11, 2016

      Python range() Explained and Visualized

      Programming September 20, 2019

      7 Best App Makers to Build Your Own Mobile App

      Tips September 19, 2019

      Subscribe to Updates

      Get The Latest News, Updates, And Amazing Offers

      About Us
      About Us

      Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

      7901 4th St N, Suite 28690
      Saint Petersburg, FL 33702-4305
      Phone: 1(877)SOSHACE

      Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
      Our Picks
      Programming

      RxJS Methods. Part 1

      LinkedIn

      Strategies for Consistent Engagement with LinkedIn Prospects

      Startups

      Strategies for Transforming Your Startup into a Profitable Venture

      Most Popular

      Leveraging Data Analytics for Informed Business Decisions

      Entrepreneurship

      List of Coding Games to Practice & Improve Your Programming Skills

      Beginners

      Becoming a Technical Lead: Working on Your Leadership Skills

      Tips
      © 2025 Soshace Digital.
      • Home
      • About
      • Services
      • Contact Us
      • Privacy Policy
      • Terms & Conditions

      Type above and press Enter to search. Press Esc to cancel.