What is the use of Clonaeable interface in java? - clone

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.

Related

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

signal listener subclassed from CIlistener

I have a signal produced from a module. I want to define a signal listener class in another module but whenever I want to subclass it from CIListener, it says it cannot make a new instance from my subclassed listener because the CIListener class is a pure virtual class (interface class). But I have re-declared or redefined all the pure virtual methods in my listener class. Instead when I user CListener class to subclass my listener it works! Do I have to subclass from CIListener?
I guess you believe that you have re-defined all pure methods, but in fact the compiler thinks otherwise. There are 7 pure virtual methods that should be implemented with the proper signatures. If you want to support only certain data types (as it is in most cases) I would suggest to implement (extend) the cListener as it is just a NOP implementation of the cIListener interface (with all its methods throwing a datatype not supported error). Be sure to see whether you indeed override the necessary methods. You may use the override C++ keyword in your method definition.

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?

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.

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.

How is Key-Value Observing implemented internally?

I got answer about Foundation magic for this question: What's the most *simple* way to implement a plain data object which conforms key-value-observing?
What's the magic? How it work internally? Because it's dangerous using framework which I can't understand its internal behavior, I want to know its behavior. Currently, I cannot understand how it work without any method definitions.
Apple's documentation describes how KVO is implemented internally.
The gist of it is that when you register an observer on an object, the framework dynamically creates a subclass of the object's original class, and adjusts the object to appear as an instance of this new dynamic class. You can see this if you inspect an object in the debugger after it has had an observer registered.
This new class intercepts messages to the object and inspects them for those matching certain patterns (such as the getters, setters, and collection access).
In a nutshell: Objective-C 2.0's #property declaration creates accessor methods for the named property, so there are method definitions. #property is just a shorthand way to define them which avoids a lot of repetitious boilerplate code.
When you observe a property, a private subclass is created which implements accessors that call the appropriate notification methods before and after changing the property value. A technique known as "isa swizzling" is then used to change the class of the observed object.

Resources