Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor Parameters vs Method Parameters? [closed]

Tags:

c#

A very simple question really and I expect an answer of 'circumstance dictates'. I was wondering however what people's thoughts are on passing parameters to a constructor or a method.

I'll try and set a context for my question:

public interface ICopier {    void Copy(); }  public class FileCopier : ICopier {    String m_source;    String m_destiniation;     FileCopier(String source_, String destination_)    {         m_source = source_;         m_destiniation = destiniation_;    }     public void Copy()    {         File.Copy(m_source, m_destiniation, true);    } } 

Or should FileCopier.Copy() accept source_ and destination_ as method parameters?

I want to keep these classes as abstract as possible.

I'm asking this question as I now have other interfaces/classes for Deleting, Renaming and so on, and I want to create a standard for doing this.

Thanks!

like image 254
adamwtiko Avatar asked Dec 06 '10 14:12

adamwtiko


People also ask

What parameters are required to be passed to a class constructor?

This method has four parameters: the loan amount, the interest rate, the future value and the number of periods. The first three are double-precision floating point numbers, and the fourth is an integer.

Should constructor parameters be final?

You dont need to define them final however if you use them parameters in inner class it is forbidden pass parameters without final.

How many parameters can a constructor have in C#?

A constructor having at least one parameter is called as parameterized constructor. It can initialize each instance of the class to different values. Example : C#

What is the purpose of constructor parameters?

Copy constructors define the actions performed by the compiler when copying class objects. A Copy constructor has one formal parameter that is the type of the class (the parameter may be a reference to an object). It is used to create a copy of an existing object of the same class.


1 Answers

It depends :)

Basically, object-orientation states that objects should encapsulate data and behavior. When you pass data as constructor parameters, you indicate that this is the data to encapsulate.

On the other hand, when you pass data as parameters, you indicate that this is data that somehow is less coupled to the object. Once you begin to move towards Data Context Interaction (DCI), lots of objects tend more and more to encapsulate behavior rather than data.

At the same time, the book Clean Code also guides us to limit the number of method parameters, towards the ultimate conclusion that a method with no parameters is the best design of all.

So I would tend towards encapsulating the data by passing it as constructor parameters in order to have simple APIs. It would then look much like a Command object.

like image 155
Mark Seemann Avatar answered Sep 20 '22 21:09

Mark Seemann