Page 3 of 3 FirstFirst 123
Results 21 to 28 of 28

Thread: c++ while loop versus For loop

  1. #21
    Join Date
    May 2005
    Location
    Delft, NL
    Beans
    3
    Distro
    Ubuntu 6.06

    Re: c++ while loop versus For loop

    Quote Originally Posted by LordHunter317
    I wasn't clear. Area shouldn't be non-friend, non-member because it is dependent on a unstated semantic property of the class.
    I fail to see how this differs from matrix multiplication. In order to perform it correctly, one must have knowledge about what a matrix is and therefore its internal structure as well.

    Quote Originally Posted by LordHunter317
    Right and you if you have both, you've broken the duplication rule. You don't do that.
    Once again, I never implied there was duplication. I merely stated that, from a programmer's perspective, there is no difference (in terms of functionality) between either interface choice (members or non-members).

    Quote Originally Posted by LordHunter317
    No, wrong, here's a simple example:
    Code:
    class IMatrix2D {
    public:
        virtual void at(int row, int col) = 0 const;
    }
    
    IMatrix2D*
    multiply(const IMatrix2D& lhs, const IMatrix2D rhs) {
        // Do multiply using at
    }
    Encapsulation is clearly enhanced here because the multiply() function can never be dependent on anything but public members of IMatrix. If the class is changed later, nothing will affect multiply unless the definition of at() is changed. Yet, I could still have two implementations of IMatrix2D: one that used an array and one that used a linked list.

    So encapsulation is unquestionably improved: I'm only dependent on a smaller set of class members (jsut the public ones).
    Code:
    class IMatrix2D {
    public:
        virtual void at(int row, int col) = 0 const;
        IMatrix2D* multiply(const IMatrix2D& rhs) const {
            // Do multiply using at
        }
    };
    This code has exactly the same guarantees (albeit not compiler verified) and exactly the same encapsulation as your code. Therefore, encapsulation is not "clearly enhanced". You seem to want data encapsulation to mean hiding class data from the programmer(s) designing/coding/maintaining a particular class. However, the classical definition relates to hiding class data from programmer(s) working with instances of the class.

    I think that this debate is essentially a difference of opinion on what defines an external utility/helper method for a class.

  2. #22
    Join Date
    Nov 2004
    Beans
    2,614

    Re: c++ while loop versus For loop

    Quote Originally Posted by StickGuy
    I fail to see how this differs from matrix multiplication.
    Because the algorithm for computing the product of two matricies is identical if I have can access every entry in the matrix via some function call. This is true regardless of how the matrix actually stores it's data in memory.

    The algorithm for computing the area of the shape is not the same, I must also know the type of shape in order to compute the area.

    The difference here is that the algorithm for doign matrix multiplication is not dependent on type. In your example, the algorithm for doing area computation was dependent on type.

    In order to perform it correctly, one must have knowledge about what a matrix is and therefore its internal structure as well.
    You're only correct about the former. I need to know nothing about the internal structure.

    If this were true, then how do the STL algorithms work on vectors, lists, sets, and maps? Clearly, they cannot know anything about the internal structure because all of those have radically different internals yet they do exactly what you claim is impossible.


    Once again, I never implied there was duplication.
    Yes, you did:
    I'm not sure that your suggestions leads to better data encapsulation. From a programmer's perspective, both member functions and these external functions present, effectively, the same interface to the data.
    (emphasis mine). My whole point is that if oyu're in this situation, you already likely made a mistake. So if you're making that statement, it means you already did something wrong.


    I merely stated that, from a programmer's perspective, there is no difference (in terms of functionality) between either interface choice (members or non-members).
    From a class user's prospective, perhaps (even that's not completely true when templates are involved). But not from the class designer's prospective at all. Non-friend, non-member functions have stronger type checking enforced by the compiler: the fact their dependent only on public data is enforced. If they are member functions, that fact cannot be enforced.


    [code]This code has exactly the same guarantee (albeit not compiler verified)[/quote]Which means it doesn't have the same guarantees. What the compiler has enforced is worlds different from what is enforced by convention.

    and exactly the same encapsulation as your code.
    Nope, greater encapsulation because of the above. The compiler is enforcing the rule now, not me.

    You seem to want data encapsulation to mean hiding class data from the programmer(s) designing/coding/maintaining a particular class.
    No, it means information hiding. If I can write my functions such that they're dependent on details that I've already had to make public, then it behooves me to write them in such a way that the compiler enforces that rule. This means that the coupling between that function and the class definition is less. It means I'm promised that in no situation will I have to change the function definition unless I change the public class members in a breaking way.

    That's a useful thing.

    However, the classical definition relates to hiding class data from programmer(s) working with instances of the class.
    That's actually not the classical defintion and it's a poor definition. The compiler is clearly capable of more than that, so it's clearly inadequate.

    I think that this debate is essentially a difference of opinion on what defines an external utility/helper method for a class.
    No, it's clearly a core one. Your definition of encapsulation is fundamentally wrong.

  3. #23
    Join Date
    Jul 2005
    Beans
    1,535
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: c++ while loop versus For loop

    It seems like this thread has turned into a debate between information hiding versus encapsulation. LordHunter seems to be using the two terms interchangeably, whereas StickGuy is attempting to draw a distinction (I apologize if my interpretation on your usage of the terms is incorrect).

    Here is a decent article (albeit using Java not C++ but still about OOP) attempting to clarify the distinction between the two. If you don't wish to read the whole thing, the following are some key statements:

    Encapsulation refers to the bundling of data with the methods that operate on that data. Often that definition is misconstrued to mean that the data is somehow hidden.

    However, hiding data is not the full extent of information hiding. David Parnas first introduced the concept of information hiding around 1972. He argued that the primary criteria for system modularization should concern the hiding of critical design decisions. He stressed hiding "difficult design decisions or design decisions which are likely to change." Hiding information in that manner isolates clients from requiring intimate knowledge of the design to use a module, and from the effects of changing those decisions.

    Encapsulation is a language construct that facilitates the bundling of data with the methods operating on that data. Information hiding is a design principle that strives to shield client classes from the internal workings of a class. Encapsulation facilitates, but does not guarantee, information hiding. Smearing the two into one concept prevents a clear understanding of either.
    Last edited by hod139; June 21st, 2006 at 09:25 PM.
    When I invented the Web, I didn't have to ask anyone's permission.
    ~Tim Berners-Lee on Net Neutrality
    -------------------------------------
    Visit the Ubuntu Programming IRC-channel at #ubuntu-programming (chat.freenode.net).

  4. #24
    Join Date
    Aug 2005
    Location
    Bremen, Germany
    Beans
    204
    Distro
    Kubuntu 6.10 Edgy

    Re: c++ while loop versus For loop

    Quote Originally Posted by hod139
    Thanks for the suggestions. I'm not sure how I missed the dataLoc += nCol_ improvement. Is this example more of what you had in mind?
    Yes. You can even drop dataOffset entirely and just go sequentially through your array.

    Edit: after taking a closer look at the code, it's not that simple to drop dataOffset . So the following code won't work. Maybe with a second pointer.... So just ignore the following code.

    Code:
    Matrix<T> operator*(const Matrix<T>& rhs) const{
        assert(nCol_ == rhs.size1() );
        const size_t rhs_size2 = rhs.size2(); 
        Matrix<T> theMatrix(nRow_, rhs_size2); 
        // size_t dataOffset = 0;  
        // T *val; // Pointer to data_ array starting at correct offset.
        const T *val = data_; // Pointer to data_ array
        for (int r=0; r < nRow_; ++r) {
           for (int c=0 ; c < rhs_size2; ++c) {
              T& x = theMatrix(r, c);
              // val = &data_[dataOffset];  
              for (int i=0; i < nCol_; ++i) {
               x += (*val++) * rhs(i,c);
             }
          }
          // dataOffset += nCol_;
       }
       return theMatrix;
    }
    But I'm really interested in the comparison between the for and while loop, when you apply this change to them. This change eleminates one of ther two additional operations I mentioned. The other one ( i = nCol_ -1; ) can be eleminated by defining a constant for (nCol_ -1) and then assingning that constant to i.

    P.S.: Sorry about becoming On-Topic again.
    Last edited by Harleen; June 21st, 2006 at 10:26 PM.

  5. #25
    Join Date
    Nov 2004
    Beans
    2,614

    Re: c++ while loop versus For loop

    Quote Originally Posted by hod139
    LordHunter seems to be using the two terms interchangeably,
    That's because they're synonymous.

    [FONT=verdana, arial, helvetica][SIZE=2]Encapsulation refers to the bundling of data with the methods that operate on that data. Often that definition is misconstrued to mean that the data is somehow hidden.
    Yet this is clearly a poor definition because it is meaningless. By that definition, any class or any function taking parameters is encapsulated at the right scope.

    Clearly, that's not a sufficent definition. Making encapsulation being synonymous with grouping hasn't gained us anything.

    More importnatly, as soon as you define it as a language construct, you include non-friend, non-member functions. So I'm still correct, because they're a method for encapsulation.

    So his definition, that encapsulation is a language feature is clearly bunk, becuase it fails to also make any distinctions. Again, any class or function taking parmeters is encapsulated.

    So clearly, we're only left with the defintions being the same. His article is based on a fundamental fallacy anyway: that since Java is OOP all code written in Java is OOP. The former isn't completely true and the latter certainly is true, so his article is bunk anyway.

  6. #26
    Join Date
    Jul 2005
    Beans
    1,535
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: c++ while loop versus For loop

    Quote Originally Posted by LordHunter317
    That's because they're synonymous.
    Oh really...
    http://nat.truemesh.com/archives/000498.html
    http://en.wikipedia.org/wiki/Information_hiding
    http://discuss.joelonsoftware.com/de...gn.4.145438.37
    http://www.toa.com/pub/abstraction.txt
    http://www.roseindia.net/software-tutorials/detail/2941

    Now, I don't expect you to read these articles (I only glanced); my point is that the while you feel the terms are synonymous, others (including it appears StickGuy who can correct me if I'm wrong) don't.

    The first article I linked sums it up pretty nice:
    Information hiding lets one build higher level abstractions on top of lower level details. Good information hiding lets one ignore details of the system that are unrelated to the task at hand.
    Encapsulation ensures that there are no unexpected dependencies between conceptualy unrelated parts of the system. Good encapsulation lets one easily predict how a change to one object will, or will not, impact on other parts of the system.
    Now, I'm still trying to sort out the distinctions myself, but after doing some googling statements such as:
    Quote Originally Posted by LordHunter317
    Your definition of encapsulation is fundamentally wrong.
    Yet this is clearly a poor definition because it is meaningless.
    That's because they're synonymous.
    appear to be more personal opinion rather than fact.

    Instead of random google hits, we can always try an appeal to authority. According to Stroustrup:
    information hiding - placing information where it can be accessed only through a well-defined interface
    encapsulation
    - the enforcement of abstraction by mechanisms that prevent access to implementation details of an object or a group of objects except through a well-defined interface. C++ enforces encapsulation of private and proteced members of a class as long as users do not violate the type system using casts.

    Except I don't think that clarifies anything and leaves the debate open
    When I invented the Web, I didn't have to ask anyone's permission.
    ~Tim Berners-Lee on Net Neutrality
    -------------------------------------
    Visit the Ubuntu Programming IRC-channel at #ubuntu-programming (chat.freenode.net).

  7. #27
    Join Date
    Nov 2004
    Beans
    2,614

    Re: c++ while loop versus For loop

    Quote Originally Posted by hod139
    Now, I don't expect you to read these articles (I only glanced); my point is that the while you feel the terms are synonymous, others (including it appears StickGuy who can correct me if I'm wrong) don't.
    And if their definitions are like the Javaworld one, then they're wrong for the same reasons. You need to make a meaingful distinction, he failed to do so.

    The first article I linked sums it up pretty nice:
    Which gives different terms to both of them. And it clearly defines encapsulation as a form of information hiding, because reducing dependencies is hiding information.

    It leaves room for more generalized information hiding, which I suppose I could accept, except that I believe it could be shown that all information hiding in code is dependency reduction. Which would make the statements equivocial.

    Except I don't think that clarifies anything and leaves the debate open
    The definition clearly includes non-friend, non-member functions as part of the interface. Stroustrup is clearly talking about more than just public class members.

  8. #28
    Join Date
    Jul 2005
    Beans
    1,535
    Distro
    Ubuntu 8.04 Hardy Heron

    Re: c++ while loop versus For loop

    Quote Originally Posted by Harleen
    But I'm really interested in the comparison between the for and while loop, when you apply this change to them.
    Sorry for taking so long to make the changes and post an update. Anyways, I made the changes to the multiply methods and also attempted to eliminate any caching/paging optimizations by declaring 2 new matrices before each multiply and deleting them afterwards.

    The 2 versions of the matrix multiply now look like:
    Code:
    Matrix<T> mult_FOR(const Matrix<T>& rhs) const{
        assert(nCol_ == rhs.size1() );    
        const size_t rhs_size2 = rhs.size2(); 
        Matrix<T> theMatrix(nRow_, rhs_size2); 
        size_t dataOffset = 0;  
        T *val;
        for (int r=0; r < nRow_; ++r) {
           for (int c=0 ; c < rhs_size2; ++c) {
              T& x = theMatrix(r, c);
              val = &data_[dataOffset];  
              for (int i=0; i < nCol_; ++i) {
               x += (*val++) * rhs(i,c);
             }
          }
          dataOffset += nCol_;
       }
       return theMatrix;
    }
    
    Matrix<T> mult_WHILE(const Matrix<T>& rhs) const{
        assert(nCol_ == rhs.size1() );
        size_t rhs_size2 = rhs.size2();
        Matrix<T> theMatrix(nRow_, rhs_size2);
        T *val;   
        int r, c, i;
        r = nRow_ -1;
        int dataOffset = nCol_*r + nCol_ -1;  
        do{
          c = rhs_size2 -1;
          do{
             T& x = theMatrix(r, c);
             val = &data_[dataOffset];  
             i = nCol_ -1;
             do{    
                x += (*val--) * rhs(i,c);
                --i;
             } while(i >= 0);
          --c;
          } while (c >= 0);
          dataOffset -= nCol_;
          --r;
        } while(r >=0);
        return theMatrix;
    }
    The for loop doing the timing/testing looks like this now:
    Code:
    for(int i = 0; i < N; ++i){
       Matrix<double> *M1 = new Matrix<double>(n1, n2);
       Matrix<double> *M2 = new Matrix<double>(n2, n3);  
       start = clock();
       M1->mult_WHILE(*M2);
       finish = clock();
       time = ((double)(finish - start))/CLOCKS_PER_SEC;
       ave_time_WHILE += time;
       delete M1;
       delete M2;
       
       Matrix<double> *M3 = new Matrix<double>(n1, n2);
       Matrix<double> *M4 = new Matrix<double>(n2, n3);    
       start = clock();
       M3->mult_FOR(*M4);
       finish = clock();
       time = ((double)(finish - start))/CLOCKS_PER_SEC;
       ave_time_FOR += time;
       delete M3;
       delete M4;
    }
    The newing and deleting seems to remove the speed ups from caching and paging, and now the methods appear to run about the same.

    And for the results:
    Code:
     ./a.out
    Average time for mult_WHILE (seconds): 1.4265
    Average time for mult_FOR (seconds): 1.384
    Or, if you feel like bigger matrices and waiting forever for a result:
    Code:
    Average time for mult_WHILE (seconds): 10.272
    Average time for mult_FOR (seconds): 10.2855
    In either case, it seems without the performance boosts from the caching, both methods appear to take just as long now. The entire code is attached here:Post3.txt
    When I invented the Web, I didn't have to ask anyone's permission.
    ~Tim Berners-Lee on Net Neutrality
    -------------------------------------
    Visit the Ubuntu Programming IRC-channel at #ubuntu-programming (chat.freenode.net).

Page 3 of 3 FirstFirst 123

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •