「開いた人が閉じる」ルール
リソースを使うときは、open〜処理〜closeの流れが見渡せるように設計すること。
例えば↓のようにしないこと。
import java.io.FileInputStream; public class Hoge { public static FileInputStream open(String name) throws Exception { return new FileInputStream(name); } public static String read(FileInputStream stream) throws Exception { String ret = ""; //なんか処理をする。 stream.close(); //こうしない。 return ret; } public static void main(String[] args) throws Exception { FileInputStream hoge = open("hoge.txt"); System.out.println(read(hoge)); } }
コレは↓のようにすること。
import java.io.FileInputStream; public class Hoge { public static FileInputStream open(String name) throws Exception { return new FileInputStream(name); } public static String read(FileInputStream stream) throws Exception { String ret = ""; //なんか処理をする。 return ret; } public static void close(FileInputStream stream) throws Exception { stream.close(); } public static void main(String[] args) throws Exception { FileInputStream hoge = open("hoge.txt"); System.out.println(read(hoge)); close(hoge); } }
1つのメソッド内で、数行で見渡せるように。というか、リソースのopen/closeは1箇所にまとめるようにしたいけど、それはどこまでできるかな。
というか、超基礎ですいません。