120 lines
2.2 KiB
Markdown
120 lines
2.2 KiB
Markdown
# Exemples / DO-DON'T — Chapitre 15 — Fonctions, méthodes et `clsmethod`
|
|
|
|
> Document compagnon. Les exemples illustrent les règles du chapitre ; la formulation normative reste dans le chapitre lui-même.
|
|
|
|
## Exemples extraits du chapitre
|
|
|
|
### Exemple 1
|
|
|
|
```text
|
|
func fonction libre
|
|
method méthode d'instance
|
|
clsmethod méthode de classe
|
|
operator implémentation d'un contrat opérateur
|
|
```
|
|
|
|
### Exemple 2
|
|
|
|
```text
|
|
T
|
|
T throws SomeException
|
|
T faults SomeFault
|
|
T throws SomeException faults SomeFault
|
|
Result<T,E>
|
|
Result<T,E> throws SomeException
|
|
Result<T,E> faults SomeFault
|
|
```
|
|
|
|
Le type de retour et le mécanisme d'échec sont indépendants.
|
|
|
|
### Exemple 3
|
|
|
|
```text
|
|
func readConfig(String path) -> Config
|
|
throws IOException
|
|
|
|
method elementAt(uint64 index) -> T
|
|
faults IndexOutOfBoundsFault
|
|
```
|
|
|
|
### Exemple 4
|
|
|
|
```text
|
|
func parseExternalInput(String input) -> Result<Value, ParseError>
|
|
```
|
|
|
|
`Result` reste utilisé lorsque l'échec doit être transporté comme une valeur.
|
|
|
|
### Exemple 5
|
|
|
|
```text
|
|
return value;
|
|
return Result::Ok(value);
|
|
return Result::Ok(Void);
|
|
```
|
|
|
|
### Exemple 6
|
|
|
|
```text
|
|
class User {
|
|
const method getName() -> String {
|
|
return this::name;
|
|
}
|
|
|
|
method setName(String name) -> Void {
|
|
this::name = name;
|
|
return Void;
|
|
}
|
|
}
|
|
```
|
|
|
|
### Exemple 7
|
|
|
|
```text
|
|
User a = ...;
|
|
const User b = a;
|
|
|
|
a::setName("John"); // OK
|
|
a::getName(); // OK
|
|
|
|
b::getName(); // OK
|
|
b::setName("John"); // ERROR
|
|
```
|
|
|
|
### Exemple 8
|
|
|
|
```text
|
|
réassigner un champ via this
|
|
appeler une method non-const via this
|
|
obtenir puis exposer comme mutable un accès disponible uniquement via this const
|
|
```
|
|
|
|
### Exemple 9
|
|
|
|
```text
|
|
allouer des valeurs locales
|
|
modifier des valeurs locales mutables
|
|
faire de l'I/O
|
|
faire du logging
|
|
lever une Exception déclarée
|
|
modifier un état externe auquel elle possède indépendamment un accès mutable
|
|
```
|
|
|
|
### Exemple 10
|
|
|
|
```text
|
|
func display(const User user) -> Void
|
|
```
|
|
|
|
### Exemple 11
|
|
|
|
```text
|
|
const method getOwner() -> const User {
|
|
return this::owner;
|
|
}
|
|
```
|
|
|
|
## DO / DON'T / WHY / compiler error / edge cases
|
|
|
|
À consolider progressivement avant la baseline publique V3 et à transformer, lorsque pertinent, en tests de conformité de la toolchain.
|