Good practice to hold a file or channel in a class

2019-07-19 04:23发布

问题:

In the following code, I am trying to make a class which can write something to a log file when asked via a method. Here, I am wondering if this is an idiomatic way for this purpose, or possibly is there a more recommended way, e.g., hold a separate field of file type (for some reason)? In other words, is it pratically no problem even if I hold only a channel type?

class Myclass {
    var logfile: channel;

    proc init() {
        writeln( "creating log.out" );
        logfile = openwriter( "log.out" );
    }
    proc log( x ) {
        logfile.writeln( x );
    }
}

proc main() {
    var a = new borrowed Myclass();
    a.log( 10 );
    a.log( "orange" );
}

回答1:

I believe what you're doing here is reasonable. The distinction between files and channels in Chapel is primarily made in support of the language's parallel computing theme, in order to support having multiple tasks access a single logical file simultaneously using distinct channels (views into the file, essentially). In a case like yours, there is a file underlying the channel you've created, but there's no need to explicitly store it if you have no need to interact further with it.

So I believe there is no practical problem to simply storing a channel as you have here.