Currently there are numerous design principles to guide developer to write good object oriented code. This one is an attempt in that direction and it is a new new hypothesis. Working to see if this can be one principles to take care of all.
What is Pure class ?
In any object oriented programming language, a pure class is a class in which all the functions(except setters) are with no arguments.
Purity measure of a class ?
Here is the formula to calculate purity of a class.
Purity = 100 - ((totalfunctionsintheclass-functionswithnoargs)/totalfunctionsintheclass)*100.
Example : If in a class out of 10 functions, 4 functions have one or more arguments. The purity of the class is 60%. 100 – ((10-4)/10)*100
Design guide.
When working on a class, try to achieve as close to as possible to 100% pure classes. It is not always possible and is certain situations understandable. But, with thought-full effort we can make all classes 100% pure classes.
Why pure classes ?
- Total encapsulation.
- Minimizes coupling.
- Maximizes cohesion.
- (SOC) separation of concerns.
- Enforces SRP. Single responsibility principle.
- Enforces delegation.
- Closer to reality.
Examples
public class PureClassClac {
int op1;
int op2;
public void setOp1(int op1) {
this.op1 = op1;
}
public void setOp2(int op2) {
this.op2 = op2;
}
public int sum() {
return this.op1 + this.op2;
}
}
-----
Client Snippet
PureClassClac calc = new PureClassClac();
cal.setOp1(200);
cal.setOp2(100);
int result = calc.sum();
-----
public class NotSoPureClassClac {
public int sum(int op1,int op2) {
return op1 + op2;
}
}
-----
Client Snippet
NotSoPureClassClac calc = new NotSoPureClassClac();
int result = calc.sum(200,100);
What is the catch ?
Like any of the other design principles your system will still work even if not made up of pure classes. So, What is the catch here ?
- Shift in orientation – This is kind of auto-suggestion to have the complete focus on the current class being developed. It is natural that there is a tendency to think of the usability of a particular class that is being worked upon. This will restrict the class to the specific usability. Pure function are self-sustaining and define the usability of itself.
- Class and its function will never use any attribute(s) or variable(s) outside itself. There is no dependencies with the out-side world. Class can stand alone.
- Separation of setup and execution.
- Closure to reality – Recollect how you use a physical calculator. Do you remember how you drive a car.
Working on examples and soon will be updated. This is a research in progress, cannot commit to be right or wrong. I am having to publish this as this needs to be reviewed and will update accordingly.
Leave a comment