In object oriented programming, is it safe to always downcast a variable? - theory

This is more about compiler theory, given I'm playing around with making one. I'm wondering if it is theoretically safe to always downcast a variable within a subclass.
class Car {
BodyType myBodyType;
}
class Corvette extends Car {
FourWheels myBodyType;
// normally this is rejected by most compilers
// redefinition of myBodyType;
}
class BodyType {}
class FourWheels extends BodyType {}
Currently in traditional OO programming, we always have to downcast myBodyType to FourWheels if we know that myBodyType is always that specific type. If this is done automatically by the compiler, would it be safe?

No, this won't be safe, because right now nothing stops a user from writing:
Car car = new Corvette();
car.myBodyType = new TwoWheels();
And now downcasting myBodyType in car to be of type FourWheels can lead to problematic behavior.
The only way that you can rely on myBodyType never being of an incorrect type is by having guarantees that a value of an incorrect type is never written into it - e.g. by making it a read-only value that is set during construction.
By the way, in a Java-like languages, a more elegant approach from the user would be something like:
class Car<MyBodyType extends BodyType> {
MyBodyType myBodyType;
}
class Corvette extends Car<FourWheels> {
...
}

Related

Error using unique pointer from interface as attribute of a class

In a nutshell, I need help with the right use of unique_ptr and not with the library ArmNN. So, the next paragraph is just for contextualization.
I am adapting my current application to use the library ArmNN. More specifically, I am doing that through the use of the interface ICaffeParser.
At line 22 of this interface, we have this using definition to define a unique_ptr to the interface, that I believe is the "cause" of my problems.
using ICaffeParserPtr = std::unique_ptr<ICaffeParser, void(*)(ICaffeParser* parser)>;
I am quite sure my problem is the incorrect use of unique_ptr in my context, once I could make some successful tests with a more simple application.
My current code contains a class, let's call it MyClass:
namespace MYNAMESPACE {
class MyClass {
public:
MyClass() {
}
// a lot of functions
// a lot of attributes
private:
// a lot of functions
// a lot of attributes
}
}
In order to make use of the ArmNN library, I have created a new private attribute for MyClass:
armnnCaffeParser::ICaffeParserPtr myParser;
and instantiated myParser at MyClass() constructor:
MyClass::MyClass() {
myParser = armnnCaffeParser::ICaffeParser::Create();
}
Remembering ICaffeParserPtr is a unique_ptr (I think), now I have the following compiling error:
/my_path/src/detector.cpp: In constructor ‘MYNAMESPACE::MyClass::MyClass()’:
/my_path/src/detector.cpp:13:20: error: no matching function for call to ‘std::unique_ptr<armnnCaffeParser::ICaffeParser, void (*)(armnnCaffeParser::ICaffeParser*)>::unique_ptr()’
MyClass::MyClass() {
^
In file included from /usr/aarch64-linux-gnu/include/c++/7/bits/locale_conv.h:41:0,
from /usr/aarch64-linux-gnu/include/c++/7/locale:43,
from /usr/aarch64-linux-gnu/include/c++/7/iomanip:43,
from /usr/include/opencv2/flann/lsh_table.h:40,
from /usr/include/opencv2/flann/lsh_index.h:49,
from /usr/include/opencv2/flann/all_indices.h:42,
from /usr/include/opencv2/flann/flann_base.hpp:43,
from /usr/include/opencv2/flann.hpp:48,
from /usr/include/opencv2/opencv.hpp:62,
from /my_path/src/detector.hpp:11,
from /my_path/src/detector.cpp:1:
/usr/aarch64-linux-gnu/include/c++/7/bits/unique_ptr.h:255:2: note: candidate: template<class _Up, class> std::unique_ptr<_Tp, _Dp>::unique_ptr(std::auto_ptr<_Up>&&)
unique_ptr(auto_ptr<_Up>&& __u) noexcept;
/usr/aarch64-linux-gnu/include/c++/7/bits/unique_ptr.h:255:2: note: template argument deduction/substitution failed:
/my_path/src/detector.cpp:13:20: note: candidate expects 1 argument, 0 provided
MyClass::MyClass() {
^
The error happens because myParser is actually being default-initialized and then assigned on the constructor body of MyClass::MyClass().
Since a function pointer is passed as a custom deleter to std::unique_ptr to form the ICaffeParserPtr type, the default constructor for this particular instance of std::unique_ptr is disabled as per [unique.ptr.single.ctor].
In other words, ICaffeParserPtr, for safety reasons, cannot be default-initialized — which specific function to otherwise assign as its deleter on initialization?
To address this, you should always initialize class members at the member initializer list. In this case, initialize myParser as such:
MyClass::MyClass():
myParser(armnnCaffeParser::ICaffeParser::Create()) {}
This avoids calling the unavailable default constructor for std::unique_ptr, and is generally a better practice than assigning to class members in the constructor body.

How does Raku deal with the diamond problem (multiple inheritance)?

So it's no secret that Raku has multiple inheritance, so that got me wondering: "how does Raku deal with that in any reasonable manner?"
Some preliminary testing reveals that default behaviour is inherited from the first class in the inheritance list, that's fine, many other languages do it like that too
class A {
has $.foo = 0;
method speak {...}
}
class B is A {
has $.foo = 1;
method speak {
say 'moo';
}
}
class C is A {
has $.foo = 2;
method speak {
say 'baa';
}
}
class D is B is C {}
class E is C is B {}
say D.new.foo; # prints 1 (from B)
say E.new.foo; # prints 2 (from C)
But that got me wondering, what if I want D to use C's speak?
Due to the inheritance order I get B's by default.
I understand that roles exist to solve this exact issue by facilitating a disambiguation mechanism, but suppose hypothetically I find myself in a situation where I don't have roles at my disposal (boss hates them, inherited a library that doesn't have them, pick your excuse) and really need to disambiguate the inherited classes.
What's the mechanism for dealing with that in Raku?
Generally you would need to provide a tie-breaker method in the class that has the (potential) ambiguity. Fortunately, you do not have to create separate methods, as you can call specific versions of methods in a call.
So the answer to your question: Add a method speak to class D, and have that call the speak method from class C:
class D {
...
method speak { self.C::speak }
}
And for methods taking parameters, take a Capture of all parameters, and pass that on:
class D {
...
method foo(|c) { self.C::foo(|c) }
}
Note that the "c" in |c is just an identifier, it could be any identifier. But it is sorta customary, at least with Raku core developers, to just use |c, with the "c" standing for "capture".
Now, this will cause some overhead, as you would have an extra level of indirection. Should this turn out to be a performance issue, there's some meta-programming you can do to alias the speak method in D to the speak method in C:
class D {
...
BEGIN D.^add_method("speak",C.^find_method("speak"));
}
This will, at compile time because of the BEGIN, add a Method object to the D class called speak that is defined by the speak method of class C. Since this is an alias, you don't have to worry about any parameters being passed.

Swift - Array with specific class type

How can i create array which will hold objects belonging a specific class.
class BaseObject {}
class Derived1: BaseObject {}
class Derived2: BaseObject {}
class Derived2: BaseObject {}
I need to create array in which will hold only Object derived from BaseObject
Something like - var array : [BaseObject.Type] = []
Is there a way to specify this ?
Also, I should be able to use it something like this
if let derived1 = object as? [Derived1] {
}
else if let derived2 = object as? [Derived2] {
}
You can obviously define your array as an array of BaseObject:
var objects: [BaseObject] = [] // or `var objects = [BaseObject]()`
But it's going to let you create a heterogenous collection (of either BaseObject or Derived1 or Derived2 or of any other subclass). That's a core OO design concept (the Liskov substitution principle) that any subclass of BaseObject should (and will) be permitted.
If all you want is to say that you can only have an array of one of the subtypes, you can obviously just define your array as such, e.g.:
var objects: [Derived1] = []
That will obviously allow only Derived1 objects (and any subclasses of Derived1.
90% of the time, the above is sufficient. But in some cases, you might needs some collection with methods that require some inherited base behavior, but for which you don't want to allow heterogenous collections. In this case, I might consider a more protocol-oriented pattern:
Bottom line, should we be subclassing, or should we be using a protocol-oriented approach? I.e. is BaseObject actually something you'll instantiate for its own purposes, or is it there merely to define some common behavior of the subclasses. If the latter, a protocol might be a better pattern, e.g.:
protocol Fooable {
func foo()
}
// if you want, provide some default implementation for `foo` in an
// protocol extension
extension Fooable {
func foo() {
// does something unique to objects that conform to this protocol
}
}
struct Object1: Fooable {}
struct Object2: Fooable {}
struct Object3: Fooable {}
This yields the sort of behavior that you may have been using in your more OO approach, but using protocols. Specifically, you write one foo method that all of the types that conform to this protocol, e.g., Object1, Object2, etc., can use without having to implement foo themselves (unless, of course, you want to because they need special behavior for some reason).
Because this eliminates the subclassing, this then opens the door for the use of generics and protocols that dictate some generalized behavior while dictating the homogenous nature of the members. For example:
struct FooCollection<T: Fooable> {
private var array = [T]()
mutating func append(_ object: T) {
array.append(object)
}
// and let's assume you need some method for your collection that
// performs some `Fooable` task for each instance
func fooAll() {
array.forEach { $0.foo() }
}
}
This is a generic which is a homogenous collection of objects that conform to your protocol. For example, when you go to use it, you'd declare a particular type of Fooable type to use:
var foo = FooCollection<Object1>()
foo.append(Object1()) // permitted
foo.append(Object2()) // not permitted
foo.fooAll()
Now, I only went down this road because in comments elsewhere, you were inquiring about generics. I'd personally only go down this road if the (a) collection really needed to be homogenous; and (b) the collection also wanted to implement some shared logic common to the protocol. Otherwise, I'd probably just stick with a simple [Derived1] (or [Object1]). The above can be powerful when needed, but is overkill for simpler situations.
For more discussion about protocol oriented programming, the homogenous vs heterogenous behavior, traditional stumbling blocks when you're coming from a traditional OO mindset, I'd refer you to the WWDC 2015 video, Protocol-Oriented Programming in Swift, or it's 2016 companion video that builds upon the 2015 video.
Finally, if you have any additional questions, I'd suggest you edit your question providing details on a practical problem that you're trying to solve with this pattern. Discussions in the abstract are often not fruitful. But if you tell us what the actual problem you're trying to solve with the pattern in your question, it will be a far more constructive conversation.

Qi4J Concerns partial implementation

is is possible to do end up with something like this:
ServiceChild (class) extends (or only partial implements) Service and overrides sayHello
Service (interface) implements hello,goodbye
Hello (has a mixin HelloMixin) has method sayHello
Goodbye (has a mixin GoodbyeMixin) has method sayGoodbye
I've tried doing the above using the concern approach in ServiceChild
public class ServiceChild extends ConcernOf<Service> implements Hello
{
#Override
public String sayHello() {
return "Rulle Pharfar";
}
}
However using this approach only the Hello implementation are detected by java and not the rest of the stuff from the Service class. So is there any other approach that would work?
I'm not sure I understand what you are trying to do, but a concern should more be seen as a wrapper around the original implementation of the class it is a concern of.
As the documentation states:
A concern is a stateless Fragment, shared between invocations, that acts as an interceptor of the call to the Mixin.
And would usually do this:
//Given interface MyStuff
#Mixins( MyStuff.Mixin.class )
#Concerns( MyStuffConcern.class )
public interface MyStuff
{
public void doStuff();
abstract class Mixin implements MyStuff
{
public void doStuff()
{
System.out.println( "Doing original stuff." );
}
}
}
public class MyStuffConcern extends ConcernOf<MyStuff>
implements MyStuff
{
public void doStuff()
{
// if I want to do anything before going down the call chain I'll do it here
System.out.println( "Doing stuff before original." );
// calling the next concern or actual implementation
next.doStuff();
// anything to do after calling down the call chain - here is the place for it
System.out.println( "Doing stuff after original." );
}
}
But nevertheless if you have a concern on a interface you should also implement said interface:
public abstract class ServiceChild extends ConcernOf<Service> implements Service
{
public String sayHello()
{
return "Rulle Pharfar";
}
}
Hope this helped.
I also don't fully understand the question.
As Arvice says, Concerns are the equivalent of around-advice in AOP, with much more precise pointcut semantics. Although it is technically correct that a concern 'wraps' the underlying concerns/mixins, I prefer to not thinking of it as a 'wrapper' but an 'interceptor'. It is the incoming call that is handled. Conceptually slightly different, and it may not work for everyone.
It is also possible that both Concerns (stateless) and Mixins (stateful) implements only a subset of the methods in the interface they override, simply by making the class 'abstract'. Qi4j will fill in the missing (and unused) method calls. And any combination may be used.
Further, well implemented concerns should call the 'next', because they should be unaware of their actual uses. If the concerns are expected to take care of the method call. There must be a Mixin for each composite type method, or assembly will fail.
So in short;
1. A Mixin implementation may implement zero (a.k.a private mixins), one or more methods of the composite type interface.
2. A Concern may implement one or more methods of the composite type interface.
It is also interesting to note that when a class (mixin or concern) calls one of its own methods that are in the composite type interface, the call will not be intra-class, but call the composite from the outside, so the entire call stack is invoked, to ensure that an internal call and an external call are identical in results. Patterns exists if this needs to be bypassed.

Static and Normal class combined in one class

I am trying my best to explain the situation. I hope, what I wrote, is understandable.
We already have class defined like
public ref class TestClass
{
public:
TestClass();
virtual ~TestClass();
protected:
Car* m_car;
}
TestClass is managed C++ and Car is unmanaged C++.
So far so good, but now I need to make static object of TestClass also. So I modify the code like below
public ref class TestClass
{
private:
static TestClass^ s_test = nullptr ;
public:
TestClass();
virtual ~TestClass();
static TestClass^ Instance();
protected:
Car* m_car;
}
When I want to use static instant of the class, I just get it from calling
TestClass staticobj = TestClass::Instance();
Elsewhere, just call
TestClass normalobj = gcnew TestClass();
Instance function is creating s_test static object and returns it.
TestClass ^ TestClass::Instance()
{
if(s_test == nullptr)
{
s_test = gcnew TestClass();
s_test->m_car = new Car();
}
return s_test;
}
Is it a good approach?
Is there any other better approach to accomplish same thing?
Edit :
FYI Above code works.
I combined Krizz and Reed Copsey’s solutions. That solve independent Singleton and memory leak.
Here is my sample code,
Special Singleton class derived from test class,
public ref class SpecialSingletonTestClass: public TestClass
{
private:
static SpecialSingletonTestClass ^ s_ SpecialSingletonTestClass = nullptr;
public:
SpecialSingletonTestClass ();
static SpecialSingletonTestClass ^ Instance();
};
Changed the testclass so it has now one more finalizer function.
public ref class TestClass
{
public:
TestClass ();
virtual ~ TestClass ();
! TestClass ();
protected:
Car* m_car;
}
I tested above pattern , it worked.
Thanks you guys,
L.E.
Is it a good approach?
I would probably not consider this a good approach, as you're making a single class both a singleton and a normal class that you can instance directly.
Typically, if you need a singleton, this would preclude the need or desire to be able to instantiate the class.
If you truly need to have a way to have a "global" instance of this class, I would encapsulate that in a separate class which implements the singleton. This would, at least, make it clear that you are dealing with something that's a single instance in that case. I would not mix both use cases into a single class.
Well, actually there is an issue with memory leaks in your code.
You declare only virtual ~TestClass(); which, for managed classes, are internally turned by C++/CLI compiler into implementation of IDisposable.Dispose().
Therefore, if you put delete car into it, it will be called only if you delete test_class or, e.g. wrap into using (TestClass tst) {} block when using from C#.
It will not be called when object is GCed!
To be sure it is called you need to add finalizer to your class !MyClass(); which is turned by compiler into virtual void Finalize() and thus non-deterministically called when GC is freeing an object.
And it is the only way to free m_car of singleton object.
Therefore, I suggest:
TestClass()
{
m_car = new Car();
}
~TestClass()
{
if (m_car)
delete m_car;
m_car = NULL;
}
!TestClass()
{
if (m_car)
delete m_car;
m_car = NULL;
}
I'm unsure as to what situation you could possibly be in that would require both singleton-style semantics and normal creation semantics for the same class.
As far as what you've coded though, it looks completely fine. My only comments would be that your Instance() function shouldn't need to perform construction on Car, the Instance() function should just call the default constructor of TestClass which should do all that.
EDIT
In reference to:
#crush . The class is already define i just need to get static object of it. Singleton means only one object of the class, but in this case, class have multiple normal object. But i want to use only one object of this class for one specific goal only for limited period of time. – L.E. 2 mins ago
A singleton is (usually) a sign of bad design - alot of people call it an anti-pattern actually. Chances are if you just need this one single specific instance of this class for a limited period of time there are some issues:
Singleton design is made for static-style existence - the variable will live for the scope of your program after lazily initialized.
Allowing global access will move your code towards spaghetti logic. You'd be better off dynamically allocating the one you need and passing the pointer to it to where you need it to be. A shared_ptr would be good for this.
You should find a way around the singleton-style implementation in this case even if it's more work for you - it'll almost certainly be better design.

Resources