Define private function in a mathematica package - package

I'm not sure I got how to define private functions right.
When I'm writing a package mathematica, I just do this:
BeginPackage["myPackage`"]
myPublicFunction::usage="myPublicFunction blahblahblah";
Begin["Private"]
myPrivateFunction[input_]:= ... ;
myPublicFunction[input_]:= ... ;
End[]
EndPackage[]
Is this the correct way or am I missing something?

Yep, that's a correct way. It may pay off to understand some of the internal package mechanics. Mathematica contexts are similar to namespaces in other languages. They can be nested. Every symbol belongs to some context. At any given moment, some context is "current". Whenever a new symbol is created, the system must decide to which context the symbol will belong. This happens at parse-time. The fundamental quantity (variable) here is $ContextPath. It is basically the search path for symbols. It is a list of contexts, and whenever the system sees a new symbol, it tests if the symbol with the same short name (that is, the name of the symbol proper, without the context) exists in some context on the $ContextPath. If it does exist, then the given occurrence of the symbol will be associated with that existing one. If it does not, then the symbol is created in a current context. Note that this is a dynamic thing - if you change the $ContextPath at any moment, the next symbol occurrence can be associated with a different symbol.
Anyways, what BeginPackage does is that it simply replaces the current value of $ContextPath with just {youPublicPackageContext, "System'"}, plus possibly additional contexts that you publicly import through the second optional argument of BeginPackage. Therefore, all symbols that are in the "public" section, are parsed into the public context, if they are not in "System'" or other contexts that you import. And what EndPackage does is to restore the value of the $ContextPath to what it was before you started loading the package. So, technically the usage message is not the only way to make a symbol public in your main context - you could just as well simply type a symbol with a semicolon, like myFunction; (this practice is discouraged, I just mentioned it to clarify the mechanism). Now, what happens when you enter Begin["'Private'"] is that the current context becomes YourContext'Private' (a sub-context). The $ContextPath is not changed. Therefore, any symbol entered there, which does not exist in your public package or other imported packages (that is, contexts currently on the $ContextPath), automatically is parsed into the 'Private' subcontext.
What really makes these symbols private is that whenever you import your package into some other context (package), only the main package is added to the $ContextPath, but not its sub-packages. Technically, you can break encapsulation by manually adding YourPackage'Private' to the $ContextPath (say, PrependTo[$ContextPath, YourPackage'Private']), and then all your private functions and other symbols will become public in that particular context where you do the import. Again, this practice is discouraged, but it explains the mechanics. The bottom line is that the notion of private or public can be entirely understood when we know how symbols are parsed, and what are the manipulations with $ContextPath and $Context (another system variable giving the value of the current context), that are performed by commands such as Begin and BeginPackage. To put it another way, one could, in principle, emulate the actions of BeginPackage,Begin, End and EndPackage with a user-defined code. There are just a few principles operating here (which I tried to outline above), and the mechanism itself is in fact very much exposed to the user, so that if, in some rare cases, one may want some other behavior, one can make some "custom" manipulations with $ContextPath and Context, to ensure some non-standard way of symbol parsing and therefore, control package-scale encapsulation in some "non-standard" way. I am not encouraging this, just mentioning to emphasize that the mechanism is in fact much simpler and much more controllable than it may seem on the surface.

Related

Class symbol introduction due to EVALFILE

Class names are available in scope after EVALFILE, while the documentation may have stated otherwise.
The documentation for EVALFILE states:
Slurps the specified file and evaluates it. Behaves the same way as EVAL with regard to Blob decoding, scoping, the $lang parameter and the $check parameter. Evaluates to the value produced by the final statement in the file when $check is not True.
The documentation for EVAL states:
since the set of symbols in a lexical scope is immutable after compile time, an EVAL can never introduce symbols into the surrounding scope.
My input file is:
class SomeClass {
method a () { "In SomeClass method a"; };
}
sub some-routine () {
"Some routine";
}
> my $f = EVALFILE("/tmp/eval-bug.raku");
&some-routine
> $f()
Some routine
> some-routine()
===SORRY!=== Error while compiling:
Undeclared routine:
some-routine used at line 1
The above three executions comply with the documentation, but the following does not:
> SomeClass.a()
In SomeClass method a
So does symbol mean only a routine name and not a class name? Or is this a bug?
since the set of symbols in a lexical scope is immutable after compile time, an EVAL can never introduce symbols into the surrounding scope
The key words here are "lexical scope". Classes, however, are not lexically scoped by default (unlike routines), but rather package scoped. This means that they introduce a global name by default. If you instead write:
my class SomeClass {
method a () { "In SomeClass method a"; };
}
Then this declares a lexically scoped class, no global name will be introduced, and thus it will not be installed anywhere that persists beyond the EVALFILE.
To me at least the documentation seems correct; it explicitly mentions lexical scope, and the words "surrounding scope" also carry the implication of textual (thus lexical) scoping. However, it could gain a mention that package-scoped things declared in the EVALFILE will be installed globally.
Looks to me it's a combination of 2 things: 1. subroutine some-routine isn't exported, and 2. problems with scoping in the REPL.
The first can be fixed in two ways:
our sub some-routine() {
or
sub some-routine() is export {
The second is, in the current state of the REPL, not really fixable (and I have tried, but all of my fixes introduced problems in other situations). The REPL is currently implemented as doing an EVAL on every line you enter, while attempts are made to share elements of any previous EVAL with the next. In the current state of the runtime, it is impossible to do that sharing completely, which is the cause of many of the issues that people report about the REPL.
Work on the RakuAST branch also implies having the state of an interpreter to be more "objectified" if you will, allowing for a better state sharing between EVALs, and thus a better REPL. But that will take at least another few months before that lands in Rakudo.

estudio does not check `require` when it should?

Eiffel Studio seems to pass through my requirements even if I have them enabled on project settings. And as far as I remember I was able some time to put a break point into the requirements...
I don't understand what I'am missing here, as you can see in my example, the requirement passes through as I have the same condition on the code and it goes into (attached {POWER_DEVICE} a_csv.device as l_dev).
A general rule for inherited assertions is the following:
preconditions can be only relaxed;
postconditions can be only strengthened.
In the particular example the effective precondition is
True
or else
valid_csv (a_csv) and then attached {POWER_DEVICE} a_csv.device
This is reflected by the keywords require at the beginning and require else in the middle of the combined precondition in the flat form of the feature. The expression True is inherited. This is the precondition of the feature in the parent.
A possible solution is to move valid_csv (a_csv) to the parent feature, and redefine valid_csv in the descendant. If valid_csv is common for all calls, but the second test varies across descendants, it might be better to introduce a new feature is_known and have 2 precondition subclauses in the parent:
is_valid_csv: is_valid_csv (a_csv)
is_known_csv: is_known_csv (a_csv)
The implementation of is_known_csv in the class POWER_CSV_PROCESSOR would be
is_known_csv (a_csv: ...)
do
Result := attached {POWER_DEVICE} a_csv.device
end
and the precondition of feature process in POWER_CSV_PROCESSOR would be empty.
The caller would then do something like
if processor.is_known_csv (csv) then
processor.process (csv)
end

Eiffel: best practices for creation procedures

Animal
deferred class ANIMAL
inherit
ANY
redefine
default_create
end
feature
creator: like Current
guts: GUTS
default_create
do
create guts
end
make_malformed
do
default_create
end
end --class
PIG
class PIG
inherit
ANIMAL
redefine
make_malformed
end
create
default_create,
make_malformed,
make_from_insemination
feature
guts: GUTS
make_malformed
do
Precursor
set_left_eye (create {MALFORMED_EYE})
end
make_from_insemination (some_humain: HUMAIN)
do
default_create
creator := some_humain
end
end --class
Into my vision of best practices, I'll say that
If there is no particular sense of making a creation procedure (like my make_malformed example) redefine the default_create
All creation procedure should call default_create and add specific behavior (like my make_from_db example)
So what is the purpose of many libraries in Eiffel which are adding a make like create {LINKED_LIST}.make
Correct me if I'm wrong. Thanks in advance!
Many Eiffel libraries were developed before default_create was added to ANY with the corresponding semantics. This explains why many classes of the base library do not use it.
Also, creation procedures can carry some specific sense. For example, make can create a container that compares internal objects using reference equality whereas make_equal can create a container that uses object equality instead (this is the case for HASH_TABLE, though there is an additional argument to indicate an expected number of elements, this argument could be omitted with some other design choice). In such cases, default_create and default_create_equal would be non-symmetric, whereas make and make_equal are symmetric, so that the design is more consistent.
As you point out, default_create should not carry any specific behavior, just some basic things, expected from all descendants.
Whether default_create should be called by all other creation procedures heavily depends on the design. One example, where this is almost a rule, is the library "vision" that encodes in default_create a correct order of initialization, crucial for void safety. It's still possibly to write a class (based on this library) that performs the initialization correctly without calling default_create in its creation procedure, but having a ready-to-follow patters simplifies development.

TCL/C - when is setFromAnyProc() called

I am creating a new TCL_ObjType and so I need to define the 4 functions, setFromAnyProc, updateStringProc, dupIntRepProc and freeIntRepProc. When it comes to test my code, I see something interesting/mystery.
In my testing code, when I do the following:
Tcl_GetString(p_New_Tcl_obj);
updateStringProc() for the new TCL object is called, I can see it in gdb, this is expected.
The weird thing is when I do the following testing code:
Tcl_SetStringObj(p_New_Tcl_obj, p_str, strlen(p_str));
I expect setFromAnyProc() is called, but it is not!
I am confused. Why it is not called?
The setFromAnyProc is not nearly as useful as you might think. It's role is to convert a value[*] from something with a populated bytes field into something with a populated bytes field and a valid internalRep and typePtr. It's called when something wants a generic conversion to a particular format, and is in particular the core of the Tcl_ConvertToType function. You probably won't have used that; Tcl itself certainly doesn't!
This is because it turns out that the point when you want to do the conversion is in a type-specific accessor or manipulator function (examples from Tcl's API include Tcl_GetIntFromObj and Tcl_ListObjAppendElement, which are respectively an accessor for the int type[**] and a manipulator for the list type). At that point, you're in code that has to know the full details of the internals of that specific type, so using a generic conversion is not really all that useful: you can do the conversion directly if necessary (or factor that out to a conversion function).
Tcl_SetStringObj works by throwing away the internal representation of your object (with the freeIntRepProc callback), disposing of the old bytes string representation (through Tcl_InvalidateStringRep, or rather its internal analog) and then installing the new bytes you've supplied.
I find that I can leave the setFromAnyProc field of a Tcl_ObjType set to NULL with no problems.
[*] The Tcl_Obj type is mis-named for historic reasons. It's a value. Tcl_Value was taken for something else that's now obsolete and virtually unused.
[**] Integers are actually represented by a cluster of internal types, depending on the number of bits required. You don't need to know the details if you're just using them, as the accessor functions completely hide the complexity.

Encapsulation concept

I have problem with concept and implementation of encapsulation.
Can someone explain it to me?
Encapsulation is a moderately easy concept once you realise it (probably) comes from the same base word as capsule.
It's simply a containment of information.
Encapsulation means that a class publishes only what is needed for others to use it, and no more. This is called information hiding and it means classes can totally change their internals without having an effect on any of their users.
In other words, a dictionary class can begin life as a simple array and progress to a binary tree of words then even maybe to some database access functions, all without changing the interface to it.
In an object oriented world, objects hold both their data and the methods used to manipulate data and that is the pinnacle of encapsulation. One way this is done is to make sure each object knows which functions to call to manipulate its data, and ensure the correct ones are called.
As an example, here's a class for maintaining integer lists in my mythical, but strangely Python-like and therefore hopefully easy to understand, language:
class intlist:
private int val[10] # Slots for storing numbers.
private bool used[10] # Whether slot is used or not.
public constructor:
# Mark all slots unused.
for i in 0..9:
used[i] = false
public function add(int v) throws out-of-memory:
# Check each slot.
for i in 0..9:
# If unused, store value, mark used, return.
if not used[i]:
used[i] = true
val[i] = v
return
# No free slots, so throw exception.
throw out-of-memory
public function del(int v) throws bad-value:
# Check each slot.
for i in 0..9:
# If slot used and contains value.
if used[i] and val[i] == v:
# Mark unused and return.
used[i] = false
return
# Value not found in any used slot, throw exception.
throw bad-value
public function has(int v):
# Check each slot.
for i in 0..9:
# If slot used and contains value.
if used[i] and val[i] == v:
return true
# Value not found in any used slot.
return false
Now the only information published here are the constructor and three functions for adding, deleting, and checking for values (including what exceptions can be thrown).
Callers need know nothing about the internal data structures being used (val and used), or the properties of the functions beyond their "signatures" (the content of the "function" lines).
Because everything else is encapsulated, it can changed it at will without breaking the code that uses it.
I could, for example, do any of the following:
make the arrays longer;
store the data sorted, or in a binary tree instead of an array to make it faster.
change the used array into a count array (initialised to zero) so that many occurrences of a single number use just the one slot, increasing the quantity of numbers that can be stored where there are duplicates.
store the numbers in a database, located on a ZX-80 retro-computer located in outback Australia, and powered by methane produced from kangaroo droppings (though you may notice a latency change).
Basically, as long as the published API doesn't change, we am free to do whatever we want. In fact, we can also add things to the API without breaking other code, I just can't delete or change anything that users already rely on.
You should note that encapsulation isn't something new with object orientation. It's been around for ages, even in C by ensuring that information is hidden within a module (usually a source file or group thereof with private headers).
In fact, the stdio.h FILE* stuff is a good example of this. You don't care what's actually behind the pointer since all the functions which use it know how to do their stuff.
link text
I always explain it to people is think of yourself as an object. Other people can see your height, they can see if your smiling, but your inner thoughts, maybe the reason while your smiling, only you know.
Encapsulation is more than just defining accessor and mutator methods for a class. It is broader concept of object-oriented programming that consists in minimizing the interdependence between classes and it is typically implemented through information hiding.
The beauty of encapsulation is the power of changing things without affecting its users.
In a object-oriented programming language like Java, you achieve encapsulation by hiding details using the accessibility modifiers (public, protected, private, plus no modifier which implies package private). With these levels of accessibility you control the level of encapsulation, the less restrictive the level, the more expensive change is when it happens and the more coupled the class is with other dependent classes (i.e. user classes, subclasses).
Therefore, the goal is not to hide the data itself, but the implementation details on how this data is manipulated.
The idea is to provide a public interface through which you gain access to this data. You can later change the internal representation of the data without compromising the public interface of the class. On the contrary, by exposing the data itself, you compromise encapsulation, and therefore, the capacity of changing the way you manipulate the data without affecting its users. You create a dependency with the data itself, and not with the public interface of the class. You would be creating a perfect cocktail for trouble when "change" finally finds you.
There are several reasons why you might want to encapsulate access to your fields. Joshua Bloch in his book Effective Java, in Item 14: Minimize the accessibility of classes and members, mentions several compelling reasons, which I quote here:
You can limit the values that can be stored in a field (i.e. gender must be F or M).
You can take actions when the field is modified (trigger event, validate, etc).
You can provide thread safety by synchronizing the method.
You can switch to a new data representation (i.e. calculated fields, different data type)
However, encapsulation is more than hiding fields. In Java you can hide entire classes, by this, hiding the implementation details of an entire API. Think, for example, in the method Arrays.asList(). It returns a List implementation, but you do no care which implementation, as long as it satisfies the List interface, right?. The implementation can be changed in the future without affecting the users of the method.
The Beauty of Encapsulation
Now, in my opinion, to really understand encapsulation, one must first understand abstraction.
Think, for example, in the level of abstraction in the concept of a car. A car is complex in its internal implementation. They have several subsystem, like a transmission system, a break system, a fuel system, etc.
However, we have simplified its abstraction, and we interact with all cars in the world through the public interface of their abstraction. We know that all cars have a steering wheel through which we control direction, they have a pedal that when you press it you accelerate the car and control speed, and another one that when you press it you make it stop, and you have a gear stick that let you control if you go forward or backwards. These features constitute the public interface of the car abstraction. In the morning you can drive a sedan and then get out of it and drive an SUV in the afternoon as if it was the same thing.
However, few of us know the details of how all these features are implemented under the hood. Think of the time when cars did not have a hydraulics directional system. One day, the car manufactures invented it, and they decide it to put it in cars from there on. Still, this did not change the way in which users where interacting with them. At most, users experienced an improvement in the use of the directional system. A change like this was possible because the internal implementation of a car is encapsulated. Changes can be safely done without affecting its public interface.
Now, think that car manufactures decided to put the fuel cap below the car, and not in one of its sides. You go and buy one of these new cars, and when you run out of gas you go to the gas station, and you do not find the fuel cap. Suddenly you realize is below the car, but you cannot reach it with the gas pump hose. Now, we have broken the public interface contract, and therefore, the entire world breaks, it falls apart because things are not working the way it was expected. A change like this would cost millions. We would need to change all gas pumps in the world. When we break encapsulation we have to pay a price.
So, as you can see, the goal of encapsulation is to minimize interdependence and facilitate change. You maximize encapsulation by minimizing the exposure of implementation details. The state of a class should only be accessed through its public interface.
I really recommend you to read a paper by Alan Snyder called Encapsulation and Inheritance in Object-Oriented programming Languages. This link points to the original paper on ACM, but I am pretty sure you will be able to find a PDF copy through Google.
Encapsulation - wrapping of data in single unit. also we can say hiding the information of essential details.
example
You have a mobile phone.... there it some interface which helps u to interact with cell phone and u can uses the services of mobile phone. But the actually working in cell phone is hide. u don't know how it works internally.
hide/bind something : eg: a capsule (which we consume when v r ill)hide/bind some powder form in itself,, means that capsule encapsulate the powder contained it.
Binding of data and behavior i.e functionality of an object in a secured and controlled manner.
or the best example of encapsulation is a CLASS because a class hides class variables/functions from outside d class..
Encapsulation:
Wrapping up data member and method together into a single unit (i.e. Class) is called Encapsulation.
Eg: we can consider a capsule. Encapsulation means hiding the internal details of an object, i.e. how an object does something. Here capsule is a single Unit contain many things. But we cant see what is there in side capsule.
This is the technique used to protect information about an object from other objects. Like variable we can set as private and property as Public. When we access the property then we validate and set it.
We can go through some other examples. Our Laptop. We can use Laptop but what operations are happening inside that we are not knowing. But we can use that. Same like mobile, TV etc.
We can conclude that a group of related properties, methods, and other members are treated as a single unit or object.An encapsulated object is often called an abstract data type.
There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.
//Declare as Private
private string _LegName;
// Property Set as public
public string LegName
{
get
{
return _LegName;
}
set
{
_LegName=value;
}
public class LegMain
{
public static int Main(string[] args)
{
Leg L= new Leg();
d.LegName="Right Leg";
Console.WriteLine("The Legis :{0}",d.LegName);return 0;
}
}
Note: Encapsulation provides a way to protect data from accidental corruption.
Thank you
Encapsulation means hiding the data. In other words a class only exposes those properties or information which is authorized to be seen. Consider the below exapmle where a certain property called ConfidentialMessage is accesible only to the Admin role. This property is made private and is returned through another method which checks the role of an user and return the message only for admin.
public class Message
{
public Message()
{
ConfidentialMessage = "I am Nemo";
}
private string ConfidentialMessage { get; set; }
public string GetMessage(string name)
{
string message = string.Empty;
if (name == "Admin")
{
message = this.ConfidentialMessage;
}
return message;
}
}
Putting definition of encapsulate
enclose in a capsule, from en- "make, put in" + capsule + -ate .
now capsule meaning is box, case
In real life example if you put things on desk open then it is accessible to anyone but if you put in case then it is accessible with the key of case to open.
Same way in class if you create a variable then it accessible whenever you create object of that class.But if you create function to access the variable then you have created case and function is key to access the variable.
So in programming language we are creating wrapper of the data by using getter and setter and making it private variable.
Encapsulation is a capsule, consider it to be a class enclosing or hiding fields, properties and functions.
Please check below url encapsulation is simplified with simple programming example.
http://itsforlavanya.blogspot.com/2020/08/encapsulation.html?m=1

Resources