Objects and Data Structures – Objects vs Data Structures

An Object and a Data Structure are not the same thing.

What’s the difference?

An object hides its data behind abstractions and data objects. When dealing with an object, we know what it can do and can see its public properties, but we don’t really know how the data is stored, or how the object works. Data structures hold data and provide basic operations that essentially allow you to put data in them and get it back.

Although Object Oriented Programming (OOP) is the norm, there can be cases where a procedural approach using data structures is more convenient.

An example using shapes

Think about a program where you want to be able to calculate the area of a shape. If you use a procedural approach, then you would code it this way:

public class Circle{
  public Point Center;
  public double Radius;
}

public class Rectangle{
  public point TopLeft;
  public double Height;
  public double Width;
}

public class Geometry{
  private const double PI = 3.14;
  public double Area(object shape){
    if (shape is Circle)
      return PI * shape.Radius * shape.Radius;
    else if(shape is Rectangle)
      return shape.Height * shape.Width;
  }
}

Using an OOP approach it would be this way:

public class Circle : Shape{
  private const double PI = 3.14;
  public Point Center;
  public double Radius;
  public double Area(){
    return PI * Radius * Radius;
  }
}

public class Rectangle : Shape{
  public point TopLeft;
  public double Height;
  public double Width;
  public double Area(){
    return Height * Width;
  }
}

Handling Changes

In the procedural example, if we want to add new functions, all we have to do is modify the Geometry class. There will be no need to touch any of the shape classes. If we want to add a new shape then we will have to modify the Geometry class as well to account for the new shape.

In the OOP example, if we want to add a new shape, all the other shape classes can stay as they are, but if we want to add a new function, then all of the shapes will have to be updated.

Which approach to use?

It depends on your needs. If the functionality doesn’t change a lot, but shapes change constantly, then OOP is best. If there will be no more shapes added, but the functionality changes constantly, then the procedural approach would be more convenient.

Your requirements will determine the best solution.

 

 

Leave a Reply