Golang OOP information hiding practice - oop

What can I do with Go struct to hide information? Go struct member is visible to all. How to hide a member in a package?

Go is not an Object oriented language. But it encapsulates things at the package level.
According to GoLang specification;-
An identifier may be exported to permit access to it from another
package. An identifier is exported if both:
the first character of the identifier's name is a Unicode upper case
letter (Unicode class "Lu"); and
the identifier is declared in the package block or it is a field
name or method name.
All other identifiers are not exported.
If you don't wants to make your struct variables public do not export them. use lowercase to create variables in a struct type.
Unexported struct fields are only accessible to same package.
// unexported struct
type person struct {
name string // unexported fields can be used only in the same package
age int
}
Only package level granularity is allowed in Go. One can declare struct in different package which can be used in those files wherever it is required

Related

List of ABAP protected type names

Out of curiosity, I tried to create an ABAP interface with name object. The compiler gives the error message "OBJECT" is a protected type name and therefore cannot be used for a user's own type definitions.
While this check is certainly a good idea, I could not find a reference to protected type name in the ABAP Keyword documentation. Are there others?
The naming conventions indicate the possible names additionally to the mandatory naming "convention":
The names of predefined ABAP types or predefined data objects must not be used for data types or data objects.
NB: I tried names of predefined data objects, they are allowed for data types, so I guess "respectively" is to be understood implicitly.
Self-defined data types must not have the name of a built-in ABAP type. This applies to type definitions in the ABAP language and in the ABAP Dictionary.
Concerning the generic types, only those made of one word are forbidden, i.e. HASHED, INDEX, SORTED, and STANDARD are allowed (and also REF):
ANY, C, CLIKE, CSEQUENCE, DATA, DECFLOAT, N, NUMERIC, OBJECT, P, SIMPLE, TABLE, X, XSEQUENCE
Other types are protected like the built-in concrete (i.e. not generic) types (error <XXXX> is a protected type name and therefore cannot be used for a user's own type definitions):
D, DECFLOAT16, DECFLOAT34, F, I, STRING, T, XSTRING
CURSOR
Obsolete types 1 and 2 (their names are also forbidden inside classes and interfaces because the name must start with A-Z, underscore).
Other types may be forbidden (error Type <XXXX> is reserved for future further developments of the ABAP language. Choose another name.) like:
INT, INT1, INT2, INT4, INT8
The list is not exhaustive. I didn't find an official list in the ABAP documentation nor in the SAP support Web site.
NB: tests done in a 7.52 system
The generic data types, which cannot be used for naming:
https://help.sap.com/doc/abapdocu_750_index_htm/7.50/en-US/abenbuilt_in_types_generic.htm
The best way to create all of your object or program or table ect.. is to put the Z or the Y before the name you want to give:
Object have to been Zobject or Yobject or ZY-YZobject
Often, we use the Z and then the module wich it refers: ZSD_OBJECT

Kotlin how to declare chained fields with same data type

In other programming languages like Java if you want to chain fields, you do like: String a, b, c, d;
Is it possible to chain fields in Kotlin too, like val a, b, c, d?
here doesn`t provide any info
No, Kotlin does not support declaration of multiple variable in a statement.
Kotlin has learned some good lessons from Java. One of that is variable declaration. Though Java support multiple variable declaration in a line, Oracle's Java Guidelines says use only one declaration per line.
Following is mentioned in Oracle Java Standard:
One declaration per line is recommended since it encourages commenting. In other words,
int level; // indentation level
int size; // size of table
is preferred over
int level, size;
In absolutely no case should variables and functions be declared on the same line. Example:
long dbaddr, getDbaddr(); // WRONG!
Do not put different types on the same line. Example:
int foo, fooarray[]; //WRONG!
Note: The examples above use one space between the type and the identifier. Another
acceptable alternative is to use tabs, e.g.:
int level; // indentation level
int size; // size of table
Object currentEntry; // currently selected table entry
Refer this link for Oracle convention: http://www.oracle.com/technetwork/java/codeconventions-150003.pdf. Page no. 14 > Declarations.
There has been some huge debates on this topic of type of declaration should be used for Java. So Kotlin just removed that as an option.
First, Kotlin is a null-safety language which means you can't declare fields without initializing them, and Kotlin has no default value for any types even if it is nullable, but there is an exception for the primitive array, e.g:IntArray(size) the default value likes as java are 0. So you can't write the form of the field declaration as in Java, for example:
//Java
private String a,b,c;// they are `null` by default.
private val a:String? // error: property must be initialized
Secondly, If you are concerned about the definition of fields/variables, they are totally different. the field/variable type is declared at the right-side, which means you can't declare a unified fields/variables in Kotlin at all, so it doesn't make sense in Kotlin, for example:
//Java
String a,b;
//Kotlin
val a, b;
// ^---^--- how to declare the variables type?
// v-- just more than one `val` after introduce the variable types
val a:String; val b:String;
Finally, field is a heavy component in Kotlin. when you declare a field in Java it is merely a field, no more. but in Kotlin when you declare a field, it maybe a property/field. and a property has getter/backing field(?)/setter(?), for example:
// java
String a; //just a field
// kotlin
var a:String = "a" // has a backing field, getter & setter
private var b:String = "b" // it is just a field
#JvmField var c:String = "c"
// ^--- it is a field but it has getter/setter in reflect
// e.g: this::c.getter & this::c.setter

What do member numbers mean in Microsoft Bond?

Using Microsoft Bond (the C# library in particular), I see that whenever a Bond struct is defined, it looks like this:
struct Name
{
0: type name;
5: type name;
...
}
What do these numbers (0, 5, ...) mean?
Do they require special treatment in inheritance? (Do I need to make sure that I do not override members with the same number defined in my ancestor?)
The field ordinals are the unique identity of each field. When serializing to tagged binary protocols, these numbers are used to indicate which fields are in the payload. The names of the fields are not used. (Renaming a field in the .bond file does not break serialized binary data compatibility [though, see caveat below about text protocols].) Numbers are smaller than strings, which helps reduce the payload size, but also ends up improving serialization/deserialization time.
You cannot re-use the same field ordinal within the same struct.
There's no special treatment needed when you inherit from a struct (or if you have a struct field inside your struct). Bond keeps the ordinals for the structs separate. Concretely, the following is legal and will work:
namespace inherit_use_same_ordinal;
struct Base {
0: string field;
}
struct Derived : Base {
0: bool field;
}
A caveat about text serialization protocols like Simple JSON and Simple XML: these protocols use the field name as the field identifier. So, in these protocols renaming a field breaks serialized data compatibility.
Also, Simple JSON and Simple XML flatten the inheritance hierarchy, so re-using names across Base and Derived will result in clashes. Both have ways to work around this. For Simple XML, the SimpleXml.Settings.UseNamespaces parameter can be set to true to emit fully qualified names.
For Simple JSON, the Bond attribute JsonName can be used to change the name used for Simple JSON serialization, to avoid the conflict:
struct Derived : Base {
[JsonName("derived_field")]
0: bool field;
}

Can I have a string object store its data within the structure?

I'm looking for a quick way to serialize custom structures consisting of basic value types and strings.
Using C++CLI to pin the pointer of the structure instance and destination array and then memcpy the data over is working quite well for all the value types. However, if I include any reference types such as string then all I get is the reference address.
Expected as much since otherwise it would be impossible for the structure to have a fixed.. structure. I figured that maybe, if I make the string fixed size, it might place it inside the structure though. Adding < VBFixedString(256) > to the string declaration did not achieve that.
Is there anything else that would place the actual data inside the structure?
Pinning a managed object and memcpy-ing the content will never give you what you want. Any managed object, be it String, a character array, or anything else will show up as a reference, and you'll just get a memory location.
If I read between the lines, it sounds like you need to call some C or C++ (not C++/CLI) code, and pass it a C struct that looks similar to this:
struct UnmanagedFoo
{
int a_number;
char a_string[256];
};
If that's the case, then I'd solve this by setting up the automatic marshaling to handle this for you. Here's how you'd define that struct so that it marshals properly. (I'm using C# syntax here, but it should be an easy conversion to VB.net syntax.)
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct ManagedFoo
{
public int a_number;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)]
public string a_string;
}
Explanation:
StructLayout(LayoutKind.Sequential) specifies that the fields should be in the declared order. The default LayoutKind, Auto, allows the fields to be re-ordered if the compiler wants.
CharSet=CharSet.Ansi specifies the type of strings to marshal. You can specify CharSet.Ansi to get char strings on the C++ side, or CharSet.Unicode to get wchar_t strings in C++.
MarshalAs(UnmanagedType.ByValTStr) specifies a string inline to the struct, which is what you were asking about. There are several other string types, with different semantics, see the UnmanagedType page on MSDN for descriptions.
SizeConst=256 specifies the size of the character array. Note that this specifies the number of characters (or when doing arrays, number of array elements), not the number of bytes.
Now, these marshal attributes are an instruction to the built-in marshaler in .Net, which you can call directly from your VB.Net code. To use it, call Marshal.StructureToPtr to go from the .Net object to unmanaged memory, and Marshal.PtrToStructure to go from unmanaged memory to a .Net object. MSDN has some good examples of calling those two methods, take a look at the linked pages.
Wait, what about C++/CLI? Yes, you could use C++/CLI to marshal from the .Net object to a C struct. If your structs get too complex to represent with the MarshalAs attribute, it's highly appropriate to do that. In that case, here's what you do: Declare your .Net struct like I listed above, without the MarshalAs or StructLayout. Also declare the C struct, plain and ordinary, also as listed above. When you need to switch from one to the other, copy things field by field, not a big memcpy. Yes, all the fields that are basic types (integers, doubles, etc.) will be a repetitive output.a_number = input.a_number, but that's the proper way to do it.

Where is the definition of a class stored in memory as opposed to the instance?

This question is merely out of interest and trying to understand something about memory management in object-oriented languages. It is not specific to one language, but I just want to understand as a general principle.
What I want to know is how the definition of an object reference is stored compared to the instance of that reference.
When you define and object in OO source code, e.g. in Java, without instantiating it:
String s;
How does this get stored? How does the memory usage of this definition differ from when the object is actually instantiated:
s = new String("abc");
? Is there a general principle that applies to all OO languages in terms of how memory is allocated or do different language implementers use different techniques for allocating memory?
Normaly when we declare a refrence like String s; it is created as a normal variable just like int , float but this type of variable hold the memory address ( it similar concept as pointers in C language) but when we use s = new String("abc");, it creates an object in heap and assign that address to the reference variable s.
In Java byte code, all Objects are stored as Objects. Explicit type-checking is added when needed. So for example this Java function
public Integer getValue(Object number){
int i = ((Number) number).toInt();
return new Integer(i);
}
is translated to a bytecode like this:
(accepts java.lang.Object, returns java.lang.Integer)
-read the first argument as an Object
-if the value is not a Number, raise an exception
-call the virtual method toInt(java.lang.Integer) of the value
and remember the int result
-use the value as an int argument
-instantiate a new java.lang.Integer
-call the constructor(int) of java.lang.Integer on the new number,
getting an Object back
[since the declared return value of Number.toInt is the same
as the return value of our function, no type checking is needed]
-return the value
So, types of unused variables get stripped out by the compiler. Types of public and protected fields are stored with its class.
The runtime type of an Object is stored with the object. In C++, it is a pointer to the Virtual Method Table. In Java, it is as a 16-bit index into the table of all loaded classes.
The Java class file stores an index of all dependent classes in a similar table. Only the class names are stored here. All field descriptions then point to this table.
So, when you write String s = new String("abc") (or even String s = "abc"), your class stores:
it is dependent on the class java.lang.String in the table of dependencies
"abc" in the table of String literals
your method loading a String literal by ID
(in the first case) your method calling a constructor of its first dependent class (String) with the first dependent class (String) as an argument.
the compiler can prove storing the new String in a String variable is safe, so it skips the type checking.
A class can be loaded as soon as it is referenced, or as late as its first use (in which case it is refered to by its depending class and ID within the class). I think the latter is always the case nowadays.
When a class is loaded:
-its class loader is asked to retreive the class by its name.
-(in the case of the system loader) the class loader looks
for the corresponding file in the program JAR, in the system library
and in all libraries referenced.
-the byte stream is then decoded into a structure in memory
-(in the case of early loading) all dependent classes are loaded recursively
if not already loaded
-it is stored in the class table
-(in the case of late loading) its static initialiser is run
(possibly loading more classes in the process).
In C++, none of the class loading takes place, as all user classes and most libraries are stored in the program as a mere virtual method table and the corresponding method. All of the system functions (not classes) can still be stored in a DLL (in case of Windows) or a similar file and loaded by the library at runtime. If a type checking is implied by an explicit type-cast, it is performed on the virtual method table. Also note that C++ did not have a type checking mechanism for a while.