2

How come I never see any Arduino Library expose some of it's internal variables as public in the header file? I only see functions which are declared as public, while every variable is declared private.

Background: I want to write my first Arduino library. And I thought of making some variables of this library public, so that I don't have to call a function later on when I import the library.

E.g. I want:

#include MyLibrary
...
MyLibrary instance();
instance.avariable = 12345;

instead of:

#include MyLibrary
...
MyLibrary instance();
instance.setVariable(12345);
Henry
  • 123
  • 3

2 Answers2

3

The Arduino ecosystem is meant mostly for beginners. This often means that people with very little knowledge will be using it and will often try random things to make stuff work. (and once they found something that works will teach it to the next guy that has the dame problem).

Disallowing things that would easily break the invariants of the library from the outset reduces the amount of support you need to give to people that inadvertently break the library by randomly changing some variable.

ratchet freak
  • 3,267
  • 1
  • 13
  • 12
2

Classes are used to hide away the complexity of a certain task. The user of the class should not worry about how the library exactly works in the inside, but instead only worry about how it should be used. In many cases directly writing to a member variable can be not only convenient, but hurtful if a wrong value is set. If you instead use a function to set the variable, the author can add code to prevent wrong values from actually being written to the variable. Also there might be some other logic involved, that is not triggered, if you write directly to the variable. So - for the ease of use - the users might want the library to be responsible for this, not themselves.

If you write a library, you have thought about how it should be used. Hiding other ways away is a common way of leading the user through the usage. Ways of usage, that don't go along with the purpose of the library can be hided away to make the correct way clearer. A manufacturer of a saw doesn't give the user instructions how to use the wrong side of the blade, because it doesn't help you with sawing.

This does not mean, that you shouldn't make variables public at all, but only if it makes sense. For example: If you are defining a class, that just represents a point in a coordinate system without hooks to other code, it is totally OK to make the coordinates public. But if you defined the class, so that the point is directly shown on a display, you might want to change the position on the display, whenever one of the coordinates is changed. In this case you can use a set-function to trigger the display update, when a new value was given for the variable.

chrisl
  • 16,622
  • 2
  • 18
  • 27