A method using different tastes of his own private members

class A{ private: std::vector<class X> flavor1 std::vector<class X> flavor2 public: void useVectorOfX(std::vector<class X> someflavor){ ... // same logic for both flavors } } 

Now I want to call useVectorOfX() from another class, giving it either flavor1 or flavor2 depending on the need. I can think of three ways -

Method 1: use Getter methods; but for class A it seems unnatural to get its own data through the Getter method.

 class B{ public: A *a = new A(); a->useVectorOfX(a->getFlavor1()); } 

Method 2: Make two vectors public (dirty)

Method 3: Separate methods?

 class B{ public: A *a = new A(); a->useVectorOfXForFlavor1(); a->useVectorOfXForFlavor2(); } 
+4
source share
5 answers

How about path 1 in a more descriptive format:

 class A { public: enum { flavor1 = 0, // used as array index, first element must be zero flavor2, } vector_flavor; static const int number_of_flavors = 2; void useVectorOfX(vector_flavor flav){ std::vector<class X> someflavor& = vectors[flav]; // ... } private: std::vector<class X> vectors[number_of_flavors]; } A object; // lol object.useVectorOfX(A::flavor1); 
+4
source

I would choose option 3. Using

 void useVectorOfXForFlavor1(){ useVectorOfX(flavor1); } 

seems quite reasonable.

+3
source

Sort of:

 std::vector<class X> flavors[2]; ... public: void useVectorOf(int X) { useVectorOf(flavors[X]); } private: void useVectorOf(std::vector<class X> &v) { ...; } 

Using enum rather than a simple int would be nicer.

+1
source

use

 class B{ public: A *a = new A(); a->useVectorOfX(a->getFlavor1()); } 

this is better because you only create one method and you do not defragment class members by the public unnecessarily.

+1
source

You have all the technically correct answers, but the real problem here is the interface design, so I would like to address this.

First, passing the object its own personal data as a parameter, its own method ... well, freaky, to say the least. It seems that you are trying to solve a low-level problem by exposing the user internal information about its implementation and making it depend on any internal changes.

My first question is: "is this useVectorOfX method really designed to work with any vector<X> ?

  • yes : you probably should have 2 methods, doSomething(const vector<X>& clientsData) and doSomething() // using your private data

  • no : second question: "is it ( semantically , from the point of view of the user, not the code), the same operation"?

    • yes : use one method with a modifier according to @nightcracker, for example. doSomething(A::highPrecision)
    • no : use 2 methods according to @Bo. This will allow you to change the internal implementation in a future way that is transparent to the user.
+1
source

All Articles