简体   繁体   中英

Explain/Give example of “Hide pointer operations” in Code Complete 2

I am reading Code Complete 2 , Chapter 7.1 and I don't understand the point author said below.

7.1 Valid Reasons to Create a Routine

Hide pointer operations

Pointer operations tend to be hard to read and error prone. By isolating them in routines (or a class, if appropriate), you can concentrate on the intent of the operation rather than the mechanics of pointer manipulation. Also, if the operations are done in only one place, you can be more certain that the code is correct. If you find a better data type than pointers, you can change the program without traumatizing the routines that would have used the pointers.

Please explain or give example of this purpose.

Essentially, the advice is a specific example of the data-hiding . It boils down to this -

Stick to Object-oriented design and hide your data within objects.

In case of pointers, the norm is to NEVER expose pointers of "internal" data-structures as public members. Rather make them private and expose ONLY certain meaningful manipulations that are allowed to be performed on the pointers as public member functions.

  • Portable / Easy to maintain
    The added advantage (as explained in the section quoted) is that any change in the internal data structures never forces the external API to be changed. Only the internal implementation of the publicly exposed member functions needs to be modified to handle any changes.

  • Code re-use / Easy to debug
    Also pointer manipulations are now NOT copy/pasted and littered all around the code with no idea what exactly they do. They are now limited to the member functions which are written keeping in mind how exactly the internal data structures are being manipulated.


For example if we have a table of data which the user is allowed to add rows into,

Do NOT expose

  • pointers to the head/tail of table.
  • pointers to the individual elements.

Instead create a table object that exposes the functions

  • addNewRowTop(newData)
  • addNewRowBottom(newData)
  • addNewRow(position, newData)

To take this further, we implement addNewRowTop() and addNewRowBottom() by simply calling addNewRow() with the proper position - another internal variable of the table object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM