Frostfyre
Frostfyre

Reputation: 201

Which is better: explicit or typeless get()?

Suppose the following two versions of the same class A:

Version 1

class A
{
   public:
      enum class Retrievable { Integer, String };

      A(): m_integer(123), m_string("string") {}
      ~A() {}

      void* get(const Retrievable r)
      {
         switch (r)
         {
            case Retrievable::Integer:
               return static_cast<void*>(&m_integer);
            case Retrievable::String:
               return static_cast<void*>(&m_string);
            default:
               throw;
         }
      }

   private:
      int m_integer;
      std::string m_string;
};

Version 2

class A
{
   public:
      A(): m_integer(123), m_string("string") {}
      ~A() {}

      int getInteger()        { return m_integer; }
      std::string getString() { return m_string;  }

   private:
      int m_integer;
      std::string m_string;
};

In terms of clarity, efficiency, and extensibility, which of these two paradigms -- a single typeless get() function or separate explicit get() functions -- is better?

Upvotes: 1

Views: 70

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275760

Option 1 casts things to void* and does run time dispatching, such is slower and less safe and harder to use.

Barring interacting with a scripting engine, I cannot imagine a reason to use option 1. And even then there are many better ways to handle it. An interviewee who proposed option 1 as even an alternative choice to option 2 would be a strong do not hire, and it would make me reconsider the funnel that got the interviewee this far.

In short, option 2 is better.

Upvotes: 3

David Haim
David Haim

Reputation: 26506

Version A will not compile anyway, because regardless of C you will try to return type which is not C (pointer where C is string etc.)

Version B is maybe better, but also quit crooked. unless you are building some polymorphic type like JSON node or something, the function should describe behaviour, not return type.

again, unless you are writing some JSON class, I don't see much sense of making a function which describe return type rather than behaviour. a Person doesn't have getHand or getLeg functions, he has functions like wave, walk etc.

performace? I doubt that a getter will screw the performance of your application.

Upvotes: 1

Related Questions