Sunday, 23 December 2018

Shallow Vs Deep copy

Simple words:

Default implementation of Object.clone() (btw you have to be clonable), provides a shallow copy,
i.e. the only primitive data type's of object will be copied but if object contains, some reference to another object, then the newly copied object will just copy the reference value of that Object.


Like

Class Employee {

int name;// this will be copied to a newly created object and set the value
int id; // this will be copied

IDepartment depart; // the newly created object will just copy the reference of the department object

//So of old object, which we are cloning/copying, changes the department object's values, the shallow copied object will also change, hence this is not 100% a freash independent copy.

}

Deep copy:
The only difference is, you are not allowed to write all the complex logic, of implementing/overriding the clone() method behaviour

Class Employee {


public Object clone() {

e = new employee();

Idepartment dep = new Department()

dep.name = this.department.getName()

more complex and nightmare code, of department also contains some other reference object and so on.


}


so this is deep copy but implementation is complex, to make it easy, we need to follow serialization, forcing all the participant to implement serialization, like Employee, Department,and its objects.

then just serialize and de-serialize the object and you will have two independent object with exactly same values.

again, of one of participant object doesn't implement serialize, its value will not be saved and result as null.(Confirm again)




 

Transient variable

Object's attributes marked as "transient" will not be "serialized" during serialization, and during de-serialized its value will be "null/default"

use for fields, like password, or which you don't want to store or send across.

S.O.L.I.D | SOLID Design principle



S: Single Responsibility Principle

Idea : Do not touch the code due to changes in unrelated things, keep everyone's responsibility separate

In DATABASE Example 
- Wrong design - If DB Reader starts performing some transformation, Later of changes in tranformation logic, we have to touch Reader code, which is risky as changes something which is not related to new requirement.
 
Correct design :
These leads to each class having own specific task and functions, like Separate class for Reader [read() function] and Transformer  [performTransform()]




Everyone does its won task with taking other task , independently and secretly(i.e. Encapsulated way).
This principle leads to concept of Containerization of modules as PODs in K8




Example :

A DB Manager may have DBSession Object and DB interactor object.
DBSession just creates a session by loading the conf, 
A DB Interactor just takes session object and perform read and write.

Benefits :
1. Maintainability 
2. Easy to extend the functionality
3. Loosely coupled interaction, Change in one functionality requires minimum/no changes in others code 



O: Open for extension and Closed for Modification

You must design your inheritance structure, Interfaces and classes in such a way that, when you want to add a new functionality.
 You should be able to do it without touching an existing implementation.

Open for extension : 
Must provide an behavior which can be extended

Closed for modification:
The new extended logic, must not impact the existing code and you should not be required to change the existing parent code, in order to accommodate new extension.





Liskovs Substitute principle:

The new extension must be replaceable/passable in any function, which takes a Base type reference

Ex:

public testBordCapabilities(IBird bird) {

bird.speek();
bird.fly();
}

//but lets says you create a wooden bird, and pass that object, then your wooden bird can also fly,
which is bad, for that now either you have to makes changes in this testFly() to handle instanceOf check(violation of OCP), or in your woodenBird's fly() method, you have  to either do nothing and throw exception, that is also bad.


Solution during the design:
IBird{

speek(); // or any other functionality, which you things all Bird should have
}

IFyableBird implements IBird{

fly()
}

So in this case any existing method (testBirdCapabilities(IBird), which takes reference of IBird, will be able to call only speek() method not fly();
and you can pass your Iflyable object to that method as well, i.e. effectively your object is substitutable to your parent.

and other method, who wants to make use of  your flying capabilities, work on your IFlyable reference not on IBird reference

public testFly(IFlyable  flyingBird){

flyingBird.fly();
}


Breaking Liskov :

- Throw a new Exception from implemented(Super Class/Interface defined) method from your subclass.
i.e. your subclass is not completely replaceable .

What you do ?
-Create one more Sub Interface, which throws those exception

I: Interface Segregation Principle

Effectively same/taken care, if you had followed Single responsibility and Liskovs Substitute priciple which protect your "Close for modification" property.

But read in a another way.

Read the same IBird, example as above.
If you provide fly() method in IBird, forcing all non flying bird to implement fly() method, by providing some empty implementation or throwing exception, that dont call fly() on non flying Birds.

Then, if your actual flying bird, lets PigeonBird, wants to change the signature of fly(), then it will require change in IBird --> fly() method, this is not OK, but real problem as per "Interface Segregation principle" is, once you change the signature of fly() in Ibird, this will force a change in other non flying birds class  signature, say in Penguin, which is already complaining by throwing exception in its unnecessary implementation fly().

Hence  "Clients should not be forced to depend upon interfaces that they do not use  "

Here the Client is, Non flying birds like "PenguinBird" and it's force to depend on "fly()" method/interface which it doesn't need".


Solution:

Just like solution for Liskov's, segregate in to single responsibility interfaces.

IBird{

speek(); // or any other functionality, which you things all Bird should have
}

IFyableBird implements IBird{

fly()
}



So, if there is change in IFlyable class's fly() method, other NonFlyableBird which implements IBirds, doesn't need to go through any change.


D: Dependency Inversion Principle 

Basically says about, how a High level class , which contains of talks to a low Level class, should not directly depend upon it, rather talk to it via abstraction/interface, so that if new types of low level class can be introduced without any single change in high level class.



Bad design:

Here manager, is highly/directly dependent on low level "Worker" class, if new worker type is added, the mamager also need lots of changes, assume the manager class is too complex with lots of reference of worker instance, you need to change lots of place, may break many functionality, test it again etc etc



// Dependency Inversion Principle - Bad example

class Worker {

 public void work() {

  // ....working

 }

}



class Manager {

 Worker worker;



 public void setWorker(Worker w) {
  worker = w;
 }

 public void manage() {
  worker.work();
 }
}

class SuperWorker {
 public void work() {
  //.... working much more
 }
}



// Dependency Inversion Principle - Good example
interface IWorker {
 public void work();
}

class Worker implements IWorker{
 public void work() {
  // ....working
 }
}

class SuperWorker  implements IWorker{
 public void work() {
  //.... working much more
 }
}

class Manager {
 IWorker worker;

 public void setWorker(IWorker w) {
  worker = w;
 }

 public void manage() {
  worker.work();
 }
}









OOPS basics



Abstraction:

remember it from example of Hypervisor, the way Hypervisor Abstract the underlying resource on same SERVER, and provide basic interface for VM creation , VM feels as if it owns the server.



Abstraction in Java is provided with "Interface".

Example:

ICar < -- MarutiCar
ICar <-- HondaCar

The client will be provide with reference to only Car interface, even though actual object ca be of any type.

Client can invoke, only those operation, which are defined in interface.

Hence abtracting the underlying different implementation of different car types.

at run time only it will be called .
Hence abstracting the underlying complexity of actual implementation

Encapsulation


Can be seen as a strategy used in order to provide abstraction.
Hide private variable, protect them from getting visible to subclasses.
and visible to the clients, when they hold the object reference, they shouldn't be able to access your internal private attributes and change it.

Its a way to implement "Single Responsibility" principle from SOLID design principle
i.e. you complete one task by your self without leaking your data hence allowing your responsibilities to be managed/alters by someone else

How Encapsulation helps

Implementation 


 Can you access non static variable in static context ?

A static variable in Java belongs to its class and its value remains the same for all its instances. A static variable is initialized when the class is loaded by the JVM. 






Saturday, 22 December 2018

Saving Singleton

Protect from reflection


Declare the instance

private constructor set be set public by reflection


 Constructor constructor = ReflectionSingleton.class.getDeclaredConstructor();
// Below code will change constructor access level from private to public

  constructor.setAccessible(true);

// Creating second instance
 ReflectionSingleton instanceTwo = (ReflectionSingleton) constructor.newInstance();


private fields can be accessed by reflection

If you try to protect constructor, by throwing exception like below

     private ReflectionSingleton() {
        if (instance != null) {
            throw new IllegalStateException("instance already created.");
        }
        System.out.println("Singleton instance is being created.");

    }

Private static field's value can also be changed by reflection , like below


Field instance = ReflectionSingleton.class.getDeclaredField("instance");
instance.setAccessible(true); instance.set(instance, null); So apart from above constructor, make the field final, so that its value can not be changed even via reflection private static final ReflectionSingleton instance = new ReflectionSingleton();


Protect from deserialization

The singleton class need to implement(Not override) readResolve()

 protected Object readResolve()
    {
        return instance;
    }

The readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered


Question:
If Object is loaded in a new JVM instance, where static singleton instance field is never initialised, how can it return the "instance" from readResolve().
even when Singlen is loaded and the static field will have the default value null, in lazy initialization strategy, of is eager strategy is used, this can work.

ANSWER:
readResolve() will work, if you try to serialize your already instantiated ("instance") singleton, in same JVM, and in same JVM you try to deserialised, it will return static reference of "instance" variable.

But if in different JVM ?

It seems, during deserialization, the object's would anyway have "instance" variable, which was serialsed and stored in file, same "instance" variable reference will be return.
For now its ok, explore more.



3. CLONING protection

Just throw exception from your singleton class


@Override
  protected Object clone() throws CloneNotSupportedException 
  {
    throw new CloneNotSupportedException();
  }





Sources : 

/DesignPatterns


https://www.geeksforgeeks.org/prevent-singleton-pattern-reflection-serialization-cloning/

Serialization inside

Why?
1. you want to store the state of your object, and shut down the jvm
come after 20 days and recreate the same object live in exactly same state.
Save where?
a. file
b.db
c. send to any other apps via network.

What is the alternative

1. you can create a REST request with all your data translated as json, send it to other party.
2. use ORM likr hibernation to store the state of your object in db.
Lets come back...
So make object state storable, java told if you want java to store the state of your object then tell the java same by implementing "serializable" interface and java will perform the serialization and deserialization algorithm for your object, if you use
objet.writeObject() and object.readObject().
what is algorithm (in short) during serialization
upon, obj.writeObject()jvm will
1. store the description of your serializable class, like its name, its serialversionUid,package name, what are fields, number of fields, type of fields
2. Same for its parents and its parents and on.
3. then it will store the the actual value of its top class parents class variable.
4. then come down to child, and child and store its variables actual value.
5. if during variables value assignment, if jvm find that variables is type of some user defined class(which implements serializable or not).
6. then process 1-2 repeats of storing that class definition, like its uid, number of variables, tupe of variables, up its parents hirarchhy, and the assign and store all the actual values.
7. then covert in to byte[] , write to file, db etc.

IMPORTANCE OF SERIALVERSIONUID

The idea of having serialVersionUID, it to force an update in client/de-serialization class and tell him, look, we updated our serializing class, if you want to use our new serialized object, you must update your de-serializing class as well.

How developer does it ?:

While modifying the new serializing class, he also changes the serialVersionUID manully.

Use case-1:

Code serialized the Object with uid = 10L

Client has a class with uid=10, which deserilised it , works fine both object's uid and deserilizing class's uid matches.

Use case-2:

Server has serialized few object on 1st Jan in DB with uid=10 and on 1st Feb server modified the code by adding a new field say "address" and removed old field "name" and changed uid=20  and client after 1 month, still has old class with uid=10.

then client will be able to de-serialized all the object which was stored during 1st Jan, but when it tries to de-serialized new object which were created after 1st Feb(with uid=20).

it will throw InvalidClassException, during de-serialized.

Why ?
Because if client doesn't update its de-serializing class, then it will not be able to recreate, new properties like address and will not find "name" value.
Hence after de-serialized the object will have name=null and adress will not at all be there.

Hence there is inconsistent, of object state and all purpose of saving/trasfering the state of object it lost/not achieved.

Wednesday, 19 December 2018

Why static code cant have instance reference

Because static code are loaded in when class gets loaded via classloader and at that time, no instance of that class would have got created...
hence compiler finds the issue and complains.

Immutability

How to break immutability if class
1. has private fields
2. no setter method
3. proper constructor for obj creation.
but failed to.mark the class as final.

then effectively, you created your immutable class and told everyone that, use my object, wherever for all immutable features, like storing immutable object as key

but since its nit final, any class
1. can extend it.
2. provide a setter functionality for its own private varible ,hence not immutable.
3. type cast this immutable object to mutable type reference.

and start passing where you had passed your immutable object , breaking your promises.

so.mark it final, so that no one can extend it.

Static Vs Dynamic Binding



similarly
binding happens for static method, they will be binded to a class they belongs.


Friday, 14 December 2018

Recursion vs Iterative


Recursion :

Advantage :
Best suited for tree structure sort of problem, like trees , makes code look less complex.

Disadvantage :
1. Use lots of Stack , as each stack call, will have its own variable
2. Difficulties during debugging


Iteration :
Just reverse advantage and disadvantages :)

Thursday, 13 December 2018

JSON parsing sample


Java Script Object Notation.


Using the org.json library:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");

List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("interestKey"));
}