function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Marco PoloMarco Polo 

How to semplify this class and make it easier to understand

Hi, I am new to developement, i would like to make this class easier and write this class as a junior dev woul write:


public with sharing class Inventory {

    public void run(){
        List<Inventory__c> items = (List<Inventory__c>) Trigger.new;
        Map<String, Inventory__c> parentItems = new Map<String, Inventory__c>();
        Map<String, List<Inventory__c>> childItems = new Map<String, List<Inventory__c>>();
        Map<Id, Inventory__c> itemsToUpdate = new Map<Id, Inventory__c>();
        for (Inventory__c item : items) {
            if (item.Parent_Serial__c == null) {
                parentItems.put(item.Serial__c, item);
            }
            else {
                List<Inventory__c> currentItems = new List<Inventory__c>(childItems.get(item.Parent_Serial__c));
                currentItems.add(item);
                childItems.put(item.Parent_Serial__c, currentItems);
            }
        }
        for (Inventory__c item : [SELECT Serial__c, Parent_Serial__c, Parent_Item__c FROM Inventory__c WHERE Parent_Serial__c IN :new List<String>(parentItems.keySet()) 
                                                                                                OR Serial__c IN :new List<String>(childItems.keySet())]) {
            if (item.Parent_Serial__c == null) {
                for (Inventory__c innerItem : childItems.get(item.Serial__c)) {
                    itemsToUpdate.put(innerItem.Id, new Inventory__c(Parent_Item__c = item.Id, Id = innerItem.Id));
                }
            }
            else {
                item.Parent_Item__c = parentItems.get(item.Parent_Serial__c).Id;
                itemsToUpdate.put(item.Id, item);
            }
        }
        if (!itemsToUpdate.isEmpty()) {
            update itemsToUpdate.values();
        }
    }
}
 
Marco PoloMarco Polo
If i would like to reproduce this class with for loop how could i accomplish that?
Thanks