使用精确的Java方法参数
了解如何在Java應用程序中選擇正確的方法參數類型并獲得更健壯和更短的代碼。
我們Java開發人員通常有一個使用方法參數的壞習慣,即不考慮實際需要什么,而只是選擇我們習慣的,可用的或首先想到的東西。 考慮以下代表性示例:
private static String poem(Map<Integer, String> numberToWord) {return new StringBuilder().append("There can be only ").append(numberToWord.get(1)).append(" of you.\n").append("Harts are better of when there are ").append(numberToWord.get(2)).append(" of them together.\n").append("These ").append(numberToWord.get(3)).append(" red roses are a symbol of my love to you.\n").toString();}使用上面的方法時,我們提供了一個將數字轉換為字符串的Map。 例如,我們可能提供以下地圖:
Map<Integer, String> englishMap = new HashMap<>();englishMap.put(1, "one");englishMap.put(2, "two");englishMap.put(3, "three");當我們用englishMap調用我們的詩歌方法時,該方法將產生以下輸出:
There can be only one of you. Harts are better of when there are two of them together. These three red roses are a symbol of my love to you.聽起來不錯。 現在,假設您的重要人物是計算機迷,并且想為自己的詩增添趣味并給人留下深刻的印象,那么這就是要走的路:
Map<Integer, String> nerdMap = new HashMap<>();nerdMap.put(1, "1");nerdMap.put(2, "10");nerdMap.put(3, "11");如果現在將nerdMap提交給poem方法,它將產生以下詩:
There can be only 1 of you. Harts are better of when there are 10 of them together. These 11 red roses are a symbol of my love to you.與所有詩歌一樣,很難判斷哪首詩比另一首更浪漫,但我當然有自己的看法。
問題所在
上面的解決方案有幾個問題:
首先,作為外部呼叫者,我們不能確定poem方法不會更改我們提供的Map。 畢竟,我們提供了一張地圖,沒有什么阻止接收者對地圖做任何可能的事情,甚至完全清除整個地圖。 當然可以通過使用Collections.unmodifiableMap()方法包裝Map或提供現有地圖的副本來避免此副本,從而避免該副本。
其次,當我們只需要將整數轉換為String的內容時,我們就不得不使用Map。 在某些情況下,這可能會創建不必要的代碼。 回想我們的nerdMap,可以使用Integer :: toBinaryString輕松計算地圖中的值,而無需手動映射它們。
解決方案
我們應該努力準確地提供在任何給定情況下所需的內容,而不是更多。 在我們的示例中,我們應該修改poem方法以采用從整數到字符串的函數。 在調用方上如何實現此功能的重要性較低,它可以是映射或函數,也可以是代碼或其他東西。 首先,這是應該如何做:
private static String poem(IntFunction<String> numberToWord) {return new StringBuilder().append("There can be only ").append(numberToWord.apply(1)).append(" of you.\n").append("Harts are better of when there are ").append(numberToWord.apply(2)).append(" of them together.\n").append("These ").append(numberToWord.apply(3)).append(" red roses are a symbol of my love to you.\n").toString();}如果我們想將poem方法與Map一起使用,則可以這樣簡單地調用它:
// Expose only the Map::get methodSystem.out.println(poem(englishMap::get));如果我們想像書呆子詩一樣計算值,那么我們可以做得更簡單:
System.out.println(poem(Integer::toBinaryString));哎呀,我們甚至可以為另一種患有雙重人格障礙的人寫一首詩:
System.out.println(poem(no -> englishMap.getOrDefault(no + 1, Integer.toString(no + 1))));這將產生以下詩歌:
There can be only two of you. Harts are better of when there are three of them together. These 4 red roses are a symbol of my love to you.注意您的方法參數!
翻譯自: https://www.javacodegeeks.com/2017/06/use-precise-java-method-parameters.html
總結
以上是生活随笔為你收集整理的使用精确的Java方法参数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 虎眼石适合什么生肖带(黄虎眼石佩戴禁忌)
- 下一篇: win10系统实现滑动关机的解决方法(图