Where and how to connect to external API in my service class?

In my service class I would like to connect to external API. Where and how should I do it?

1) Inject in constructor ExternalClass and assign to private property. Next in other property in constructor call connect.

public MyClass(ExternalApi externalApi) {     this.externalApi = externalApi;     this.ExternalApiConnect externalApiConnect = externalApi.connect; }      public void firstMethod() {    externalApiConnect.first(); }  public void secondMethod() {    externalApiConnect.second(); } 

2) Outside constructor, so if I build dependencies in DI, then I don’t call connection to external service.

private ExternalApiConnect externalApiConnect;  public MyClass(ExternalApi externalApi) {     this.externalApi = externalApi;  }      public void firstMethod() {    if (externalApiConnect == null) {         externalApiConnect = externalApi.connect;    }    externalApiConnect.first(); }  public void secondMethod() {    if (externalApiConnect == null) {         externalApiConnect = externalApi.connect;    }    externalApiConnect.second(); } 

But now I have two repetitions and I have state in my service class. I don’t think the state should be in service class?

How is the best way for this?

C++ Wrapper Class to Mimic The Behavoir of a C Array’s Initialization

I have an inheritance class that mimic the behavior of C style array’s initialization by using a class template that has a variadic constructor but the template itself is not a variadic template. The base class stores the contents from two flavors of constructors either a Variadic Constructor, or a Variadic Constructor that takes an std::initializer_list as it’s parameter. The base class also contains a size that is inferred by its populated member vector, a function to return its size and an overloaded operator operator()() that will return its internal vector.

The child class inherits this functionality. It only has one member and that is a pointer to <T>. It has the corresponding matching constructors as its parent class, a set of overloaded subscript-indexing operators and a public method to retrieve it’s internal pointer. This class’s internal pointer is set to point to its parent’s internal vector’s data.

As far as I can tell the appears to be bug free to the best of my knowledge and it is producing expected values. Here is what I have so far.


#include <vector> #include <string> #include <sstream> #include <iostream> #include <exception> #include <type_traits> #include <initializer_list> #include <utility>  template<typename T> class ParamPack { protected:     std::vector<T> values_;     size_t size_; public:     template<typename... U>     ParamPack( U... u ) : values_{ static_cast<T>(u)... } {         size_ = values_.size();     }      template<typename ... U>     ParamPack( std::initializer_list<std::is_same<T, U...>( U...)> il ) : values_( il ) {         size_ = values_.size();     }      std::vector<T> operator()() {         return values_;     }      const size_t size() const { return size_; } };  template<typename T> class Array : public ParamPack<T> { private:     T* items_; public:      template<typename... U>     Array( U... u ) : ParamPack<T>::ParamPack( u... ) {         items_ =  this->values_.data();     }      template<typename... U>     Array( std::initializer_list<U...> il ) : ParamPack<T>::ParamPack( il ) {         items_ = this->values_.data();     }      T& operator[]( int idx ) {         return items_[idx];     }      T operator[]( int idx ) const {         return items_[idx];     }      T* data() const { return items_; }  };  int main() {     try {         // Parameter Pack Examples:         // Variadic Constructor { ... }         std::cout << "ParamPack<T> Examples:\n";         std::cout << "Using ParamPack<T>'s Variadic Constructor\n";         ParamPack<int> pp1( 1, 2, 3, 4  );         std::cout << "Size: " << pp1.size() << " | Elements: ";         for( auto& v : pp1() ) {             std::cout << v << " ";         }         std::cout << '\n';               //std::initializer_list<int> il{ 1,2,3,4 };         std::cout << "Using ParamPack<T>'s Initializer List\n";         ParamPack<int> pp2( { 5, 6, 7, 8 } );         std::cout << "Size: " << pp2.size() << " | Elements: ";         for( auto& v : pp2() ) {             std::cout << v << " ";         }         std::cout << "\n\n";          // Array Examples:         // Using  Variadic Constructor         std::cout << "Array<T> Examples:\n";         std::cout << "Using Array<T>'s Variadic Constructor\n";         Array<int> testA( 9, 8, 7, 6 );         for( size_t i = 0; i < testA.size(); i++ ) {             std::cout << testA[i] << " ";         }         std::cout << '\n';          Array<std::string> testB( "Hello", " World" );         for( size_t i = 0; i < testB.size(); i++ ) {             std::cout << testB[i] << " ";         }         std::cout << "\n\n";          // Using Constructor w/ Initializer List         std::cout << "Using Array<T>'s Constructor with Initializer List\n";         Array<int> testC( { 105, 210, 420 } );         for( size_t i = 0; i < testC.size(); i++ ) {             std::cout << testC[i] << " ";         }         std::cout << "\n\n";          // Using Initializer List with =         std::cout << "Using Array<T>'s Initializer List with =\n";         Array<int> a = { 1, 2, 3, 4 };         for( size_t i = 0; i < a.size(); i++ ) {             std::cout << a[i] << " ";         }         std::cout << '\n';                          Array<char> b = { 'a', 'b', 'c', 'd' };         for ( size_t i = 0; i < b.size(); i++ ) {             std::cout << b[i] << " ";         }         std::cout << '\n';          Array<double> c = { 1.2, 3.4, 4.5, 6.7 };         for( size_t i = 0; i < c.size(); i++ ) {             std::cout << c[i] << " ";         }         std::cout << "\n\n";           // Using Initializer List directly         std::cout << "Using Array<T>'s Initalizer List directly\n";         Array<uint32_t> a1{ 3, 6, 9, 12 };         for( size_t i = 0; i < a1.size(); i++ ) {             std::cout << a1[i] << " ";         }         std::cout << "\n\n";          // Using user defined data type         struct Point {             int x_, y_;             Point( int x, int y ) : x_( x ), y_( y ) {}         };         Point p1( 1, 2 ), p2( 3, 4 ), p3( 5, 6 );          // Variadic Constructor         std::cout << "Using Array<T>'s Variadic Consturctor with user data type\n";         Array<Point> d1( p1, p2, p3 );         for( size_t i = 0; i < d1.size(); i++ ) {             std::cout << "(" << d1[i].x_ << "," << d1[i].y_ << ") ";         }         std::cout << '\n';          // Initializer List Construtor (reversed order)         std::cout << "Using Array<T>'s Initializer List Constructor with user data type\n";         Array<Point> d2( { p3, p2, p1 } );         for( size_t i = 0; i < d2.size(); i++ ) {             std::cout << "(" << d2[i].x_ << "," << d2[i].y_ << ") ";         }         std::cout << '\n';          // Initializer List Version = {...} p2 first         std::cout << "Using Array<T>'s  = Initializer List with user data type\n";         Array<Point> d3 = { p2, p1, p3 };         for( size_t i = 0; i < d3.size(); i++ ) {             std::cout << "(" << d3[i].x_ << "," << d3[i].y_ << ") ";         }         std::cout << '\n';          // Initializer List Directly p2 first p1 & p3 swapped         std::cout << "Using Array<T>'s Initializer List directly with user data type\n";         Array<Point> d4{ p2, p3, p1 };         for( size_t i = 0; i < d4.size(); i++ ) {             std::cout << "(" << d4[i].x_ << "," << d4[i].y_ << ") ";         }         std::cout << "\n\n";                  // Need a local copy of the vector instead?         std::cout << "Using Array<T>'s base class's operator()() to retrieve vector\n";         std::vector<Point> points = d4(); // using operator()()         for( auto& p : points ) {             std::cout << "(" << p.x_ << "," << p.y_ << ") ";         }         std::cout << '\n';          // Need a local copy of the pointer instead?         std::cout << "Using Array<T>'s data() to get the contents of its internal pointer\n";         Point* pPoint = nullptr;         pPoint = d4.data();         for( size_t i = 0; i < d4.size(); i++ ) {             std::cout << "(" << pPoint[i].x_ << "," << pPoint[i].y_ << ") ";         }         std::cout << '\n';          // Will Not Compile: Must Be Instantiated By Type Explicitly         // Array e( 1, 2, 3, 4 );         // Array e( { 1,2,3,4 } );         // Array f{ 1, 2, 3, 4 };         // Array g = { 1,2,3,4 };          } catch( const std::runtime_error& e ) {         std::cerr << e.what() << '\n';         return EXIT_FAILURE;     }      return EXIT_SUCCESS; } 

-Output-

ParamPack<T> Examples: Using ParamPack<T>'s Variadic Constructor Size: 4 | Elements: 1 2 3 4 Using ParamPack<T>'s Initializer List Size: 5 | Elements: 5 6 7 8   Array<T> Examples: Using Array<T>'s Variadic Constructor 9 8 7 6 Hello World  Using Array<T>'s Constructor with Initializer List 105 210 420  Using Array<T>'s Initializer List with = 1 2 3 4 a b c d 1.2 3.4 5.6 7.8  Using Array<T>'s Initializer List directly 3 6 9 12  Using Array<T>'s Variadic Constructor with user data type (1,2) (3,4) (5,6) Using Array<T>'s Initializer List Constructor with user data type (5,6) (3,4) (1,2) Using Array<T>'s = Initializer List with user data type (3,4) (1,2) (5,6) Using Array<T>'s Initializer List directly with user data type (3,4) (5,6) (1,2)  Using Array<T>'s base class's operator()() to retrieve vector (3,4) (5,6) (1,2)    Using Array<T>'s data() to get the contents of its internal pointer (3,4) (5,6) (1,2)      

There are few things I’d like to know about this code: The main concerns are more towards the classes themselves than the actual code use within the main function. However, suggestions towards the use of the class are accepted as well.

  • Does this follow modern best practices? Note: I know I can encapsulate it in an namespace but for simplicity I just posted the classes themselves
    • If not what changes or fixes need to be made?
  • Is it considered readable enough?
  • Is the code efficient?
    • What can be done to improve its efficiency?
  • Are there an unforeseen bugs or gotchas that I overlooked?
  • Is this considered portable, reusable, and generic?
  • Will the derived class invoke the appropriate constructor or will it just fall back to one of them?

Minimalistic, self-contained class for reading a sectionless INI file

When sections are ignored and no writing capability is needed, an INI reader becomes quite simple to implement. Here is my attempt at reading a sectionless INI file without any non-std dependencies.

The general idea is to store all keyvalue pairs in a <string, string> map, and use getters to convert the value string to desired type on demand.

#include <fstream> #include <iostream> #include <map> #include <string>  class SectionlessINIReader {  private:     std::map<std::string, std::string> dict;  public:      // https://stackoverflow.com/a/1798170/3516684     static std::string trim(const std::string& str,                  const std::string& whitespace = " \t")     {         const auto strBegin = str.find_first_not_of(whitespace);         if (strBegin == std::string::npos)             return ""; // no content          const auto strEnd = str.find_last_not_of(whitespace);         const auto strRange = strEnd - strBegin + 1;          return str.substr(strBegin, strRange);     }      SectionlessINIReader(const std::string& filename) {          std::ifstream file(filename);         std::string line;         int idxEq;         while (std::getline(file, line))         {              if ((line.find_first_not_of(";#")==0) &&                 ((idxEq = line.find("=")) != std::string::npos)) {                      std::string key = trim(line.substr(0,idxEq));                     std::string value = trim(line.substr(idxEq+1));                      dict[key] = value;                 }         }     }      std::string get(std::string key) {         return dict[key];     }      bool getLong(std::string key, long* p_value) {          std::string value = dict[key];          if (value=="") {             return false;          } else {             *p_value = std::strtol(dict[key].c_str);             return true;         }     }      // bool getDouble(...)  }; 

Using add_filter inside another class

I’m building a plugin which generates custom css, I have 2 classes:

  1. The main class, with core functions
  2. The compiler class

as following (I simplify everything, because there is a lot of options):

class compiler  {    public function __construct(){       $  this->generateCss();       $  this->enqueueCss();       //other functions    }    public function generateCss(){       //this is the filter       $  css = apply_filters('dynamic_css', '.your_code{}');       $  content = $  css;       //the rest of the function which generates and upload the file    }    //other functions to enqueue the generated file }  $  compiler = new compiler();  class my_class {    public function __construct() {       //blablabla       $  this->pluginSetup();    }    public function pluginSetup(){       //other functions to save css in option "custom css"       add_action('admin_init', array($  this, 'set_css'));    }    public function set_css(){       add_filter( 'dynamic_css', array( $  this, 'load_custom_css' ));    }    public function load_custom_css(){       //css has been inserted in option "custom css" through omitted functions       $  css = get_option("custom_css");       return $  css;    } } $  my_class = new my_class(); 

The file is generated and enqueued correctly, but the filter dynamic_css doesn’t work and I only get the default value of .your_code{}.

The code in option("custom_css") exists and is valid on var_dump().

I want to keep separated these 2 classes and I cannot find a solution, I tried to change the order of initialisation without success.

Better way of access the stateful variables objects in the given class hierarchy

I asked this question already at stackoverflow together with a serialization related part. Since the design related part receives no answers or comments I’d like to have a review on this here.

The problem: I have a complicated class hierarchy in which the classes are similar to each other but every class contains a bunch of more or less complicated stateful variables. To give you an impression, please have a look at this minimal working example:

class OptVar:     """     Complicated stateful variable     """     def __init__(self, name="", **kwargs):         self.name = name         self.parameters = kwargs   class OptVarContainer:     """     Class which contains several OptVar objects and nested OptVarContainer     classes. Is responsible for OptVar management of its sub-OptVarContainers     with their respective OptVar objects.     """     def __init__(self, name="", **kwargs):         self.name = name         for (key, value_dict) in kwargs.items():             setattr(self, key, OptVar(name=key, **value_dict))      def getAllOptVars(self):          def addOptVarToDict(var,                             dictOfOptVars={},                             idlist=[],                             reducedkeystring=""):             """             Accumulates optimizable variables in var and its linked objects.             Ignores ring-links and double links.              @param var: object to evaluate (object)             @param dictOfOptVars: optimizable variables found so far (dict of dict of objects)             @param idlist: ids of objects already evaluated (list of int)             @param reducedkeystring: to generate the dict key (string)             """              if id(var) not in idlist:                 idlist.append(id(var))                  if isinstance(var, OptVarContainer):                     for (k, v) in var.__dict__.items():                         newredkeystring = reducedkeystring + var.name + "."                         dictOfOptVars, idlist = addOptVarToDict(v,                                                                 dictOfOptVars,                                                                 idlist,                                                                 newredkeystring)                  elif isinstance(var, OptVar):                     newreducedkeystring = reducedkeystring + var.name                     dictOfOptVars[newreducedkeystring] = var              return dictOfOptVars, idlist          (dict_opt_vars, idlist) = addOptVarToDict(self, keystring="")         return dict_opt_vars    class C(OptVarContainer):     """     Specific implementation of class OptVarContainer     """     def __init__(self, name=""):         super(C, self).__init__(name=name,                 **{"my_c_a": {"c1": 1, "c2": 2},                    "my_c_b": {"c3": 3, "c4": 4}})   class B(OptVarContainer):     """     Specific implementation of class OptVarContainer     """     def __init__(self, name=""):         super(B, self).__init__(name=name, **{"b": {"1": 1, "2": 2}})         self.c_obj = C(name="cname")   class A(OptVarContainer):     """     Specific implementation of class OptVarContainer     """     def __init__(self, name=""):         super(A, self).__init__(name=name,                 **{"a1": {"1": 1, "2": 2},                    "a2": {"a": "a", "b": "b"}})         self.b_obj = B(name="bname")   def main():     # creating OptVarContainer with some nested OptVarContainers.     my_a_obj = A(name="aname")      # It is intended behaviour to access the OptVar objects via     # scoping within the class hierarchy.     print(my_a_obj.b_obj.b.parameters)     my_a_obj.b_obj.b.parameters["2"] = 3     print(my_a_obj.b_obj.b.parameters)     print(my_a_obj.b_obj.c_obj.my_c_a.parameters["c1"])     my_a_obj.b_obj.c_obj.my_c_a.parameters["c1"] = 6     print(my_a_obj.b_obj.c_obj.my_c_a.parameters)      # This construction is quite ugly:     # a) due to the dict: order is not fixed     # b) due to recursion (and maybe lexical sorting) it is not fast     # c) goal: hand over these optvars into some numerical optimization     # via a numpy array => should be fast     optvarsdict = my_a_obj.getAllOptVars()     print(optvarsdict)   if __name__ == "__main__":     main() 

The question is now: How to access the OptVar objects the best. I already thought about to use some kind of pool object and use some proxy within the class hierarchy to have a link to the pool. This pool should not be a singleton, since it should be possible to manage more than one pool at a time. Up to now the access to the OptVar variables within my own code is done via the getAllOptVars function. This is quite ugly and only considered temporary. Is there a better alternative to this function?

To summarize and clarify my goals:

  1. The class hierarchy is ok and reflects the model context of our problem
  2. The OptVars belong to each object in the hierarchy and should also stay there also due to model context
  3. The access and post processing of the OptVars (i.e. collecting them from the hierarchy and handing them over to an optimizer as a numpy array) is not considered to be optimal. There I need some suggestions on doing better (i.e. getting rid of isinstance and id queries).
  4. A nice to have would be: Decouple serialization of the OptVars and version management from the object hierarchy

I am aware that no unique solutions exist for this design problem, but I need further input on that.

The full context of this question is given here but after some discussions I separated the design part.

Mapping Data Transfer Objects to my Model Class

//This represents my rows in my database public class PersonModel {     public int Id{get;set;}     public string FirstName{get;set;}     public string LastName{get;set;}     public DateTime CreatedBy{get;set;}  }   //This is what the client receives public class PersonDto {     public int Id{get;set;}     public string FirstName { get; set; }     public string LastName { get; set; }     }  //I have this DTO for other Views that  //I only need to show FirstName  public class PersonFirstNameOnlyDto {     public int Id {get;set;}     public string FirstName{get;set;}    }  public class Person {     IPerson person;     public Person(IPerson person)     {         this.person=person;     }     public void SavePerson(PersonDto person)     {         this.person.SavePerson(person);      } }   public interface IPerson {      void SavePerson(PersonDto person); } 

When saving a Person, I need to pass in PersonDTO to the SavePerson method but how if i want to pass the PersonFirstNameOnlyDto?. What I have in mind is to convert the PersonFirstNameOnlyDto into PersonDto(I can use AutoMapper here) or add another method to the Person class that accepts a PersonFirstNameOnlyDto. I am just thinking if there’s a better way to do this, maybe using Generics but I really don’t know how I can achieve it.

Regards