Thursday, July 2, 2026

Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly.

Main keywords:

  • export → make something available from a file to outside.

  • import → use something from another file into a file.

export:

Use export when you want to share variables, functions, or classes from a file.

math.js

export const pi = 3.14;

export function add(a, b) {
return a + b;
}

Here, pi and add() can be used in other files.

import:

Use import to bring exported things into another file.

app.js

import { pi, add } from "./math.js";

console.log(pi); // 3.14
console.log(add(2, 3)); // 5

Default Export

A file can have one default export.

user.js

export default function greet() {
console.log("Hello");
}

Import it without {}

app.js

import greet from "./user.js";

greet();

Thursday, November 6, 2025

Element of a good table (Ref: Database design mere mortals by Michael J. Hernandez)

 Elements of the Ideal Table:

  1. It represents a single subject, which can be an object or event that reduces the risk of potential data integrity problems.

  2. It has a primary key. This is important for two reasons: A primary key uniquely identifies each record within a table, and it plays a key role (no pun intended) in establishing table relationships.

  3. It does not contain multipart or multi-valued fields.

  4. It does not contain calculated fields.

Ex:

Table orders:


id

unit_price

quantity

total_amount

1

10

5

50

2

5

2

10

This is bad table design.

 Problems:

  1. Redundancytotal_amount = unit_price * quantity is stored unnecessarily.

  2. Inconsistency risk → If quantity is updated but total_amount isn’t recalculated, the data becomes wrong.

  3. Extra storage → You’re saving the same information twice (derived + original).

Solution:

id

unit_price

quantity

1

10

5

2

5

2

5. It does not contain unnecessary duplicate fields.

6.It contains only an absolute minimum amount of redundant data.


Wednesday, September 24, 2025

Clean code chapter 3(Robert C.martin)

 

Summary: -------- 

1. Functions should hardly ever be 20 lines long.

 2.Keep blocks (inside if, else, while, for, etc.) short.

 Ideally, just one line long. And that line should usually be a function call with a descriptive name. Don’t let functions get so big that they require deep nesting.

 If you see more than 1–2 levels of indentation, it’s a smell.

 Break the nested logic into smaller functions.

 Example: Problem: Deep nesting(messy)

 public void handleOrder(Order order) {
    if (order != null) {
        if (order.hasItems()) {
            for (Item item : order.getItems()) {
                if (item.isInStock()) {
                    // process item
                    System.out.println("Processing item: " +                                 item.getName());
                    item.setStatus("PROCESSED");
                } else {
                    System.out.println("Item out of stock: " +                             item.getName());
                }
            }
        } else {
            System.out.println("Order has no items.");
        }
    } else {
        System.out.println("Order is null.");
    }
}

Clean Code:

 public void handleOrder(Order order) {
    if (isProcessable(order)) {
        processOrder(order);
    }
}


// ---- helper functions ----

private boolean isProcessable(Order order) {
    return order != null && order.hasItems();
}

private void processOrder(Order order) {
    for (Item item : order.getItems()) {
        processItem(item);
    }
}

private void processItem(Item item) {
    if (item.isInStock()) {
        markItemAsProcessed(item);
    } else {
        logOutOfStock(item);
    }
}

private void markItemAsProcessed(Item item) {
    System.out.println("Processing item: " + item.getName());
    item.setStatus("PROCESSED");
}

private void logOutOfStock(Item item) {
    System.out.println("Item out of stock: " + item.getName());
}

3. Do one thing:   

If you can extract a piece of code into a well-named function that adds understanding, your original function is probably doing more than one thing.

Friday, August 1, 2025

Testing controller

------Controller-------------

@RestController
@RequestMapping("/items")
public class ItemController {
    private final ItemService itemService;    

@Autowired
    public ItemController(ItemService itemService) {
        this.itemService = itemService;
    }
    @GetMapping
    public ResponseEntity<List<Item>> getAllItems() {
        List<Item> allItems = itemService.findAllItems();
        return ResponseEntity.ok(allItems);
    }
}

----------Service---------

@Slf4j
@Service
public class ItemServiceImpl implements ItemService {
    @Override
    public List<Item> findAllItems() {
        return Arrays.asList(new Item(BigInteger.valueOf(1), "pen", 10), new Item(BigInteger.valueOf(2), "pencil", 5));
    }
}
 

Now we want to test ItemController. we can do this by the below way ----

-------Test code---------------------

@WebMvcTest(ItemController.class) // load only mvc part not full app.
public class ItemControllerTest {
    @Autowired
    private MockMvc mockMvc; // can simulate http request without start server
    @MockBean
    private ItemService itemService;
    @Test
    void testFindAllItems() {
        // arrange
        List<Item> items = Arrays.asList(new Item(BigInteger.valueOf(1), "pen", 10),
                new Item(BigInteger.valueOf(2), "pencil", 5));
        when(itemService.findAllItems()).thenReturn(items);//stub so no actual method .
        try {
            // act
            ResultActions resultActions = mockMvc.perform(get("/items").contentType(MediaType.APPLICATION_JSON));
            // assert
            resultActions.andExpect(status().isOk())
            .andExpect(jsonPath("$.size()").value(2))
                    .andExpect(jsonPath("$[0].title").value("pen"))
                    .andExpect(jsonPath("$[1].price").value(5));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Notes:
--------

 1.@WebMvcTest(ItemController.class) : Load only MVC part not full app.

2. MockMvc :  Can simulate HTTP request without start server.

3. . $ : Root of the response json.

 

Wednesday, July 30, 2025

Dummy Vs Stub Vs fake

 Do I need to pass an object just to satisfy the method signature?
→ Use a Dummy

Do I need to simulate return values (e.g., from a repository)?
→ Use a Stub

Do I need to simulate real logic or store data?
→ Use a Fake

Wednesday, March 12, 2025

Abstract factory pattern

When single task can be done by multiple groups/family of objects and decision is taken at the runtime.




 

Tuesday, November 5, 2024

Fluent interface pattern

 public class UserConfigurationManager {
    private String userName;
    private String password;
    private UserConfigurationManager() {
    }
    public UserConfigurationManager setUserName(String userName) {
        this.userName = userName;
        return this;
    }
    public UserConfigurationManager setPassword(String password) {
        this.password = password;
        return this;
    }
    public static UserConfigurationManager make(Consumer<UserConfigurationManager> consumer) {
        System.out.println("making configuration..........");
        UserConfigurationManager configurationManager = new UserConfigurationManager();
        consumer.accept(configurationManager);
        return configurationManager;
    }
}

public class MainApp {
    public static void main(String[] args) {
        UserConfigurationManager.make(configManager -> configManager.setUserName("lokman").setPassword("12345"));
    }

Note: Fluent pattern can be used to define Model in JPA

Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...