-1

To Attention DRY principle, I want to know is true define a function to return instance of class or no!

You suppose we have a class and create instance many times in code, Is it better create instance it any time or define a function and use it?

class Job(name:String, maxPool:Int)
val job = Job("JOB_1",100)
val job2 = Job("JOB_2",100)
val job3 = Job("JOB_3",200)

or define a function

fun newJob(name:String = "NEW_JOB", maxPool:Int = 100) : Job{
   Job(name, maxPool)
}
val job = newJob()
val job2 = newJob("JOB_2")
val job3 = newJob("JOB_3")

ImanX
  • 789
  • 6
  • 23

1 Answers1

1

What you have there is a factory function.  And because it's closely coupled to the class, it's best to keep it in (or near) the class; that way it's easier to find, less likely to get out-of-date, etc.

  • If the function isn't doing any significant processing before creating the instance, just call the constructor directly (as per your first example).

  • Or if the function is merely inserting a constant value for some parameters, then give the constructor those default argument values.

  • Or if the function is converting parameters to different types, or other simple processing, then use a secondary constructor which does the conversion before calling the primary constructor.

  • Or if the function is doing more complex processing, then put the factory function in the class's companion object.  (If you call it operator fun invoke(), then it will look like a constructor call — though it's only worth doing that if the parameter types make its meaning obvious; otherwise, give it a meaningful name.)

  • Only if the function is doing some processing that doesn't belong in the class at all — e.g. it's implementing some business logic that the class doesn't need to know about — is it worth having a separate factory function as in your second example.

gidds
  • 16,558
  • 2
  • 19
  • 26