问题描述
我只是用Flutter的BLoC架构弄湿了我的脚.在这里,我希望创建一个 Bloc
类,这将帮助我将用户输入转换为流数据的形式.为了完成该任务,假设我首先创建一个名为 email
的 Bloc
类的实例,然后
I'm just getting my feet wet with the BLoC architecture of Flutter. Here, I wish to create a Bloc
class, which will help me to convert the user input in the form of stream data. To do that task, let's say that first of all I create an instance of Bloc
class with the name email
and then,
- 使用代码段0&然后调用
email.emailController.sink.add(some_string)
- 或者利用代码段1,然后调用
email.streamEmail(some_string)
- 或者,使用代码段2的代码,然后调用
email.streamEmail(some_string)
向流中添加字符串输入
代码段:
//Snippet 0 : w/o any `method`
class Bloc{
final emailController = StreamController<String>();
}
//Snippet 1 : using regular 'method'
class Bloc{
final emailController = StreamController<String>();
void streamEmail(String value) => emailController.sink.add(value);
}
//Snippet 2 : using 'get' based 'method'
class Bloc{
final emailController = StreamController<String>();
Function(String) get streamEmail => emailController.sink.add;
}
我了解到,就代码的可读性而言,使用代码段1或2更好.我知道该片段1&2是做同一件事的2种不同方式.但是,我不清楚片段2通过使用getter方法带来的差异.
I learned that making use of snippet 1 or 2 is a rather better to approach, in terms of code readability.I know that snippet 1& 2 are just 2 different ways of doing the same thing. However, I'm not clear about the differences that snippet 2 brings in, by making use of the getter method.
来自 Dart语言之旅,
目前,我对getter的唯一了解是它们代表了一种在类中定义方法的替代方法.所以,确切地说,我的问题是:
At the moment, the only thing I understand about getters is that they represent an alternative approach to define methods within a class. So, to be precise my questions are :
- 使用getter方法是否会增强或降低应用程序内.性能?
- 何时&为什么我应该使用代码段2类型类定义而不是代码段1?
推荐答案
否,使用getter/setter代替方法不会影响性能.
No, using getter/setter instead of methods does not impact performance.
何时使用getter/setter是有关口味的问题,与其他开发人员相比,某些开发人员更可能使用它们.我猜一般的设计目标应该是:getter/setter的行为类似于对象的常规属性,因此,除了获取/设置属性之外,不应做出任何其他未知行为.(例如,获取对象的属性将最终将某些文件保存到文件系统中.)
When to use getters/setters is a question about taste and some developers are more likely to use them than others. I guess a general design goal should be that getters/setters acts like normal properties on an object and should therefore not make any additional unknown behavior than getting/setting a property. (e.g. get a property of a objects will end up saving some files to the file system).
在您的示例中,我将使用代码段1(也许使用不同的方法名称),因为您的示例并不是使用属性的好用例.片段2似乎是强迫使用吸气剂的明智尝试,由于吸气剂最终返回功能,最终变得有点怪异.
In your example I would go with snippet 1 (and maybe with a different name of the method) since your example is not really a good use case of using properties. Snippet 2 seems like a forced clever attempt to make use a getter which ends up being a little weird since the getter ends up returning a Function.
但是,这又是一个关于品味的问题,我敢肯定,有些开发人员会使用代码段2.
But again, this is a question about taste and I am sure there are some developers which would go with snippet 2.
这篇关于Dart中的getter和常规方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!