Hacker Newsnew | comments | show | ask | jobs | submit login

Here is another way to refactor that example in JS -

    // constructor for the FileInfo class
    FileInfo = function(filename) {
    
      function withFile(block) {
        var f;
        try {
          f = File.open(filename, "r");
          return block(f);
        } finally {
          f.close();
        }
      }

      this.mtime = function () {
        var mtime = withFile(File.mtime);
    
        if (mtime < new Date() - 1000) {
          return "too old";
        }

        sys.print(mtime);
      };
    
      this.body = function () {
        return withFile(function (f) { return f.read(); });
      };
    
    };
 
An advantage with this refactoring is that the file handle, which isn't required after getting the mtime, is closed before doing other things.



Applications are open for YC Winter 2016

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: