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

Monday, October 21, 2024

Command Design Pattern using lambda expression

 Command design pattern: The main concept of command pattern is how the command will be executed that process is encapsulated in a class . So the the process will be hide into that class.

Command :  Command object knows about receiver and call a method of receiver.

Receiver:  Who receives command and acts based on that command;

Invoker: Who only have reference of command interface . Who does not know about the implementation of the command . 

Client: It hold all the list of command. Just invoke to the invoker whatever need .

Example:

Command:

public interface Command {
    void execute();
}

public class OnCommand implements Command {
    private Tv tv;
    public OnCommand(Tv tv) {
        this.tv = tv;
    }
    @Override
    public void execute() {
        tv.switchOn();
    }
}

 public class OffCommand implements Command {
    private Tv tv;
    public OffCommand(Tv tv) {
        this.tv = tv;
    }
    @Override
    public void execute() {
        tv.switchOff();
    }
}

Invoker:

public class RemoteControl {
    private List<Command> history = new ArrayList<>();
    public void press(Command command) {
        history.add(command);
        command.execute();
    }
}

Client:

public class TvClient {
    public static void main(String[] args) {
        Tv tv = new Tv();

        Command onCommand = new OnCommand(tv);

        Command offCommand = new OffCommand(tv);
        RemoteControl remote = new RemoteControl();
        remote.press(onCommand);
        remote.press(offCommand);
    }
}

Here command interface has  one abstract method. So we can use lambda expression here . so no need to create OnCommand and OffCommand class .

public class TvClient {
    public static void main(String[] args) {
        Tv tv = new Tv();
        RemoteControl remote = new RemoteControl();
        remote.press(tv - > switchOn);
        remote.press(tv -> switchOff);

    }

we can replace it using method reference also ,

public class TvClient {
    public static void main(String[] args) {
        Tv tv = new Tv();
        RemoteControl remote = new RemoteControl();
        remote.press(tv:: switchOn);
        remote.press(tv:: switchOff);

    }
}

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

  Elements of the Ideal Table: It represents a single subject, which can be an object or event that reduces the risk of potential data integ...