I am learning qemu and qom recently. I am perplexed when I meet the conception of ObjectClass and Object. I already understand that ObjectClass stands for class while Object means instance of class. However, what I want to know is What kind of information should store in ObjectClass and what's going on in Object.
As far as I am concerned, like C++ or Java, Object just the same as what's define in Class and be used in real logic. In this case, Class seems like a template which produce Object the real be used.
In qemu, everything seems different. We define these two in two struct, and they have different properties, which leads to separation of Class and Object. Does it means I can use one ObjectClass to produce many Object that differ with each other? And secondly, why should I do this? Are there any advantages of this pattern? In detail, what's the role ObjectClass and Object plays in qemu respectively? And what about their relationship? If I want to design a new device, What should I do in initialization of MyObjectClass and MyObject?
What's more, I notice that qemu will initialize every ObjectClass by TypeImpl, which is initialized by TypeInfo defined by developer.
TypeInfo => ModuleEntry => TypeImpl => ObjectClass => Object
Of course they do different things. TypeInfo converts to ModuleEntry before main function is executed(__attribute__((constructor))), which contains initial functions of ObjectClass and Object. Why we need this mechanism? On the other words, what if we just create ObjectClass instead of create TypeImpl and create ObjectClass after that? Any advantages?
This is part of QEMU's object model (QOM), which is documented in the developer section of the documentation. You should read that, and also look through include/qom/object.h for more details of the object model.
In QOM, for any class there is one class struct -- for the base Object type the class struct is ObjectClass. There are then multiple objects created at runtime, each of which is a struct Object. This applies also for subtypes of Object, like DeviceState, whose class struct is DeviceClass. The class struct holds fields which are common to every instance of that object type, notably including the function pointers which are the equivalent of methods. The object struct holds all the fields which are per-instance. Because each Object contains a pointer to the corresponding ObjectClass, you can always get from a pointer to an instance of an object to its class information.
Because we're implementing an object-oriented model in C, we have to have everything be explicit -- in C++ and Java, because the object model is part of the language the compiler can sort out under the hood a lot of the things QOM has to manage manually with class structs and object structs and so on.
More generally, if your aim is "write a new device" I would recommend that you do not spend any time looking into the internals of the QOM implementation. Instead you should look at how other devices similar to yours are implemented and at what the patterns of code are that they use to declare and use a new device type.
Related
I am new to schema.org. Currently i am trying to use it as our internal data model for imports as it offers a good "common ground" for all source systems.
The Hotel schema (https://schema.org/Hotel) offers a "photo" (singular) property, it inherits from Place. It used to have a "photos" (plural) property in the past.
When using schema.org for markup, this would not matter, as i can just mark up multiple elements as "photo".
However, when using it as a data class, how should i model it?
Should i just make it an array of Photograph?
If yes, does schema.org actually assume on ANY property that it may be multiple (amenityFeature, availableLanguage, etc. suspiciously look like that)?
Does that mean, i have to actually model every property as an array?
After some additional research i have to assume schema.org is not meant as a full data model. It is mostly about providing a common vocabulary and a hierarchy of information. Its primary use case seems to be markup, so types definitions are very vague since they have to work on content that is actually meant to be presented to a user. So i will have to specify my own schema and let my decisions and my naming be guided by schema.org.
I got this problem,
"The deserializer has no knowlege of any type that maps to this contract"
After googling, I reached this post
The deserializer has no knowlege of any type that maps to this contract
where the answer says, the base class have to declare "KnownTypes" like
[DataContract, KnownType(typeof(Subclass)) ...],
If I have to declare this in my parent class, [DataContract, KnownType(typeof(Subclass))], doesn't it break the principles of OO Design that parent class doesn't have to know about subclass?
What is the right way of doing this?
The serializer is designed in a way that, if it serializes an object, it should be able to read it back. If you attempt to serialize an object with a declared type of 'Base', but an actual type of 'Derived' (see example below), if you want to be able to read back from the serialized object an instance of 'Derived', you need to somehow annotate the XML that the instance is not of the type of which it was declared.
[DataContract]
public class MyType
{
[DataMember]
public object obj = new Derived();
}
The serialized version of the type would look something like the XML below:
<MyType>
<obj actualType="Derived">
<!-- fields of the derived type -->
</obj>
</MyType>
When the type is being deserialized, the serializer will look at the "actualType" (not actual name) attribute, and it will have to find that type, initialize it, and set its properties. It's a potential security issue to let the serializer (with in Silverlight lives is a trusted assembly and has more "rights" than the normal user code) to create arbitrary type, so that's one reason for limiting the types which can be deserialized. And based on the design of the serializer (if we can serialize it, we should be able to deserialize it), the serialization fails for that reason as well.
Another problem with that is that the serialized data is often used to communicate between different services, in different computers, and possibly with different languages. It's possible (and often it is the case) that you have a class in a namespace in the client which has a similar data contract to a class in the server side, but they have different names and / or reside in different namespaces. So simply adding the CLR type name in the "actualType" attribute won't work in this scenario either (the [KnownType] attribute helps the serialzier map the data contract name / namespace to the actual CLR type). Also, if you're talking to a service in a different language / platform (i.e., Java), CLR type names don't even make sense.
Another more detailed explanation is given at the post http://www.dotnetconsult.co.uk/weblog2/PermaLink,guid,a3775eb1-b441-43ad-b9f1-e4aaba404235.aspx - it talks about [ServiceKnownType] instead of [KnownType], but the principles are the same.
Finally, about your question: does it break that OO principle? Yes, that principle is broken, that's a price to pay for being able to have lose coupling between the client and services in your distributed (service-oriented) application.
Yes it breaks the principles of OO design. This is because SOA is about sharing contracts (the C in ABC of services) and not types, whereas OO is about type hierarchies. Think like this the client for a service may not be even in an OO language but SOA principles can still be applied. How the mapping is done on server side is an implementation issue.
Does Encapsulation is information Hiding or it leads to information hiding??
As we say that Encapsulation binds data and functions in a single entity thus it provides us control over data flow and we can access the data of an entity only through some well defined functions. So when we say that Encapsulation leads to abstraction or information hiding then it means that it gives us an idea which data to hide and which data to show to users... coz the data that users cant access can be hidden from them thus encapsulation gives us a technique to find out what data to be hidden and what should be visible... Is this concept correct??
And what is the difference between information hiding and abstraction??
Possible duplicate of the this
public class Guest {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
See the above code, we have encapsulated the String name, we provide the access to it through public methods.
Say we have created object of Guest called guest. Then the following will be illegal.
System.out.println("Guests name : "guest.name);
Access through public methods is what can only be done.
guest.getName();
Benefits of Encapsulation:
The fields of a class can be made
read-only or write-only.
A class can have total control over
what is stored in its fields.
The users of a class do not know how
the class stores its data. A class
can change the data type of a field,
and users of the class do not need
to change any of their code.
Encapsulation means hiding the implementation
Abstraction means providing blueprint about the implementation
Data Hiding means controlling access to DataMember or attributes
Information is a more general term, hence, i believe, to say Encapsulation is Information hiding, will not be appropriate.
I would say Encapsulation is Data Hiding.
Encapsulation means ...
Combining an Object's State & behavior (that operates on that State), in one single unit.
This closely mimics a real world Object.
Hiding & Securing Object's State from accidental external alterations by providing a well-defined, controlled access (through behaviors).
In Java, the definition can be detailed out as ...
In Java, Classes and Enums are single units for implementing encapsulation. State is defined using variables (primitives, references to objects), and behavior using methods.
Data Hiding is achieved using private access specifier on variables (so that no one can access them from outside).
Controlled Access is achieved by providing Getters / Setters and/or business logic methods. Both Setters and other State affecting methods should have boundary condition checks for keeping the State logically correct.
Encapsulation talks about hiding data into something and give it a name ( private data members in a class - Car) and binding behavior methods with it which will mutate or provide access to those data variables.
Abstraction provides perspective of the client in abstract terms. As a concept or idea. Car is concrete entity where as Drivable, Trackable(which has position and can be tracked down) can be abstraction for Car for different clients.
You can check some real life examples of Abstraction and Encapsulation here.
Encapsulation is a technique used for hiding properties & behavior of an object.
Abstraction refers to representing essential features.
Encapsulation - Work complete and door permanently closed. Get work benefits through method name.
Abstraction - Work started and door temperately closed. Open and change work using overriding Key.
Both these OOP principles involve information hiding but are different.
Encapsulation involves restricting the direct access to the variables of the class by making them private and giving public getters and setters to access them.
Purpose: This is done so that the members of the class cannot be accidentally manipulated (and thus corrupted) from outside.
Abstraction involves exposing only the relevant details to the caller while hiding other details (details of implementation). The client does not need to bother about implementation which may change later. Example: The caller will call the add method of List, the implementation of which may be ArrayList today but may change to LinkedList tomorrow.
Purpose: This provides flexibility that tomorrow the implementation can be changed. Also, it simplifies the design.
As the red block above (warning that this is a subjective question and may be closed) there may not be a stone etched law on this, but I don't see why that would warrant closing a question.
...Rant aside
I am planning on implementing Hibernate as my persistence framework, which may fix my problem upon implementation, but I have DB tables that translate into class and sub-class (many specifics and complications that exist in real life are omitted :) ):
//dbo.a with column Name
class a {
public String Name;
}
//dbo.b with column Name and a foreign key to dbo.a
class b extends a {
public String Name;
}
So, for the what should be done and why:
Shadowing:
I could leave these as is, which would require some reflection cleverness (per http://forums.sun.com/thread.jspa?threadID=5419973 ), when working with objects whose types are unknown at compile.
Compound Names:
I could name all of my fields preceded by its class's name i.e. a.aName and b.bName, which gets really ugly in real life: Door.DoorName and RotatingDoor.RotatingDoorName
Getters and Setters:
I didn't mention this one, since with JavaBeans these will be derived from the field names, and I believe Hibernate uses annotated POJOs.
To influence the results a little, shadowing seems to be the most robust, at least in my case where class a extends an abstract class with Name defined, then b shadows with its own Name when applicable. Using compound names would mean that if I wanted to add a NickName column to all my DB tables then I would have to add that field to each type (and then what's the point of inheritance?!)
In the end I decided to find out what people, hopefully who have experienced pros/cons of an implementation of one or more of these technique, have to say on the issue; or that convenient stone etched best practice will do :)
-Nomad311
you should only define your member in the base class if you need it in all subclasses. hibernate offers various types of mappings for class trees. take a look at Inheritance mapping in the manual to get a feeling of it.
you can define your mapping either via an xml file or via annotations.
In general I think I can convey most programming related concepts quite well.
Yet, I still find it hard to summarise the relationship between Fields, Classes and Packages.
How do You summarise "Fields", "Classes" and "Packages" and "Their Relationship" ?
I've faced a similar problem since I taught C, C++, and Java.
Here is what I do:
First, I keep packages separately and explain them in the end.
Ideally, in my opinion, students should first learn about ADTs, preferably in C. They have the struct, they have the separate operations on it. Fields are then simply the "slots" in the struct and you can even show the memory layout to demonstrate it. Functions are separate entities that operate on those structs.
You then make the transition to classes, methods, and fields and show that in essence (barring inheritance and some anecdotes) they are in many ways syntactic sugar for ADTs.
If you need, you can then teach object layouts, inheritance, and virtual tables (in my experience it helps students understand inheritance better to see the memory layout).
Finally you get to the topic of how to organize classes together. If you teach C++, you don't really have packages but you can explain namespaces and discuss organization and separate compilation.
If you are in Java, then you just explain that these are collections of classes in the same namespace, that have special access rules and show them. The package system in Java is kind of broken anyway so I usually go through patterns (e.g., separating a UI package from the C).
So in summary: Classes form the basis for objects that are a memory arrangement of several fields and associated methods that operate on them. Packages are collections of classes that have one more access restriction mechanism.
The way I describe it is:
Objects are collections of slots, slots holding data are fields, slots holding code are methods. Public slots are on the outside of the object, private slots are on the inside. Methods should be mostly public because an object offers services to clients, fields should be private so clients don't know how the services work. Fields are therefore an implementation detail of objects.
Class names need to be unique, so that you can combine your code with third party libraries. Simple/short class names are insufficient, since there are probably thousands of classes called 'List', 'Customer' etc... Hence classes are placed in packages to create longer, harder to duplicate names. Only a subset of the classes in the package need to be visible to clients, hence the two access levels of public and default. This allows a package to function as a library.
So fields are an implementation detail of objects, whose classes live in packages to guarantee unique names and provide library-like modularity.
Depending on the age of the person you're trying to explain it to, there's a simple analogy that can be used: tax forms. A tax form (such as the 1040EZ, for instance) is like a class, and each space to be filled in on the form is a field of the form. The tax form even contains instructions on what to be done with the information in the fields, just as a class includes member functions to be performed on the data in the fields. And just as a complete set of tax forms includes not just the main tax form, but others that may need to be filled out (additional schedules, for example) so a package contains not just the main classes but other classes it may need to interact with.
Fields are variables that belong to the class, or to object instances of the class. The difference between a local variable and a field is that fields have a broader scope.
Classes are templates for user-defined data types. Classes are more advanced than the primitive data types because they have both state and behavior.
Packages are used to group classes and to resolve potential naming conflicts. With multiple developers and publicly available code libraries it's very likely that some of us will name our classes the same (Math, LinkedList, FileUtils, etc.). Having a unique package name prefixing the class name allows the compiler (and other developers) to determine which class you intend to use.
Interestingly, you tackled OO programming without mentioning objects. I think that may be your problem.
Here's what I use.
Objects are things. They have attributes (measurements, states of being, etc.) Attributes can be called fields. [I often use things I find in the classroom -- cups, markers, hats, coats, etc., to illustrate this.]
Objects also engage in behaviors, called methods, method functions or operations.
The features (attributes and operations, fields and methods, whatever) of an object provide a way to classify objects.
The features that are common to a class of objects is -- well -- can be collected into a class definition. A class definition describes the attributes and methods of the objects that are members of the class.
A package is a collection of class definitions. While -- ideally -- the classes in a package have something in common, that isn't a requirement and isn't a helpful distinction.