How to decide parameters of a constructor

Aada :

I have a class with constructor accepting context as a parameter. Using context its deriving other properties.

My question is should I pass those properties as param of a constructor or derive them using Context.

Example:

class A (val context:Context){

  val someOtherClass = SomeOtherClass(context)
  val derivedValue = someOtherClass.deriveValue

}
William Burnham :

You should give the class what it needs to do its job and not more. Derive the parameters the class needs outside of the scope of the class. The constructor's job should be just variable initialization (ideally of private final fields).

If you have a few parameters (someOtherClass, derivedValue) pass those directly to the constructor. If you have lots, instead of the Context object, create your own object such that it's not directly dependent on the context. That way you can mock it relatively easy as needed for testing and it's decoupled from your context object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325273&siteId=1