What is the correct way to implement a "clone" method in languages that do not support type reflection and have no built-in cloning mechanism? - clone

Problem background
Suppose I have a class called Transaction and a subclass called NetTransaction. The Transaction class implements a clone method which constructs a new Transaction with multiple constructor parameters.
Such a cloning pattern presents a problem for subclasses like NetTransaction, because calling super.clone will return an object of type Transaction which cannot be up casted to NetTransaction. Therefore, I'd have to reimplement (duplicate) the code in the Transaction class's clone method. Obviously, this is an unacceptable pattern.
Java's solution -- works for languages with built-in cloning logic or type reflection
In Java (so I've read), calling super.clone always returns an object of the correct type as long as every override in the chain calls super.clone, because the base Object's clone method will automatically return an object of the correct type, presumably a feature built into the runtime.
The existence of such a clone method implies that every clonable object must have a parameterless default constructor (either explicitly or implicitly) for two reasons. Firstly, Object's implementation would not be capable of choosing an arbitrary constructor for a subclass it knows nothing about, hence the need for a parameterless constructor. Secondly, although a copy constructor might be the next logical choice, it implies that every object in the class chain would also have to have a copy constructor, otherwise every copy constructor would be faced with the same decision as clone (i.e. to call the default constructor or a copy constructor). That ultimately implies that all the cloning logic would have to be in copy constructors, which would make overriding "clone" unnecessary; therefore, we arrive at the logical conclusion that it would be self-defeating to have clone call anything other than a parameterless default constructor (i.e. the runtime would have to create an instance that require no special construction logic to run).
So Java's cloning implementation, which also seems to provide some built-in shallow copying, is one way to implement cloning that makes sense.
Correct alternative for languages without built-in cloning or type reflection?
But what about other languages that don't have such built-in functionality and lack type reflection? How should they implement cloning? Are copy constructors the only way to go?
I think the only way that really makes sense is copy constructors, and as far as implementing or overriding a clone method for the sake of returning a common interface or base type or just "object", the correct implementation is to simply always call the current object's copy constructor. Is this correct?
The pattern would be, in C# for example:
class A
{
public A( A original_to_copy ) { /*copy fields specific to A*/ }
public object clone() { return new A( this ); }
}
class B: A
{
public B( B original_to_copy ):this (original_to_copy) { /*copy fields specific to B*/ }
public override object clone() { return new B( this ); }
}
class C: B
{
public C( C original_to_copy ):this(original_to_copy) { /*copy fields specific to C*/ }
public override object clone() { return new C( this ); }
}

In systems without a built-in cloning facility, there's really no alternative to using a virtual clone method chain to a copy constructor. I would suggest, however, that one should have the copy constructor and virtual cloning method be protected, and have the base-class copy constructor throw an exception if the exact types of the passed-in object does not match the exact type of the object under construction. Public cloning methods should not be virtual, but should instead chain to the virtual method and cast the result to their own type.
When practical, one should avoid having classes which expose public cloning methods be inheritable; consumers should instead refer to class instances using interface types. If some of the consumers of a type will need to clone it and others won't, some potential derivatives of the type could not logically be cloned, and if a derivative of the type which wasn't cloneable should be usable by code that doesn't need to clone it, splitting things that way will allow for the existence of BaseFoo, CloneableBaseFoo, FancyFoo, and CloneableFancyFoo types; code which needs fancy abilities but doesn't need to clone an object will be able to accept FancyFoo and CloneableFancyFoo objects, while code that doesn't need a fancy object but needs cloning ability will be able to accept CloneableBaseFoo and CloneableFancyFoo objects.

Related

Are there penalties for just using the new keyword instead of creating a class variable before calling the class method?

Example
(1)
var classVar = new class();
classVar.Method();
(2)
new class().Method();
I like the second way, less wordy.
Is there a performance difference?
Is it considered bad coding practice?
If your Method() doesn't use anything from that class, why is it defined there? You could use namespace instead.
The only difference between your (1) and (2) is that the class instance is destructed immediately in (2).
in your case Method seems to be static (ie there is no useful data stored inside the instance of 'class' (note I am ignoring all the invalid / not recommended name issues). Assuming this is c# but all languages have the same ideas, you would go
public class class{ // ugh
public void static Method(){
Console.WriteLine("I am Method");
}
}
now you can go
class.Method();
so the code is neatly filed away inside 'class' but you dont have to pay any overhead.
If you really need to instantiate 'class' then presumably you need to do more than just call one method on it. In which case
new class().Method();
makes no sense, since you call create it, call a method and destroy it.
Really a more concrete example is needed

What is the use of Clonaeable interface in java?

Please don't close as duplicate. I know there are multiple threads on this topic but none of them answers my question.
I am still struggling to understand why do we need Cloneable interface in java. If we want to create copy of an object, we can simply override clone method from Object class and call super.clone().
Since clone method in Object class is native, we don't know if the native implementation checks for instanceOf Cloneable and then create a copy else throw CloneNotSupportedException.
I know it's not a good practice to override clone() method to create a copy and should go for copy constructor instead, but still I want to know is the existence of Cloneable marker interface justified.
Whether an object implements Cloneable or not only matters if the built-in Object.clone() method is called (probably by some method in your class that calls super.clone()). If the built-in Object.clone() method is called, and the object does not implement Cloneable, it throws a CloneNotSupportedException. You say "we don't know" whether the Object.clone() method does that -- we do -- the documentation for Object.clone() method in the Java class library explicitly promises it, and it describes in detail the cloning operation that the method performs.
If you implement a cloning method that does not call up to Object.clone(), then whether the object implements Cloneable or not has no effect.

Extend interface of overridden method in ABAP

As it commonly known, one cannot extend or redefine interface of the overridden method in the inherited ABAP class. Help:
The interface and the category of the method (a general or functional instance method or event handler) are not changed in a redefinition.
This covers both global and local classes redefinition.
What are the probable workarounds of this limitation if one wants to add or remove methods parameters or change their type? Optional parameters is a way, though not very comfy. Any other ways?
You cannot change the signature of an interface method in any way in its implementations. This is simply because there is no way to do this that would not produce hard-to-analyze syntax errors at run time. An interface is a contract - any class implementing it promises that it will implement all methods (and variables...) that are present in the interface.
Assume there is a method METH of interface IF1 taking a single parameter PAR1 of type TYPE1. If you now write a class that implements a method METH with a single parameter PAR1 of type TYPE2, then you have not written a class that implements IF1. A caller that passes a parameter of type TYPE1 to the method of your class will encounter a type conversion error (whether at runtime or at compile time depends somewhat on the genericity of the types).
Therefore, there is no way to change the signature of an interface method in its redefinition without producing such runtime errors - your class does not implement the interface. Implementing an interface means that the class will accept exactly the number, type and kind of parameters specified for the methods in the interface. There is literally no use case in which you could meaningfully want to change this while still claiming that your class implements the interface. Whatever you're trying to do, this isn't the solution.
You can create your own interface, extending the existing interface. Add same method with different parameters. Then create abstract class from your extended interface and fill methods with code for calling real method with setting values to optional parameters. After then create your class from abstract.
interface
|--> extented interface
|--> abstract class
|--> class

Mocking objects instantiated inside a class to be tested

So I am learning TDD using the many resources here on SO, but I just cant seem to figure out what I do with private/protected objects instantiated inside a given method/constructor. Lets say I have a connection string. That connection string is used to construct a Sqlcommand or Sqlhelper. Well I want to mock that Sqlhelper so that when I test other methods I don't have to rely on the results coming from my database. But I cant access the Sqlhelper.
How do I work around this?
Its generally best (except for a very few rare occasions) to test only the public interface of the class as a whole. Try not to use one of the workaround methods (such as private objects) unless you really have to. Accessing private members of classes in tests tends to look good at first as theres less code to write to test an object, however when things start to change (and they will) anything accessing the internals of a class makes it more difficult to change its implementation, this can be crippling to a project if most of the tests are written in this way.
In this particular case you are interacting with an external dependency outside of your control (i.e. SqlHelper), I'd recommend wrapping the SqlHelper object in your own object that implements an ISqlHelper interface (or a more reasonably named interface for your scenario).
e.g.
public interface ISqlHelperWrapper
{
void ExecuteQuery();
}
Then inject this in through the constructor of you're object under test:
public class SqlConsumer
{
private ISqlHelperWrapper _sqlHelper;
public SqlConsumer(ISqlHelperWrapper helper)
{
this._sqlHelper = helper;
}
public void QuerySomething()
{
this._sqlHelper.ExecuteQuery();
}
}
Not only is this a better design (you've isolated the sql implementation specific stuff from the SqlConsumer, and given it fewer reasons to change). But you can now mock the ISqlHelper instance using a mocking framework as well as switch the implementation on construction.
Given your connectionstring scenario above, you could initialise the sqlhelperwrapper (There are better names for this) with the connectionstring and your SqlConsumer object doesn't need to know about it.

TDD-friendly Singleton-like class

I have repository class that is used by at least 2 other classes. This repository class needs to be initialized - which is high in cost (querying database). Now, I create separate instances of repository wherever I need it. The thing is, that everytime I create repository it has to be initialized. How to design such repository to be TDD-friendly? The first thing in my mind was Singleton but it's not the solution.
I hope by TDD-friendly you mean 'testable' code. For a Singleton ObjectX, I think the most common way is to split the responsibility (SRP) of 'controlling creation' to another class so ObjectX does all the things it is supposed to do.
Then you have another class ObjectXFactory or Host or whatever you wanna call it that is responsible for providing a single instance for all clients (and providing thread sync if needed and so on)
Object X can be TDDed independently. You can create a new instance in your test case and test functionality.
ObjectXFactory on the other hand is also easy to test.. you just need to see if multiple GetInstance() calls return the same object. OR better delegate this responsibility to an IOC framework like Spring, which lets you declaratively mark an object definition to obtain singleton behavior (Saving you the effort of writing tests as well)
You just need to educate and conform to a Team convention that ObjectX constructor is not to be called - always use ObjectXFactory.CreateInstance(). (If you find that you have a awareness/discipline problem, mark ObjectX's ctor as internal and visible to only to the test assembly via the sneaky InternalsVisibleToAttribute)
HTH
One answer for the TDD part is learn mocking.
Check out this excellent article by Stephen Walther:
http://stephenwalther.com/blog/archive/2008/03/23/tdd-introduction-to-rhino-mocks.aspx
Do you use any type of IOC container? Unity is my container of choice, and it contains a ContainerControledLifetimeManager which makes your class a singleton, but not managed by yourself.
Consider caching instances for performance improvement before you consider singletons. But for TDD friendly designs consider strategy injection so that 'slow' bits can be removed for testing and replaced with stubs and mocks. Try not to do db calls in tests if you can.
You can't do that -- at least not in a true TDD sense.
Relying on DI/IoC strategies such as Unity means your tests are dependent on an external component and are not tested in isolation.
The tests then become integration tests, not unit tests.
==Ignore the answer below here==
I guess you wanted to know how to make Repository testable.
Introducing an interface for it would allow you to mock or stub it, which will in turn make sure that you can test your objects independent of any concrete implementation of Repository.
I'll illustrate this using Rhino Mocks 3.5 for .NET 3.5:
Let's make an interface out of Repository, let's call that IRepository
public interface IRepository
{
}
Now, since you need to use IRepository for two different objects, then let's just use generics so you can instantiate your repository with that:
public interface IRepository<T>
of course that would mean that you would have some sort of find method:
{
public IEnumerable<T> Find(Criteria criteria)
}
where your criteria object is some object that allows you to set what to look for, e.g., your where clause.
Now, you have your object:
public class SomeObject
{
IRepository<SomeObject> repository;
public SomeObject(){}
public IRepository<SomeObject> repository { get; set; }
IEnumerable<SomeObject> FindAll()
{
//let's assume new Criteria() will return all results
return respository.Find(new Criteria());
}
}
You want to to test SomeObject such that FindAll() will return an expected set of results -- this is where Rhino Mocks would come in:
[TestFixture]
public class SomeObjectTests
{
[Test]
public void TestSomeObjectFindAll()
{
IRepository<SomeObject> stubRepository = MockRepsitory.GenerateStub<IRepsitory<SomeObject>>();
stubRepository.Expect(r => r.Find(new Criteria())
.Return(new List<SomeObject>{
new SomeObject(),
new SomeObject(),
new SomeObject());
var testObject = new SomeObject { Repository = stubRepository };
IList<SomeObject> findAllResult = testObject.FindAll();
//returned list contains 3 elements, as expected above
Assert.AreEqual(3, findAllResult.Count)
}
}
Note that the code above is not TDD best practice in all respects, but it's a place to start.
Key concept here is introducing interfaces to allow for loose coupling of objects, especially when the object tends to do things like access databases, file systems, etc.
There is a more comprehensive example and better examples on Ben Hall's article on Rhino Mocks.

Resources