UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 4.1 Free with a free account
Defining Data Behavior Without Implementation Details
Data Structures and Algorithms · Chapter 4: Abstract Types, Exceptions, and Nested ClassesSection 4.1 · lesson 11 of 8710 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Turning Data Definitions into Working Java Code →← Choosing Between Contracts and Partial BlueprintsNext lesson: Turning Data Definitions into Working Java Code →
In this lesson
Specify data by its operations, conditions and invariants before coding.
- Define an abstract data type by its operations, preconditions, postconditions and invariants
- Explain how a specification acts as a contract between caller and implementer
- Distinguish a specification from its many possible implementations
- Decide how operations should return results and handle broken preconditions
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,467 words). Read along, or search it.
Opening Question
Building a Display Before the Counter
Ana is building a display that shows how many visitors are inside a shop. It needs a counter. Ben will build that counter, but he hasn't written a single line yet, and he hasn't even decided how to store the number. Can Ana start her part today, without waiting for Ben? And if she can, what would she need from him first?
Definition
What an Abstract Data Type Describes
Think of the volume button on a remote. Press it, and the sound gets louder. You don't know which circuit does the work. And the maker can redesign that circuit, without changing what the button means. Programmers do the same with data. Before deciding how to store information, they write down what the data must do. That written description is an abstract data type, or A D T. It describes data by what you can do with it, and what happens when you do. It says nothing about memory layout, or the steps inside. A vending machine is a good picture. Put in money, choose an item, and the item drops. Whether a motor, a spring or a robot arm delivers it is invisible, and it doesn't matter to you.
Specification Parts
Operations, Conditions and Invariants
A complete specification answers four questions. Operations: what can be asked of this data? For a counter, which remembers one whole number: increment, decrement, and get count. Preconditions: what must be true before an operation is called? Decrement needs the count to be above zero. Postconditions: what will be true after it finishes? After increment, the count is one more than before. And invariants: what is always true, before and after every operation? The count is never negative.
Contract
Who Promises What
Together, these parts work like a contract between a caller and an operation. The caller promises the precondition. Call decrement on a counter that's already zero, and you've broken your side of the deal. The implementer promises the postcondition and the invariant. If the precondition was met, the result must be exactly as described, and the always-true fact must still be true. If the precondition is broken, the contract makes no promise at all. That's why a good specification also says what happens in that case.
Worked Example
A Full Counter Specification
Here's a full specification for the counter, in words and a table. There's no code, and no mention of how the number is stored. Its purpose: remember a single whole number, the count, such as the number of people in a room. It starts at zero, and its invariant is that the count is never negative. Increment returns nothing, can always be called, and leaves the count one higher. Decrement needs a count above zero, and leaves it one lower. Get count returns the current count, and changes nothing. Reset sets the count to zero.
Invariant Protection
Why Decrement Needs a Precondition
Why does decrement have a precondition? Because of the invariant. If the count were zero and decrement ran anyway, the count would become minus one, and never negative would be broken. The precondition protects the invariant. Follow some calls. From zero, increment gives one, increment gives two, and decrement gives one. Get count reports one. Decrement gives zero. And one more decrement is refused, because its precondition fails. The count stays at zero, and every state kept the invariant.
Quick Check
Which Call Breaks the Contract
Quick check. A new counter starts at zero. The calls are: increment, decrement, decrement, increment. Which call breaks the caller's side of the contract? Pause, and decide. The second decrement. After increment and one decrement, the count is back to zero, so the precondition, count above zero, is false when the second decrement is called. The first decrement was fine: the count was one. And increment has no precondition at all, so it can never break the contract.
Implementation
Many Implementations of One Specification
A specification says what an ADT does. An implementation is one particular way of making it happen, and many implementations can satisfy the same specification. One counter keeps the count in a single whole number, and adds or subtracts one. Another keeps a list, with one tally mark for every increment, and removes a mark for every decrement. Wasteful, but after any valid sequence of calls, get count answers the same. Users depend on the specification. The implementations can be swapped behind it.
Benefits
Five Payoffs of Separation
Keeping them separate pays off five ways. Freedom to improve: replace the tally marks with a single number, and nobody using the counter is affected. Easier teamwork. Back to Ana and Ben: she can build the visitor display using only the counter's specification, while he builds the counter. That's what she needs from him first. Clearer thinking: you notice that decrement at zero needs a rule, before any storage is chosen. Easier testing: the specification says exactly what to check. And reuse: the same counter can count visitors, clicks, or items in a basket.
Second Example
Specifying a Bag of Items
A second, richer example: the bag. A bag holds items in no particular order, and the same item may appear more than once, like a shopping bag with three apples and two lemons. It starts empty. Add puts in an item. Remove takes one copy out, and needs at least one copy to be there. Count of tells how many copies of an item the bag holds. Size gives the total, and is empty says yes or no. Three invariants tie them together. Count of is never negative. Size always equals the total of every count. And is empty is true exactly when size is zero.
Observation
A Bag Counts Many Items at Once
Notice that the bag is a counter for many items at once, each with its own count. And nothing says whether the items sit in a list, a table, or something else. That's left to the implementation.
Design Decision
A Small, Complete Set of Operations
Writing a specification is a design task, and three decisions shape it. First: which operations should it offer? Operations come in two families. Updates change the state: increment, reset, add, remove. Queries report on it without changing it: get count, size, is empty. Keep the set small: every extra operation is one more promise every implementation must keep. Keep it complete: users must reach every fact they need. And keep each one focused, with updates and queries apart, so that asking a question never changes the answer.
Design Decision
What Each Operation Returns
Second: what should each operation return? Queries return the answer in its simplest useful form: a whole number, a yes or no, or the item itself. Updates usually return nothing. Sometimes they return yes or no, to report whether the change happened, and then the specification must say exactly what each answer means. And name the return even when it's nothing, so no one has to guess.
Design Decision
Three Ways to Handle Failure
Third: what happens when an operation can't do its job, like removing an item that isn't in the bag? Silence leaves every implementer to guess differently, so the specification must choose. Choice one: refuse, and report an error. Calling remove without a copy breaks the precondition. That's good when a missing item usually means a bug in the calling code, but callers must check first. Choice two: return yes or no, yes if a copy was removed. Good when callers often don't know whether the item is there, though they can ignore the answer by mistake. Choice three: redefine the case as valid. If the item isn't there, remove does nothing. Good when the goal, the item gone, is already met, though real mistakes can slip by unnoticed.
Quick Check
Removing an Item Already Gone
Quick check. A family shares a shopping list. Two people often tap remove on the same item, and the second tap finds it already gone. The app simply redraws the list after each tap. Which way should the specification handle a missing item? Pause, and decide. Treat it as valid. The goal is an item that's off the list, and that's already true, so remove can simply do nothing. Refusing would turn an ordinary double tap into an error. And a yes or no answer would only be ignored, since the app never uses it.
Checklist
Steps for Writing a Specification
So, to write a specification: state the purpose in one sentence, and the starting state. List the invariants. List the operations, as updates and queries, each with its precondition, postcondition and return value. Say what happens when each precondition isn't met. Then read it all again, looking for any word that describes how instead of what, and remove it.
Key Takeaways
Specifications as Contracts
To summarize. An ADT describes data by its operations, preconditions, postconditions and invariants. The specification is a contract: the caller meets the precondition, and the operation delivers the postcondition and keeps the invariant. Specification and implementation stay separate, so implementations can change without disturbing users. And always state what happens when an operation can't do its job. Silence is the real mistake.
Think About It
Specifying a Stopwatch
Something to think about. Imagine a stopwatch, with start, stop, and get elapsed time. Write one invariant for it. Then decide what stop should do if the stopwatch was never started, and which of the three choices you picked, and why.
About Data Structures and Algorithms at UPI Study
Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms
Why take it here
Why students take Data Structures and Algorithms with UPI Study
Where the credit goes
Universities that work with NCCRS
Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Defining Data Behavior Without Implementation Details
What is an abstract data type?
What is the difference between a precondition, a postcondition and an invariant?
What is the difference between an ADT and its implementation?
How should an ADT specification handle an operation that cannot succeed?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Data Structures and Algorithms.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →