Home > OS >  Dart and object oriented programming
Dart and object oriented programming

Time:07-27

Why do certain names or properties get repeated, and use a capital letter in the second instance? e.g., mainAxisAlignment = MainAxisAlignment.start

I just struggle with why OOP wouldn’t simply just cut out the second instance and use a single name. I know this is basic but it comfiest me elsewhere, e.g. color = Color.red

CodePudding user response:

It has been a convention for programmers to write variable/object names in camel case, meaning the first letter of every word except the first word has to be capitalized (like this: heyThisIsAVariable). Also, for enums and classes, we tend to capitalize the first letter of the first word as well. Dart has just made this mandatory in order to make things super clear. It's just something that you have to get used to, and you will be thankful later :)

CodePudding user response:

var color = Color.red

color are here the name of the variable we are trying to create. This could be whatever name you want. E.g. redColor. We use lower casing because of naming conventions since it makes it easier to read the code and spot what is variables.

Color are the name of a class. We know that because naming conventions says we should start class names with cased letter. This name cannot just be changed since it comes from the Flutter API.

.red means we are accessing a static property/variable (starting with lower casing) of the Color object. The property/variable are static since we can access it directly on the class without the need of creating an object/instance of the class.

In short, nothing here are repeated information. It only seems repeated because of the choice of name of the variable.

CodePudding user response:

It's just a hint of what type you should use in the named argument: following your example, mainAxisAlignment is the named argument, and takes an object of MainAxisAlignment type. I would not suggest it in this case, but in other cases it leaves you the possibility to subclass the type required by the named argument.

I'm not sure, but probably the stronger the hint is, the better is that you stick to the suggestion. Think of all the child argument in almost any widget: it usually takes a Widget object, that can be easily extended, so the argument name is vague. In cases like mainAxisAlignment or crossAxisAlignment, instead, the hint is so strong that you even have an enum or class with the same name...so you'd better use that.

  • Related