パンくず
Effective Java
パラメータの正当性を検証する
概要
パラメータの正当性を検証する
詳細
サンプルコード
package effective.creation.chapter6; public class SampleNo38 { public static void main(String[] args) { printPrivateHoge("hoge"); printPrivateHoge(""); printPrivateHoge(null); printPublicHoge("hoge"); try { printPublicHoge(""); } catch (Exception e) { e.printStackTrace(); } try { printPublicHoge(null); } catch (Exception e) { e.printStackTrace(); } } /** * 引数で指定した文字列を出力する。 * * <pre> * 指定した文字列がnull、もしくは空文字の場合に * IllegalArgumentExceptionをthrowする。 * </pre> * * @param hoge 任意の文字列 */ public static void printPublicHoge(String hoge) { if (hoge == null) { throw new IllegalArgumentException("hoge is null"); } if (hoge == "") { throw new IllegalArgumentException("hoge is empty"); } System.out.println(hoge); } private static void printPrivateHoge(String hoge) { assert hoge != null; assert hoge != ""; System.out.println(hoge); } }
出力
hoge null hoge java.lang.IllegalArgumentException: hoge is empty at effective.creation.chapter6.SampleNo38.printPublicHoge(SampleNo38.java:38) at effective.creation.chapter6.SampleNo38.main(SampleNo38.java:11) java.lang.IllegalArgumentException: hoge is null at effective.creation.chapter6.SampleNo38.printPublicHoge(SampleNo38.java:35) at effective.creation.chapter6.SampleNo38.main(SampleNo38.java:16)