Ver código fonte

Add "variables" section

Alois Mahdal 8 anos atrás
pai
commit
23bb7dece0
1 arquivos alterados com 52 adições e 1 exclusões
  1. 52
    1
      notes/style.md

+ 52
- 1
notes/style.md Ver arquivo

@@ -277,8 +277,59 @@ Common language constructs
277 277
 --------------------------
278 278
 
279 279
 
280
-### functions ###
280
+### variables ###
281
+
282
+Common advice applies to variable naming, but capitalization is decided
283
+based on scope:
284
+
285
+ *  Global variables must be `ALL_CAPS`.
286
+
287
+ *  Local variables must be `lowercase` or `snake_case`, and *must not*
288
+    be used in inherited scope, i.e. in a child function.
289
+
290
+ *  Optionally an exception from the previous rule can be granted to
291
+    a specific variable.  However, such variable must be named using
292
+    `CamelCase`.
293
+
294
+ *  Both kinds of local variables (inherited and non-inherited) should
295
+    be defined in header of the function, that is, before actual code.
296
+    It's also recommended to comment variables here.
297
+
298
+For example:
299
+
300
+    #
301
+    # My global variable
302
+    #
303
+    PLANET_NAME=Earth
281 304
 
305
+    main() {
306
+        local name=$1       # name to greet
307
+        local TimeOfDay     # morning, afternoon or night
308
+        TimeOfDay=$(determine_timeofday)
309
+        greet "$name"
310
+    }
311
+
312
+    greet() {
313
+        #
314
+        # Greet user $1 based on $TimeOfDay
315
+        #
316
+        local name=$1       # name to greet
317
+        case $TimeOfDay in
318
+            morning)    echo "Good $PLANET_NAME morning, $name!"   ;;
319
+            afternoon)  echo "Nice $PLANET_NAME afternoon, $name!" ;;
320
+            night)      echo "Sleep well, $name!"                  ;;
321
+        esac
322
+    }
323
+
324
+    main "$1"
325
+
326
+Notice that while `TimeOfDay` is allowed to slip through and be referenced
327
+in `greet()`, `name` is purely local to `main()`, and then again to
328
+`greet()`.  (It's probably not a good idea to mix variables like that,
329
+the example is ugly, but you get the point.)
330
+
331
+
332
+### functions ###
282 333
 
283 334
 Preferred way of declaration is a variation of most common Bourne shell
284 335
 way with K&R-style brackets: