How to re-structure OOPs code with multiple subclasses to avoid downcasting? - oop

I am having with doubts regarding structuring of a code which involves multiple classes.
I have multiple services like ServiceX,ServiceY and so on. Now all the services has certain code data members (variables) which are common. So what I thought is to create a separate class Common which will contain common data and all the service class can extend it.
public class Common{
int a;
int b;
int c;
public int getA()
public int getB()
public int getC()
}
public class ServiceX extends Common{
int x1;
int x2;
int x3;
public int getX1()
public int getX2()
public int getX3()
}
But now, I have some interface HandleService
public interface HandleService{
public String foo(Common comm);
}
This interface is implemented by services to do something and want their specific service data memebers. For example:
public class HandleServiceX implements HandleService{
#Override
public String foo(Common comm){
// Here I want both Common and ServiceX data members also i.e. a,b,c,x1,x2,x3.
}
Main(){
// Here I have to handle all the services. For example:
HandleService serv = new HandleServiceX(); // Handling service X
serv.foo(new ServiceX());
}
Although I have passed ServiceX object in the function though I cannot access its members without downcasting. Otherwise, I have to downcast to all the HandleService Types to their respective service.
Is there any possible way to avoid downcasting here? Or Maybe some restructuring of full code to do it more better and efficient way?
If I go with downcasting thing, I am not sure if it is a good practice?
Any help is highly appreciated!!!

what you can do is to create an overloaded method that would accept the subtype, in that way you avoid downcasting.

Related

How to model similar but not exact data in object oriented paradigm?

I have an interface and two data sources that populate concrete instances of objects that implement the interface. The interface exposes methods that only one of the two instances can satisfy in a meaningful way.
public interface IFoo {
public int getValueA();
public int getValueB();
}
public FooFromFile implements IFoo {
int a;
int b;
...
public int getValueA() {
return a;
}
public int getValueB() {
return b;
}
}
public FooFromNetwork implements IFoo {
int a;
...
public int getValueA() {
return a;
}
public int getValueB() {
return 0; // return 0 because FooFromNetwork never gets value b.
}
}
Every code base I've worked on has code like this and I find it usually stems from a desire to apply 'is-a' relationships where something else may be more appropriate. I have some time to refactor the code base on which I am currently working. What would be some good modeling solutions for situations like this? The actual code is much more complicated than this but solving the toy issue here, with a robust pattern that scales, would go a long way.
The problem described here "is a" (pun intended) violation of the Liskov Substitution Principle. There are many solutions to LSP violations, but nothing is one-size-fits-all. For example, depending on context you may choose to favor composition over inheritance or apply interface segregation.

What is the job of 'Interface' in OO programming?

From what I understand, does it mean. making methods to build up different components of a program. e.g. if i was to make a program that adds and subtracts numbers then I would have something like;
public void addnum(int addnum){
addnum= addnum+1;
system.out.println(addnum);
}
public void subtractnum int subtractnum){
subtractnum = subtractnum-1;
system.out.println(addnum);
}
public static void main(String args[]){
int num = 21;
addnum(num);
subtractnum(num);
}
Am I correct, or does it mean something else?
In the Java and .NET frameworks, among others, having a class X inherit from Y has two benefits:
Instances of class X encapsulate the values of all of Y's fields, and can use any of Y's protected members on themselves as if those members belonged to X; additionally, the definition of class X may use Y's static members as though they were its own.
Variables of type Y may hold references to instances of type X.
Allowing a class object to regard as its own the contents of multiple other classes makes it impossible to have upcasts and downcasts preserve identity; since identity-preserving upcasts and downcasts are useful, Java and .NET allow each class to regard members of only one parent as its own (members of the parent's parent are also members of the parent, and get incorporated as such). The limitation of incorporating members from only one parent class is generally not overly restrictive.
On the other hand, if each type could only be stored in references of its own type or its ancestors' types, that would be restrictive. To allow for the possibility that it may be helpful to store references to an object in multiple independent types, Java and .NET both make it possible to define interface types. A reference to an object which implements an interface may be stored in a variable of that interface type (achieving the second benefit of inheritance) but unlike class inheritance which is restricted to a single parent, interface implementation is relatively unrestricted. A class may implement an arbitrary number of independent interfaces, and references to such a class may be stored in variables of any of those interfaces' types.
In short, interfaces provide the most important benefit of inheritance (reference substitutability), but give up some features in exchange for giving up a significant restriction (the inability to inherit from multiple classes).
You´re confusing different methods with different parameter types.
Maybe this example will help:
public interface GeometricalObject {
double getArea();
double getPerimeter();
}
...
public class Circle implements GeometricalObject {
public double r;
public double getArea() {
return 3.14 * r * r;
}
public double getPerimeter()
{
return 3.14 * 2 * r;
}
}
...
public class Square implements GeometricalObject {
public double s;
public double getArea() {
return s * s;
}
public double getPerimeter()
{
return 4 * s;
}
}
...
public void printGeomObject(GeometricalObject g) {
System.out.println("Area is " + g.getArea());
System.out.println("Perimeter is " + g.getPerimeter());
}
Interface provides us the way of multilevel inheritance.
Interface can be extended to any class
Common properties of any class can be define in interface and can be inherited to many classes.

In Object oriented programming when do we need abstraction?

I read many posts about the "Interface" and "Abstract Class"
Basically, we use "Abstract Class" when we talking about the characteristic of the Object.
And we use "Interface" when we taling about what the object capable can do.
But it still confuse so I make up an example for myself to practice.
so now I thinking of a Object 'Cargo;
public abstract class cargo {
protected int id;
public abstract int getWidth(int width);
public abstract int setWidth(int width);
public abstract int setHeight(int h);
public abstract int getHeight(int h);
public abstract int setDepth(int d);
public abstract int getDepth(int d);
public abstract int volume(int w,int h,int d);
public int getId(){
return this.id;
}
public abstract int setId();
public abstract void setBrand();
public abstract void getBrand( );
.....so on , still have a lot of characteristic of a cargo
}
//in the other class
public class usaCargo extends cargo{
....
private
}
So here is few Question about my design.
1.So in the real programming project world, are we actually doing like above? for me i think it's ok design, we meet the basic characteristic of cargo.
if we setup "private id" , then we actually can't use "id" this variable in any subclass because it's private, so is that mean every variable we defined in abstract class must be either public/ protected?
can someone give some suitable example so my cargo can implement some interface?
public interface registration{
public void lastWarrantyCheck();
}
But seems not suitable here...
we dont usually define variable inside interface, do we ??
I try to gain more sense on OOP . Forgive my long questions.
You would define variables in the Abstract class so that methods defined in the abstract class have variables to use. The scope of those variables depend on how you want concrete classes to access those variables:
private should be used when you want to force a concrete class to go through a getter or setter defined in the abstract class.
protected should be used when you want to give the concrete class direct access to the variable.
public should be used when you want the variable to be accessible by any class.
A reasonable interface that a Cargo object might implement could be Shippable as in how to move the cargo from a source to a destination. Some cargo may be shipped via freight train, some might be shippable by airplane, etc. It is up to the concrete class to implement Shippable and define just how that type of cargo would be shipped.
public interface Shippable {
public void ship();
}
Lastly a variable defined in an interface must be public static and final meaning it would be a constant variable.
Hope this clears it up for you!
Abstract classes can contain implementation, so they can have private variables and methods. Interfaces on the other hand cannot.
You can find some examples on how to implement interfaces here. However, I included how you would implement your registration example below.
public class Cargo implements Registration{
public void lastWarrantyCheck(){
System.out.println("Last warranty check");
}
}
Interface variables are possible, but they should only include constant declarations (variable declarations that are declared to be both static and final). More information about this can be found here.
Variables in an abstract class may be declared as protected, and they will only be available within it and any extending classes. Private variables are never accessible inside extending classes.
Interfaces provide a list of functions that are required by the classes that implement them. For example, you might use an interface hasWarranty to define all the functions that an object would need to handle warranty-related activities.
public interface hasWarranty {
public void lastWarrantyCheck();
public void checkWarranty();
}
Then, any objects that need to perform warranty-related activities should implement that interface:
// Disclaimer: been away from Java for a long time, so please interpret as pseudo-code.
// Will compile
public class Car implements hasWarranty {
public void lastWarrantyCheck() {
... need to have this exact function or program won't compile ...
}
public void checkWarranty() {
... need to have this exact function or program won't compile ...
}
}
// Missing one of the required functions defined in hasWarranty
public class Bus implements hasWarranty {
public void lastWarrantyCheck() {
... need to have this exact function or program won't compile ...
}
}
Only constants, really, as variables declared in an interface are immutable and are shared by all objects that implement that interface. They are implicitly "static final".

does it make sense to cache in private field arrays that not part of the class?

One method of my class need fresh copy of some array for internal stuff, so I should write something like that:
public void FrequentlyCalledMethod {
int[] a = new int[100];
....
But because method is frequently called and because content of the array doesn't make sense (it will be replaced anyway) and because array is big enough i want to optimize and write something like that:
private int[] a = new int[100];
public void FrequentlyCalledMethod {
....
Assuming that method is called 100 times per second I will save about 100 * 100 * sizeof(int) bytes of heap memory every second.
The problem is that now class declaration is "dirty". It contains in field the information that only one method needs. Having too much such fields will make class very "unreadable" as "normal" fields will be mixed with "perfomance optimizations" field.
What can I do? Or I should just choose either perfomance or readablity? Can I have both somehow?
No your class declaration is not dirty. Class declaration is dirty only when you mangle its public interface. And this is a private field. Private fields are used for this.
If you are too worried about the too many private variables then try using small classes. If a method needs 3 private variables you can create a class with those 3 variables and store the object as private filed in current class.
class A{
private int a;
private int b;
private int c;
public int get_num(){
return a+b+c;
}
}
you can use this,
class B{
private int a;
private int b;
private int c;
public int get_num(){
return a+b+c;
}
}
class A{
private B b;
public int get_num(){
return b.get_num();
}
}
If the first case, the array inside FrequentlyCalledMethod is referenced using a local variable, so it will be garbage-collected when the method ends: there's no heap over-usage in that scenario.
However, if you declare your array as a member attribute; the array instance will persist for all your parent-object life, even if the method FrequentlyCalledMethod is called or not.
In conclusion, if you wanna preserve heap-space and make your program more memory efficient go with local attributes and avoid instance variables in your particular case.

Why extract an interface when we can DI a delegate to make it testable?

I was browsing SO and came across this comment on an answer:
Why do we go through the ceremony of extracting an interface when we
can DI a delegate to make it testable?
This articulated a thought I had earlier in the year. Is there anything inherently wrong with injecting pure functionality (function pointers, I guess) instead of interface implementations?
The word 'ceremony' in describing interfaces sounds suspiciously like a comment from a Ruby-ist who anti static-typing. With a good refactoring and templating tool, most of the ceremony goes unnoticed anyway.
While passing in a delegate has its place, IoC with interfaces is normally easier to implement, use, understand, and maintain.
Consider a typical constructor:
public class MyClass
{
public MyClass(IAmEasyToUnderstand easy)
{
if (easy == null) throw new ArgumentNullException("easy");
}
public MyClass(Func<bool, int, int, Point> IAmNot, Func<bool> Clear, Action aboutAnything)
{
//multiple null checks.
}
}
public interface IAmEasyToUnderstand
{
bool DoPointStuff(int a, int b, Point point);
bool CanHazExecute();
Action RunRun();
}
Now consider a class that returns an interface for consumption by another:
public MyClass
{
//IFace
public IAmEasyToUnderstand FindEasy();
//Not Iface
Func<bool, int, int, Point> ReturnPointStuffDoer();
Func<bool> ReturnCanHazExecuteCallback();
Action WowThisIsAnnoying();
}
var easy = myclassInstance.FindEasy();
var consumer = new EasyConsumer(easy);
....
var consumer = new EasyConsumer(
myClassInstance.ReturnPointStuffDoer(),
myClassInstance.ReturnCanHazExecuteCallback(),
myClassInstance.WowThisIsAnnoying());
In looking at latter consumption example, the obvious cleanup would be:
var consumer = new EasyConsumer(myclassInstance);
which means you need an replace the class type with an interface for mocking.