You need to sign in to do that
Don't have an account?
Marco 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();
}
}
}
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();
}
}
}
Thanks