Changing immutable members inside the constructor - constructor

void increment(ref int i)
{
++i;
}
class Class
{
immutable int member;
this(int parameter)
{
member = parameter;
++member; // okay
increment(member); // compile-time error
}
}
Why is ++member okay, but increment(member) isn't? Shouldn't both behave the same way?

Probably because the reference to increment isn't scope, so it has the potential to be escaped past the scope of the constructor, which would break the immutability of member, and the compiler can't verify that it's fine.
(It might be that scope won't work either, but it should. If implemented properly, I think scope would fix a lot of bugs like these, as well as providing for interesting optimizations. If it doesn't, I'd say it's a bug.)
I've pointed out semi-similar bugs before, but with delegates.
Const/immutable do have such problems in D.

What if increment was this?
int* p;
void increment(ref int i)
{
p = &i;
}
Uh oh, you've created a mutable reference to immutable data, breaking the type system.

I am guessing that
this(int parameter) {
member = parameter;
++member;
}
is an equivalent of
Class(int parameter): member(parameter+1) {}
in C++.
I think member field is not truly mutable in constructor, so compiler can optimize it to just init it. But it cannot do it with call to another function.
PS. It works on ideone: http://ideone.com/5ym5u

Related

Why can't the "`main`" function be declared as a lambda in Kotlin?

The following trivial Kotlin code snippet
fun main() {}
compiles just fine, but the following
val main : () -> Unit = {}
makes the compiler complain that "No main method found in project.", while I was expecting them to be equivalent (I expect a programming language to be as conceptually uniform as possible).
Why does this happen? Is it related only to main, or does this behaviour concern a larger class of functions? Is there some subtle difference between declaring functions with "fun" and declaring them as lambdas?
Conceptually, they are different things. To see that, let's take a look at roughly what the equivalent Java would be. I'll use JVM for examples in this answer, but the same principles apply to all of the other Kotlin backends.
object Foo {
fun main() { ... }
}
This is roughly
class Foo {
public static void main() { ... }
}
Again, roughly. Technically, you'll get a singleton object and a method on it unless you use #JvmStatic (I assume there's some special handling for main that produces a static function on JVM, but I don't know that for a fact)
On the other hand,
object Foo {
val main: () -> Unit = { ... }
}
Here, we're declaring a property, which in Java is going to get implemented as a getter-setter pair
class Foo {
// Singleton instance
public static Foo instance = new Foo();
public Supplier<Void> main;
Foo() {
main = new Supplier<Void>() {
Void get() {
...
}
}
}
}
That is, there isn't actually a main method. There's a main field which, deep down somewhere, has a function inside of it. In my example above, that function is called get. In Kotlin, it's called invoke.
The way I like to think of it is this. Methods in Kotlin (i.e. the things you define on objects that designate their behavior) are not themselves first-class objects. They're second-class citizens which exist on an object. You can convert them to first-class objects by making them into functions. Functions are ordinary objects, like any other. If you take an ordinary object, which may or may not be a function, and call it with (), then you're actually invoking the method .invoke(...) on it. That is, () is an operator on objects which really ends up calling a method. So in Kotlin, functions are really just objects with a custom invoke and a lot of syntax sugar.
Your val defines a field which is a function. Your fun defines a method. Both of these can be called with (), but only one is a genuine method call; the other is secretly calling .invoke on another object. The fact that they look syntactically the same is irrelevant.
As the old adage goes, functions are a poor man's objects, and objects are a poor man's functions.
There is a subtle (or more than subtle) difference. Declaring it with val means that main is a property containing a reference to an anonymous function (which you defined with the lambda). If you define it with val, then when you call main(), you are actually calling the getter of the main property, and then using the invoke() operator to call invoke() on the return value of the property (the anonymous function).

Do function arguments violate encapsulation?

This question is related to OOP practice in general.
Say we have a class with a public function accepting passed in arguments from outside of the object. Is that not a violation of encapsulation in itself? On the other hand why is this practice used so widely? After all the constructor of the class and member variables are kind of "by-passed" when calling the function. As an relatively new programmer to OOP and my understanding of encapsulation my function parameters are passed into the object through setters, so that I keep all of my functions without any arguments using the passed in member variables only.
I know that certain arguments can be passed in through the constructor (BTW, I use dependency injection), but what if those parameters change after the object is being instantiated? There must be a way to change those values after the object is created. So far I found no other option than using setters to accomplish this task, but there is a long lasting discussion among programmers about getters and setters to be "evil" or at least considered no good programming practice.
Can anyone tell my where I missed the point and how to solve this dilemma in a clean way?
Many thanks in advance for any support.
Here is a concrete very simple example using C#:
we have a form in a windows form project holding 3 textboxes ,named textBox1 and textBox2 and textBox3.
The task is to add values of textBox1 and textBox2 and returning the result to textBox3 using class AddTextboxValues instantiated by event handler any time the value of textBox1 or textBox2 changes:
The way I see it often and ask if is violation of encapsulation:
public class AddTextBoxValues
{
public double TextBoxValueSum(double textBox1value, double textBox2Value)
{
return textBox1value + textBox2Value;
}
}
This is the way I use at the moment as per my understanding of encapsulation:
public class AddTextBoxValues
{
private double textBox1Value;
private double textBoxValue2;
private double textBoxValue3;
public double TextBox1Value
{
set { textBox1Value = value; }
}
public double TextBoxValue2
{
set { textBoxValue2 = value; }
}
public double TextBoxValue3
{
get { return textBoxValue3; }
}
public void TextBoxValueSum()
{
textBoxValue3= textBox1Value + textBoxValue2;
}
}
This has also the advantage that it can be injected into the form constructor.
Any comment is highly appreciated.
Thank you very much Jon Skeet, you are a real professional.
You diagnosed my problem exactly and opened my eyes for the lack of knowledge to understand and find a solution to my own question. It was indeed a deeper understanding of encapsulation and "object state" which built the missing piece of my puzzle.
Everything seems logic and clear now for me and I hope it will help others in the future,too.
Both examples are not object oriented programming. They are examples of procedural programming.
First "class" is, in fact, just a namespace wrapping TextBoxValueSum function.
Second "class" is just a structure with public fields (there is no difference between getters-setters and public fields).
If you want to use real object oriented programming, you should think of objects, that they are representation of things.
In your case, I'd write class Sum which is a real thing that represent one, specific sum:
class Sum {
private double a, b;
public Sum (double a, double b) { this.a = a; this.b = b; }
public double value() { return this.a + this.b; }
}

Immutability in D constructors

My previous question discussed making a copy constructor like so:
struct Foo {
int i;
this(int j) { i = j; }
this(Foo rhs) { this = rhs; }
}
void main()
{
auto f = Foo(5);
auto g = new Foo(f);
}
But, if I make i immutable, the constructor fails to compile with
Error: cannot modify struct this Foo with immutable members
Why is this the case? I was under the impression that immutable members of a class or struct do not become immutable until the end of the constructor is reached.
Okay. In general, I'd advise against having structs with immutable members. There are just too many places where it's useful to be able to assign to one. What you typically want to do with a struct is make it so that it can be mutable, const, or immutable as a whole. And for the most part, that just works. e.g.
struct Foo
{
int i;
this(int j) { i = j; }
this(Foo rhs) { this = rhs; }
}
void main()
{
immutable f = Foo(5);
}
compiles just fine. The one area that generally causes trouble with that is when you have to have a postblit constructor, because those don't currently work with const or immutable structs (it's something that sorely needs to be fixed, but it's still an open problem due to how the type system works - it may result in us having to add copy constructors to the language, or we may figure out how to do it, but for now, it doesn't work, and it can be annoying). But that only affects you if you need a postblit constructor, which most structs don't need (the problem will be fixed eventually though, because it really needs to be; it's just a question of how and when).
However, to answer your question more generally, let's look at a class. For instance, this code won't compile, because the constructor is not immutable, and the compiler can't convert an immutable class object to a mutable one (it can do that with structs, because it makes a copy, but with a class, it's just copying the reference, not the object, so it doesn't work):
class Foo
{
int i;
this(int j) { i = j; }
}
void main()
{
auto f = new immutable Foo(5);
}
Instead of that compiling, you get this lovely error message:
q.d(10): Error: mutable method q.Foo.this is not callable using a immutable object
q.d(10): Error: no constructor for Foo
There are three ways to solve this. The first is to make the constructor immutable
class Foo
{
int i;
this(int j) immutable { i = j; }
}
and that works, but it makes it so that you can only construct Foos which are immutable, which usually isn't what you want (though it sometimes is). So, the second way to solve the problem would be to take the first solution a step further and overload the constructor. e.g.
class Foo
{
int i;
this(int j) { i = j; }
this(int j) immutable { i = j; }
}
However, that requires code duplication, which isn't a lot here, but it could be a lot for other types. So, what is generally the best solution is to make the constructor pure.
class Foo
{
int i;
this(int j) pure { i = j; }
}
This works, because the compiler then knows that nothing has escaped the constructor (since pure guarantees that nothing escapes by being assigned to a global or static variable, and the constructor's parameters don't allow anything to escape either), and because it knows that no references to Foo or its members can escape the constructor, it knows that there are no other references to this Foo and that it therefore can safely convert it to mutable, const, or immutable without violating the type system. Of course, that only works if you can make the constructor pure and nothing can escape via the constructor's arguments, but that's usually the case, and when it isn't, you can always just overload the constructor on mutability, much as that's less desirable.
The same techniques can be used on structs if you really want const or immutable members, but again, I'd advise against it. It's just going to cause you more trouble than it's worth, especially when it's usually trivial to just make the whole struct const or immutable when declaring a variable.
Making members of structs immutable stops assigning to the struct which in turn causes quite a few issues, you may which to rethink that.
Otherwise assign the members directly instead of relying on the assignment operator:
struct Foo {
immutable int i;
this(int j) { i = j; }
this(in Foo rhs) { this.i = rhs.i; }
}

Function objects in C++ (C++11)

I am reading about boost::function and I am a bit confused about its use and its relation to other C++ constructs or terms I have found in the documentation, e.g. here.
In the context of C++ (C++11), what is the difference between an instance of boost::function, a function object, a functor, and a lambda expression? When should one use which construct? For example, when should I wrap a function object in a boost::function instead of using the object directly?
Are all the above C++ constructs different ways to implement what in functional languages is called a closure (a function, possibly containing captured variables, that can be passed around as a value and invoked by other functions)?
A function object and a functor are the same thing; an object that implements the function call operator operator(). A lambda expression produces a function object. Objects with the type of some specialization of boost::function/std::function are also function objects.
Lambda are special in that lambda expressions have an anonymous and unique type, and are a convenient way to create a functor inline.
boost::function/std::function is special in that it turns any callable entity into a functor with a type that depends only on the signature of the callable entity. For example, lambda expressions each have a unique type, so it's difficult to pass them around non-generic code. If you create an std::function from a lambda then you can easily pass around the wrapped lambda.
Both boost::function and the standard version std::function are wrappers provided by the li­brary. They're potentially expensive and pretty heavy, and you should only use them if you actually need a collection of heterogeneous, callable entities. As long as you only need one callable entity at a time, you are much better off using auto or templates.
Here's an example:
std::vector<std::function<int(int, int)>> v;
v.push_back(some_free_function); // free function
v.push_back(&Foo::mem_fun, &x, _1, _2); // member function bound to an object
v.push_back([&](int a, int b) -> int { return a + m[b]; }); // closure
int res = 0;
for (auto & f : v) { res += f(1, 2); }
Here's a counter-example:
template <typename F>
int apply(F && f)
{
return std::forward<F>(f)(1, 2);
}
In this case, it would have been entirely gratuitous to declare apply like this:
int apply(std::function<int(int,int)>) // wasteful
The conversion is unnecessary, and the templated version can match the actual (often unknowable) type, for example of the bind expression or the lambda expression.
Function Objects and Functors are often described in terms of a
concept. That means they describe a set of requirements of a type. A
lot of things in respect to Functors changed in C++11 and the new
concept is called Callable. An object o of callable type is an
object where (essentially) the expression o(ARGS) is true. Examples
for Callable are
int f() {return 23;}
struct FO {
int operator()() const {return 23;}
};
Often some requirements on the return type of the Callable are added
too. You use a Callable like this:
template<typename Callable>
int call(Callable c) {
return c();
}
call(&f);
call(FO());
Constructs like above require you to know the exact type at
compile-time. This is not always possible and this is where
std::function comes in.
std::function is such a Callable, but it allows you to erase the
actual type you are calling (e.g. your function accepting a callable
is not a template anymore). Still calling a function requires you to
know its arguments and return type, thus those have to be specified as
template arguments to std::function.
You would use it like this:
int call(std::function<int()> c) {
return c();
}
call(&f);
call(FO());
You need to remember that using std::function can have an impact on
performance and you should only use it, when you are sure you need
it. In almost all other cases a template solves your problem.

Do I need to use dynamic_cast when calling a function that accepts the base class?

I have some classes like this:
interface class IA
{
};
interface class IB
{
};
public ref class C : public IA, public IB
{
};
public ref class D
{
void DoSomething(IA^ aaa)
{
}
void Run()
{
C^ bob = gcnew C();
DoSomething(dynamic_cast<IA^>(bob)); // #1
DoSomething(bob); // #2
}
};
At the moment I always try to use dynamic casting when calling such a function, (the #1 above).
However it does make the code quite ugly, so I want to know if it is actually necessary.
Do you use dynamic_cast in this way? If so what is the main reason?
In standard C++, you use dynamic_cast to walk down the hierarchy, not up. In this case, you'd use it to try and convert an IA or IB into a C:
IA^ temp = /* get a C in some way. */;
C^ tempC = dynamic_cast<C^>(temp);
Since we know bob is of type C^, we know at compile time it can be downcasted to IA^ safely, and so dynamic_cast is equivalent to static_cast here. Moreover, the implicit cast you propose is also safe.
dynamic_cast is only needed when upcasting from a base type to a derived.
No, I would think that in C++/CLI you also don't need the dynamic cast here. Derived* implicitly converts to Base* unless there's an ambiguity w.r.t. multiple inheritance. The same it probably true for "gc-pointers". In C++ a dynamic cast -- when upcasting -- requires polymorphic classes (with at least one virtual function). I don't know how C++/CLI handles it, though. I would think every CLI class is by default polymorphic.
You may want to remove the C++ tag, by the way. ;)