Whats is methodLists attribute of the structure objc_class for? - objective-c

Looking inside the runtime.h, I found the definition of the structure objc_class.
Among various members, We have this :-
struct objc_method_list **methodLists
We definitely need to know what all methods a class has,
But a list of methods should be fine, but why do we have "lists" ?
Why not just one list ?
Also, can anyone specify that, Are methods inherited from superclass part of that list or we get to them via superclass pointer that points to parent class's structure.

Here is my detail investigation into struct objc_method_list **methodLists : http://blog.csdn.net/jasonblog/article/details/7303618
And in short, methodLists stores SEL-IMP mapping of the instance methods by default. In this situation, it has only one list.
As the name 'methodLists' suggests, it can contain more than one list. If you add a category to a class, the runtime system will insert one more list into methodLists, which points to the method-list of the category.
I tried to answer this question several months ago, but at that time SO discard my answer due to network problem. Now I meet it again :)

The purpose is explained in objc-class.m, as linked by Georg:
cls->methodLists may be in one of three forms:
NULL: The class has no methods.
non-NULL, with CLS_NO_METHOD_ARRAY set: cls->methodLists points
to a single method list, which is the class's only method list.
non-NULL, with CLS_NO_METHOD_ARRAY clear: cls->methodLists points to
an array of method list pointers. The end of the array's block
is set to -1. If the actual number of method lists is smaller
than that, the rest of the array is NULL.
Attaching categories and adding and removing classes may change
the form of the class list. In addition, individual method lists
may be reallocated when fixed up.
Classes are initially read as #1 or #2. If a category is attached
or other methods added, the class is changed to #3. Once in form #3,
the class is never downgraded to #1 or #2, even if methods are removed.
Classes added with objc_addClass are initially either #1 or #3.
The short answer is therefore "because of categories." When a category is injected, rather than try to combine its method list with the one existing list, a new entry is simply added to methodLists, and set to the list coming from the category. This probably makes category injection faster, since it avoids (potential) large reallocations and copying.

Related

Differences between Function that returns a string and read only string property [duplicate]

I need to expose the "is mapped?" state of an instance of a class. The outcome is determined by a basic check. It is not simply exposing the value of a field. I am unsure as to whether I should use a read-only property or a method.
Read-only property:
public bool IsMapped
{
get
{
return MappedField != null;
}
}
Method:
public bool IsMapped()
{
return MappedField != null;
}
I have read MSDN's Choosing Between Properties and Methods but I am still unsure.
The C# standard says
§ 8.7.4
A property is a member that provides access to a characteristic of an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on. Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written.
while as methods are defined as
§ 8.7.3
A method is a member that implements a computation or action that can be performed by an object or class. Methods have a (possibly empty) list of formal parameters, a return value (unless the method’s return-type is void ), and are either static or non-static.
Properties and methods are used to realize encapsulation. Properties encapsulate data, methods encapsulate logic. And this is why you should prefer a read-only property if you are exposing data. In your case there is no logic that modifies the internal state of your object. You want to provide access to a characteristic of an object.
Whether an instance of your object IsMapped or not is a characteristic of your object. It contains a check, but that's why you have properties to access it. Properties can be defined using logic, but they should not expose logic. Just like the example mentioned in the first quote: Imagine the String.Length property. Depending on the implementation, it may be that this property loops through the string and counts the characters. It also does perform an operation, but "from the outside" it just give's an statement over the internal state/characteristics of the object.
I would use the property, because there is no real "doing" (action), no side effects and it's not too complex.
I personally believe that a method should do something or perform some action. You are not performing anything inside IsMapped so it should be a property
I'd go for a property. Mostly because the first senctence on the referenced MSDN-article:
In general, methods represent actions and properties represent data.
In this case it seems pretty clear to me that it should be a property. It's a simple check, no logic, no side effects, no performance impact. It doesn't get much simpler than that check.
Edit:
Please note that if there was any of the above mentioned and you would put it into a method, that method should include a strong verb, not an auxiliary verb like is or has. A method does something. You could name it VerifyMapping or DetermineMappingExistance or something else as long as it starts with a verb.
I think this line in your link is the answer
methods represent actions and properties represent data.
There is no action here, just a piece of data. So it's a Property.
In situations/languages where you have access to both of these constructs, the general divide is as follows:
If the request is for something the object has, use a property (or a field).
If the request is for the result of something the object does, use a method.
A little more specifically, a property is to be used to access, in read and/or write fashion, a data member that is (for consuming purposes) owned by the object exposing the property. Properties are better than fields because the data doesn't have to exist in persistent form all the time (they allow you to be "lazy" about calculation or retrieval of this data value), and they're better than methods for this purpose because you can still use them in code as if they were public fields.
Properties should not, however, result in side effects (with the possible, understandable exception of setting a variable meant to persist the value being returned, avoiding expensive recalculation of a value needed many times); they should, all other things being equal, return a deterministic result (so NextRandomNumber is a bad conceptual choice for a property) and the calculation should not result in the alteration of any state data that would affect other calculations (for instance, getting PropertyA and PropertyB in that order should not return any different result than getting PropertyB and then PropertyA).
A method, OTOH, is conceptually understood as performing some operation and returning the result; in short, it does something, which may extend beyond the scope of computing a return value. Methods, therefore, are to be used when an operation that returns a value has additional side effects. The return value may still be the result of some calculation, but the method may have computed it non-deterministically (GetNextRandomNumber()), or the returned data is in the form of a unique instance of an object, and calling the method again produces a different instance even if it may have the same data (GetCurrentStatus()), or the method may alter state data such that doing exactly the same thing twice in a row produces different results (EncryptDataBlock(); many encryption ciphers work this way by design to ensure encrypting the same data twice in a row produces different ciphertexts).
If at any point you'll need to add parameters in order to get the value, then you need a method. Otherwise you need a property
IMHO , the first read-only property is correct because IsMapped as a Attribute of your object, and you're not performing an action (only an evaluation), but at the end of the day consistancy with your existing codebase probably counts for more than semantics.... unless this is a uni assignment
I'll agree with people here in saying that because it is obtaining data, and has no side-effects, it should be a property.
To expand on that, I'd also accept some side-effects with a setter (but not a getter) if the side-effects made sense to someone "looking at it from the outside".
One way to think about it is that methods are verbs, and properties are adjectives (meanwhile, the objects themselves are nouns, and static objects are abstract nouns).
The only exception to the verb/adjective guideline is that it can make sense to use a method rather than a property when obtaining (or setting) the information in question can be very expensive: Logically, such a feature should probably still be a property, but people are used to thinking of properties as low-impact performance-wise and while there's no real reason why that should always be the case, it could be useful to highlight that GetIsMapped() is relatively heavy perform-wise if it in fact was.
At the level of the running code, there's absolutely no difference between calling a property and calling an equivalent method to get or set; it's all about making life easier for the person writing code that uses it.
I would expect property as it only is returning the detail of a field. On the other hand I would expect
MappedFields[] mf;
public bool IsMapped()
{
mf.All(x => x != null);
}
you should use the property because c# has properties for this reason

Smalltallk - How can I get an Array (or Collection) of the all the Instance variables in an Object (the current Instance) of a Class?

Let's say we have a Class and we instantiate it, creating an Instance of that Class. This Instance has a number of (instance)variables, defined by the class, that I need to use. I'd like to get all these (instance)variables in an Array or some Collection so I can iterate through them and set them to some value, not nil.
How can I do this?
I would like to build up on #Uko's answer because there is a more direct way to implement his idea.
The message instSize sent to a Class will answer the number of named instance variables of its instances. This, of course, would include instance variables defined in superclasses.
For instance, RemoteTempVectorNode instSize answers with 17 (wow!). Therefore you could do:
fields := (1 to: anObject class instSize) collect: [:i | anObject instVarAt: i]
and then, change them with:
values withIndexDo: [:v :i | anObject instVarAt: i put: v]
where values is the array of new values you want to inject into the object.
So, why I'm suggesting this instead of instVarNamed:? Because the latter is indirect. If you take a look at its implementation you will see that it has to first find out the name of the i-th ivar by sending instVarIndexFor:ifAbsent: to the object's class. In other words, if you need the ivar names, follow #Uko's suggestion; otherwise don't bring them into the equation because they will only add CPU cycles to your program.
One more thing. As #Sean DeNegris wisely raised in his comment to your question, it would be beneficial if you elaborated a little bit more on why you need such an unusual maneuver.
EDIT:
Now that Pharo has Flexible Object Layouts the mapping between inst var names and the class instSize is no longer valid (in classes that use the new capability.) So, the simpler approach of using just indexes would not work with generality. In fact, under the new "taxonomy" the instSize (number of fields) of an object may be different from the #numberOfInstanceVariables. I guess that the added flexibility has its costs and benefits.
You can send #allInstVarNames to a class (Behavior) to get names of all instance variables defined by it and by superclasses. If you need without superclass variables, you can use #instVarNames
Let's say that var is your variable that you need to work with. Then you can get the collection of instance variable names and iterate them.
You can use #instVarNamed:put: to set instance variable by name, and #instVarNamed: to get the value by name (in case you need).
I think that something like this may help you:
var class allInstVarNames do: [ :instVarName |
var instVarNamed: instVarName put: <yourValue>

Overextending object design by adding many trivial fields?

I have to add a bunch of trivial or seldom used attributes to an object in my business model.
So, imagine class Foo which has a bunch of standard information such as Price, Color, Weight, Length. Now, I need to add a bunch of attributes to Foo that are rarely deviating from the norm and rarely used (in the scope of the entire domain). So, Foo.DisplayWhenConditionIsX is true for 95% of instances; likewise, Foo.ShowPriceWhenConditionIsY is almost always true, and Foo.PriceWhenViewedByZ has the same value as Foo.Price most of the time.
It just smells wrong to me to add a dozen fields like this to both my class and database table. However, I don't know that wrapping these new fields into their own FooDisplayAttributes class makes sense. That feels like adding complexity to my DAL and BLL for little gain other than a smaller object. Any recommendations?
Try setting up a separate storage class/struct for the rarely used fields and hold it as a single field, say "rarelyUsedFields" (for example, it will be a pointer in C++ and a reference in Java - you don't mention your language.)
Have setters/getters for these fields on your class. Setters will check if the value is not the same as default and lazily initialize rarelyUsedFields, then set the respective field value (say, rarelyUsedFields.DisplayWhenConditionIsX = false). Getters they will read the rarelyUsedFields value and return default values (true for DisplayWhenConditionIsX and so on) if it is NULL, otherwise return rarelyUsedFields.DisplayWhenConditionIsX.
This approach is used quite often, see WebKit's Node.h as an example (and its focused() method.)
Abstraction makes your question a bit hard to understand, but I would suggest using custom getters such as Foo.getPrice() and Foo.getSpecialPrice().
The first one would simply return the attribute, while the second would perform operations on it first.
This is only possible if there is a way to calculate the "seldom used version" from the original attribute value, but in most common cases this would be possible, providing you can access data from another object storing parameters, such as FooShop.getCurrentDiscount().
The problem I see is more about the Foo object having side effects.
In your example, I see two features : display and price.
I would build one or many Displayer (who knows how to display) and make the price a component object, with a list of internal price modificators.
Note all this is relevant only if your Foo objects are called by numerous clients.

Finding variables that share common properties

I'm using Mathematica and have a set of variables (A,B,C,D,...) with properties A=(blue, big, rounded), B=(red, small, spiky), and so forth. Those properties can be common between variables. What would be the best, general way to find all variables that share a common property (of being, for instance, small)? Thanks.
Here's a list of possible properties:
In[1]:= properties={"red","green","blue","big","small","rounded","spiky"};
And here's a list of objects with some of those properties
In[2]:= list={{"blue","big","rounded"},{"red","small","spiky"},
{"red","big","rounded"},{"blue","small","spiky"}};
You can find all objects that have the property of, e.g., being "blue" using Select
In[3]:= Select[list, MemberQ[#,"blue"]&]
Out[3]= {{blue,big,rounded},{blue,small,spiky}}
This could be wrapped up into a function. Although how I would write that function would depend on the data structures and usage that you're planning.
Actually, I just reread you question you have a list of objects with some properties and you want to refer to those objects by name. So you probably want something more like
In[1]:= listProperties["A"]:={"blue","big","rounded"}
listProperties["B"]:={"red","small","spiky"}
listProperties["C"]:={"red","big","rounded"}
listProperties["D"]:={"blue","small","spiky"}
Above I defined some properties that are associated with certain strings. You don't have to use strings in the above or below, and you can create a better structure than that if you want. You could also make a constructor to create the above, such a constructor could also check if the list of properties supplied is of the right form - i.e. does not have contradictory properties, are all in a list of known properties etc...
We then define a function to test if an object/string has a certain property associated with it
In[2]:= hasProperty[obj_, property_]:=MemberQ[listProperties[obj],property]
You might want to return an error or warning message if listProperties[obj] does not have a definition/rule associated with it.
Use Select to find all "objects" in a list that have the associated property "blue":
In[3]:= Select[{"A","B","C","D"}, hasProperty[#,"blue"]&]
Out[3]= {A,D}
There are other ways (probably better ways) to set up such a data structure. But this is one of the simplest ways in Mathematica.

What is an instance of a field called?

This might be an odd question, but it has actually caused me some headache.
In Object oriented programming, there are accepted names for key concepts. In our model, we have classes with methods and fields. Now, going to the data world:
An instance of a class is called an object.
An instance of a field is called... what?
A value? Isn't the term value a little broad for this? I have been offered "property" as well, but isn't property also part of the model and not the data?
(This is not purely academic, I am actually coding these concepts.)
Updated: Let me take an example. I have a class "Person" with a field "age". If I create 20 Person instances, each such instance is called an object. So far so good. But let's say I take Person "Igor", and set his age to 20. What is the storage location that contains the number 20 now called? Is it a field, or a value, or something else?
Another update: A quote from Pavel Feldman in this related question describes in different words what I tried to describe above:
"I'd say that in class-based OOP field belongs to class and does not have a value. It is so when you look at reflection in c# or java - class has fields, field has type, name, etc. And you can get value of the field from object. You declare field once, in class. You have many objects with same fields but different values."
A field can't be instantiated. A field can only contain a value. The value can be either a primitive/native type or a reference/pointer to an object instance.
As per your update: if the object represents a real world entitiy, then it's often called property. With a "real world entity" I mean something personal/human, e.g. Person, Product, Order, Car, etc. If the object does not represent something personal/human, e.g. List, String, Map, then it's more often called field. That's just what I've observed as far.
Agree with BalusC. However I think what you are asking is what to call the field of an instantiated object. Remember that an object contains both state (data) and operations (methods) you could refer to an object field as state
A field is a field weather you talk about it in the context of a class, or in the context of an object.
class C {
int i; // i is a field
}
and
obj = new C();
obj.i = 7; // obj.i is a field
As opposed to parameter vs argument there is no distinction in terminology for "instantiated" an "uninstantiated" fields.
An instance of a class is an object, a class may contain fields that point to other instantiated objects (or a null pointer). It makes no sense to say an instance of a field, but rather you might talk about the object to which a particular field points to, which may be different for different instances. Or you may talk about the type of a field (which class it belongs to)
Isn't the answer basically that we have no name for values of fields of an instance of a class (or object)?
It's like giving a name to the value returned by a method of an instance of a class...
I guess "state" is the best answer anyway as suggested "BalusC".