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

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.

Related

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

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.

Concepts where an object can behave like it implements an interface which it has the method signatures for, w/o explicitly implementing the interface?

I'd like to ask whether this is a useful concept, if other languages have ever done this sort of thing, or if this idea is problematic or just bad. If it is problematic, an explanation of what principles it violates would also be greatly appreciated.
For the sake of being clear about what I mean, I've written some C# pseudocode where I've created an imaginary "lazy" keyword that provides a concrete implementation of this idea. The "lazy" keyword instructs the compiler to 1) explicit cast any object that has functions that conform to an interface contract to that interface, even if the object in question does not explicitly implement the interface and 2) if said explicit cast function doesn't exist, create it, 3.) The object can be cast back to what it was originally, 4.) If the object doesn't implement the methods required by the interface, you get a compiler error.
Then the following code would compile and run.
class Program
{
public interface iRoll
{
public void Roll();
public int Dimensions { get; set;}
}
public class Basketball
{
public void Roll()
{
Console.WriteLine("I'm a rolling basketball");
}
private int _dimensions = 3;
public int Dimensions { get { return _dimensions; } set { _dimensions = value; } }
public string Brand = "BallCo.";
}
public class Tire
{
public void Roll()
{
Console.WriteLine("I'm a rolling tire");
}
private int _dimensions = 3;
public int Dimensions { get { return _dimensions; } set { _dimensions = value; } }
}
static void Main(string[] args)
{
Tire MyTire = new Tire();
Basketball MyBall = new Basketball();
var myList = new List<iRoll>();
myList.Add(lazy iRoll MyTire);
myList.Add(lazy iRoll MyBall);
foreach(iRoll myIRoll in myList)
{
myIRoll.Roll();
Console.WriteLine("My dimensions: " + myIRoll.Dimensions);
}
}
}
The benefits are not always having classes implement interfaces like crazy, and not having to derive from a base class just to implement a custom interface when the base class already has the methods and properties you need (e.g., certain situations with external libraries, certain UI controls).
Good idea, bad idea, terrible idea? Do any other languages experiment with this?
Thanks to all of you for the information. I found a similar question to my own with some interesting information. Two very important related and different concepts to learn about are structural typing and duck typing , both of which could fit my original question.
In my example, C# uses nominal typing which is not compatible with structural typing. The "lazy" keyword I proposed is a keyword that causes a nonimally-typed system to do certain things that make it look to a programmer like a structurally typed system. That should be static duck typing in a nominally typed language, for this example.
I wonder if someone could say the lazy keyword isn't "really" duck typing, but semantic sugar to have classes implement interfaces, if the implementation details of the lazy keyword caused the compiler to have the class operated on to implement any interfaces it needs to implement at compile time. However, I think duck typing is an OOP concept, so this should be duck typing regardless of what the compiler does as long as the end result acts like duck typing. Please feel free to correct anything I'm mistaken about or disagree.
There's a great section in the Wikipedia article about duck typing that shows many examples of it in programming languages.

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.

Type safety with object-oriented methods

I'm trying to think of how to solve this problem correctly using object-oriented methods. The language isn't important—I would actually like to write code, but it's more the general principles I care about.
I want to implement a field: a collection of 'numbers' on which the operations +, -, *, and / operate. Further, I would like to be able to implement higher operations like ^ and cycle-finding which (1) do not need to be defined for a given field but which (2) can be overridden if desired, say for efficiency reasons.
Here's the catch. It's not good enough to declare
FieldElement power (FieldElement base, FieldElement exponent)
because I want type safety: it should not be possible to add, say, a member of a finite field to an integer.
Perhaps what I'm really looking for is a meta-object, or super-interface, or something that ties together different classes (one for integers, one for 7-adics, one for the finite field F_4, etc.). Or maybe there's something better.
N.B. Code is welcome (even encouraged) in answers, if it would be enlightening, but declarations are probably enough: presumably everyone here could write out the obvious methods for at least a few fields.
I'll mention other conditions which matter to me but are (apparently) unrelated to the main OO issue: I don't want field elements to carry their type information around, and further I want them to be lightweight (since I may need to deal with large arrays of field elements). These desiderata may not be achievable—though frankly I'm more likely to abandon OO here than efficiency. But an answer would be appreciated regardless, since I'm interested in learning about these issues even apart from the particular problem at hand.
This is called the binary method problem. Quick googling will reveal some (lots of) information. In particular, the article "On binary methods" by Luca Cardelli et al gives the subject a thorough treatment.
You may want to learn some Haskell to see how a practical programming language deals with this problem.
EDIT Loluca → Luca. Damn the tiny phone screen and its tinier keyboard ;)
I have tried to express these concepts in C# before, but I have encountered language barriers: language is not rich enough, or specific enough. For example, if I define an Element of a Field like this:
public abstract class FieldElement
{
public abstract FieldElement Add(FieldElement another);
public abstract FieldElement SumInvert();
public abstract FieldElement MultiplicationInvert();
public abstract FieldElement MultiplyBy(FieldElement another);
public abstract FieldElement One; //Multiplication neutral element
public abstract FieldElement Zero; //Addition neutral element
public FieldElement Subtract(FieldElement another)
{
return this.Add(another.SumInvert());
}
public FieldElement Divide(FieldElement another)
{
return this.MultiplyBy(another.MultiplicationInvert());
}
public virtual FieldElement Power(uint b)
{
if (b == 0)
return this.One;
else
{
FieldElement result = this;
for (int i = 0; i < b - 1; i++)
result = result.MultiplyBy(result);
return result;
}
}
}
Then I define Real Numbers like this:
public class RealNumber : FieldElement
{
public double Value { get; set; }
public RealNumber(double value)
{
this.Value = value;
}
public override FieldElement Power(uint b)
{
return new RealNumber(Math.Pow(Value, b));
}
public override FieldElement Add(FieldElement another)
{
if (another.GetType() != typeof(RealNumber)) //Ugly typecast to enforce type-safety
throw new ArgumentException("RealNumber expected in Add method");
return new RealNumber(Value + (another as RealNumber).Value);
}
}
I can then define generically operations on Field Elements (by using generics):
public class FieldOperations<T> where T: FieldElement
{
public T Add(T a, T b)
{
return a.Add(b) as T;
}
public T Multiply(T a, T b)
{
return a.MultiplyBy(b) as T;
}
public T Subtract(T a, T b)
{
return a.Subtract(b) as T;
}
public T Divide(T a, T b)
{
return a.Divide(b) as T;
}
public T Power(T a, uint b)
{
return a.Power(b) as T;
}
}
And I will use it like this in code:
public class TestFieldOperations
{
public static void TestAddRealNumbers()
{
FieldOperations<RealNumber> operations = new FieldOperations<RealNumber>();
RealNumber a = new RealNumber(0.5);
RealNumber b = new RealNumber(0.7);
RealNumber c = operations.Add(a, b);
RealNumber d = operations.Power(c, 3);
}
}
Similarly, I could have FieldOperations on Vectors, FieldOperations on InvMatrix...
Being able to abstract the concept of Field operations in a type-safe and object-oriented way can be very powerful: being able to deal with numbers, vectors and (invertible) matrices arithmetic at the same level of abstraction.

What is the real significance(use) of polymorphism

I am new to OOP. Though I understand what polymorphism is, but I can't get the real use of it. I can have functions with different name. Why should I try to implement polymorphism in my application.
Classic answer: Imagine a base class Shape. It exposes a GetArea method. Imagine a Square class and a Rectangle class, and a Circle class. Instead of creating separate GetSquareArea, GetRectangleArea and GetCircleArea methods, you get to implement just one method in each of the derived classes. You don't have to know which exact subclass of Shape you use, you just call GetArea and you get your result, independent of which concrete type is it.
Have a look at this code:
#include <iostream>
using namespace std;
class Shape
{
public:
virtual float GetArea() = 0;
};
class Rectangle : public Shape
{
public:
Rectangle(float a) { this->a = a; }
float GetArea() { return a * a; }
private:
float a;
};
class Circle : public Shape
{
public:
Circle(float r) { this->r = r; }
float GetArea() { return 3.14f * r * r; }
private:
float r;
};
int main()
{
Shape *a = new Circle(1.0f);
Shape *b = new Rectangle(1.0f);
cout << a->GetArea() << endl;
cout << b->GetArea() << endl;
}
An important thing to notice here is - you don't have to know the exact type of the class you're using, just the base type, and you will get the right result. This is very useful in more complex systems as well.
Have fun learning!
Have you ever added two integers with +, and then later added an integer to a floating-point number with +?
Have you ever logged x.toString() to help you debug something?
I think you probably already appreciate polymorphism, just without knowing the name.
In a strictly typed language, polymorphism is important in order to have a list/collection/array of objects of different types. This is because lists/arrays are themselves typed to contain only objects of the correct type.
Imagine for example we have the following:
// the following is pseudocode M'kay:
class apple;
class banana;
class kitchenKnife;
apple foo;
banana bar;
kitchenKnife bat;
apple *shoppingList = [foo, bar, bat]; // this is illegal because bar and bat is
// not of type apple.
To solve this:
class groceries;
class apple inherits groceries;
class banana inherits groceries;
class kitchenKnife inherits groceries;
apple foo;
banana bar;
kitchenKnife bat;
groceries *shoppingList = [foo, bar, bat]; // this is OK
Also it makes processing the list of items more straightforward. Say for example all groceries implements the method price(), processing this is easy:
int total = 0;
foreach (item in shoppingList) {
total += item.price();
}
These two features are the core of what polymorphism does.
Advantage of polymorphism is client code doesn't need to care about the actual implementation of a method.
Take look at the following example.
Here CarBuilder doesn't know anything about ProduceCar().Once it is given a list of cars (CarsToProduceList) it will produce all the necessary cars accordingly.
class CarBase
{
public virtual void ProduceCar()
{
Console.WriteLine("don't know how to produce");
}
}
class CarToyota : CarBase
{
public override void ProduceCar()
{
Console.WriteLine("Producing Toyota Car ");
}
}
class CarBmw : CarBase
{
public override void ProduceCar()
{
Console.WriteLine("Producing Bmw Car");
}
}
class CarUnknown : CarBase { }
class CarBuilder
{
public List<CarBase> CarsToProduceList { get; set; }
public void ProduceCars()
{
if (null != CarsToProduceList)
{
foreach (CarBase car in CarsToProduceList)
{
car.ProduceCar();// doesn't know how to produce
}
}
}
}
class Program
{
static void Main(string[] args)
{
CarBuilder carbuilder = new CarBuilder();
carbuilder.CarsToProduceList = new List<CarBase>() { new CarBmw(), new CarToyota(), new CarUnknown() };
carbuilder.ProduceCars();
}
}
Polymorphism is the foundation of Object Oriented Programming. It means that one object can be have as another project. So how does on object can become other, its possible through following
Inheritance
Overriding/Implementing parent Class behavior
Runtime Object binding
One of the main advantage of it is switch implementations. Lets say you are coding an application which needs to talk to a database. And you happen to define a class which does this database operation for you and its expected to do certain operations such as Add, Delete, Modify. You know that database can be implemented in many ways, it could be talking to file system or a RDBM server such as MySQL etc. So you as programmer, would define an interface that you could use, such as...
public interface DBOperation {
public void addEmployee(Employee newEmployee);
public void modifyEmployee(int id, Employee newInfo);
public void deleteEmployee(int id);
}
Now you may have multiple implementations, lets say we have one for RDBMS and other for direct file-system
public class DBOperation_RDBMS implements DBOperation
// implements DBOperation above stating that you intend to implement all
// methods in DBOperation
public void addEmployee(Employee newEmployee) {
// here I would get JDBC (Java's Interface to RDBMS) handle
// add an entry into database table.
}
public void modifyEmployee(int id, Employee newInfo) {
// here I use JDBC handle to modify employee, and id to index to employee
}
public void deleteEmployee(int id) {
// here I would use JDBC handle to delete an entry
}
}
Lets have File System database implementation
public class DBOperation_FileSystem implements DBOperation
public void addEmployee(Employee newEmployee) {
// here I would Create a file and add a Employee record in to it
}
public void modifyEmployee(int id, Employee newInfo) {
// here I would open file, search for record and change values
}
public void deleteEmployee(int id) {
// here I search entry by id, and delete the record
}
}
Lets see how main can switch between the two
public class Main {
public static void main(String[] args) throws Exception {
Employee emp = new Employee();
... set employee information
DBOperation dboper = null;
// declare your db operation object, not there is no instance
// associated with it
if(args[0].equals("use_rdbms")) {
dboper = new DBOperation_RDBMS();
// here conditionally, i.e when first argument to program is
// use_rdbms, we instantiate RDBM implementation and associate
// with variable dboper, which delcared as DBOperation.
// this is where runtime binding of polymorphism kicks in
// JVM is allowing this assignment because DBOperation_RDBMS
// has a "is a" relationship with DBOperation.
} else if(args[0].equals("use_fs")) {
dboper = new DBOperation_FileSystem();
// similarly here conditionally we assign a different instance.
} else {
throw new RuntimeException("Dont know which implemnation to use");
}
dboper.addEmployee(emp);
// now dboper is refering to one of the implementation
// based on the if conditions above
// by this point JVM knows dboper variable is associated with
// 'a' implemenation, and it will call appropriate method
}
}
You can use polymorphism concept in many places, one praticle example would be: lets you are writing image decorer, and you need to support the whole bunch of images such as jpg, tif, png etc. So your application will define an interface and work on it directly. And you would have some runtime binding of various implementations for each of jpg, tif, pgn etc.
One other important use is, if you are using java, most of the time you would work on List interface, so that you can use ArrayList today or some other interface as your application grows or its needs change.
Polymorphism allows you to write code that uses objects. You can then later create new classes that your existing code can use with no modification.
For example, suppose you have a function Lib2Groc(vehicle) that directs a vehicle from the library to the grocery store. It needs to tell vehicles to turn left, so it can call TurnLeft() on the vehicle object among other things. Then if someone later invents a new vehicle, like a hovercraft, it can be used by Lib2Groc with no modification.
I guess sometimes objects are dynamically called. You are not sure whether the object would be a triangle, square etc in a classic shape poly. example.
So, to leave all such things behind, we just call the function of derived class and assume the one of the dynamic class will be called.
You wouldn't care if its a sqaure, triangle or rectangle. You just care about the area. Hence the getArea method will be called depending upon the dynamic object passed.
One of the most significant benefit that you get from polymorphic operations is ability to expand.
You can use same operations and not changing existing interfaces and implementations only because you faced necessity for some new stuff.
All that we want from polymorphism - is simplify our design decision and make our design more extensible and elegant.
You should also draw attention to Open-Closed Principle (http://en.wikipedia.org/wiki/Open/closed_principle) and for SOLID (http://en.wikipedia.org/wiki/Solid_%28Object_Oriented_Design%29) that can help you to understand key OO principles.
P.S. I think you are talking about "Dynamic polymorphism" (http://en.wikipedia.org/wiki/Dynamic_polymorphism), because there are such thing like "Static polymorphism" (http://en.wikipedia.org/wiki/Template_metaprogramming#Static_polymorphism).
You don't need polymorphism.
Until you do.
Then its friggen awesome.
Simple answer that you'll deal with lots of times:
Somebody needs to go through a collection of stuff. Let's say they ask for a collection of type MySpecializedCollectionOfAwesome. But you've been dealing with your instances of Awesome as List. So, now, you're going to have to create an instance of MSCOA and fill it with every instance of Awesome you have in your List<T>. Big pain in the butt, right?
Well, if they asked for an IEnumerable<Awesome>, you could hand them one of MANY collections of Awesome. You could hand them an array (Awesome[]) or a List (List<Awesome>) or an observable collection of Awesome or ANYTHING ELSE you keep your Awesome in that implements IEnumerable<T>.
The power of polymorphism lets you be type safe, yet be flexible enough that you can use an instance many many different ways without creating tons of code that specifically handles this type or that type.
Tabbed Applications
A good application to me is generic buttons (for all tabs) within a tabbed-application - even the browser we are using it is implementing Polymorphism as it doesn't know the tab we are using at the compile-time (within the code in other words). Its always determined at the Run-time (right now! when we are using the browser.)