Nombrar datos
En su forma más simple, la programación informática se basa en la manipulación de datos, ya que todo lo que se ve en la pantalla se puede reducir a números. A veces se representan y se trabaja con datos como diversos tipos de números, pero otras veces, los datos se presentan en formatos más complejos, como texto, imágenes y colecciones.
En tu código Dart, puedes asignar a cada dato un nombre que puedas usar para referirte a él más adelante. El nombre lleva asociado un tipo que indica a qué tipo de dato se refiere, como texto, números o una fecha. Aprenderás sobre algunos de los tipos básicos en este capítulo y encontrarás muchos otros tipos a lo largo del libro.
Variables
Eche un vistazo a lo siguiente:
int number = 10;
Esta declaración declara una variable llamada number
de tipo int
. A continuación, asigna el valor de la variable al número 10
. La parte int
de la declaración se conoce como anotación de tipo, que indica a Dart explícitamente el tipo.
Una variable se llama variable porque su valor puede cambiar. Si desea cambiar el valor de una variable, simplemente puede asignarle un valor diferente del mismo tipo:
int number = 10;
= 15; number
number
comenzó como 10
pero luego cambió a 15
.
El tipo int
puede almacenar números enteros. La forma de almacenar números decimales es la siguiente:
double apple = 3.14159;
Esto es similar al ejemplo int
. Sin embargo, esta vez la variable es double
, un tipo que puede almacenar decimales con alta precisión.
Para los lectores familiarizados con la programación orientada a objetos, les interesará saber que 10
, 3.14159
y cualquier otro valor que se pueda asignar a una variable son objetos en Dart. De hecho, Dart no tiene los tipos de variable primitivos que existen en algunos lenguajes. Todo es un objeto. Aunque int
y double
parecen primitivos, son subclases de num
, que a su vez es una subclase de Object
.
Con los números como objetos, esto te permite hacer algunas cosas interesantes:
10.isEven
// true
3.14159.round()
// 3
Type Safety (Seguridad de tipos)
Dart is a type-safe language. That means once you tell Dart what a variable’s type is, you can’t change it later. Here’s an example:
int myInteger = 10;
= 3.14159; // No, no, no. That's not allowed :] myInteger
3.14159 is a double
, but you already defined myInteger
as an int
. No changes allowed!
Dart’s type safety will save you countless hours when coding since the compiler will tell you immediately whenever you try to give a variable the wrong type. This prevents you from having to chase down bugs after you experience runtime crashes.
Of course, sometimes it’s useful to be able to assign related types to the same variable. That’s still possible. For example, you could solve the problem above, where you want myNumber
to store both an integer and floating-point value, like so:
num myNumber;= 10; // OK
myNumber = 3.14159; // OK
myNumber = `ten`; //No, no, no. myNumber
The num
type can be either an int
or a double
, so the first two assignments work. However, the string value ‘ten’ is of a different type, so the compiler complains.
Now, if you like living dangerously, you can throw safety to the wind and use the dynamic
type. This lets you assign any data type you like to your variable, and the compiler won’t warn you about anything.
dynamic myVariable;
= 10; // OK
myVariable = 3.14159; // OK
myVariable = 'ten'; // OK myVariable
But, honestly, don’t do that. Friends don’t let friends use dynamic
. Your life is too valuable for that.
In Chapter 3, “Types & Operations”, you’ll learn more about types.
Type Inference
Dart is smart in a lot of ways. You don’t even have to tell it the type of a variable, and Dart can still figure out what you mean. The var
keyword says to Dart, “Use whatever type is appropriate.”
var someNumber = 10;
There’s no need to tell Dart that 10
is an integer. Dart infers the type and makes someNumber
an int
. Type safety still applies, though:
var someNumber = 10;
= 15; // OK
someNumber = 3.14159; // No, no, no. someNumber
Trying to set someNumber
to a double
will result in an error. Your program won’t even compile. Quick catch; time saved. Thanks, Dart!
Constants
Dart has two different types of “variables” whose values never change. They are declared with the const
and final
keywords, and the following sections will show the difference between the two.
Const Constants
Variables whose value you can change are known as mutable data. Mutables certainly have their place in programs, but can also present problems. It’s easy to lose track of all the places in your code that can change the value of a particular variable. For that reason, you should use constants rather than variables whenever possible. These unchangeable variables are known as immutable fata.
To create a constant in Dart, use the const keyword:
const myConstant = 10;
Just as with var
, Dart uses type inference to determine that myConstant
is an int
.
Once you’ve declared a constant, you can’t change its data. For example, consider the following example:
const myConstant = 10;
= 0; // Not allowed. myConstant
The previous code produces an error:
't be assigned a value. Constant variables can
In VS Code, you would see the error represented this way:
If you think “constant variable” sounds a little oxymoronic, just remember that it’s in good company: virtual reality, advanced BASIC, readable Perl and internet security.
Final Constants
Often, you know you’ll want a constant in your program, but you don’t know what its value is at compile time. You’ll only know the value after the program starts running. This kind of constant is known as a runtime constant.
In Dart, const
is only used for compile-time constants; that is, for values that can be determined by the compiler before the program ever starts running.
If you can’t create a const
variable because you don’t know its value at compile time, then you must use the final
keyword to make it a runtime constant. There are many reasons you might not know a value until after your program is running. For example, you might need to fetch a value from the server, or query the device settings, or ask a user to input their age.
Here is another example of a runtime value:
final hoursSinceMidnight = DateTime.now().hour;
DateTime.now()
is a Dart function that tells you the current date and time when the code is run. Adding hour
to that tells you the number of hours that have passed since the beginning of the day. Since that code will produce different results depending on the time of day, this most definitely a runtime value. So to make hoursSinceMidnight
a constant, you must use the final
keyword instead of const
.
If you try to change the final
constant after it´s already been set:
= 0; hoursSinceMidnight
this will produce the following error:
final variable 'hoursSinceMidnight' can only be set once. The
You don’t actually need to worry too much about the difference between const
and final
constants. As a general rule, try const
first, and if the compiler complains, then make it final
. The benefit of using const
is it gives the compiler the freedom to make internal optimizations to the code before compiling it.
No matter what kind of variable you have, though, you should give special consideration to what you call it.
Using Meaningful Names
Always try to choose meaningful names for your variables and constants. Good names act as documentation and make your code easy to read.
A good name specifically describes the role of a variable or constant. Here are some examples of good names:
personAge
numberOfPeople
gradePointAverage
Often a bad name is simply not descriprtive enough. Here are some examples of bad names:
a
temp
average
The key is to ensure that you’ll understand what the variable or constant refers to when you read it again later. Doin’t make the mistake of thinking you have an infallible memory! It’s common in computer programming to look back at your own code as early a day or two later and have forgotten what it does. Make it easier for yourself by giving your variables and constants intuitive, precise names.
Also, note how the names above are written. In Dart, its standard to use lowerCamelCase
for variable and constant names. Follow these rules to properly case your names:
- Start with a lowercase letter.
- If the name is made up of multiple words, join them together and start every word after the first one with an uppercase letter.
- Treat abbreviations like words, for example,
sourceUrl
andurlDescription
.
Exercises
If you haven’t been following along with these exercises in VS Code, now’s the time to create a new project and try some exercises to test yourself!
- Declare a constant of type
int
calledmyAge
and set it to your age. - Declare a variable of type
double
calledaverangeAge
. Initially, setr the variable to your own age. Then, set it to the average of your age and your best friend’s age. - Create a constant called
testNumber
and initialize it with whatever integer you’d like. Next, create another constant calledevenOdd
and set it equal totestNumber
modulo2
. Now changetestNumber
to various numbers. What do you notice aboutevenOdd
?