Ask Question, Ask an Expert

+61-413 786 465

info@mywordsolution.com

Ask C/C++ Expert


Home >> C/C++

Should one design a classes from the outside (interfaces first) or inside (data first)?

A: From the outside.

A superior interface provides a simplified view which is expressed in the vocabulary of a user. In the case of OO software, normally the interface is the set of public methods of either a single class or a tight group of classes.

First think regarding what the object represents logically, not how you intend to physically build it. For instance, imagine you have a Stack class which will be built by containing a LinkedList:

class Stack {

public:

... private: LinkedList list_;

};

Should Stack encompass a get() method that returns the LinkedList? Or a set() method which takes a LinkedList? Or a constructor which takes a LinkedList? Clearly the answer is No, since you must design your interfaces from the outside-in. I.e., users of Stack objects don't care regarding LinkedLists; they care regarding popping and pushing.

Now for another instance that is a bit more subtle. Imagine class LinkedList is built via a linked list of Node objects, where each of the Node object has a pointer to the next Node:

class Node { /*...*/ };

class LinkedList {

public:

... private: Node* first_;

};

Be supposed to the LinkedList class have a get() method which will let users access the first Node? Be supposed to the Node object have a get() method which will let users follow that Node to the next Node in the chain? In other terms, what must a LinkedList look like from the outside? Is a LinkedList actually a chain of Node objects? Or is that only an implementation detail? And if it is only an implementation detail, how will the LinkedList allow users access each of the elements in LinkedList one at time?

The key insight is realization which a LinkedList is not a chain of Nodes. That might be how it is built, however that is not what it is. What it is sequence of elements? thus the LinkedList abstraction must provide a LinkedListIterator class as well, and which LinkedListIterator may have an operator++ to go to the next element, & it might contain a get()/set() pair to access its value stored in Node (the value in Node element is exclusively the responsibility of the LinkedList user, that is why there is a get()/set() pair that let the user to freely manipulate that value).

Beginning from the user's perspective, we may want our LinkedList class to hold up operations which look similar to accessing an array via pointer arithmetic:

void userCode(LinkedList& a)

{

for (LinkedListIterator p = a.begin(); p != a.end(); ++p)

std::cout << *p << '\n';

}

To implement this interface, LinkedList will require a begin() method and an end() method. These return LinkedListIterator object. The LinkedListIterator will require a method to go forward, ++p; a method to access current element, *p; and a comparison operator, p != a.end().

The code follows. The significant thing to notice down is which LinkedList does not have any methods that allow users access Nodes. Nodes are an implementation method that is totally buried. It makes the LinkedList class safer (no possibility a user will mess up the invariants and linkages among the various nodes), easier to use (users don't require to expend extra effort keeping the node-count equivalent to the real number of nodes, or any other infrastructure stuff), and more flexible (through changing a single typedef, users could modify their code through using LinkedList to some other list-like class & the bulk of their code would compile modestly and hopefully with enhanced performance characteristics).

#include // Poor man's exception handling class LinkedListIterator;

class LinkedList;

class Node {

// No public members; it is a "private class" friend class LinkedListIterator; // A friend class friend class LinkedList;

Node* next_;

int elem_;

};

class LinkedListIterator {

public:

bool operator== (LinkedListIterator i) const; bool operator!= (LinkedListIterator i) const; void operator++ (); // Go to next element int & operator* (); // Access the current element private:

LinkedListIterator(Node* p); Node* p_;

friend class LinkedList; // thus LinkedList can construct a LinkedListIterator

};

class LinkedList {

public:

void append(int elem); // Adds elem after the ending

void prepend(int elem); // Adds elem before the starting

...

LinkedListIterator begin(); LinkedListIterator end();

... private: Node* first_;

};

Here are the methods which are obviously inlinable (probably in the similar header file):

inline bool LinkedListIterator::operator== (LinkedListIterator i) const

{

return p_ == i.p_;

}

inline bool LinkedListIterator::operator!= (LinkedListIterator i) const

{

return p_ != i.p_;

}

inline void LinkedListIterator::operator++()

{

assert(p_ != NULL); // or if (p_==NULL) throw ... p_ = p_->next_;

}

inline int& LinkedListIterator::operator*()

{

assert(p_ != NULL); // or if (p_==NULL) throw ... return p_->elem_;

}

inline LinkedListIterator::LinkedListIterator(Node* p)

: p_(p)

{ }

inline LinkedListIterator LinkedList::begin()

{

return first_;

}

inline LinkedListIterator LinkedList::end()

{

return NULL;

}

Conclusion: The linked list contained two different types of data. The values of elements hold up in the linked list are the duty of the user of the linked list (& only the user; the linked list itself makes no effort to prohibit users from altering the third element to 5), & the linked list's infrastructure data (next pointers, etc.), whose values are the duty of the linked list (and only the linked list; for example., the linked list does not allow users change (or even look at!) the several next pointers).

Therefore the only get()/set() methods were to obtain and set the elements of linked list, however not the infrastructure of linked list. As the linked list hides the infrastructure pointers/etc., this is able to make very strong promises regarding that infrastructure (for example if it was a doubly linked list, it may guarantee that each forward pointer was matched through a backwards pointer through the next Node).

So, we illustrates here an instance of where the values of some class's data is the duty of users (wherein case the class require to have get()/set() methods for that data) however the data that the class wish to control does not essentially have get()/set() methods.

Note: the cause of this instance is not to illustrate you how to write a linked-list class. Actually you must not "roll your own" linked-list class as you must use one of the "container classes" provided with your compiler. If possible you'll utilize one of the standard container classes like the std::list template.

C/C++, Programming

  • Category:- C/C++
  • Reference No.:- M9529217

Have any Question?


Related Questions in C/C++

There are several ways to calculate the pulse width of a

There are several ways to calculate the pulse width of a digital input signal. One method is to directly read the input pin and another method (more efficient) is to use a timer and pin change interrupt. Function startTi ...

Software development fundamentals assignment 1 -details amp

Software Development Fundamentals Assignment 1 - Details & Problems - In this assignment, you are required to answer the short questions, identify error in the code, give output of the code and develop three C# Console P ...

What are the legal requirements with which websites must

What are the legal requirements with which websites must comply in order to meet the needs of persons with disabilities? Why is maximizing accessibility important to everyone?

Project - space race part a console Project - Space Race Part A: Console Implementation

Project - Space Race Part A: Console Implementation INTRODUCTION This assignment aims to give you a real problem-solving experience, similar to what you might encounter in the workplace. You have been hired to complete a ...

Assignment word matchingwhats a six-letter word that has an

Assignment: Word Matching What's a six-letter word that has an e as its first, third, and fifth letter? Can you find an anagram of pine grave. Or how about a word that starts and ends with ant (other than ant itself, of ...

Question 1find the minimum and maximum of a list of numbers

Question: 1. Find the Minimum and Maximum of a List of Numbers: 10 points File: find_min_max.cpp Write a program that reads some number of integers from the user and finds the minimum and maximum numbers in this list. Th ...

1 implement the binary search tree bst in c using the node

1. Implement the Binary Search Tree (BST) in C++, using the Node class template provided below. Please read the provided helper methods in class BST, especially for deleteValue(), make sure you get a fully understanding ...

Assign ment - genetic algorithmin this assignment you will

ASSIGN MENT - GENETIC ALGORITHM In this assignment, you will use your C programming skills to build a simple Genetic Algorithm. DESCRIPTION OF THE PROGRAM - CORE REQUIREMENTS - REQ1: Command-line arguments The user of yo ...

Why do researcher drop the ewaste and where does it end

Why do researcher drop the ewaste and where does it end up?

  • 4,153,160 Questions Asked
  • 13,132 Experts
  • 2,558,936 Questions Answered

Ask Experts for help!!

Looking for Assignment Help?

Start excelling in your Courses, Get help with Assignment

Write us your full requirement for evaluation and you will receive response within 20 minutes turnaround time.

Ask Now Help with Problems, Get a Best Answer

Why might a bank avoid the use of interest rate swaps even

Why might a bank avoid the use of interest rate swaps, even when the institution is exposed to significant interest rate

Describe the difference between zero coupon bonds and

Describe the difference between zero coupon bonds and coupon bonds. Under what conditions will a coupon bond sell at a p

Compute the present value of an annuity of 880 per year

Compute the present value of an annuity of $ 880 per year for 16 years, given a discount rate of 6 percent per annum. As

Compute the present value of an 1150 payment made in ten

Compute the present value of an $1,150 payment made in ten years when the discount rate is 12 percent. (Do not round int

Compute the present value of an annuity of 699 per year

Compute the present value of an annuity of $ 699 per year for 19 years, given a discount rate of 6 percent per annum. As