How to exclude debug code
Asked Answered
L

2

5

Let's say I have simple logger:

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

I want this code to run in the dev mode (VM checked mode) but i don't want it in my production code. And i want it to be "tree shaked" away with the dart2js compiler. Is there some standard way?

Lovieloving answered 13/6, 2014 at 14:50 Comment(0)
L
6

You could embed the code in an assert. Assertions are ignored in production code and I'm sure not built to JS when pub build is run in release mode.

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
}

When you create a wrapper method that returns true than you don't have to do it explicit each time.

You can also take a look at this question How to achieve precompiler directive like functionality

Lilywhite answered 13/6, 2014 at 14:52 Comment(1)
Why do I need create a new instance of X, if I can just call print(m) (instead new X()...log(m)), inside wrapper "log" function?Hammerlock
L
2

I put @GünterZöchbauer "assert trick" inside the factory constructor:

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");
}

This way nothing sticks out.

Lovieloving answered 13/6, 2014 at 16:28 Comment(4)
Seems I misunderstood your question about the factory constructor. Thanks for posting your solution.Ecdysis
@GünterZöchbauer I should spend some time learning not only Dart but also English :P I deleted my comment to Your's answer and You, probably, should fix it a bit to make it clearer.Lovieloving
Sorry, I'm not sure what you mean by 'make it clearer' make what clear?Ecdysis
@GünterZöchbauer Code sample could be more concise without the factory boilerplate, because it has nothing to do with the original question and exists only as a result of me misleading you with the unclear comment.Lovieloving

© 2022 - 2024 — McMap. All rights reserved.