Showing posts with label Java Standards. Show all posts
Showing posts with label Java Standards. Show all posts

Saturday, January 28, 2017

Java Coding - Few Basic Rules

1. Variables Passed by Value, Objects Passed by Reference

In Java, variable method arguments e.g. intString are passed by Value while the objects are passed by reference. Be mindful to it.

2. You can not create object of an abstract class directly

You need to extend this class and implement missing abstract methods (If any). Abstract class may not contain any abstract method if needed so.

3. Java does not support multiple inheritance

Though you can give a hand to it through a class implementing multiple interfaces e.g. class C implements A, B.

Sunday, December 25, 2016

Java Coding- Inheritance Rules

Inheritance should be used wisely. Purpose of inheritance is to have a parent-child (Superclass-Subclass) relationship between objects. In result, it facilitates code reuse. But don't use Inheritance just for code reuse. 
Following two principles help you to use inheritance wisely-

is A? Principle

It helps you decide if you should inherit a class from other i.e. is the new class should or should not extends a super class. So before you decide to extend ask the below question-

Is a "Circle" a "Shape"?
Is a "Triangle" a "Circle"?
Is a "Cat" an "Animal"?

If answer is "Yes" then you should extend the super class.
If answer is "No" then you should NOT extend the super class.

has A? Principle

It helps you decide if a class should have a field or is it relevant to add a new field to a class? Ask below question-

Has a "Circle" has a "radius"?
Has a "Triangle" has a "radius"?

If answer is yes then you should have the field in the class otherwise NOT.


Inheritance facilitates one more Advantage that is in form of another principle-

Liskov Substitution Principle

Any child type of a parent type should be able to stand in for that parent without things blowing up. Reverse of this is not true i.e. you can not replace a child type object with it's parent type object. If you try do so i.e. by means of type casting the parent type object, there is a risk that it may blow up things.

Consider an example where "Animal" <---- "Dog" i.e. Dog extends Animal

A. Suppose a  method which accepts Animal - makeNoise(Animal a). You can always call this method with child type object i.e. makeNoise(d) where d is an object of class Dog.

B. Take another method which accepts Dog - sniffDanger(Dog d). Now you can NOT call this method with parent type object i.e. sniffDanger(a) where a is an object of class Animal. Even if you try to typecast a, something like this: sniffDanger((Dog) a), there is high possibility that it may blow up things, so not a safe approach.

CDN | Clearing Cloudflare cache

In order to clear Cloudflare cache automatically via code, follow below steps: 1. Develop Custom TransportHandler Develop a custom Trans...