How to reduce the implementation code of lots of wrapper classes?

use of wrapper class in java
wrapper class methods in java
list all wrapper classes in java
advantage of wrapper class in java
custom wrapper class in java
wrapper class for short in java
wrapper class in java javatpoint
wrapper class c#

I am developing a library with some classes, let's call them C1, C2 and ... Cn. Each of these classes realize some interfaces, i.e. I1, I2, ... Im. (n > m). The relationship between objects in the library is complex and I have to provide some API for my library users to access these objects using smart pointers.

After some discussions, I found that returning shared pointers to the library users is not a good idea, because in that case I cannot make sure that the object can be removed precisely in my library's memory. Returning weak pointers have the same issue, because if the user of the API .lock()s the weak pointer and keep the resulted shared pointer somewhere, I will face the same problem again.

The final idea I have, is to expose some kind of wrappers for the weak pointers. A wrapper class can be something like this:

class Wrapper_C1 : public I1
{
   std::weak_ptr<C1> mC1;
public:
   Wrapper_C1() = delete;
   Wrapper_C1(const std::weak_ptr<C1> & c1) : mC1(c1)
   {
   }

   int method1_C1(int x)
   {
       if (auto sp = mC1.lock())
       {
           sp->method1_C1(x);
       }
       else
       {
            throw std::runtime_error("object C1 is not loaded in the lib.");
       }
   }

   void method2_C1(double y)
   {
       if (auto sp = mC1.lock())
       {
           sp->method2_C1(y);
       }
       else
       {
            throw std::runtime_error("object C1 is not loaded in the lib.");
       }
   }

   // The same for other methods
};

As you see, all of this wrapper classes, share the same implementation. What is the best way to reduce the code of ALL of these wrapper classes? Is there anyway to avoid repeating the similar codes?

If you drop inheritance in the wrapper, you might do something like the following to factorize all wrappers:

template <typename T>
class Wrapper
{
private:
   std::weak_ptr<T> m;
public:
   Wrapper() = delete;
   Wrapper(const std::weak_ptr<T> & w) : m(w) {}

   auto operator -> () /* const */
   {
       if (auto sp = m.lock())
       {
           return sp;
       }
       else
       {
            throw std::runtime_error("object is not loaded in the lib.");
       }
   }
};

How do I avoid writing lots of pass-through functions in a wrapper , Is any of the three types (Car, Trailer, CarWithTrailer) in an area of the code that developers go into while reducing the consequences of coupling to the CarWithTrailerWrapper, since you can do way more with just that one implementation. Think of property delegates in Kotlin as a language feature that helps reduce duplicated code in custom property getters and setters. So instead of writing a lot of code at first glance, but

The best you can do without resorting to macros (which also wouldn't help here, to fully resolve your problem we would need some kind of static reflection) is fix these repetitions:

if (auto sp = mC1.lock())
{
    sp->method1_C1();
}
else
{
     throw std::Exception("object C1 is not loaded in the lib.");
}

What I see you can easily reduce it to template function like this one:

template<class T, class R, class... Args>
R call_or_throw(const std::weak_ptr<T>& ptr, const std::string& error, R (T::*fun)(Args...), Args... args) {
    if (auto sp = ptr.lock()) 
    {
        return std::invoke(fun, *sp, args...);
    }
    else 
    {
        throw std::runtime_error(error.c_str());
    }
}

Than you can use it like that:

int method1_C1(int x)
{
    return call_or_throw(mC1, "object C1 is not loaded in the lib.", &C1::method1_C1, x);
}

void method2_C1(double y)
{
    return call_or_throw(mC1, "object C1 is not loaded in the lib.", &C1::method2_C1, y);
}

You can even make macro out of it

Java Wrapper Classes, Each of eight primitive of java data types has a class dedicated to it, are known as The wrapper classes are part of the java.lang package, which is imported by For example to create Integer object we can have the following syntax. Returns a negative value if the invoking object has a lower value. Importance of Wrapper classes There are mainly two uses with wrapper classes. 1) To convert simple data types into objects, that is, to give object form to a data type; here constructors are used. 2) To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used. Features of the Java wrapper Classes.

Using smart-pointers for tree/graph nodes is less than ideal. The tree node destructors destroy the smart-pointers to child nodes and those in turn call child node destructors resulting in recursion which may overflow the stack when the trees are deep or available stack size is small.

An alternative design is to have a tree class that manages the lifetime of its nodes and uses plain pointers, a-la std::map. And have a rule that removing a node invalidates pointers and references to the removed sub-tree.

Such a design is simple, robust and most efficient at run-time.

Java Wrapper Classes Internal Caching, To avoid this expensive object creation process, many of the frameworks JDK provided wrapper classes also provide this in form of instance pooling i.e. type in form of cache and whenever required, you can use them in your code. It helps in saving lots of byes in your program runtime. here example are very useful I’ve seen a lot of developers forget one particular edge case. Let’s say we have a wrapper with max-width set to 980px. The edge case appears when the user’s device screen width is exactly 980px. The content then will exactly glue to the edges of the screen with no breathing room left.

NET: A Complete Development Cycle, It's a good practice to write a wrapper class for these DLL functions that and to reduce the likelihood of bugs and resource or memory leaks, we implement a NET Framework enforces the rule that all code dealing directly with pointers must not support multiple Listing 9.6 OGL3DText.cs: Class Member Implementation​  To future-proof new codebases from this kind of scenario, I often consider (and sometimes implement) a wrapper class to encapsulate the logging functionality and make it easier, though not foolproof, to alter the way in which logging works in future with minimal change; the code calls the wrapper, the wrapper passes the call to the logging

Hadoop Real-World Solutions Cookbook, We know that when we execute the map reduce code, a lot of data gets transferred over the network when this shuffle takes place. Sometimes, the size of the  To get the minimum or maximum value of a primitive data types such as byte, short, int, long, float and double we can use the wrapper class provided for each of them, the wrapper classes are Byte, Short, Integer, Long, Float and Double which is located in java.lang package.

Hadoop: Data Processing and Modelling, We know that when we execute the map reduce code, a lot of data gets transferred map reduce programmer, Hadoop has introduced a set of box/​wrapper classes such Implementing. a. user-defined. counter. in. a. Map. Reduce. program. The roles and profiles method separates your code into three levels: Component modules — Normal modules that manage one particular technology, for example puppetlabs/apache. Profiles — Wrapper classes that use multiple component modules to configure a layered technology stack.

Comments
  • Do you mean 'refactor'?
  • @dandan78 No, I edited the post title.
  • Meta-programming ( interface names can be static) or Bridge Design Pattern should be good.
  • @seccpur Any examples?
  • @Gupta this might be possible with __declspec(propety .... this can allow a getter (checkout) and setter (checkin) while still making '.' syntax possible - this would need clang or msvc at least
  • I must admit this is even better than mine ;)
  • Wow, looks great.
  • shared_ptr<int> stolen; void func(Wrapper<int> ptr) { stolen = ptr.operator->(); }
  • @firda: Try to guard against Murphy, not Machiavelli :-).
  • Looks good, Thanks. It seems that realization of ALL of the methods is unavoidable, right?
  • @Gupta yes, it is impossible to autogenerate methods according to some scheme. As I said, you need either static reflection in cpp or static code generator
  • I created a large binary tree on my machine with 24 levels and 1.67772e+07 nodes, each node contains two shared pointers. This is the biggest tree I can create on my laptop, because with 25 level it cannot allocate memory for shared pointers. While destruction, a takes some time but it does not overflow the stack. The reason is clear, because I will not have more than 24 activation records on top of the stack for calling nested destructors.
  • @Gupta With a balanced tree you may get away with that.
  • But you are right, if the depth of my tree goes over 750 (for an unbalanced tree), I will have an stack overflow while destruction. Nice point. Thanks ;)