Implementing Clone() method in base class - oop

Here's a Clone() implementation for my class:
MyClass^ Clone(){
return gcnew MyClass(this->member1, this->member2);
}
Now I have about 10 classes derived from MyClass. The implementation is the same in each case. Owing to the fact that I need to call gcnew with the actual class name in each case, I am required to create 10 nearly identical implementations of Clone().
Is there a way to write one single Clone() method in the base class which will serve all 10 derived classes?
Edit: Is there a way to invoke the constructor of a class via one of it's objects? In a way that will invoke the actual derived class constructor. Something like:
MyClass ^obj2 = obj1->Class->Construct(arg1, arg2);
I'm doing this on C++/CLI but answers from other languages are welcome.

In plain old C++, you can do this with compile-time polymorphism (the curiously-recurring template pattern). Assuming your derived classes are copyable, you can just write:
class Base
{
public:
virtual Base* Clone() const = 0;
//etc.
};
template <typename Derived>
class BaseHelper: public Base
{
//other base code here
//This is a covariant return type, allowed in standard C++
Derived * Clone() const
{
return new Derived(static_cast<Derived *>(*this));
}
};
Then use it like:
class MyClass: public BaseHelper<MyClass>
{
//MyClass automatically gets a Clone method with the right signature
};
Note that you can't derive from a class again and have it work seamlessly - you have to "design in" the option to derive again by templating the intermediate classes, or start re-writing Clone again.

Not in C++ that I'm aware of. As you say, you need to create an object of a different class in each implementation of Clone().

Hm, I think you can use Factory pattern here. I.e.:
MyClass Clone(){
return MyClassFactory.createInstance(this.getClass(), this.member1, this.member2, ...);
}
In the factory, you would have to create instance of subclass based on passed class type. So probably it has the same disadvantages as your approach.

I would suggest using copy constructors instead (as derived classes can call the base implementation's copy constructor as well) -- also handy, as it will be familiar territory for C++ programmers.
You might be able to create a single Clone method that uses reflection to call the copy constructor on itself in this instance.
Possibly also worth noting that Jeffrey Richter said in the Framework Design Guidelines book, "The ICloneable interface is an example of a very simple abstraction with a contract that was never explicitly documented. Some types implement this interface's Clone method so that it performs a shallow copy of the object, whereas some implementations perform a deep copy. Because what this interface's Clone method should do was never fully documented, when using an object with a type that implements ICloneable, you never know what you're going to get. This makes the interface useless" (emphasis mine)

Related

How do compilers compile virtual/overridden methods

I am developing a compiler for an object oriented language targeted on a virtual machine I wrote that I am using as a cross platform abstraction layer. I am sort of confused about how inherited methods works. Lets say I had the following lines of C# code.
class myObject : Object {
public int aField;
public override string ToString() {
return "Dis be mah object";
}
public void regularMethod() { }
}
Object test = new myObject();
Console.WriteLine(test.ToString());
Now this would output 'Dis be mah object'. If I called regularMethod however the compiled code would in reality do something like this:
struct myObject {
public int aField;
}
public static void regularMethod(ref myObject thisObject)
{
}
How would the inherited method ToString be handled after compilation? The compiler could not do what I did above with regularMethod, because if it did then 'Dis be mah object' would only be returned when creating myObject types and not plain Object types. My guess is that the struct myObject would contain a function pointer/delegate that would get assigned when a new instance is created.
If you are dealing with static overloading, it is really simple: you bind to the correct implementation when processing the code.
But, if you are working with dynamic overloading, you must decide things at runtime. For this you need to use dynamic dispatch, using the real object type. This is the same thign that is done with method overriding.
Dynamic dispatching is not the same as late binding. Here, you are chosing an implementation and not a name for your operation (despite the fact that this binding will occur at compile time, the implementation will only occur at runtime).
Staticly, you would only bind to implementation of the declared type of the object. It is done at compile time.
The are some mechanisms you could use to achieve the dynamic dispathing, it will dictate your language paradigm.
Is your language typed? Weakly typed?
C++, for instance, offers the two types of dispatch I mentioned. For the dynamic one (which I believe is the one you are interested), it uses a virtual table to do the mapping for one class. Each instance of that class will point have a pointer to that vtable.
Implementing
The vtable (one for all objects of same class) will have the addresses of all dynamicly bound methods. One of those addresses will be fetched from this table when a call is made. Type-compatible objects have tables with addresses with the same offset for the methods of all compatible classes.
Hope I've helped.

adapter pattern and dependency

I have little doubt about adapter class. I know what's the goal of adapter class. And when should be used. My doubt is about class construction. I've checked some tutorials and all of them say that I should pass "Adaptee" class as a dependency to my "Adapter".
e.g.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
This example is copied from wikipedia. As you can see AdapteeClass is passed to my object as dependency. The question is why? If I'm changing interface of an object It's obvious I'm going to use "new" interface and I won't need "old" one. Why I need to create instance of "old" class outside my adapter. Someone may say that I should use dependency injection so I can pass whatever I want, but this is adapter - I need to change interface of concrete class. Personally I think code bellow is better.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
{
mInstance= new AdapteeClass();
}
}
What is your opinion?
I would say that you should always avoid the new operator in a class when it comes to complex objects (except when the class is a Builder or Factory) to reduce coupling and make your code better testable. Off course objects like a List or Dictionary or value objects can be constructed inside a class method (which is probably the purpose of the class method!)
Lets say for example that your AdapteeClass is a Remote Proxy. If you want to use Unit Testing, your unit tests will have to use the real proxy class because there is no way to replace it in your unit tests.
If you use the first approach, you can easily inject a mock or fake into the constructor when running your unit test so you can test all code paths.
Google has a guide on writing testable code which describes this in more detail but some important points are:
Warning Signs for not testable code
new keyword in a constructor or at field declaration
Static method calls in a constructor or at field declaration
Anything more than field assignment in constructors
Object not fully initialized after the constructor finishes (watch out for initialize methods)
Control flow (conditional or looping logic) in a constructor
Code does complex object graph construction inside a constructor rather than using a factory or builder
Adding or using an initialization block
AdapteeClass can have one or more non-trivial constructors. In this case you'll need to duplicate all of them in your SampleAdapter constructor to have the same flexibility. Passing already constructed object is simpler.
I think creating the Adaptee inside the Adapter is limiting. What if some day you want to adapt a pre-existing instance?
To be honest though, I'd do both if at all possible.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
: base (new AdapteeClass())
{
}
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
Let's assume you have an external hard drive with a regular USB port and you are trying to hook it up with a Mac which only has type-c ports. Yes, you can buy a new drive which has a type-c port but what about the data in it?
It's the same for the adapter pattern. There're times you initialize AdapteeClass with tons of flavors. When you do the conversion, you want to keep all the context.

static function in class which instantiates object

I often use a pattern where I have a static member function in a class which instantiates object of itself, uses it, and destroys it.
Is this a good pattern? I think so. Does the pattern have a name?
I guess it's sort of a combination of Singleton and Factory method patterns. "Singletory" maybe?
The pattern is called 'Factory method'.
I often use this pattern, if using a factory class is a bit overkill, and when creating an instance of the class is a bit cumbersome (some initialization that has to be done for instance on other objects), or, when you want to have an easy way of creating different types of instances of that class.
are you saying you are doing this
class MyClass {
static void util(){
obj = new MyClass();
obj.InstanceMem();
obj.destroy();
}
void InstanceMem(){}
}
i see this more of a utility method.
well if you think it solves a common reoccurring problem then it may be called as a pattern.

When should I use static methods in a class and what are the benefits?

I have concept of static variables but what are the benefits of static methods in a class. I have worked on some projects but I did not make a method static. Whenever I need to call a method of a class, I create an object of that class and call the desired method.
Q: Static variable in a method holds it's value even when method is executed but accessible only in its containing method but what is the best definition of static method?
Q: Is calling the static method without creating object of that class is the only benefit of static method?
Q: What is the accessible range for static method?
Thanks
Your description of a static variable is more fitting to that found in C. The concept of a static variable in Object Oriented terms is conceptually different. I'm drawing from Java experience here. Static methods and fields are useful when they conceptually don't belong to an instance of something.
Consider a Math class that contains some common values like Pi or e, and some useful functions like sin and cos. It really does not make sense to create separate instances to use this kind of functionality, thus they are better as statics:
// This makes little sense
Math m = new Math();
float answer = m.sin(45);
// This would make more sense
float answer = Math.sin(45);
In OO languages (again, from a Java perspective) functions, or better known as methods, cannot have static local variables. Only classes can have static members, which as I've said, resemble little compared to the idea of static in C.
Static methods don't pass a "this" pointer to an object, so they can't reference non-static variables or methods, but may consequently be more efficient at runtime (fewer parameters and no overhead to create and destroy an object).
They can be used to group cohesive methods into a single class, or to act upon objects of their class, such as in the factory pattern.
Syntax (php) for static methods:
<?php
class Number {
public static function multiply($a, $b) {
return $a * $b;
}
}
?>
Client code:
echo Number::multiply(1, 2);
Which makes more sense than:
$number = new Number();
echo $number->multiply(1, 2);
As the multiply() method does not use any class variables and as such does not require an instance of Number.
Essentially, static methods let you write procedural code in an object oriented language. It lets you call methods without having to create an object first.
The only time you want to use a static method in a class is when a given method does not require an instance of a class to be created. This could be when trying to return a shared data source (eg a Singleton) or performing an operation that doesn't modify the internal state of the object (String.format for example).
This wikipedia entry explains static methods pretty well: http://en.wikipedia.org/wiki/Method_(computer_science)#Static_methods
Static variables and static methods are bound to the class, and not an instance of the class.
Static methods should not contain a "state". Anything related to a state, should be bound to an instantiated object, and not the class.
One common usage of static methods is in the named constructor idiom. See: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.8.
Static Methods in PHP:
Can be called without creating a class object.
Can only call on static methods and function.
Static variable is used when you want to share some info between different objects of the class.As variable is shared each object can update it and the updated value be available for all other objects as well.
As static variable can be shared,these are often called as class variable.
static elements are accessible from any context (i.e. anywhere in your script), so you can access these methods without needing to pass an instance of the class from object to object.
Static elements are available in every instance of a class, so you can set values that you want to be available to all members of a type.
for further reading a link!

Rule of thumb for naming wrapper classes

I find myself creating a significant number of wrapper classes, purely because I want to mock out the behaviour of
Classes that don't lend themselves well to the RhinoMocks isolation model (for instance like DirectoryInfo or WindowsIdentity)
Native Win API methods (I normally collect all the methods I need into a single class and wrap the native calls as a class method)
I then find myself appending the class that is wrapped with a 'W' (to indicate that it's a wrapper) and so I end up with DirectoryInfoW (as opposed to DirectoryInfoWrapper which seems rather verbose). Similarly, I end up with wrapped native methods called NativeMethods.DuplicateTokenW.
What would be a good rule of thumb to follow when naming wrapper classes?
Naming conventions are whatever works for the team that you're working with. As long as everyone's ok with a particular convention, then it's ok.
I tend to prefer the more verbose version though, i.e. DirectoryInfoWrapper, rather than having a single letter that doesn't explain anything to anyone who's not familiar with the code. But that's just me.
I'll agree with aberrant80 , if everyone agrees with the convention you are using, then it'll work.
I personally prefer using names that are shorter and descriptive to the class's purpose. At least at the interface level. If you're using a mock framework, then IDirectory or IDirectoryInfo would be a decent set of names, while DirectoryInfoW or DirectoryInfoWrapper would be an interface implementer.
A better example might be wrapping an HttpRequest; define an IRequest to state 'this is what is important to my application', then Request, HttpRequestWrapper, Request, etc would be implementers.
So, to summarize, try and use descriptive, non-overly-verbose interface names.
Just as a side note, I found a more aesthetically pleasing (well, to me) way of wrapping native method calls:
public class NativeMethods
{
// made virtual so that it can be mocked - I don't really want
// an interface for this class!
public virtual bool RevertToSelf()
{
return WinApi.RevertToSelf();
}
...
private static class WinApi
{
[DllImport("advapi32.dll")]
public static extern bool RevertToSelf();
...
}
}
i.e. avoid name collision by encapsulating native method calls in a private nested class.
No 'good' solution to the wrapper class naming issue though, I'd probably go with aberrant80's suggestion and explicitly call my wrappers wrappers.
If you are using C++, you can use namespaces and then just re-use the same class name. For example:
namespace WrapperNamespace
{
class MyClass {...};
}
namespace InternalNamespace
{
class MyClass {...};
}