Package organization
The key point is not to set the usage message between BeginPackage
and Begin["`Private`"]
, but just to mention the symbol.
A better way to do this would be:
BeginPackage["Foo`"];
f1
f2
Begin["`Private`"];
f1::usage = "f1[] ....";
f1[]:= code for f1
f2::usage = "f2[] ....";
f2[]:= code for f2
f3[]:= code for f3 (not visible as only in the private context)
End[];
EndPackage[];
Whatever you mention there will be a public symbol (f1
, f2
). What you don't mention will not be public (f3
). That's because after the BeginPackage
, $Context
will be Foo`
, meaning that new symbols are created there. $Context
controls where new symbols are created. After the Begin["`Private`"]
, $Context
is changed, but Foo`
is still in $ContextPath
. $ContextPath
controls where Mathematica should look for symbol names. It only creates a new symbol if it didn't find the name in $ContextPath
.
You could use the explicit context for every definition, but personally I don't like this because it keeps repeating the name of the context, thus making it difficult to change in the future. It is also good to point out that you'd only need to use an explicit context when mentioning the symbol for the first time. I.e. this would be sufficient (though potentially confusing):
Foo`f1::usage = "f1[] ....";
f1[]:= code for f1
It is good practice to use different naming conventions for public and non-public symbols. Public ones are preferably capitalized. This will also help in catching errors such as not making a symbol public.
It is possible, your code works. I don't see any downsides which aren't a matter of taste.
I like to keep usages next to definitions too. But I hate using full names, you can just mention symbols in a proper place to create them in appropriate context.
BeginPackage["Foo`"];
f1; f2;
Begin["`Private`"];
f1::usage = "f1[] ....";
f1[]:= code for f1
f2::usage = "f2[] ....";
f2[]:= code for f2
f3[]:= code for f3
End[]
EndPackage[];
?Foo`*
?f1
Reading the answers I just realized that the logic can be pushed a little bit further. If we want to group "everything" together, the following might be a possible solution (with the inconvenience of some repetitions of the Foo` context)
BeginPackage["Foo`"];
Begin["`Private`"];
(*-------*)
Foo`f1;
f1::usage="f1[] ....";
f1[]:=code for f1
(*-------*)
Foo`f2;
f2::usage="f2[] ....";
f2[]:=code for f2
(*-------*)
f3[]:=code for f3
(*-------*)
End[]
EndPackage[];