S
S
sanphir2016-07-08 17:09:54
Programming
sanphir, 2016-07-08 17:09:54

How to use a constructor correctly?

A holistic question arose with colleagues, how to use the object constructor more correctly?
Option 1:

public class Circle
{
 public Circle()
 {
 }

 public void Draw()
 {
  //draw code
 }
}

class Program
{
 static void Main(string[] args)
 {
  var circle = new Circle();
  circle.Draw();
 }
}

or
Option 2
public class Circle
{
 public Circle()
 {
   this.Draw();
 }

 public void Draw()
 {
  //draw code
 }
}

class Program
{
 static void Main(string[] args)
 {
  var circle = new Circle();  
 }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2016-07-08
@sanphir

The constructor should have one responsibility - to initialize the resources. He must not draw.
So option two is a no-brainer.
If you need to create and draw at the same time, create a static method for this that will create, draw and return an instance.

A
Alexey Ukolov, 2016-07-08
@alexey-m-ukolov

It is more correct to use it as required in a particular situation. If some code needs to be called always when creating an object, it makes more sense to put it in a constructor. If you pass a flag to the constructor that determines whether this or that method will be run internally, this is a signal that you need to either create specialized child classes or call the method after initializing the object by hand, where it is required.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question