Welcome back! Today, we'll master what we learned about backward compatibility in practice. Prepare to apply all the knowledge to practical tasks, but first, let's look at two examples and analyze them.
Let's say that initially, we have a complex data processing class designed to operate on a list of HashMaps
, applying a transformation that converts all string values within the HashMaps
to uppercase. Here's the initial version:
Java1import java.util.ArrayList; 2import java.util.HashMap; 3import java.util.List; 4import java.util.Map; 5 6class DataProcessor { 7 void processData(List<Map<String, Object>> items) { 8 List<Map<String, Object>> processedItems = new ArrayList<>(); 9 for (Map<String, Object> item : items) { 10 Map<String, Object> processedItem = new HashMap<>(); 11 for (Map.Entry<String, Object> entry : item.entrySet()) { 12 if (entry.getValue() instanceof String) { 13 processedItem.put(entry.getKey(), ((String) entry.getValue()).toUpperCase()); 14 } else { 15 processedItem.put(entry.getKey(), entry.getValue()); 16 } 17 } 18 processedItems.add(processedItem); 19 } 20 for (int i = 0; i < Math.min(3, processedItems.size()); i++) { 21 System.out.println("Processed Item: " + processedItems.get(i)); 22 } 23 } 24}
We intend to expand this functionality, adding capabilities to filter the items based on a condition and to allow for custom transformations. The aim is to retain backward compatibility while introducing these enhancements. Here's the updated approach using method overloading:
Java1import java.util.*; 2import java.util.function.Predicate; 3import java.util.function.Function; 4 5class DataProcessor { 6 void processData(List<Map<String, Object>> items) { 7 processData(items, item -> true, null); 8 } 9 10 void processData(List<Map<String, Object>> items, Function<Map<String, Object>, Map<String, Object>> transform) { 11 processData(items, item -> true, transform); 12 } 13 14 void processData(List<Map<String, Object>> items, Predicate<Map<String, Object>> condition, Function<Map<String, Object>, Map<String, Object>> transform) { 15 List<Map<String, Object>> processedItems = new ArrayList<>(); 16 for (Map<String, Object> item : items) { 17 if (condition.test(item)) { // Apply condition to filter items 18 Map<String, Object> processedItem; 19 if (transform != null) { 20 processedItem = transform.apply(item); // Apply custom transformation if provided 21 } else { 22 // Default transformation: Convert string values to uppercase 23 processedItem = new HashMap<>(); 24 for (Map.Entry<String, Object> entry : item.entrySet()) { 25 if (entry.getValue() instanceof String) { 26 processedItem.put(entry.getKey(), ((String) entry.getValue()).toUpperCase()); 27 } else { 28 processedItem.put(entry.getKey(), entry.getValue()); 29 } 30 } 31 } 32 processedItems.add(processedItem); 33 } 34 } 35 for (int i = 0; i < Math.min(3, processedItems.size()); i++) { 36 System.out.println("Processed Item: " + processedItems.get(i)); 37 } 38 } 39} 40 41// Usage examples: 42public class Main { 43 public static void main(String[] args) { 44 List<Map<String, Object>> data = new ArrayList<>(); 45 Map<String, Object> item1 = new HashMap<>(); 46 item1.put("name", "apple"); 47 item1.put("quantity", 10); 48 data.add(item1); 49 Map<String, Object> item2 = new HashMap<>(); 50 item2.put("name", "orange"); 51 item2.put("quantity", 5); 52 data.add(item2); 53 54 DataProcessor processor = new DataProcessor(); 55 56 // Default behavior - convert string values to uppercase 57 processor.processData(data); 58 59 // Custom filter - select items with a quantity greater than 5 60 processor.processData(data, item -> (Integer) item.get("quantity") > 5, null); 61 62 // Custom transformation - convert names to uppercase and multiply the quantity by 2 63 processor.processData(data, item -> { 64 Map<String, Object> transformed = new HashMap<>(); 65 for (Map.Entry<String, Object> entry : item.entrySet()) { 66 if (entry.getKey().equals("name")) { 67 transformed.put(entry.getKey(), ((String) entry.getValue()).toUpperCase()); 68 } else { 69 transformed.put(entry.getKey(), (Integer) entry.getValue() * 2); 70 } 71 } 72 return transformed; 73 }); 74 } 75}
In this evolved version, we've introduced method overloading with additional parameters: Predicate<Map<String, Object>> condition
to filter the input list based on a given condition, and Function<Map<String, Object>, Map<String, Object>> transform
for custom transformations of the filtered items. The default behavior processes all items, converting string values to uppercase, which ensures that the original functionality's behavior is maintained for existing code paths. This robust enhancement strategy facilitates adding new features to a function with significant complexity while preserving backward compatibility, showcasing an advanced application of evolving software capabilities responsively and responsibly.
Imagine now that we are building a music player, and recently, the market demands have grown. Now, users expect support not just for MP3 and WAV but also for FLAC files within our music player system. This development poses a unique challenge: How do we extend our music player's capabilities to embrace this new format without altering its established interface or the Adapter we've already implemented for WAV support?
Let's say that we currently have a MusicPlayer
class that can only play MP3 files:
Java1class MusicPlayer { 2 void play(String file) { 3 if (file.endsWith(".mp3")) { 4 System.out.println("Playing " + file + " as mp3."); 5 } else { 6 System.out.println("File format not supported."); 7 } 8 } 9}
Let's approach this challenge by introducing a composite adapter, a design that encapsulates multiple adapters or strategies to extend functionality in a modular and maintainable manner.
Java1class MusicPlayerAdapter { 2 private final MusicPlayer player; 3 private final Map<String, Runnable> formatAdapters; 4 private String file; 5 6 public MusicPlayerAdapter(MusicPlayer player) { 7 this.player = player; 8 this.formatAdapters = new HashMap<>(); 9 formatAdapters.put(".wav", this::convertAndPlayWav); 10 formatAdapters.put(".flac", this::convertAndPlayFlac); 11 } 12 13 public void play(String file) { 14 this.file = file; 15 String fileExtension = file.substring(file.lastIndexOf(".")).toLowerCase(); 16 Runnable adapterFunc = formatAdapters.get(fileExtension); 17 18 if (adapterFunc != null) { 19 adapterFunc.run(); 20 } else { 21 player.play(file); 22 } 23 } 24 25 private void convertAndPlayWav() { 26 // Simulate conversion 27 String convertedFile = file.replace(".wav", ".mp3"); 28 System.out.println("Converting " + file + " to " + convertedFile + " and playing as mp3..."); 29 player.play(convertedFile); 30 } 31 32 private void convertAndPlayFlac() { 33 // Simulate conversion 34 String convertedFile = file.replace(".flac", ".mp3"); 35 System.out.println("Converting " + file + " to " + convertedFile + " and playing as mp3..."); 36 player.play(convertedFile); 37 } 38} 39 40// Upgraded music player with enhanced functionality through the composite adapter 41public class Main { 42 public static void main(String[] args) { 43 MusicPlayer legacyPlayer = new MusicPlayer(); 44 MusicPlayerAdapter enhancedPlayer = new MusicPlayerAdapter(legacyPlayer); 45 enhancedPlayer.play("song.mp3"); // Supported directly 46 enhancedPlayer.play("song.wav"); // Supported through adaptation 47 enhancedPlayer.play("song.flac"); // Newly supported through additional adaptation 48 } 49}
This sophisticated adaptation strategy ensures that we can extend the MusicPlayer
to include support for additional file formats without disturbing its original code or the initial adapter pattern's implementation. The MusicPlayerAdapter
thus acts as a unified interface to the legacy MusicPlayer
, capable of handling various formats by determining the appropriate conversion strategy based on the file type.
Great job! You've delved into backward compatibility while learning how to utilize method overloading and the Adapter Design Pattern. Get ready for some hands-on practice to consolidate these concepts! Remember, practice makes perfect. Happy Coding!