2


コードを因数分解する方法を学んでいるので、入力ファイルからcharを取得するためだけの関数を作成するとよいと思いました。これは私が念頭に置いていることです:

    public char getChar( String infile )
    {
       try
       {
           BufferedReader in = new BufferedReader( new FileReader( infile ));
           int ch = in.read();
           // do some decision making
           return (char)ch;
       }
       catch( IOException e )
       {
           System.out.println( e.getMessage() );
           System.exit(1);
       } 
     }

次に、コンストラクターまたは別の関数で、次のように使用できます。

    public constructor( String infile )
    {
        char newChar = getChar( infile ); 
        // some lines of codes later.. need another character
        newChar = getChar( infile );
    }

PS私はこれらのコードをテストしていないので、エラーが含まれている可能性がありますが、私の考えが理解できることを願っています。

これが良い/悪い考えなのか、それともこの種のファクタリングがさまざまな方法で実行できるのかを教えてください。読んでくれてありがとう。

編集:はい、私はBufferedReaderが次の文字を行に取得することを望んでいます..そして最初からやり直さないでください
例:infileには次のような文字列が含まれています: "ABC"
thisShouldBeA = getChar(infile);
thisSoundBeB = getChar(inflie);

4

1 に答える 1

1
class Helper {
  private BufferedReader in;

  Helper(String infile) {
    this.in = new BufferedReader(new FileReader(infile));
  }

  char getChar() {
    try {
      return in.read();
    } catch (IOException e) {
       System.out.println( e.getMessage() );
       System.exit(1);
    }
  }

  void close() {
    this.in.close();
  }
}

class Other {
  void something(String infile) {
    Helper helper = new Helper(infile);
    char newChar = helper.getChar();
    char anotherNewChar = helper.getChar();

    helper.close();
   }
}
于 2013-01-28T22:34:19.830 に答える