Premium Partner

Software Construction: Encapsulation

Cards to learn encapsulation

Cards to learn encapsulation


Kartei Details

Karten 15
Sprache Deutsch
Kategorie Informatik
Stufe Universität
Erstellt / Aktualisiert 03.01.2020 / 10.01.2020
Lizenzierung Keine Angabe
Weblink
https://card2brain.ch/box/20200103_software_construction_encapsulation
Einbinden
<iframe src="https://card2brain.ch/box/20200103_software_construction_encapsulation/embed" width="780" height="150" scrolling="no" frameborder="0"></iframe>

System Decomposition software design principle (Definition)

Decompose a system into distinct manageable abstractions. For a decomposition to be useful, the abstractions have to be well isolated from each other.

Encapsulation (Definition)

In software design we encapsulate both data and computation to limit the number of contact points between different parts of the code.

Advantages

  • it makes it easier to understand a piece of code in isolation
  • it makes the use of the isolated part by rest of the code less error-prone
  • it makes it easier to change one part of the code without breaking anything else

Primitive Obsession Design antipattern (Definition)

The tendency to use primitive types to represent other abstractions. This is bad design!

Shown with the example of a (bad) card implementation.

Major drawbacks

  • the representation of a card does not map to the corresponding domain concept
  • the representation of a card is coupled to its implementation
  • it is easy to corrupt a variable that represents a card

Example representing a card using enums

Example representing a deck of cards using a list

List<Card> deck = new ArrayList<>();

This (as standalone solution) is bad design, because

  • a list of cards is not strongly tied to the concept of a deck
  • using a list of cards ties the representation of a deck in the program with its implementation
  • the structure can easily be corrupted

 

Example Scope & Visibility Restrictions (Simple Card implementation)

By returning values as references (i.e. return aRank in getRank) we reveal the underlying implementation of the program, this is bad design! We need to escape the references!

Example (simple) Cards Object Diagram

By returning a reference to deck we also return a reference to the underlying implementation (i.e. the client is able to then also use methods of the two cards, even if unwanted!). This is bad design!

Example (simple) Deck Implementation

getCards() returns a reference to aCards. This is bad design, as the client can then directly edit the deck without using the class Deck!