Saturday, August 26, 2023

A Tribute to Writers of Unorganized Test Code

Photo by Scott Graham on Unsplash

When you inquire with a Developer about how thoroughly they’ve tested their code, you might receive a series of explanations for why they haven’t written many Unit Tests. Sometimes they’ll mention challenges in creating the tests, or they might debate whether the benefits are worth the work required.

The issue here is that the code for Unit Tests, Functional Tests, and Regression Tests isn’t given as much importance. Usually, the time and work needed for these tests aren’t taken into account when planning the development work for a sprint.

As the code becomes bigger over time and when we add new features, they can sometimes cause existing things to stop working correctly. But usually, people don’t consider spending time to write tests for these changes.

Sometimes, even if we write test code just to meet the requirements, it might not follow the good coding rules (like SOLID principles). I’ve noticed that test code is often untidy, and I’ve told the developers responsible to clean it up. However, there’s a common belief that since the messy code only runs tests, not the real system, it’s okay for it to be messy.

For those who write messy tests, there’s a rule called “FIRST” that should be kept in mind when creating test code:

  • Fast
  • Isolated/Independent
  • Repeatable
  • Self-validating
  • Timely

Fast: Make sure your tests complete quickly. I’ve observed situations where test suites take hours to finish, which can sometimes become quite frustrating.

Here’s a simple example where you’re testing a function that adds two numbers:

@Test
public void testAddition() {
int result = Calculator.add(3, 5);
assertEquals(8, result);
}

Isolated/Independent: Ensure that every test is self-contained and doesn’t depend on or influence the results of other tests. This approach allows you to run different tests separately and autonomously.

Here’s an example testing a class that simulates a stack:

@Test
public void testPush() {
Stack stack = new Stack();
stack.push(42);
assertEquals(1, stack.size());
}

@Test
public void testPop() {
Stack stack = new Stack();
stack.push(42);
int poppedValue = stack.pop();
assertEquals(42, poppedValue);
assertEquals(0, stack.size());
}

Repeatable: Make certain that tests always generate consistent outcomes, meaning they yield the same results whether run once or a hundred times. The output should remain unchanged.

Here’s an example testing a sorting method:

@Test
public void testSort() {
int[] unsorted = {3, 1, 4, 1, 5};
int[] sorted = {1, 1, 3, 4, 5};

Arrays.sort(unsorted);

assertArrayEquals(sorted, unsorted);
}

Self-validating: Tests should possess distinct criteria for passing or failing. This entails including both positive and negative scenarios within the test code.

Here’s an example testing a method to check if a number is prime:

@Test
public void testIsPrime() {
assertTrue(MathUtil.isPrime(17));
assertFalse(MathUtil.isPrime(6));
}

Timely: Start writing tests early in the process of developing your code. This principle is incredibly important. Before you even start writing your actual code, take time to consider the test cases and begin crafting test code as soon as you can. Delaying writing test code often means you’ll never find the time to do it later.

Here’s an example testing a method that calculates the Fibonacci sequence:

@Test
public void testFibonacci() {
assertEquals(0, MathUtil.fibonacci(0));
assertEquals(1, MathUtil.fibonacci(1));
assertEquals(55, MathUtil.fibonacci(10));
}

Happy coding :)

Innovating Financial Inclusion: The e-RUPI Initiative in India

 


e-RUPI is a targeted electronic voucher created to ensure that the designated funds are delivered to the intended recipient and can solely be utilized for the precise purpose it was intended for. It operates as a cashless system, making it person and purpose-specific.

The objective is to establish an efficient and secure delivery system with minimal logistics for various government Direct Benefit Transfer (DBT) programs nationwide. The digital e-voucher platform can also serve organizations seeking to contribute to welfare services by using e-RUPI instead of cash, ensuring a leak-proof and accountable process.


What sets apart the normal rupee used in cash transactions from digital transactions?

The primary distinction lies in the utilization of e-RUPI by a designated individual for a particular purpose, ensuring the funds are directed solely for that specific use.

For instance, if a farmer is provided with an e-RUPI voucher to purchase fertilizer for their crops, the voucher’s usage is restricted solely to acquiring fertilizer, and it cannot be utilized for any other purpose.

The implementation of e-RUPI enhances security against potential misuse by middlemen in DBT. Nevertheless, there remains a possibility of middlemen resorting to covert arrangements to illicitly benefit from the system.


Below are the entities engaged in the creation and redemption of e-RUPI vouchers:

Issuer Bank/Payer PSP: The issuing bank or payment service provider (PSP) is responsible for initiating the request to create an e-RUPI voucher with NPCI.

Sponsor: The sponsor refers to a corporate entity, a State or Union Government department, or a business customer of the bank who requests the bank for the creation of an e-RUPI voucher.

e-RUPI beneficiary: The person who receives the e-RUPI voucher is known as the e-RUPI beneficiary. It's important to note that an e-RUPI beneficiary may not have a UPI (Unified Payments Interface) account or be a bank account holder.

Designated Merchant: Designated merchant are specific voucher acceptance points where e-RUPI voucher can be redeemed/used.

Acquiring Bank/Payee PSP: Acquiring bank/Payee PSP shall be providing facility/capability to designated merchants to accept the e-RUPI voucher for redemption.

NPCI: NPCI is the owner, network operator, service provider, and coordinator of the UPI Network.


e-RUPI Work Flow:


An overview of the Open Network for Digital Commerce (ONDC) from a bird's-eye perspective

In this article, we're delving into the government's recent initiative to democratize digital ecommerce – the Open Network for Digital Commerce (ONDC). Traditional ecommerce involves four main entities: Buyers, Sellers/Merchants, E-commerce Platforms (e.g., Bigbasket, Swiggy, Amazon), and Payment Service Providers. The typical flow of an ecommerce transaction follows this structure:

In this setup, buyers are freed from the need to know about sellers' identities or product delivery specifics. This is all managed by the e-commerce platform. However, there's a challenge when it comes to product discovery for smaller merchants. Wealthier merchants can make their products more visible by establishing special agreements with the platform. This results in fewer transactions and revenue for smaller players. Additionally, buyers might have limited options since not all merchants offering a product might be on the platform they're using.

This approach brings three problems:

  1. Limited Visibility for Smaller Merchants: Smaller players struggle to get noticed among bigger ones dominating the platform.
  2. Fewer Options for Buyers: Buyers have limited product choices as not all merchants are available on their chosen platform.
  3. Monopoly of E-commerce Players: A single dominant player can lead to issues like unfair competition and limited consumer choice.

So, how does ONDC address this? ONDC offers solutions like:

  1. Enhanced Visibility for Smaller Merchants: ONDC maintains a central repository of merchants and their catalog information, ensuring their discoverability.
  2. Expanded Choices for Buyers: ONDC's search API provides access to a global catalog, allowing buyers to find similar items across multiple catalogs.
  3. Decentralized Collaboration: ONDC promotes a decentralized ecosystem where various stakeholders collaborate to create an inclusive and competitive marketplace. This prevents excessive power concentration in one player's hands and encourages diversity and innovation.

Key Entities within ONDC:

  • Buyer: The individual/entity making purchases through the platform.
  • Buyer Applications: Apps enabling buyers to search product catalogs.
  • Seller Applications: Apps for sellers to manage orders, logistics, etc.
  • Sellers: Merchants using the platform to sell products.
  • ONDC Ecosystem: Includes gateway and centralized services. The gateway authenticates participants like Business Process Partners (BPPs) and Buyer Application Partners (BAPs).

ONDC API Architecture:

ONDC's API structure follows an asynchronous model where each action triggers a callback. The requester initiates a request, and the target entity sends back a callback. Some key actions and their corresponding APIs include:

  1. Search: Find products in the catalog.
  2. Select: Choose products for purchase.
  3. Initialize: Start an order.
  4. Confirm: Confirm and finalize an order.
  5. Status: Check order status.
  6. Track: Track order progress.
  7. Cancel: Cancel an order.

For more detailed API information, visit the ONDC API Documentation.

Feel free to share your thoughts and questions on this exciting initiative!


Sunday, July 2, 2023

Unified Payment Interface(UPI) Architecture


Unified Payment Interface(UPI) Architecture

In the digital age, where convenience and speed are very very important, the Unified Payments Interface (UPI) has emerged as a game-changer in the realm of financial transactions in India. UPI, introduced by the National Payments Corporation of India (NPCI), has revolutionized the way people send and receive money, making it as simple as a few taps on their smartphones. With its seamless integration across multiple banking platforms and widespread adoption by various payment apps, UPI has become the go-to solution for instant, secure, and cashless transactions.

In this tech blog, we will delve into the world of UPI and explore its inner workings, advantages, and the impact it has had on the Indian digital payments landscape. Whether you are a tech enthusiast, a curious user, or a business owner looking to embrace UPI for your enterprise, this comprehensive guide will provide you with the insights you need to navigate the exciting world of UPI.

Transactions stats for Year 2023:

Transactions in Million

If you compare month on month between May 2022 vs 2023 — (9415–5955/5955) * 100 ~ 59% increase, this is really huge.

9415*1000k/24*60*60*30 ~ 4k transactions/s, this is very high QPS. How does UPI system is able to handle such load?

First let’s start with the basic flow diagram of any UPI transaction and later we will deep dive into the detailed architecture of it.


UPI high level transaction flow

Here are the entities involved in above transaction:

  1. User :Initiates a transaction for another UPI ID after login to his/her PSP app account.
  2. PSP — Payer: Validate the user(with the help of NPCI) and forwards request to NPCI for the further processing of the transaction.
  3. NPCI UPI ecosystem: Forwards the request to PSP(Payee) for further address resolution and processing.
  4. PSP — Payee: Uses NPCI APIs to find out the account details/address of the Payer’s bank/Remitter Bank.
  5. Remitter Bank: Validate and confirms the account deduction request raised by the Beneficiary Bank. Sends the confirmation back to NPCI.
  6. Beneficiary Bank: Validate and confirms the account credit request raised by the Remitter Bank. Sends the confirmation back to NPCI.

Finally NPCI notifies about the successful or failed transaction request back to all involved PSP. This notification may be push/pull type based on the configuration.

References:

https://www.youtube.com/watch?v=QpLy0_c_RXk

Sunday, June 18, 2023

Message Acknowledgement types and different delivery methods in a Distributed Message Queuing system

In today's world of communication, message queues are ubiquitous.

In the world of distributed systems, message queue plays a vital role in enabling reliable and asynchronous communication between components.

One critical aspect of this communication is message acknowledgement. 

Acknowledgement ensures that messages are delivered successfully and processed by the intended recipients. 

In this blog post, we will explore the various types of message acknowledgements and the different delivery methods employed in a distributed message queuing system.

Sunday, June 4, 2023

Popular Open APIs available for developers

There are several open APIs (Application Programming Interfaces) available for developers across various domains. Here are a few popular ones:

  1. OpenWeatherMap API: Provides access to weather data and forecasts worldwide.

    Website: https://openweathermap.org/api
    Website: https://developers.google.com/maps/documentation
    Website: https://developer.twitter.com/en/docs/twitter-api
    Website: https://docs.github.com/en/rest
    Website: https://stripe.com/docs/api
    Website: https://www.twilio.com/docs/quickstart
    Website: https://api.nasa.gov/
    Website: https://platform.openai.com/docs/quickstart
    Website: https://developer.spotify.com/documentation/web-api/
    Website: https://wiki.openstreetmap.org/wiki/API

  2. Google Maps API: Enables integration with Google Maps services, including mapping, geocoding, and routing.

  3. Twitter API: Allows developers to interact with the Twitter platform, access tweets, post tweets, and perform various other actions.

  4. GitHub API: Enables developers to interact with GitHub repositories, manage issues, pull requests, and perform various Git operations.

  5. Stripe API: Provides a platform for developers to integrate online payment processing into their applications.

  6. Twilio API: Allows developers to add SMS, voice, and video communication capabilities to their applications.

  7. NASA API: Provides access to various NASA data sets, including astronomy images, Mars Rover photos, and more.

  8. OpenAI API: Offers access to powerful natural language processing models and capabilities, including text generation and language translation.

  9. Spotify API: Enables developers to integrate with the Spotify music platform, access playlists, search for tracks, and manage user libraries.

  10. OpenStreetMap API: Provides access to crowd-sourced map data, geocoding, and routing information.


Let's start with OpenAI APIs:

First of you would need to know what are the different models which is available, and, then, find a API which fits your use case.

I tried Image APIs, which can be useful for designers to create/update images in different format.

Example:

curl https://api.openai.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "prompt": "A cute baby sea otter",
    "n": 2,
    "size": "1024x1024"
  }'


Interesting part is Prompt, you can pass simple conversation type command similar to the way you interact with your designer while building a product.

Another API which I have tried is extracting tags from a list of product attributes. 
This is the API:

curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [{"role": "user", "content": "Extract Tags from this product description: You can get your clothes thoroughly cleaned in the LG FHM1006SDW 6 kg Front-loading Washing Machine. Its 6 Motion Direct Drive technology pushes the wash drum in numerous directions when you select a wash programme. This ensures that your garments are gently yet thoroughly washed. In addition, this washing machine produces less noise, vibration, and wear and tear as its motor is directly attached to the drum. Moreover, this washing machine removes pet hair, pollen allergens, and house dust mites from delicate garments that require special care, thanks to its Steam Wash programme"}]
  }'

Response:

"choices": [
        {
            "message": {
                "role""assistant",
                "content""LG, FHM1006SDW, 6 kg, Front-loading, Washing Machine, 6 Motion Direct Drive, wash programme, gentle washing, less noise, vibration, wear and tear, motor, drum, pet hair, pollen allergens, house dust mites, delicate garments, special care, Steam Wash programme."
            }
]


Referencehttps://platform.openai.com/docs/api-reference/chat/create


 









Saturday, June 3, 2023

Self vs Team's visibility

Today, I am going to discuss about the self vs team's visibility.

I hope most of you would have seen this Bollywood movie "Gangaajal", in one of the scene when the hero of the movie (Ajay Devgan) was getting the president medal because of a successful crackdown in one case.

He refused to take the credit, instead he said that it's his team who has done this, but, the guy who was giving his medal said"Sainik to kaam karte heen hain, lekin, credit to finally senapati ko heen milta hai, directly ya indirectly".

I was the firm believer of the above thought, if my team's work or team members are visible in the system, this means, I am visible by default.

As a leader of your team, it's your responsibility that you need to make sure that the last line of people in your team should get the due credit and right visibility.

What about you? It's equally important for you also to be on top everything and to be shown as leading from the front.

Getting things done is not longer seen as adding very much value, because, that is just one part of your role. There are other parts, like adding value, right delegation etc.....

So, how to build the self visibility? Here are a few steps which you should do, I am also trying to do the same:

1. Any collaboration opportunity outside your team, you should lead it.

2. Product ideation, first level of thought should come from you and make sure that's visible to your boss 🙂.

3. Start giving valuable inputs in any cross team discussion, this will establish you as a thought leader.

4. Start giving internal/external teach talk.

5. Collaborate with the guy in your team who is afraid of doing presentation, this will help him/her in building visibility.

6. Talk, over communicate about self and team's achievement.

7. Write Blog, organise tech meet-up....

This list is very long, pick the top three and start doing it today.

One of my friend keep quoting this "Career is a hard fought battle, you need to fight very hard". True, very, very true.

Happy learning...

LocalBaniya: Giving Every Small Shop in India a Digital Identity

  LocalBaniya: Giving Every Small Shop in India a Digital Identity More:  Localbaniya.shop