Declaring static variables in cocoa - cocoa

I want to have a static variable in Cocoa.
After looking at How do I declare class-level properties in Objective-C?, I am unclear whether there is anything wrong with what I have always done so far, i.e.
// Foo.m
static NSString* id;
#interface Foo ()
instead of
// Foo.h
#interface Foo {
}
+(NSString*) id;
// Foo.m
+(NSString*) id
{
static NSString* fooId = nil;
if (fooId == nil)
{
// create id
}
return fooId;
}
Obviously, the second approach offers an opportunity for initializing the id. But if I initialize the id myself somewhere else in the code, within, say a getter:
-(NSString*) getId
{
if (id==nil) {
id = ... // init goes here
}
return id;
}
Then is there anything wrong with the simple static declaration approach as opposed to the more complex class function approach? What am I missing?

First, what you are asking for is a global variable, a static is similar but a little bit different...
Putting a static declaration outside of any #interface in a header (.h) file will create a different variable in each implementation (.m) file you include the header in - not what you want in this case.
So static on a declaration creates a variable whose lifetime is that of the whole application execution but which is only visible within the compilation unit (e.g. the implementation file) in which it appears - either directly or via inclusion.
To create a global variable visible everywhere you need to use extern in the header:
extern NSString *id;
and in your implementation repeat the declaration without the extern:
NSString *id;
As to what is wrong with global variable vs. class methods, that is a question on program design and maintainability. Here are just a few points to consider:
With a method the value cannot be changed unless you provide a setter method as well as getter method. Variables are always read-write.
Namespace pollution: a class method is only valid when paired with its class name ([YourClass id]); the variable name is valid everywhere it's included simply as id; that both pollutes the name space and loses the connection between id and YourClass - which leads us to...
Encapsulation: globals variables break strong encapsulation, and encapsulation aids program design and maintenance - this is a big topic.
That said, there can be a time and a place for globals, sometimes...
After question updated
A static variable declared in the implementation is effectively a "class variable" - a variable shared by all instances of the class.
The pros'n'cons of a class variable vs. setter & getter class methods are exactly the same as the pros'n'cons of an instance variable vs. properties & setter/getter instance methods.
Class setters/getters allow for validation and other logic to be executed on each read/write; and localization of memory management - in short the abstraction and encapsulation benefits of any method.
Therefore whether you use a variable or a setter/getter depends on your application. It is the same question as whether you use an instance variable or setter/getter/property.

Related

Is Virtual destructor rule inherited or not? [duplicate]

With the struct definition given below...
struct A {
virtual void hello() = 0;
};
Approach #1:
struct B : public A {
virtual void hello() { ... }
};
Approach #2:
struct B : public A {
void hello() { ... }
};
Is there any difference between these two ways to override the hello function?
They are exactly the same. There is no difference between them other than that the first approach requires more typing and is potentially clearer.
The 'virtualness' of a function is propagated implicitly, however at least one compiler I use will generate a warning if the virtual keyword is not used explicitly, so you may want to use it if only to keep the compiler quiet.
From a purely stylistic point-of-view, including the virtual keyword clearly 'advertises' the fact to the user that the function is virtual. This will be important to anyone further sub-classing B without having to check A's definition. For deep class hierarchies, this becomes especially important.
The virtual keyword is not necessary in the derived class. Here's the supporting documentation, from the C++ Draft Standard (N3337) (emphasis mine):
10.3 Virtual functions
2 If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.
No, the virtual keyword on derived classes' virtual function overrides is not required. But it is worth mentioning a related pitfall: a failure to override a virtual function.
The failure to override occurs if you intend to override a virtual function in a derived class, but make an error in the signature so that it declares a new and different virtual function. This function may be an overload of the base class function, or it might differ in name. Whether or not you use the virtual keyword in the derived class function declaration, the compiler would not be able to tell that you intended to override a function from a base class.
This pitfall is, however, thankfully addressed by the C++11 explicit override language feature, which allows the source code to clearly specify that a member function is intended to override a base class function:
struct Base {
virtual void some_func(float);
};
struct Derived : Base {
virtual void some_func(int) override; // ill-formed - doesn't override a base class method
};
The compiler will issue a compile-time error and the programming error will be immediately obvious (perhaps the function in Derived should have taken a float as the argument).
Refer to WP:C++11.
Adding the "virtual" keyword is good practice as it improves readability , but it is not necessary. Functions declared virtual in the base class, and having the same signature in the derived classes are considered "virtual" by default.
There is no difference for the compiler, when you write the virtual in the derived class or omit it.
But you need to look at the base class to get this information. Therfore I would recommend to add the virtual keyword also in the derived class, if you want to show to the human that this function is virtual.
The virtual keyword should be added to functions of a base class to make them overridable. In your example, struct A is the base class. virtual means nothing for using those functions in a derived class. However, it you want your derived class to also be a base class itself, and you want that function to be overridable, then you would have to put the virtual there.
struct B : public A {
virtual void hello() { ... }
};
struct C : public B {
void hello() { ... }
};
Here C inherits from B, so B is not the base class (it is also a derived class), and C is the derived class.
The inheritance diagram looks like this:
A
^
|
B
^
|
C
So you should put the virtual in front of functions inside of potential base classes which may have children. virtual allows your children to override your functions. There is nothing wrong with putting the virtual in front of functions inside of the derived classes, but it is not required. It is recommended though, because if someone would want to inherit from your derived class, they would not be pleased that the method overriding doesn't work as expected.
So put virtual in front of functions in all classes involved in inheritance, unless you know for sure that the class will not have any children who would need to override the functions of the base class. It is good practice.
There's a considerable difference when you have templates and start taking base class(es) as template parameter(s):
struct None {};
template<typename... Interfaces>
struct B : public Interfaces
{
void hello() { ... }
};
struct A {
virtual void hello() = 0;
};
template<typename... Interfaces>
void t_hello(const B<Interfaces...>& b) // different code generated for each set of interfaces (a vtable-based clever compiler might reduce this to 2); both t_hello and b.hello() might be inlined properly
{
b.hello(); // indirect, non-virtual call
}
void hello(const A& a)
{
a.hello(); // Indirect virtual call, inlining is impossible in general
}
int main()
{
B<None> b; // Ok, no vtable generated, empty base class optimization works, sizeof(b) == 1 usually
B<None>* pb = &b;
B<None>& rb = b;
b.hello(); // direct call
pb->hello(); // pb-relative non-virtual call (1 redirection)
rb->hello(); // non-virtual call (1 redirection unless optimized out)
t_hello(b); // works as expected, one redirection
// hello(b); // compile-time error
B<A> ba; // Ok, vtable generated, sizeof(b) >= sizeof(void*)
B<None>* pba = &ba;
B<None>& rba = ba;
ba.hello(); // still can be a direct call, exact type of ba is deducible
pba->hello(); // pba-relative virtual call (usually 3 redirections)
rba->hello(); // rba-relative virtual call (usually 3 redirections unless optimized out to 2)
//t_hello(b); // compile-time error (unless you add support for const A& in t_hello as well)
hello(ba);
}
The fun part of it is that you can now define interface and non-interface functions later to defining classes. That is useful for interworking interfaces between libraries (don't rely on this as a standard design process of a single library). It costs you nothing to allow this for all of your classes - you might even typedef B to something if you'd like.
Note that, if you do this, you might want to declare copy / move constructors as templates, too: allowing to construct from different interfaces allows you to 'cast' between different B<> types.
It's questionable whether you should add support for const A& in t_hello(). The usual reason for this rewrite is to move away from inheritance-based specialization to template-based one, mostly for performance reasons. If you continue to support the old interface, you can hardly detect (or deter from) old usage.
I will certainly include the Virtual keyword for the child class, because
i. Readability.
ii. This child class my be derived further down, you don't want the constructor of the further derived class to call this virtual function.

Why should functions used for creating a Predicate be defined as static?

While reading up on the new features introduced in Java 8, I came across the concept of Predicates. I noticed that most of the examples provided on the internet and in books use static functions to create predicates.
Consider the following Apple class for example :
public class Apple {
private String color;
private int weight;
private static final int SMALL_APPLE_MAX_WEIGHT = 150;
public Apple(String color, int weight) {
this.color = color;
this.weight = weight;
}
public static boolean isGreenApple(Apple apple) {
return null!=apple && null!=apple.getColor() && "green".equals(apple.getColor());
}
public boolean isBigApple() {
return this.getWeight() > SMALL_APPLE_MAX_WEIGHT;
}
}
I can now create a new predicate as follows :
Predicate<Apple> isGreenApple = Apple::isGreenApple;
Predicate<Apple> isBigApple = Apple::isBigApple;
As shown above, I can create a predicate using both a static as well as an instance method. Which approach is the preferred approach then and why?
For a method reference, there is no difference between an instance method A.foo() and a static method foo(A), in fact, the compiler will reject a method reference as ambiguous if both exist.
So the decision whether to use an instance method or a static method does not depend on the question whether you want to create a function via method reference for it.
Rather, you have to apply the same considerations us usual. Should the method be overridable, it has to be an instance method, otherwise, if it represents a fixed algorithm, you may consider a static method, but of course, a final method would do as well.
static methods are obviously unavoidable when you are not the maintainer of the class whose instance you want to process, in other words, when the containing class has to be different than the class of the instance. But even if the class is the same but you feel that it could be placed in another (utility) class as well, declaring it as static might be the better choice.
This holds especially when there are more than one parameter and the first one isn’t special to the operation, e.g. max(Foo,Foo) should be a static method rather than an instance method max(Foo) on Foo.
But in the end there are different programming styles out there and the answer is that method references do not mandate a particular programming style.
Regarding why there are so many examples using static methods; well I don’t know enough examples to decide whether your observation is right or just a subjective view. But maybe some tutorial writers are themselves not aware about the possibility to refer to an instance method as a function taking the method receiver as first argument.
I think, there are examples, like
Predicate<String> empty=String::isEmpty;
Predicate<CharSequence> isHello="hello"::contentEquals;
which are worth to be shown in tutorials to emphasize that you are not required to create methods specially intended to be used as method references, but that in fact there are a lot of already existing methods, static and non-static, to be directly usable with method references.
What I am more interested in knowing is why are all examples on predicates shown using static methods?
The reference appears on the Class as no additional argument is required.
Any specific reason for not using instance methods?
For non-static methods that would make sense. In the case of
Predicate<Apple> isBigApple = Apple::isBigApple;
Predicate needs a argument so it takes this. An example of a non-method call would be something like
List<Apple> bigApples = new ArrayList<>();
apples.stream().filter(Apple::isBigApple).forEach(bigApple::add);

Cplex C++ interface. How to clean up memory?

Background: The C++ interface of IBM ILOG Cplex allocates and de-allocates memory rather unconventionally:
A declaration of an ILO environment IloEnv environment;, followed by a construction of models and solvers within this environment, followed by all these objects (including the environment) going out of scope results in a memory leak. Note that I have not used the new operator. One way to avoid this is to call environment.end(); before the object goes out of scope.
Setting: Now, I have a class whose purpose is to solve a specific ILP. This class has some member variables:
IloEnv ilpEnvironment_;
IloObjective ilpObjective_;
IloExpr ilpExpression_;
IloModel ilpModel_;
IloCplex ilpSolver_;
IloNumArray ilpSolution_;
IloNumVarArray ilpVariables_;
IloNumArray ilpStartValues_;
IloRangeArray constraints_;
These member variables are initialized in the initializer list of the constructor:
inline MyClass::MyClass()
: ilpEnvironment_(),
ilpObjective_(ilpEnvironment_),
ilpExpression_(ilpEnvironment_),
ilpModel_(ilpEnvironment_),
ilpSolver_(ilpModel_),
ilpSolution_(ilpEnvironment_),
ilpVariables_(ilpEnvironment_),
ilpStartValues_(ilpEnvironment_),
constraints_(ilpEnvironment_)
{ /* ... */ }
The destructor de-allocates all the memory (that has been allocated by member functions of the class that operate on the member variables):
inline MyClass::~MyClass() {
ilpEnvironment_.end();
}
Question: How do i implement a member function void clear() that de-allocates the memory and puts the class back into its initial state? Here are two rather naive attempts I made that don't work:
inline void MyClass::clear() {
ilpEnvironment_.end();
ilpEnvironment_ = IloEnv(); // does not work, whether or not I comment this line out
ilpObjective_ = IloObjective(ilpEnvironment_);
ilpExpression_ = IloExpr(ilpEnvironment_);
ilpModel_ = IloModel(ilpEnvironment_);
ilpSolver_ = IloCplex(ilpEnvironment_);
ilpSolution_ = IloNumArray(ilpEnvironment_);
ilpVariables_ = IloNumVarArray(ilpEnvironment_);
ilpStartValues_ = IloNumArray(ilpEnvironment_);
constraints_ = IloRangeArray(ilpEnvironment_);
}
If the purpose of the class is to solve a specific ILP model, then I would initialize the class with the model size/parameters, and create and destroy the CPLEX objects within a solve() member function while saving only the results as class members. Class members would be model parameters, and the object would keep all CPLEX dealings hidden.
You could even have a class member that keeps track of which constraints to activate in that particular solve() call.
If you absolutely have to use the CPLEX objects as changeable class members, then you might want to try to use object pointers as class members instead of the objects themselves. Calling IloEnv::end() destroys the objects associated with it, so you could call IloEnd::end() and then reassign the pointers to new objects.

Class: Immutability vs Not Extensible

I was reading that there are many reasons for making a class final in SO threads and also in an arcticle
Two of which were
1. To remove extensibility
2. to make class immutable.
Does making a class immutable have the characteristic along with it as being final ( it's methods )? I don't see the difference between the two?
Immutable object does not allow to change his state. Final class does not allow to inherit itself. For example class Foo (see below) is immutable (the state, ie _name is never changed ) and class Bar is mutable (rename method allows to change the state):
final class Foo
{
private String _name;
public Foo(string name)
{
_name = name;
}
public String getName()
{
return _name;
}
}
final class Bar
{
private String _name;
public Bar(string name)
{
_name = name;
}
public String getName()
{
return _name;
}
public void rename(string newName)
{
_name = newName;
}
}
It can sometimes be useful to recognize types as "verifiably deeply immutable", meaning that static analysis can demonstrate that (1) once an instance is constructed, none of its properties will ever change, and (2) every object instance to which it holds a reference is verifiably deeply immutable. Classes which are open to extension cannot be verifiably deeply immutable, because a static analyzer would have no way of knowing whether a mutable subclass might be created, and a reference to that mutable subclass stored within what's supposed to be a verifiably deeply immutable object.
On the other hand, it can sometimes be useful to have abstract (and thus extensible) classes which are specified to be deeply immutable. The abstract class would have no way of forcing derived classes to immutable, but any mutable derived classes should be considered "broken". The situation would be somewhat analogous to the requirement that two object instances which report themselves as "equal" to each other should report the same hash code. It's possible to design classes which violate that requirement, but any errant hash-table behavior that results is the fault of the broken hash-code function, rather than the hash table.
For example, one might have an abstract ImmutableMatrix property with a method to read the element at a given (row,column) location. One possible implementation would be to back an NxM ImmutableMatrix with an array of N*M elements. On the other hand, it may also be useful to define some subclasses like ImmutableDiagonalMatrix, with an array of N elements, where Value(R,C) would yield 0 for R!=C, and Arr[R] for R==C. If a significant fraction of the arrays one is using will be diagonal arrays, one could save a lot of memory for each such instance. While leaving the class extensible would leave open the possibility that someone might extend it in a fashion which is open to mutation, it would also leave open the possibility that a programmer who knew that many of the arrays a program used would fit some particular form could design a class to optimally store that form.

Is there a hook for when anonymous classes are assigned to a constant?

I've been practicing some Ruby meta-programming recently, and was wondering about assigning anonymous classes to constants.
In Ruby, it is possible to create an anonymous class as follows:
anonymous_class = Class.new # => #<Class:0x007f9c5afb21d0>
New instances of this class can be created:
an_instance = anonymous_class.new # => #<#<Class:0x007f9c5afb21d0>:0x007f9c5afb0330>
Now, when the anonymous class is assigned to a constant, the class now has a proper name:
Foo = anonymous_class # => Foo
And the previously created instance is now also an instance of that class:
an_instance # => #<Foo:0x007f9c5afb0330>
My question: Is there a hook method for the moment when an anonymous class is assigned to a constant?
There are many hooks methods in Ruby, but I couldn't find this one.
Let's take a look at how constant assignment works internally. The code that follows is extracted from a source tarball of ruby-1.9.3-p0. First we look at the definition of the VM instruction setconstant (which is used to assign constants):
# /insns.def, line 239
DEFINE_INSN
setconstant
(ID id)
(VALUE val, VALUE cbase)
()
{
vm_check_if_namespace(cbase);
rb_const_set(cbase, id, val);
INC_VM_STATE_VERSION();
}
No chance to place a hook in vm_check_if_namespace or INC_VM_STATE_VERSION here. So we look at rb_const_set (variable.c:1886), the function that is called everytime a constant is assigned:
# /variable.c, line 1886
void
rb_const_set(VALUE klass, ID id, VALUE val)
{
rb_const_entry_t *ce;
VALUE visibility = CONST_PUBLIC;
# ...
check_before_mod_set(klass, id, val, "constant");
if (!RCLASS_CONST_TBL(klass)) {
RCLASS_CONST_TBL(klass) = st_init_numtable();
}
else {
# [snip], won't be called on first assignment
}
rb_vm_change_state();
ce = ALLOC(rb_const_entry_t);
ce->flag = (rb_const_flag_t)visibility;
ce->value = val;
st_insert(RCLASS_CONST_TBL(klass), (st_data_t)id, (st_data_t)ce);
}
I removed all the code that was not even called the first time a constant was assigned inside a module. I then looked into all the functions called by this one and didn't find a single point where we could place a hook from Ruby code. This means the hard truth is, unless I missed something, that there is no way to hook a constant assignment (at least in MRI).
Update
To clarify: The anonymous class does not magically get a new name as soon as it is assigned (as noted correctly in Andrew's answer). Rather, the constant name along with the object ID of the class is stored in Ruby's internal constant lookup table. If, after that, the name of the class is requested, it can now be resolved to a proper name (and not just Class:0xXXXXXXXX...).
So the best you can do to react to this assignment is to check the name of the class in a loop of a background worker thread until it is non-nil (which is a huge waste of resources, IMHO).
Anonymous classes don't actually get their name when they're assigned to a constant. They actually get it when they're next asked what their name is.
I'll try to find a reference for this. Edit: Can't find one, sorry.

Resources