Why do people make code "private" and can we do better? ======================================================= [Published 2022-08-05] The word "private" is often used in source code to restrict the places where something can be used. Why would you do that? After asking people [1], I think I have figured out what the point of it is: If there is any reason to access a variable through a function rather than directly, you want to have a list of those functions to make them easier to find for those who want to use them. Private ensures that all functions that access the variable are added to the list. The list is the function declarations/definitions in the class definition. Using private can reduce code duplication because people can find functions to use in that list so they don't accidentaly create another duplicate function. Problems with private --------------------- One problem with private is that it makes it harder to write code and in some languages it restricts the places where you can write that code. In languages where you can define the member functions in any place (like C++), you still have to manually keep the function list updated which means some duplicated code (the function declarations). Private only gives one bit of information while in reality there can be multiple levels of usage. Example: The "player" class has a "health" member variable. You might want to set the health directly without any other effects when you load a new game. When the player takes fall damage you want to set the health and play a damage sound and animation. When the player gets shot you want to do the same as for fall damage but also record who shot the player. Even if we use private on the health variable, the programmer can call the wrong function, e.g. the fall damage function when the player gets shot or maybe even the function that only changes the health variable. Can we do better? ----------------- It is possible to get the benefit of having the function list without the restriction of where you can write the code. Example in C: struct Player { // Functions that modify `health`: // shoot_player() if player is shot by other player // damage_player() if player takes other damage (like falling) // set_player_health() for setting health without any effects int health; }; This solves the problem of multiple access levels. It also means less code duplication because you only need to mention the names of the functions so you don't need to change in the list when a type changes. A drawback is that you can forget to add a function to the list or change a function name. If you don't want to have a list of functions, it can still help to put relevant functions in files with obvious names so that programmers know where to look to find them. --- [1] https://news.ycombinator.com/item?id=32227737