我是一名资深的C#开发人员,现在正在学习dart /Flutter 翼.在c#中,我更喜欢提前返回模式,例如:
private void myHandler()
{
if (checkSomething())
{
doSomething();
return;
}
if (checkSomethingElse())
{
doSomethingElse();
return;
}
doRegularStuff();
}
这在DART中也被普遍认为是好的做法吗?我在DART中创建了以下键盘处理程序,灵感来自于我在网上找到的各种示例.对于格式,我使用了dart format
命令行命令.老实说,我觉得真的很难看:
/// Handles key presses.
KeyEventResult _keyPressed(FocusNode node, KeyEvent event) {
if (event is! KeyDownEvent) return KeyEventResult.ignored;
if (event.isBarcodeChar()) {
_keyboardBuffer.write(event.character);
} else if (event.isBackspaceKey() && _keyboardBuffer.isNotEmpty) {
String shortenedBuffer =
_keyboardBuffer.toString().substring(0, _keyboardBuffer.length - 1);
_keyboardBuffer.clear();
_keyboardBuffer.write(shortenedBuffer);
} else if (event.logicalKey == LogicalKeyboardKey.enter) {
_codeScanned(_keyboardBuffer.toString());
_keyboardBuffer.clear();
} else {
return KeyEventResult.ignored;
}
return KeyEventResult.handled;
}
/// Handles scaned barcodes.
void _codeScanned(String code) {
// Handle some stuff and update the state of the application
}
}
当_keyPressed
方法返回handled
或ignored
时,它的代码并不清楚.它看起来也真的结成了一团.我还在c#中了解到,所有这else if
条语句都有一股难闻的味道.那么,在DART中使用提前返回模式是否也是一个很好的练习呢?
附加问题:在DART中创建像My void _codeScanned()
这样的一次性方法来提高可读性被认为是好做法吗?该方法只能从键盘处理程序内部使用,不能在其他地方使用.
官方的DART编码指南在这方面相当不清楚(或者我太愚蠢了,找不到合适的章节).因此,感谢您提前给予我们深刻的帮助.