Let's say I am working with bicycles and I need to group them by different criterias.
class Bicycle {
String brand { get; set; }
Date purchaseDate { get; set; }
}
class GroupedBicycles {
String groupingCriteria { get; set; }
/*
will contain all bikes with this criteria
for example, if grouped by brand, all bikes in this list will have current brand
*/
List<Bicycle> bicycles { get; set; }
}
class BicyclesByBrand extends GroupedBicycles {
}
class BicyclesByPurchaseDate extends GroupedBicycles {
Date groupingCriteria { get; set; } // will contain purchase date
}
List<BicyclesByBrand> groupBicyclesByBrand(List<Bicycle> bicycles) {
List<BicyclesByBrand> result = new List<BicyclesByBrand>();
// Here is my own logic for grouping bicycles by criteria
for (Bicycle bike : bicycles) {
Boolean thisBikeIsGrouped = false;
for (BicyclesByBrand bikesByBrand : result) {
if (bikesByBrand.groupingCriteria == bike.brand) { // **MARK1 will explain below**
bikesByBrand.bicycles.add(bike);
thisBikeIsGrouped = true;
break;
}
}
if (!thisBikeIsGrouped) {
BicyclesByBrand bikesByBrand = new BicyclesByBrand();
bikesByBrand.groupingCriteria = bike.brand;
bikesByBrand.bikes = new List<Bicycle> { bike };
}
}
return result;
}
the issue for me is that for grouping bikes by purchase date, I need to copy the same method and change only line marked as MARK1 Field needs to be changed from brand to purchaseDate.
Is there a way in apex to create this method only once, but pass field for grouping as parameter? I believe this is possible in java by using reflection.
I expect this method to have following signature:
List<GroupedBicycles> groupBicyclesList<Bicycle> bicycles, String fieldCriteria)
I have already implemented displaying this data in visualforce, I have one apex:repeat that uses base class as var attribute, and in controller different implementations are assigned depending on grouping selected, so I am aiming to do minimal changes of data structure.
groupingCriteriaforBicyclesByPurchaseDate. Perhaps that boolean If conditions needs to be abstracted into another method. As in a Criteria Method or subclass. Even as an interface perhaps? – crmprogdev May 13 '16 at 15:10Map<String,List<Bicycle>>orMap<Date,List<Bicycle>>would do the exact same thing? – Sebastian Kessel May 13 '16 at 15:15