A language that has function scoped, class life time variable - oop

After asking this question, I just wondered is there any language that has this concept. Consider this piece of arbitrary code:
class Foo {
void bar() {
static int i = 0;
print(i++);
}
}
Foo foo = new Foo();
foo.bar(); // prints 0
foo.bar(); // prints 1
Foo foo2 = new Foo();
foo2.bar(); // prints 2
foo2.bar(); // prints 3
So the static i variable shared across all instances of Foo class and it's life time starts at first encounter and lasts all program long. What I wonder is, is there any language that has some_magic_keyword for defining a variable, that makes the variable function scoped and makes it life time equal to it's class life time and not sharing it along the instances of the class. So the code can be something like this:
class Foo {
void bar() {
some_magic_keyword int i = 0;
print(i++);
}
}
Foo foo = new Foo();
foo.bar(); // prints 0
foo.bar(); // prints 1
Foo foo2 = new Foo();
foo2.bar(); // prints 0
foo2.bar(); // prints 1
delete foo2; // the "i" variable is also deleted from memory, so no memory leaks
There is some questions about if we can implement this in some particular language but I couldn't find any asking if any language has it.
And it doesn't have to be an object oriented language, I can't think of any functional language with this concept for obvious reasons but if you can make the analogy, why not?
EDIT: If there isn't any which seems like, why not? I mean the concept is pretty straightforward. Actually when I first used a static variable in a function, I was expecting the same behaviour I'm asking here.

Related

Is there an equivalent to Fortran's select type statement in Chapel?

I'd like to try out classes and polymorphism in Chapel, so I am trying to
get the following example code to work:
module SomeAnimals {
class Animal {
}
class Bird: Animal {
}
class Fish: Animal {
}
proc Bird.fly() {
writeln("Flying ...!");
}
proc Fish.swim() {
writeln("Swimming ...!");
}
} // module SomeAnimals
proc main() {
use SomeAnimals;
var anim: Animal;
anim = new Fish();
select (anim.type) {
when Fish do anim.swim();
}
delete anim;
anim = new Bird();
select (anim.type) {
when Bird do anim.fly();
}
delete anim;
} // proc main
This compiles, but upon running it, it simply exits without producing any
print-out. Apparently, the calls to the anim.swim() and anim.fly() methods, contained within the select statements, aren't executed for some reason. Without making use of these select statements to check the actual type of the polymorphic variable "anim", the code, of course, doesn't compile.
The above example is actually a rather literal translation of a working
Fortran 2008 code that makes use of Fortran's "select type" statement. Does
Chapel provide a similar statement, or does this example have to be coded in a completely different fashion in order to work in Chapel? I couldn't find anything of relevance in the Chapel documentation.
The key for understanding why your code isn't working is that myVar.type in Chapel refers to the variable's static type rather than its dynamic type. So even though you and I can see that anim is a Fish initially and a Bird later, anim.type will always be Animal since it was declared as var anim: Animal; giving it the static type Animal. You can see this by changing your main() function to the following (try it online):
proc main() {
use SomeAnimals;
var anim: Animal;
anim = new Fish();
writeln(anim.type:string);
anim = new Bird();
writeln(anim.type:string);
} // proc main
where the output will be:
Animal
Animal
One way to reason about a class variable's dynamic type in Chapel is to apply the cast operator (:) to it, which behaves similarly to dynamic casts in C++. Namely, if I try to cast a variable whose static type is Animal to Fish but it's really a Bird, I'll get nil back, indicating that the class object was neither a Fish nor a subclass of Fish.
So a rewrite of your main() that behaves as you'd like would be the following (try it online):
proc main() {
use SomeAnimals;
var anim: Animal = new Fish();
var aFish = anim:Fish;
if aFish then
aFish.swim();
delete anim;
anim = new Bird();
var aBird = anim:Bird;
if aBird then
aBird.fly();
delete anim;
} // proc main
(where I'm using the shorthand if classVar ... for if classVar != nil ...)
Rewinding to your specific question about whether Chapel has a Fortran-like type select statement, it does not at present. For reasoning about static types (like int vs. real vs. my record R vs. a subclass of C), using the select statement on a variable's type as you did is completely reasonable (or you could provide overloads of a function where we'd choose the correct one based on the argument's static type). But for cases where you're working within a class hierarchy and have to reason about the dynamic type of the object, your main tools will be casting, as above, or dynamic dispatch, or storing an explicit field in the class to distinguish between the cases (which can be thought of as a manual implementation of the dynamic cast).

Indirect initialization of memory via UnsafeMutablePointer types

I encountered an unfamiliar pattern of initialization from Objective-C that I'm struggling to replicate in Swift.
Objective-C
In the example code, they defined a C struct such as this (abbreviated, original here):
struct AQPlayerState {
AudioFileID mAudioFile;
}
Here's an example that uses AQPlayerState:
AQPlayerState aqData; // 1
OSStattus result =
AudioFileOpenURL(
audioFileURL,
fsRdPerm,
0,
&aqData.mAudioFile // 2
);
The key takeaway from above is that aqData currently has uninitialized properties, and AudioFileOpenURL is initializing aqData.mAudioFile on it's behalf.
Swift
I'm trying to replicate this behaviour in Swift. Here's what I've tried so far:
Models:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
class Foo {
var person: Person?
}
My idea was to replicate the Objective-C code by passing a reference of Foo.person into a function that would instantiate it on it's behalf.
Initialization Function:
func initializeWithBob(_ ptr: UnsafeMutablePointer<Person?>) {
ptr.pointee = Person(name: "Bob")
}
initializeWithBob takes a pointer to an address for a Person? type and initializes it with a Person(name: "Bob") object.
Here's my test code:
let foo = Foo()
let ptr = UnsafeMutablePointer<Person?>.allocate(capacity: 1)
ptr.initialize(to: foo.person)
defer {
ptr.deinitialize()
ptr.deallocate(capacity: 1)
}
initializeWithBob(ptr)
print(foo.person) // outputs nil
initializeWithBob failed to "install" an instance of type Person in my Foo instance. I presume some of my assumptions are wrong. Looking for help in correcting my assumptions and understanding of this situation.
Thanks in advance!
You can achieve what you are looking for via withUnsafeMutablePointer(to:_:) like so:
let foo = Foo()
withUnsafeMutablePointer(to: &foo.person) { (ptr) -> Void in
initializeWithBob(ptr)
}
print(foo.person!.name) // outputs Bob
However, I wouldn't recommend this approach. IMHO it makes more sense to wrap the APIs you are working with in a C function that you can make 'nice' to call from Swift. The problem with your current approach is that this type of Swift is hard to read for Swift developers and also hard to read for Audio Toolbox developers.
#kelvinlau Is this what you were thinking of trying to achieve?
func initializeWithBob(_ ptr: UnsafeMutablePointer<Foo>) {
ptr.pointee.person = Person(name: "Bob")
}
let foo = Foo()
let ptr = UnsafeMutablePointer<Foo>.allocate(capacity: 1)
ptr.initialize(to: foo)
initializeWithBob(ptr)
print(foo.person?.name ?? "nil")
ptr.deinitialize()
ptr.deallocate(capacity: 1)
print(foo.person?.name ?? "nil")
The code pattern you have in Objective-C is for out parameters, that is parameters which return a value, or in out parameters, that is parameters which both pass a value in and return one. Objective-C does not directly support these so pointers are used to produce the semantics.
Swift has in out parameters indicated by the keyword inout in the function declaration. Within the function an assignment to an inout parameters effectively assigns a value to the variable that was passed as the argument. At the function call site the variable must be prefixed by & to indicate it is the variable itself and not its value which is effectively being passed.
Keeping your Person and Foo as is your function becomes:
func initializeWithBob(_ ptr: inout Person?)
{
ptr = Person(name: "Bob")
}
and it may be used, for example, like:
var example = Foo()
initializeWithBob(&example.person)
Using inout in Swift is better than trying to build the same semantics using pointers.
HTH
Note: You can skip this unless you are curious
"Effectively" was used a few times above. Typically out parameters are implemented by the parameter passing method call-by-result, while in out use call-by-value-result. Using either of these methods the returned value is only assigned to the passed variable at the point the function returns.
Another parameter passing method is call-by-reference, which is similar to call-by-value-result except that each and every assignment to the parameter within the function is immediately made to passed variable. This means changes to the passed variable may be visible before the function returns.
Swift by design does not specify whether its inout uses call-by-value-result or call-by-reference. So rather than specify the exact semantics in the answer "effectively" is used.

What is 'Access specifier' in Object Oriented Programming

What is 'Access specifier' in Object oriented programming ?
I have searched for it's definition several times but not get the satisfactory answer.
Can anyone please explain it to me with realistic example ?....
Thanks in advance
What are they?
This wikipedia article pretty much sums it up. But Let's elaborate on a few main points. It starts out saying:
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.1
So an Access Specifier aka Access Modifier takes certain class, method, or variable and decides what other classes are allowed to use them. The most common Access Specifiers are Public, Protected, and Private. What these mean can vary depending on what language you are in, but I'm going to use C++ as an example since that's what the article uses.
Accessor Method | Who Can Call It
-----------------------------------------------------------------------
Private | Only the class who created it
Protected | The class who created it and derived classes that "inherit" from this class
Public | Everyone can call it
Why is this important?
A big part of OOP programming is Encapsulation. Access Specifiers allow Encapsulation. Encapsulation lets you choose and pick what classes get access to which parts of the program and a tool to help you modularize your program and separate out the functionality. Encapsulation can make debugging a lot easier. If a variable is returning an unexpected value and you know the variable is private, then you know that only the class that created it is affecting the values, so the issue is internal. Also, it stops other programmers from accidentally changing a variable that can unintentionally disrupt the whole class.
Simple Example
Looking at the example code from the article we see Struct B i added the public in there for clarity:
struct B { // default access modifier inside struct is public
public:
void set_n(int v) { n = v; }
void f() { cout << "B::f" << endl; }
protected:
int m, n; // B::m, B::n are protected
private:
int x;
};
This is what would happen if you created an inherited struct C that would try and use members from struct B
//struct C is going to inherit from struct B
struct C :: B {
public:
void set_m(int v) {m = v} // m is protected, but since C inherits from B
// it is allowed to access m.
void set_x(int v) (x = v) // Error X is a private member of B and
// therefore C can't change it.
};
This is what would happen if my main program where to try and access these members.
int main(){
//Create Struct
B structB;
C structC;
structB.set_n(0); // Good Since set_n is public
structB.f(); // Good Since f() is public
structB.m = 0; // Error because m is a protected member of Struct B
// and the main program does not "inherit" from struct B"
structB.x = 0; // Error because x is a private member of Struct B
structC.set_n() // Inheritied public function from C, Still Good
structC.set_m() // Still Good
structC.m = 0 // Error Main class can't access m because it's protected.
structC.x = 0; // Error still private.
return 0;
}
I could add another example using inheritance. Let me know if you need additional explanation.

Does fragile base class issue exist in Go?

Despite using composition over inheritance?
If so, is there any solution for it at the language level?
As VonC wrote, but I'd like to point out something.
The fragile base class problem is often blamed on virtual methods (dynamic dispatch of methods – this means if methods can be overridden, the actual implementation that has to be called in case of such an overridden method can only be decided at runtime).
Why is this a problem? You have a class, you add some methods to it, and if MethodA() calls MethodB(), you can't have any guarantee that the MethodB() you wrote will be called and not some other method of a subclass that overrides your MethodB().
In Go there is embedding, but there is no polymorphism. If you embed a type in a struct, all the methods of the embedded type get promoted and will be in the method set of the wrapper struct type. But you can't "override" the promoted methods. Sure, you can add your own method with the same name, and calling a method by that name on the wrapper struct will invoke your method, but if this method is called from the embedded type, that will not be dispatched to your method, it will still call the "original" method that was defined to the embedded type.
So because of this, I'd say the fragile base class problem is only present in a quite mitigated form in Go.
Example
Demonstrating the problem in Java
Let's see an example. First in Java, because Java "suffers" from this kind of problem. Let's create a simple Counter class and a MyCounter subclass:
class Counter {
int value;
void inc() {
value++;
}
void incBy(int n) {
value += n;
}
}
class MyCounter extends Counter {
void inc() {
incBy(1);
}
}
Instantiating and using MyCounter:
MyCounter m = new MyCounter();
m.inc();
System.out.println(m.value);
m.incBy(2);
System.out.println(m.value);
The output is as expected:
1
3
So far so good. Now if the base class, Counter.incBy() would be changed to this:
void incBy(int n) {
for (; n > 0; n--) {
inc();
}
}
The base class Counter still remains flawless and operational. But the MyCounter becomes malfunctioning: MyCounter.inc() calls Counter.incBy(), which calls inc() but due to dynamic dispatch, it will call MyCounter.inc()... yes... endless loop. Stack overflow error.
Demonstrating the lack of the problem in Go
Now let's see the same example, this time written in Go:
type Counter struct {
value int
}
func (c *Counter) Inc() {
c.value++
}
func (c *Counter) IncBy(n int) {
c.value += n
}
type MyCounter struct {
Counter
}
func (m *MyCounter) Inc() {
m.IncBy(1)
}
Testing it:
m := &MyCounter{}
m.Inc()
fmt.Println(m.value)
m.IncBy(2)
fmt.Println(m.value)
Output is as expected (try it on the Go Playground):
1
3
Now let's change Counter.Inc() the same way we did in the Java example:
func (c *Counter) IncBy(n int) {
for ; n > 0; n-- {
c.Inc()
}
}
It runs perfectly, the output is the same. Try it on the Go Playground.
What happens here is that MyCounter.Inc() will call Counter.IncBy() which will call Inc(), but this Inc() will be Counter.Inc(), so no endless loop here. Counter doesn't even know about MyCounter, it does not have any reference to the embedder MyCounter value.
The Fragile base class problem is when a seemingly safe modifications to a base class, when inherited by the derived classes, may cause the derived classes to malfunction.
As mentioned in this tutorial:
For all intents and purposes, composition by embedding an anonymous type is equivalent to implementation inheritance. An embedded struct is just as fragile as a base class.

How to make a Rust singleton's destructor run?

These are the ways I know of to create singletons in Rust:
#[macro_use]
extern crate lazy_static;
use std::sync::{Mutex, Once, ONCE_INIT};
#[derive(Debug)]
struct A(usize);
impl Drop for A {
fn drop(&mut self) {
// This is never executed automatically.
println!(
"Dropping {:?} - Important stuff such as release file-handles etc.",
*self
);
}
}
// ------------------ METHOD 0 -------------------
static PLAIN_OBJ: A = A(0);
// ------------------ METHOD 1 -------------------
lazy_static! {
static ref OBJ: Mutex<A> = Mutex::new(A(1));
}
// ------------------ METHOD 2 -------------------
fn get() -> &'static Mutex<A> {
static mut OBJ: *const Mutex<A> = 0 as *const Mutex<A>;
static ONCE: Once = ONCE_INIT;
ONCE.call_once(|| unsafe {
OBJ = Box::into_raw(Box::new(Mutex::new(A(2))));
});
unsafe { &*OBJ }
}
fn main() {
println!("Obj = {:?}", PLAIN_OBJ); // A(0)
println!("Obj = {:?}", *OBJ.lock().unwrap()); // A(1)
println!("Obj = {:?}", *get().lock().unwrap()); // A(2)
}
None of these call A's destructor (drop()) at program exit. This is expected behaviour for Method 2 (which is heap allocated), but I hadn't looked into the implementation of lazy_static! to know it was going to be similar.
There is no RAII here. I could achieve that behaviour of an RAII singleton in C++ (I used to code in C++ until a year a back, so most of my comparisons relate to it - I don't know many other languages) using function local statics:
A& get() {
static A obj; // thread-safe creation with C++11 guarantees
return obj;
}
This is probably allocated/created (lazily) in implementation defined area and is valid for the lifetime of the program. When the program terminates, the destructor is deterministically run. We need to avoid accessing it from destructors of other statics, but I have never run into that.
I might need to release resources and I want drop() to be run. Right now, I end up doing it manually just before program termination (towards the end of main after all threads have joined etc.).
I don't even know how to do this using lazy_static! so I have avoided using it and only go for Method 2 where I can manually destroy it at the end.
I don't want to do this; is there a way I can have such a RAII behaved singleton in Rust?
Singletons in particular, and global constructors/destructors in general, are a bane (especially in language such as C++).
I would say the main (functional) issues they cause are known respectively as static initialization (resp. destruction) order fiasco. That is, it is easy to accidentally create a dependency cycle between those globals, and even without such a cycle it is not immediately clear to compiler in which order they should be built/destroyed.
They may also cause other issues: slower start-up, accidentally shared memory, ...
In Rust, the attitude adopted has been No life before/after main. As such, attempting to get the C++ behavior is probably not going to work as expected.
You will get much greater language support if you:
drop the global aspect
drop the attempt at having a single instance
(and as a bonus, it'll be so much easier to test in parallel, too)
My recommendation, thus, is to simply stick with local variables. Instantiate it in main, pass it by value/reference down the call-stack, and not only do you avoid those tricky initialization order issue, you also get destruction.