Should I always use "this" in Dart? - flutter

Is it a good practice to use always 'this' in a method.
Even if there is no usage of the same variable name as input to this method.
String getStory(number) {
return this.storyData[number];
}
By doing this there won't have any conflicts with any input variable name (never).
Thank you in advance for your feedback.

Generally this. is only supposed to be used when there is ambiguity about what variable is being used.
class Test{
final int x;
Test(this.x);
}

Related

How to take integer input from user in dart

i am new in dart and just want to know how to take integer input from user in dart with null safety. i found out a way to take number input from dart which is:
String? chossenNumber = stdin. readLineSync();
if(chossenNumber !=null)
{
int number = int.parse(chossenNumber);
}
but i am unable to use number variable outside of the scope. Please tell me a way to solve this issue.
You can define the variable at the top of the class and initialize it here so you will be able to use it everywhere in the class
The solution of it very simple just take input of number as String i.e
String? chossenNumber = stdin. readLineSync();
and when you want to use this variable parse it to the 'int' i.e
if(int.parse(chossenNumber) <100)
{
print("Your Statement");
}

Dart: How to force string interpolation on a variable

I have a variable that contains a string with interpolated variables. In the code below, that variable is template. When I pass this variable to generateString function, I want to apply string interpolation on it because the values which interpolated variables require are available in generateString function only.
void main() {
String template = '<p>\${name}</p>';
var res = generateString(template);
}
generateString(template) {
var name = 'abc';
print(template);
return template;
}
The problem is when I am printing and returning template inside generateString fn, I am getting <p>${name}</p> instead of <p>abc</p>. Is there a way to explicitly tell the dart to so string interpolation?
I am new to Dart. I don't know if it is even possible to achieve or not. Please suggest how do I do this.
Edit: Based on the inputs from other users, I would like to make a clarification about the scenario presented. The value of template variable is not a string literal. I get that from UI as a user input. I have shown it here as a string literal for code simplicity. Also, please consider that name and template are not in the same scope in my scenario.
The other answers so far are wrong.
String interpolation (looking for $, etc) happens only while compiling from the source code to the value in memory. If that string in turn also has a $, it's no longer special.
It's not possible to trigger interpolation past the original compilation step. You can write a templating system that would look for something like {{name}} in the value, and replace it with the current value of name.
If you have the template and the variable in the same scope, it works as expected.
// evaluate variable inside ${}
var sport = 'basketball';
String template = 'I like <p>${sport}</p>';
print(template);
I didn't fully understand your question maybe this will help
void main() {
print(generateString('abc')); //<p>abc</p>
}
generateString(String template) {
return r"<p>" "$template" r"</p>";
}
Walter White here.
You must define the variable name as global var, so it can "cook" the string for you

What does mean of using the "this" keyword in Dart?

I'm sorry if this sounds like an extremely foolish question but it's really been bugging me.
What is the "this." that I see? Whenever I see the documentation in flutter I see it used in things like the following in the documentation:
this.initialRoute,
this.onGenerateRoute,
this.onGenerateInitialRoutes,
this.onUnknownRoute,
this.navigatorObservers
I'll be more than happy to also read up any links or documentation regarding it.
The 'this' keyword refers to the current instance.
You only need to use this when there is a name conflict. Otherwise, Dart style omits the this.
class Car {
String engine;
void newEngine({String engine}) {
if (engine!= null) {
this.engine= engine;
}
}
}
So you can be consistent with the name of your parameters, either in the constructor or in some function in the class.
class Car {
String engine;
void updateEngine({String someWeirdName}) {
engine = someWeirdName;
}
}
If you don't have a name conflict, you don't need to use this.
In other languages ​​like Python and Swift, the word 'self' will do the same thing as 'this'.
Basically, this keyword is used to denotes the current instance. Check out the below example.
void main() {
Person mike = Person(21);
print(mike.height);
}
class Person {
double height;
Person(double height) {
height = height;
}
}
When we run this dart code, it outputs null as the height. Because we have used height = height inside the Person constructor, but the code doesn't know which height is the class property.
Therefore, we can use this keyword to denotes the current instance and it will help the code to understand which height belongs to the class. So, we can use it as below and we will get the correct output.
void main() {
Person mike = Person(21);
print(mike.height);
}
class Person {
double height;
Person(double height) {
this.height = height;
}
}
Use of this keyword
The this keyword is used to point the current class object.
It can be used to refer to the present class variables.
We can instantiate or invoke the current class constructor using this keyword.
We can pass this keyword as a parameter in the constructor call.
We can pass this keyword as a parameter in the method call.
It removes the ambiguity or naming conflict in the constructor or method of our instance/object.
It can be used to return the current class instance.

Better way to do class type alias?

From time to time, I would like to call a class differently depending on the context or to reduce duplication.
Let's assume, I have the following classes defined:
// in file a.dart
class A {
final String someprop;
A(this.someprop)
}
// in file b.dart
abstract class BInterface {
String get someprop;
}
class B = A with EmptyMixin implements BInterface;
For this syntax to check out, I have to define EmptyMixin so that the syntax is OK.
Do you know of a better/prettier way to do this "aliasing" in Dart?
I'm afraid the way you're doing it is the prettiest way to do this at the moment. There is a very old, but still open and active issue: https://github.com/dart-lang/sdk/issues/2626 that proposes the typedef B = A; syntax for aliasing types.

Is it bad practice to have my getter method change the stored value?

Is it bad practice to change my getter method like version 2 in my class.
Version 1:
public String getMyValue(){
return this.myValue
}
Version 2:
public String getMyValue(){
if(this.myValue == null || this.myValue.isEmpty()){
this.myValue = "N/A";
}
return this.myValue;
}
I think it is actually quite a bad practice if your getter methods change the internal state of the object.
To achieve the same I would suggest just returning the "N/A".
Generally speaking this internal field might be used in other places (internally) for which you don't need to use the getter method. So in the end, the call to foo.getMyValue() could actually change the behaviour of foo.
Alternatively, the translation from null to "N/A" could be done in the setter, i.e. the internal value could be set to "N/A" if null is passed.
A general remark:
I would only add states such as "N/A" if they are expected by some API or other instance relying on your code. If that is not the case you should rely on the standard null types that are available to you in your programming language.
In my opinion, unless you are doing lazy-loading (which you are not in that case), getters should not change the value. So I would either:
Put the change in the setter
public void setMyValue(String value) {
if(value == null || value.isEmpty()){
this.myValue = "N/A";
} else {
this.myValue = value;
}
}
Or make the getter return a default value if value not set properly:
public String getMyValue() {
if(this.myvalue == null || this.myvalue.isEmpty()){
return "N/A";
}
return this.myValue;
}
In the case of lazy-loading, where I would say that changing your members in a getter is fine, you would do something like:
public String getMyValue() {
if (this.myvalue == null) {
this.myvalue = loadMyValue();
}
return this.myValue;
}
No. You're doing two things here. Getting and setting.
Yes. It's a bad practice.
Why?
When the value is set (in a constructor or setter method), it should be validated, not when a getter method is called. Creating a private validate* method for this is also a good idea.
private boolean validateThisValue(String a) {
return this.myValue != null && !this.myValue.isEmpty();
}
public void setThisValue(String a) {
if (validateThisValue(a)) {
this.myValue = a;
}
else {
// do something else
// in this example will be
this.myValue = "N/A";
}
}
And, in the getter method, never ever change the state of the object. I have worked on some projects, and the getter often must be made const: "this method cannot change internal state".
At least, if you do not want to complicate things, in the getter method, you should return "N/A" rather than change internal state and set myValue to "N/A".
I usually define a specific getter.
Never alter original getter:
public String getMyValue(){
return this.myValue
}
And create a specific getter:
public String getMyValueFormatted(){
if(this.myvalue == null || this.myvalue.isEmpty()){
return "N/A";
}else{
return this.myValue;
}
}
I think it's better to initialize this.myValue = "N/A". And subsequent calls to setMyValue should modify the this.myValue according to your business conditions.
The getMyValue shouldn't modify in any way this.myValue. If your needs are to return a certain value, you should return that value (like "N/A") and not alter this.myValue . Getters must not modify member's value.
I would change better the setter method so, if the value is null or empty, the N/A is assigned to the attribute. So, if you use the attribute in other methods inside the class (v.g. toString()) you will have the intended value there.
Alternatively, change the setter method to launch an exception when the value being set is not right, so the programmer is forced to improve its handling prior to setting the value.
Other than that, it is ok.
I do feel this is a bad practice unless and until you explain the reason why it is so necessary for you modify the object inside the getter method instead of doing it inside the setter method.
Do you feel this cannot be done for some reason? Could you please elaborate?
Do what ever you like. After all getters and setters are just another public methods. You could use any other names.
But if you use frameworks like Spring, you are bound to use those standard names and you should never put your custom codes inside them.
absolutely yes, it's a bad pratice.
Imagine you communicate accross network with a third party (remoting, COM, ...), this will increase the round-trip and then hit application performance.
A setter could modify as part of validation, but a getter should return the value and let the validation be done by the caller. If you do validate, then how should be documented.
This actually highly depends on the contract you want to enforce with your get()-method. According to design-by-contract conventions the caller has to make sure that the preconditions are met (which means doing a validation in a setter method often is actually bad design) and the callee (I do not know if that's the correct english term for that, i.e., the called one) makes sure that the post conditions are met.
If you define your contract so that the get()-method is not allowed to change the object then you are breaking your own contract. Think about implementing a method like
public isValid() {
return (this.myvalue == null || this.myvalue.isEmpty());
}
Advantage of this approach is that you do not have to check wether the return of your get() is "N/A" or something else. This also can be called before calling set() to validate that you do not insert illegal values into your object.
If you want to set a default value you should do that during initialization.
State changes in getters should be a hanging offence. It means that client code must be careful about the order in which it accesses getters and setters and to do this it must have knowledge of the implementation. You should be able to call the getters in any order and still get the same results. A related problem occurs when the setter modifies the incoming value depending on the current state of the object.
You can use some value holder for this purpose. Like Optional class in guava library.