Propper way of handeling large Dependency Injected Constructors

I have many dataservices/classes injected into a constructor.

public MyClassConstructor (IAclass A, IBclass B, .... , IZclass Z){     ... } 

The number I have to pass down goes well beyond 100. To solve this I created a Injected class that contains all the DataServices. Making it more streamline:

public MyClassConstructor (IDataServices dataServices){...} 

This works well, but is unfortunately an anti-pattern. When testing I need to manually instantiate all the classes even if just a single one is needed (for all functions). As an alternative I created Interfaces to be passed down for only classes that are needed.

public MyClassConstructor (IMainInterface mainInterface) {     A = new A(mainInterface);     B = new B(mainInterface); }  public AClassContructor (IAInterface) {...}  public BClassContructor (IBInterface) {...} 

This Resolves the previous two issues, but creates a new one where I am sitting with 100s of different Interface Classes.

Which one of these are is the best approach, and are there any more efficient/better ways to handle this problem?

Should I do a runtime type check inside generic constructors?

Given this generic class and constructor,

class A<E extends Number> {      A(E number, Comparable<E> comparable) {         //...     } } 

it is ensured that a call to the generic constructor will check the arguments’ types at compile time:

new A<>(Integer.valueOf(4), Integer.valueOf(4)); // ok new A<>(Integer.valueOf(4), Long.valueOf(4)); // error: Cannot infer type arguments for A<> 

(of course, even explicitly stating the parametrized type instead of letting the compiler infer the type gives the same end result because the relation cannot be satisfied).

However, the raw constructor allows both calls to compile:

new A(Integer.valueOf(4), Integer.valueOf(4)); new A(Integer.valueOf(4), Long.valueOf(4)); 

with the warning on both invocations:

Type safety: The constructor A(Number, Comparable) belongs to the raw type A. References to generic type A<E> should be parameterized 

My question is, should the constructor perform type checks (e.g., instanceof, isAssignableFrom or isInstance) in its body to ensure that the class is not created in an invalid state in case the raw constructor is called?
These type checks are completely redundant if the constructor call is parametrized. Is the compiler warning about type safety a good enough excuse to not do these checks?

Spring Boot – What is the purpose of Autowired Constructors?

I’ve been developing in Spring Boot for just over a year but have yet to understand the benefits of using an Autowired constructor and I was wondering if someone could explain this to me and what would be considered best practice.

Let’s say I have a bean as follows

@Component public class MyBean {      void doSomeStuff() {     }  } 

And I have a service that has a dependency on that bean

@Service public class MyServiceImpl implements MyService {      private MyBean myBean;  } 

To me, the simplest way of injecting the dependency in this class would be to simply annotate the variable with @Autowired

@Service public class MyServiceImpl implements MyService {      @Autowired     private MyBean myBean;  } 

But there are other places online (and also other developers on my team) who favour something like this approach:

@Service public class MyServiceImpl implements MyService {      private MyBean myBean;      @Autowired     public MyServiceImpl(MyBean myBean) {         this.myBean = myBean;     }  } 

To me, using a constructor like that is simply redundant code. Autowiring the bean is much simpler and straightforward than what appears to me to be boilerplate code.

The type ‘Microsoft.SharePoint.SPUserCollection’ has no constructors defined

I need to get users within SPFieldUserValueCollection and set them inside SPUserCollection, but I have the following build error:

The type ‘Microsoft.SharePoint.SPUserCollection’ has no constructors defined

 SPFieldUserValueCollection employees = item["employees"] as SPFieldUserValueCollection;             SPUserCollection users = new SPUserCollection();              if (values != null)             {                 foreach (SPFieldUserValue userValue in employees)                 {                     users.Add(userValue.User.LoginName, userValue.User.Email, userValue.User.Name, userValue.User.Notes);                 }                  return users;             } 

How I can initialize SPUserCollection?

Interface does not have constructors Kotlin Recyclerview Interface error

Am trying to convert some java code to Kotlin and am getting interface does not have constructors on RecyclerItemClickListener.OnItemClickListener

The action part on Mainactivity

  rv!!.addOnItemTouchListener(RecyclerItemClickListener(applicationContext,                 RecyclerItemClickListener.OnItemClickListener { view: View, position: Int ->                     viewPager.currentItem = position                     addBackFeed()                     try {                         //  toolbar.setTitle(tabButtonAdapter.getTabs().get(position).getTitle());                         title_toolbar!!.text = tabButtonAdapter!!.tabs[position].title                         if (tabButtonAdapter!!.tabs[position].title == "Buy") {                             bottomBar!!.visibility = View.VISIBLE                          } else {                             bottomBar!!.visibility = View.GONE                          }                     } catch (e: JSONException) {                         e.printStackTrace()                         //    toolbar.setTitle(titleApp);                         title_toolbar!!.text = titleApp                     }                      rv!!.visibility = View.GONE                     //;                      toggle!!.isDrawerIndicatorEnabled = false                 }))          tabButtonAdapter!!.notifyDataSetChanged()         rv!!.scheduleLayoutAnimation()      } 

The RecyclerItemClickListener class is

 class RecyclerItemClickListener(context: Context, private val mListener: OnItemClickListener?) : RecyclerView.OnItemTouchListener {      internal var mGestureDetector: GestureDetector      override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {      }      interface OnItemClickListener {         fun onItemClick(view: View, position: Int)     }      init {         mGestureDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {             override fun onSingleTapUp(e: MotionEvent): Boolean {                 return true             }         })     }      override fun onInterceptTouchEvent(view: RecyclerView, e: MotionEvent): Boolean {         val childView = view.findChildViewUnder(e.x, e.y)         if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {             mListener.onItemClick(childView, view.getChildPosition(childView))             return true         }         return false     }      override fun onTouchEvent(view: RecyclerView, motionEvent: MotionEvent) {} }  

Am not exactly sure how to sort the error

Should I use the Factory Pattern when instantiating objects with very different constructors?

Let’s say (just for the sake of example) I have three classes that implement IShape. One is a Square with a constructor of Square(int length). Second is a Triangle with a constructor of Triangle(int base, int height). Third is a Circle with a constructor of Circle(double radius).

Considering all the objects share the same interface, my mind goes to the factory pattern as a creational pattern to use. But, the factory method would be awkward as it must provide parameters for these various constructors – for instance:

IShape CreateShape(int length, int base, int height, double radius) {     ...     return new Circle(radius);      ...     return new Triage(base, height);      ...     return new Square(int length); } 

This factory method seems quite awkward. Is this where an abstract factory or some other design pattern comes into play as a superior approach?

Can any one explain how constructors, inheritance and run time polymorphism works ? Also explain logic behind the below output

I undertand the reason behind my output is run time polymorphism. But I am unable to figure it out how ? Please Explain how run time polymorphism, constructors and inheritance are related.

This is JAVA code. I have triend understanding run time polymorphism but I have failed to figure it out.

package df;

class A1 {

A1(){     System.out.println("Constructor A() called");  } void m1() {      System.out.println("Inside A's m1 method");  }  


class B2 extends A1 {

B2(){     System.out.println("Constructor B() called");  }  void m1() {      System.out.println("Inside B's m1 method");  }  


class C3 extends A1 {

C3(){     System.out.println("Constructor C()");  } void m1() {      System.out.println("Inside C's m1 method");  }  


public class Cldf {

// object of type A  public static void main(String[] args) {     A1 a = new B2();   } 


I expected result as below

Constructor B() called.

but result is

Constructor A() called Constructor B() called

Should my classes have separate constructors just for unit testing?

I like to write classes with two constructors: a primary constructor used in production code, and a default constructor just for unit tests. I do this because the the primary constructor creates other concrete dependencies that consume external resources. I can’t do all that in a unit test.

So my classes look like this:

public class DoesSomething : BaseClass {     private Foo _thingINeed;     private Bar _otherThingINeed;     private ExternalResource _another;      public DoesSomething()     {         // Empty constructor for unit tests     }      public DoesSomething(string someUrl, string someThingElse, string blarg)     {          _thingINeed = new Foo(someUrl);          _otherThingINeed = Foo.CreateBar(blarg);          _another = BlargFactory.MakeBlarg(_thingINeed, _otherThingINeed.GetConfigurationValue("important");     } } 

The comment inside the default constructor is real. I started putting that there after someone asked what it was for. I think they already knew what it was for and they were just messing with me.

You’re probably wondering how it’s possible to create and test an instance of the class if it has other dependencies that it needs in production, but my default constructor doesn’t create them.

I mostly work around that by making most of my methods public. The method called from production code calls other public methods, most of which don’t use all of those dependencies. They communicate with each other by storing their results in fields. One method stores its results in a field, and the next method reads them. To make sure all the methods get called in order I call them all from the base class.

That way I can write tests for all those methods separately. I can’t test everything, but this gets me most of the way. We have high standards which include 85% unit test coverage. (“Real” constructors are excluded from code coverage since they can’t be tested.)

Anyway, my question really isn’t about that. I just want to know if it’s a good idea to have a separate constructor for unit tests. I think it’s a great pattern. In fact, I require other developers to copy and paste my classes and use them as a template.

Defer pattern for constructors in C++

In some specific scenarios, I want to run code after the constructor for a class has run (namely: access std::enable_shared_from_this::shared_from_this()).

To solve this without introducing an error prone init method for all classes with this behaviour I have built a generic pattern that allows constructors to “defer” lambdas to run after the constructor has run (example in end of snippet):

// If derived from this subclasses may call enable_defer::defer in their // constructor to run code directly _after_ their constructor has completed // This is useful when for example the constructor wants to access the weak_ptr // from std::enable_shared_from_this in the constructor. // Note naming convention matching std::enable_shared_from_this & underscores to avoid collisions in subclasses class enable_defer {     // Allowed factories     template <typename T>     friend std::shared_ptr<T> make_shared_deferrable();      template <typename T, typename... Args>     friend std::shared_ptr<T> make_shared_deferrable(Args&&... args);      // Allowed implementations     template <typename T>     friend class __impl__;  private:     std::vector<std::function<void()>> defered;     bool constructed = false;      // Only friend classes may have access to this type     // this is because we only want friend classes to be able to implement the interface     class __Tag__ {};      virtual void __constructed__(__Tag__ = __Tag__()) = 0;      // Implementation of enable_defer kept private     // to make sure only friend factories above may     // construct implementations     template <typename T>     class __impl__ : public T     {         static_assert(std::is_base_of<enable_defer, T>::value, "Must be enable_defer");          // Forward base class constructors         using T::T;          virtual void __constructed__(__Tag__) override         {             constructed = true;             for (auto fn : defered)                 fn();         }     };  protected:      void defer(std::function<void()> fn)     {         // Make sure defer is only called in constructor         assert(!constructed);         defered.push_back(fn);     } };  // Create std::shared_ptr from enable_defer template <typename T> std::shared_ptr<T> make_shared_deferrable() {     auto shared(std::shared_ptr<T>(new enable_defer::__impl__<T>()));     shared->__constructed__();     return shared; }  // Create std::shared_ptr from enable_defer template <typename T, typename... Args> std::shared_ptr<T> make_shared_deferrable(Args&&... args) {     auto shared(std::shared_ptr<T>(new enable_defer::__impl__<T>(std::forward<Args>(args)...)));     shared->__constructed__();     return shared; }    class Example : public enable_defer, public std::enable_shared_from_this<Example> { public:      Example()     {         defer([this]() {             shared_from_this(); // Works!         });     }      // Factory     static std::shared_ptr<Example> create()     {         return make_shared_deferrable<Example>();     } }; 


  • Are there better ways to accomplish the enforcements of the implementation class and factories?
  • General improvements
  • Bugs?
  • Naming?
  • General thoughts on this pattern.