Myriad Benefits of Composition

Nateyana Blake
Future Vision
3 min readApr 25, 2019

--

Want cool Future Vision Merch? Check out our store here

Hey all! The past few weeks have been pretty busy between my internship, interview prep, and writing code. However, I must say that I enjoy having so much to do. A part of my interview prep process has involved solidifying my Object Oriented programming knowledge. For today’s post, I want to focus on a topic by the name of…Composition!

Ok, so what is Composition?

Composition is a design pattern used to implement a has-a relationship between classes. This technique is a great way to reduce boilerplate code (sections of code that have to be included in multiple locations with little or no alterations) and falls right in line with the DRY principle (Don’t Repeat Yourself). Composition helps developers create well-encapsulated classes and code that is overall easier to maintain. The idea that objects can be made up of other objects is one of the main characteristics of an object-oriented language.

How would this look within our code?

This is a class created without composition:

This class has a lot of fields and feels a bit cumbersome. There are many fields dedicated to the studio’s address.

Here is another way of doing this:

We have a class for Game:

Left out getters and setters for easier viewing

A class for the studio:

And a final class for address:

Main Idea?

One or more of a class’s fields are other objects rather than primitive types or strings.

There are actually many real-world examples of Composition. The most popular is probably the fast food restaurant analogy. These restaurants operate through the use of many different components. You need a kitchen, food, workers, etc. The kitchen staff uses ovens and grills but the restaurant is not an oven or grill. It has-a oven.

Compositon is a great way to write code that is clean and well-encapsulated. It’s also a great way to reuse existing code!

--

--