【问题标题】:How to exclude debug code如何排除调试代码
【发布时间】:2014-08-04 04:24:54
【问题描述】:

假设我有一个简单的记录器:

void main() {
  var logger = new MyLogger();
  logger.log("hello Dart");
}

我希望此代码在开发模式(VM 检查模式)下运行,但我不希望它出现在我的生产代码中。我希望它被 dart2js 编译器“摇动”掉。有什么标准方法吗?

【问题讨论】:

    标签: dart flutter dart2js


    【解决方案1】:

    您可以将代码嵌入assert。断言在生产代码中被忽略,当pub buildrelease 模式下运行时,我肯定不会为 JS 构建。

    class X {
      X() {
        print('x created');
      }
    
      void log(String m) {
        print(m);
      }
    }
    
    bool log(String m) {
      new X()..log(m);
          return true;
    }
    
    void main() {
      assert(() {
        new X()..log('in Assert');
        return true;
      });
    
      assert(() => log('in Assert')); // use a wrapper function
    }
    

    当您创建一个返回 true 的包装器方法时,您不必每次都显式地执行此操作。

    你也可以看看这个问题How to achieve precompiler directive like functionality

    【讨论】:

      【解决方案2】:

      我将@GünterZöchbauer“断言技巧”放在工厂构造函数中:

      class _ProductionPlug implements DebugClass{
        const _ProductionPlug();
        noSuchMethod(_) {} //do nothing
      }
      
      class DebugClass{
        static final DebugClass _plug = const _ProductionPlug();
        log(msg){print(msg);}
        DebugClass._(){}
        factory DebugClass(){
          DebugClass instance;
          assert((){
          instance = new DebugClass._();
          return true;
              });
          return instance != null ?  instance :  _plug;
        }
      }
      void main() {
        print("hello");
        new DebugClass()
          ..log("debugging");
      }
      

      这样就没有什么突出的了。

      【讨论】:

      • 似乎我误解了你关于工厂构造函数的问题。感谢您发布您的解决方案。
      • 抱歉,我不知道你所说的“让它更清楚”是什么意思,让什么清楚?
      • @GünterZöchbauer 代码示例在没有工厂样板的情况下可能会更简洁,因为它与原始问题无关,只是因为我用不明确的评论误导了你而存在。
      猜你喜欢
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2023-03-16
      • 2015-11-15
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      相关资源
      最近更新 更多