-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslides.qmd
1370 lines (833 loc) · 29.1 KB
/
slides.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
format:
revealjs:
css: style.css
theme: simple
slide-number: true
preview-links: auto
embed-resources: true
footer: "Source code for these slides can be found [on GitHub](https://github.com/IndrajeetPatil/second-hardest-cs-thing/){target='_blank'}."
# pdf:
# title: "Dealing with the Second Hardest Thing in Computer Science"
# subtitle: "Thoughts on naming things for software development"
# author: "Indrajeet Patil"
#affiliation:
execute:
echo: true
eval: false
keywords: ["naming", "software-engineering", "computer-science", "software-development"]
license: "CC0 1.0 Universal"
pagetitle: "Dealing with the Second Hardest Thing in Computer Science"
author-meta: "Indrajeet Patil"
date-meta: "`r Sys.time()`"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(eval = FALSE)
```
## Dealing with the Second Hardest Thing in Computer Science {style="margin-top: 2em; margin-bottom: 1em;"}
<!-- Don't render this file locally Run `renderer.R` script instead. -->
::: {style="margin-top: 1em; margin-bottom: 1em; font-size: 1em"}
Indrajeet Patil
{.absolute width="500" height="350" right="40" top="100"}
:::
# "There are only two hard things in Computer Science: cache invalidation and naming things."
\- Phil Karlton
#
The following advice on naming applies to all kinds of programming entities (variables, functions, packages, classes, etc.) and is **language-agnostic**.
#
::: {.callout-important}
## *Principle*: **Names are a form of abstraction**
"[T]he best names are those that focus attention on what is most important about the underlying entity, while omitting details that are less important."
\- John Ousterhout
:::
. . .
::: {.callout-tip}
### *Importance*: **Names are at the core of software design**
If you can't find a name that provides the right abstraction for the underlying entity, it is possible that the design isn't clear.
:::
. . .
::: {.callout-note}
## *Properties*: **Good names are precise and consistent**
If a name is good, it is difficult to miss out on critical information about the entity or to misunderstand what it represents.
:::
# "The beginning of wisdom is to call things by their proper name."
\- Confucius
## Good names are a form of documentation {.smaller}
How good a name is can be assessed by how detailed the accompanying comment needs to be.
. . .
E.g., the function and parameter are named poorly here, and so comments need to do all the heavy lifting:
```{js}
// function to convert temperature from Fahrenheit to Celsius scale
// temp is the temperature in Fahrenheit
double unitConverter(double temp)
```
. . .
Contrast it with this:
```{js}
double fahrenheitToCelsius(double tempFahrenheit)
```
No need for a comment here!
. . .
::: {.callout-tip}
**Good names rarely require readers to read the documentation to understand what they represent.**
:::
## Generic names should follow conventions {.smaller}
Using generic names can improve code readability, but *only if* language or domain customs are followed.
. . .
Examples:
- In a nested loop, using `j` for outer and `i` for inner loop index is confusing!
```{js}
for (let j = 0; j < arr.length; j++) {
for (let i = 0; i < arr[j].length; i++) {
```
- `tmp` shouldn't be used to store objects that are not temporary
- `retVal` shouldn't be used for objects not returned from a function
. . .
::: {.callout-tip}
**Don't violate reader assumptions about what generic names represent.**
:::
## Alternatives to generic names {.smaller}
If a loop is longer than a few lines, use more meaningful loop variable names than `i`, `j`, and `k` because you will quickly lose track of what they mean.
:::: {.columns}
::: {.column width='50%'}
```{js}
# abstruse
exam_score[i][j]
```
:::
::: {.column width='50%'}
```{js}
# crystal clear
exam_score[school][student]
```
:::
::::
. . .
<br>
All variables are temporary in some sense. Calling one `tmp` is inviting carelessness.
:::: {.columns}
::: {.column width='50%'}
```{js}
# generic name
if (right < left) {
tmp = right
right = left
left = tmp
}
```
:::
::: {.column width='50%'}
```{js}
# more descriptive
if (right < left) {
old_right = right
right = left
left = old_right
}
```
:::
::::
. . .
<br>
::: {.callout-tip}
**Even when you *think* you need generic names, you are better off using descriptive names.**
:::
## Names should be consistent {.smaller}
Consistent names **reduce cognitive burden** because if the reader encounters a name in one context, they can safely reuse that knowledge in another context.
. . .
For example, these names are inconsistent since the reader can't safely assume that the name *size* means the same thing throughout the program.
:::: {.columns}
::: {.column width='70%'}
```{js}
// context-1: `size` stands for number of memory bytes
{
size = sizeof(x);
}
// context-2: `size` stands for number of elements
{
size = strlen(a);
}
```
:::
::: {.column width='30%'}
```{js}
// context-1:
{
size = sizeof(x);
}
// context-2:
{
length = strlen(a);
}
```
:::
::::
. . .
::: {.callout-tip}
**Allow users to make safe assumptions about what the names represent across different scopes/contexts.**
:::
## {.smaller}
### Unnecessary details in names should be removed...
:::: {.columns}
::: {.column width='50%'}
```{r}
# okay
convert_to_string()
fileObject
strName # Hungarian notation
```
:::
::: {.column width='50%'}
```{r}
# better
to_string()
file
name
```
:::
::::
:::{.callout-note}
## Avoid redundancy
- In type names, avoid using *class*, *data*, *object*, and *type* (e.g. bad: `classShape`, good: `Shape`)
- In function names, avoid using *be*, *do*, *perform*, etc. (e.g. bad: `doAddition()`, good: `add()`)
:::
### **but** important details should be kept!
:::: {.columns}
::: {.column width='50%'}
```{r}
# okay
child_height
password
id
address
```
:::
::: {.column width='50%'}
```{r}
# better
child_height_cm
plaintext_password
hex_id
ip_address
```
:::
::::
::: {.callout-tip}
**If some information is critical to know, it should be part of the name.**
:::
## Names should utilize the context {.smaller}
When naming, avoid redundant words by exploiting the context.
E.g. if you are defining a class, its methods and variables will be read in that context.
:::: {.columns}
::: {.column width='50%'}
```{js}
# okay
Router.run_router()
FileHandler.close_file()
BeerShelf.beer_count
```
:::
::: {.column width='50%'}
```{js}
# better
Router.run()
FileHandler.close()
BeerShelf.count
```
:::
::::
But, if doing so imposes ambiguity, then you can of course tolerate some redundancy.
:::: {.columns}
::: {.column width='50%'}
```{js}
# bad
MediaPlayer.play()
```
:::
::: {.column width='50%'}
```{js}
# better
MediaPlayer.play_audio()
MediaPlayer.play_video()
```
:::
::::
. . .
::: {.callout-tip}
**Shorten names with the help of context.**
:::
## Names should be precise but not *too* long {.smaller}
How precise (and thus long) the name should be is a **subjective decision**, but keep in mind that long names can obscure the visual structure of a program.
. . .
You can typically find a middle ground between too short and too long names.
```{r}
# not ideal - too imprecise
d
# okay - can use more precision
days
# good - middle ground
days_since_last_accident
# not ideal - unnecessarily precise
days_since_last_accident_floor_4_lab_23
...
```
. . .
::: {.callout-tip}
**Don't go too far with making names precise.**
:::
## Names should be difficult to misinterpret {.smaller}
Try your best to misinterpret candidate names and see if you succeed.
. . .
E.g., here is a GUI text editor class method to get position of a character:
```{c}
std::tuple<int, int> getCharPosition(int x, int y)
```
. . .
How I interpret: *"`x` and `y` refer to pixel positions for a character."*
. . .
In reality: *"`x` and `y` refer to line of text and character position in that line."*
. . .
You can avoid such misinterpretation with better names:
```{c}
std::tuple<int, int> getCharPosition(int lineIndex, int charIndex)
```
. . .
::: {.callout-tip}
**Precise and unambiguous names leave little room for misconstrual.**
:::
## Names should be distinguishable {.smaller}
Names that are too similar make great candidates for mistaken identity.
. . .
E.g. `nn` and `nnn` are easy to be confused and such confusion can lead to painful bugs.
:::: {.columns}
::: {.column width='40%'}
```{js}
// bad
let n = x;
let nn = x ** 2;
let nnn = x ** 3;
```
:::
::: {.column width='60%'}
```{js}
// good
let n = x;
let nSquare = x ** 2;
let nCube = x ** 3;
```
:::
::::
. . .
::: {.callout-tip}
**Any pair of names should be difficult to be mistaken for each other.**
:::
## Names should be searchable {.smaller}
While naming, always ask yourself how easy it would be to find and update the name.
. . .
E.g., this function uses `a` and `f` parameters to represent an array and a function.
:::: {.columns}
::: {.column width='40%'}
```{r, tidy=FALSE}
# bad
arrayMap <- function(a, f) {
...
}
```
:::
::: {.column width='60%'}
```{r, tidy=FALSE}
# good
arrayMap <- function(arr, fun) {
...
}
```
:::
::::
If needed, it wouldn't be easy either to search for and/or to rename these parameters in the codebase because searching for `a` or `f` would flag **all** *a*s and *f*s (**a**pi, **f**ile, etc.).
Instead, if more descriptive identifiers are used, both search and replace operations will be straightforward.
In general, searchability of a name indexes how generic it is.
. . .
::: {.callout-tip}
**Choose names that can be searched and, if needed, replaced.**
:::
## Names should honour the conventions {.smaller}
The names should respect the conventions adopted in a given project, organization, programming language, domain of knowledge, etc.
. . .
For example, C++ convention is to use PascalCase for class names and lowerCamel case for variables.
:::: {.columns}
::: {.column width='50%'}
```{js}
// non-conventional
class playerEntity
{
public:
std::string HairColor;
};
```
:::
::: {.column width='50%'}
```{js}
// conventional
class PlayerEntity
{
public:
std::string hairColor;
};
```
:::
::::
. . .
::: {.callout-tip}
**Don't break conventions unless other guidelines require overriding them for consistency.**
:::
<!-- ## Names should clarify dependencies {.smaller} -->
<!-- If a set of functions have dependencies (because they share the same data, e.g.), their names should clarify this dependence. -->
<!-- . . . -->
<!-- E.g., computing annual revenues involves computing quarterly revenues, which in turn requires computing monthly revenues. -->
<!-- ```{r} -->
<!-- revenues <- compute_revenues_data(raw_revenues_data) -->
<!-- revenues <- compute_monthly_revenues(revenues) -->
<!-- revenues <- compute_quarterly_revenues(revenues) -->
<!-- revenues <- compute_annual_revenues(revenues) -->
<!-- ``` -->
<!-- Each of the function names makes clear the order in which they need to be run. -->
## Name Booleans with extra care {.smaller}
Names for Boolean variables or functions should make clear what true and false mean. This can be done using prefixes (**is**, **has**, **can**, etc.).
:::: {.columns}
::: {.column width='50%'}
```{r}
# not great
if (child) {
if (parentSupervision) {
watchHorrorMovie <- TRUE
}
}
```
:::
::: {.column width='50%'}
```{r}
# better
if (isChild) {
if (hasParentSupervision) {
canWatchHorrorMovie <- TRUE
}
}
```
:::
::::
. . .
In general, use positive terms for Booleans since they are easier to process.
:::: {.columns}
::: {.column width='50%'}
```{r}
# double negation - difficult
is_firewall_disabled <- FALSE
```
:::
::: {.column width='50%'}
```{r}
# better
is_firewall_enabled <- TRUE
```
:::
But if the variable is only ever used in its false version (e.g. `is_volcano_inactive`), the negative version can be easier to work with.
::::
. . .
::: {.callout-tip}
**Boolean variable names should convey what true or false values represent.**
:::
## Avoid implementation details in names {.smaller}
Names with implementation details (e.g., data structure) have high maintenance cost. When implementation changes, identifiers need to change as well.
. . .
E.g., consider variables that store data in different data structures or cloud services:
:::: {.columns}
::: {.column width='50%'}
```{python}
# bad
bonuses_pd # pandas DataFrame
bonuses_pl # polars DataFrame
aws_s3_url # AWS bucket
gcp_url # GCP bucket
```
:::
::: {.column width='50%'}
```{python}
# good
bonuses # data structure independent
bucket_url # cloud service independent
```
:::
Note that good names don't need to change even if the implementation details change.
::::
. . .
::: {.callout-tip}
**Names should be independent of implementation details.**
:::
## Find correct abstraction level for names {.smaller}
Don't select names at a lower level of abstraction just because that's where the corresponding objects were defined.
E.g., if you are writing a function to compute difference between before and after values, the parameter names should reflect the higher-level concept.
:::: {.columns}
::: {.column width='50%'}
```{r}
# bad
function(value_before, value_after) { ... }
```
:::
::: {.column width='50%'}
```{r}
# good
function(value1, value2) { ... }
```
:::
::::
Note that the good parameter names clarify the general purpose of the function, which is to compute difference between *any* two values, not just before and after values.
. . .
::: {.callout-tip}
**Choose names that reflect the higher-level concept.**
:::
## Test function names should be detailed {.smaller}
If unit testing in a given programming language requires writing test functions, choose names that describe the details of the test.
The test function names should effectively act as a comment.
:::: {.columns}
::: {.column width='30%'}
```{.python}
# bad
def test1
def my_test
def retrieve_commands
def serialize_success
```
:::
::: {.column width='70%'}
```{.python}
# good
def test_array
def test_multilinear_model
def all_the_saved_commands_should_be_retrieved
def should_serialize_the_formula_cache_if_required
```
:::
::::
:::{.callout-note}
Don't hesitate to choose lengthy names for **test** functions.
Unlike regular functions, long names are less problematic for test functions because
- they are not visible or accessible to the users
- they are not called repeatedly throughout the codebase
:::
## Names should be kept up-to-date {.smaller}
To resist software entropy, not only should you name entities properly, but you should also update them. Otherwise, names will become something worse than meaningless or confusing: **misleading**.
. . .
For example, let's say your class has the `$getMeans()` method.
- In its initial implementation, it used to return *precomputed* mean values.
- In its current implementation, it *computes* the mean values on the fly.
Therefore, it is misleading to continue to call it a getter method, and it should be renamed to (e.g.) `$computeMeans()`.
. . .
::: {.callout-tip}
**Keep an eye out for API changes that make names misleading.**
:::
## Names should be pronounceable {.smaller}
This is probably the weakest of the requirements, but one can't deny the ease of communication when names are pronounceable.
. . .
If you are writing a function to generate a time-stamp, discussing the following function verbally would be challenging.
```{r}
# generate year month date hour minute second
genymdhms()
```
This is a much better (and pronounceable) alternative:
```{r}
generateTimeStamp()
```
. . .
Additionally, avoid naming separate entities with homonyms.
Discussing entities named `waste` and `waist` is inevitably going to lead to confusion.
## Use consistent lexicon in a project {.smaller}
Once you settle down on a mapping from an abstraction to a name, use it consistently *throughout the code base*.
. . .
E.g., two similar methods here have different names across `R6` classes:
```{r}
CreditCardAccount$new()$retrieve_expenditure()
DebitCardAccount$new()$fetch_expenditure()
```
Both of these methods should either be named `$retrieve_expenditure()` or `$fetch_expenditure()`.
. . .
::: {.callout-tip}
**Consistency of naming conventions should be respected at both narrow and broad scopes.**
:::
## Choose informative naming conventions {.smaller}
Having different name formats for different entities **acts like syntax highlighting**. That is, a name not only represents an entity but also provides hints about its nature.
:::{.callout-note}
## Example of coding standards adopted in [OSP organization](https://github.com/Open-Systems-Pharmacology/Suite/blob/develop/CODING_STANDARDS.md){target="_blank"}
- Use all ALL_CAPS for constant variables (`public const double PI = 3.14;`)
- Prefix private/protected member variable with `_` (`private int _currentDebt`)
- Use Pascal Casing for class names (`public class GlobalAccounting`)
- Use Pascal Casing for public and protected method name (`public void GetRevenues()`)
- Use Camel Casing for private method name (`private int balanceBooks()`)
- ...
:::
. . .
::: {.callout-tip}
**Following *a* convention consistently is more important than *which* convention you adopt.**
:::
## ICYMI: Available casing conventions {.smaller}
There are various casing conventions used for software development.
```{r}
#| echo: false
#| eval: true
#| fig-align: "center"
#| fig-alt: "An illustration showing casing conventions used for software development."
knitr::include_graphics("media/horst_cases.jpeg")
```
:::{style="text-align: center; font-size: 0.9rem;"}
Illustration (CC-BY) by [Allison Horst](https://allisonhorst.com/){target="_blank"}
:::
# A sundry of don'ts
You won't have to remember any of these rules if you follow the following principle:
"Names must be readable for the *reader*, not *writer*, of code."
## {.smaller}
- **Don't use pop-culture references in names.** Not everyone can be expected to be familiar with them. E.g. `female_birdsong_recording` is a better variable name than `thats_what_she_said`.
. . .
- **Don't use slang.** You can't assume current or future developers to be familiar with them. E.g. `exit()` is better than `hit_the_road()`.
. . .
- **Avoid unintended meanings.** Do your due diligence to check dictionaries (especially [Urban dictionary](https://www.urbandictionary.com/){target="_blank"}!) if the word has unintended meaning. E.g. `cumulative_sum()` is a better function name than [`cumsum()`](https://rdrr.io/r/base/cumsum.html){target="_blank"}.
. . .
- **Avoid imprecise opposites**, since they can be [confusing](https://github.com/pomber/awesome-word-pairs). E.g. parameter combination `begin`/`last` is worse than either `begin`/`end` or `first`/`last`.
. . .
- **Don't use hard-to-distinguish character pairs in names** (e.g., `l` and `I`, `O` and `0`, etc.). With certain fonts, it can be hard to distinguish `firstl` from `firstI`.
## {.smaller}
- **Don't use inconsistent abbreviations.** E.g. instead of using `numColumns` (*number* of columns) in one function and `noRows` (*number* of rows) in another, choose one abbreviation as a prefix and use it consistently.
. . .
- **Don't misspell to save a few characters.** Remembering spelling is difficult, and remembering *correct misspelling* even more so. E.g. don't use `hilite` instead of `highlight`. The benefit is not worth the cost here.
. . .
- **Don't use commonly misspelled words in English.** Using such names for variables can, at minimum, slow you down, or, at worst, increase the possibility of making an error. E.g. is it `accumulate`, `accummulate`, `acumulate`, or `acummulate`?!
. . .
- **Don't use numeric suffixes in names to specify levels.** E.g. variable names `level1`, `level2`, `level3` are not as informative as `beginner`, `intermediate`, `advanced`.
## {.smaller}
- **Don't use misleading abbreviations.** E.g., in R, `na.rm` parameter removes (`rm`) missing values (`NA`). Using it to mean "remove (`rm`) non-authorized (`NA`) entries" for a function parameter will be misleading.
. . .
- **Don't allow multiple English standards.** E.g. using both American and British English standards would have you constantly guessing if the variable is named (e.g.) `centre` or `center`. Adopt one standard and stick to it.
. . .
- **Don't use similar names for entities with different meanings.** E.g. `patientRecs` and `patientReps` are easily confused because they are so similar. There should be at least two-letter difference: `patientRecords` and `patientReports`.
# Case studies
Looking at names in the wild that violate presented guidelines.
This is **not** to be taken as criticisms, but as learning opportunities to drive home the importance of these guidelines.