Questions tagged [constructors]

The tag has no usage guidance.

Filter by
Sorted by
Tagged with
162
votes
9answers
123k views

Why should I use a factory class instead of direct object construction?

I have seen the history of several С# and Java class library projects on GitHub and CodePlex, and I see a trend of switching to factory classes as opposed to direct object instantiation. Why should I ...
48
votes
12answers
5k views

Is there ever a reason to do all an object's work in a constructor?

Let me preface this by saying this is not my code nor my coworkers' code. Years ago when our company was smaller, we had some projects we needed done that we did not have the capacity for, so they ...
37
votes
7answers
12k views

Is using “new” in the constructor always bad?

I have read that using "new" in a constructor (for any other objects than simple value ones) is bad practice as it makes unit testing impossible (as then those collaborators needs to be created too ...
34
votes
9answers
33k views

Constructor parameter validation in C# - Best practices

What is the best practice for constructor parameter validation? Suppose a simple bit of C#: public class MyClass { public MyClass(string text) { if (String.IsNullOrEmpty(text)) ...
33
votes
5answers
20k views

Should I initialize C structs via parameter, or by return value? [closed]

The company I work at is initializing all of their data structures through an initialize function like so: //the structure typedef struct{ int a,b,c; } Foo; //the initialize function ...
30
votes
3answers
2k views

Is a “start”, “run” or “execute” method a good practice?

I'm currently working on a code base that has many classes that implement a Start method. This seems like two-phase construction to me, which I had always considered a bad practice. I can't tell the ...
28
votes
3answers
10k views

Optional parameters or overloaded constructors

I am implementing a DelegateCommand, and when I was about to implement the constructor(s), I came up with the following two design choices: 1: Having multiple overloaded constructors public ...
23
votes
5answers
9k views

Why did it not become a common pattern to use setters in the constructor?

Accessors and modifiers (aka setters and getters) are useful for three main reasons: They restrict access to the variables. For example, a variable could be accessed, but not modified. They ...
23
votes
4answers
4k views

Legitimate “real work” in a constructor?

I am working on a design, but keep hitting a roadblock. I have a particular class (ModelDef) that is essentially the owner of a complex node tree built by parsing an XML schema (think DOM). I want to ...
22
votes
4answers
20k views

C++ - Constructor or Initialize Method to Startup [duplicate]

Possible Duplicate: Avoid having an initialization method I want to determine when to do non-trivial initialization of a class. I see two times to do initialization: constructor and other method. ...
21
votes
5answers
2k views

How can you decompose a constructor?

Lets say I have a Enemy class, and the constructor would look something like: public Enemy(String name, float width, float height, Vector2 position, float speed, int maxHp, int ...
19
votes
3answers
12k views

Constructor with tons of parameters vs builder pattern

It is well know that if your class have a constructor with many parameters, say more than 4, then it is most probably a code smell. You need to reconsider if the class satisfies SRP. But what if we ...
18
votes
3answers
11k views

how complex a constructor should be

I am having a discussion with my co-worker on how much work a constructor can do. I have a class, B that internally requires another object A. Object A is one of a few members that class B needs to do ...
14
votes
1answer
1k views

Is it fine to make a default constructor unusable?

Specifically asking about the default constructor Given that the constructor initializes all the data for an object, if I create a class that can't be used without proper initialization, is it not ...
13
votes
3answers
2k views

How does one keep argument counts low and still keep third party dependencies separate?

I use a third party library. They pass me a POJO that, for our intents and purposes, is probably implemented like this: public class OurData { private String foo; private String bar; private ...
11
votes
2answers
4k views

Unit Test to test the creation of a Domain Object

I have a Unit Test, which looks like this: [Test] public void Should_create_person() { Assert.DoesNotThrow(() => new Person(Guid.NewGuid(), new DateTime(1972, 01, 01)); } I am asserting that ...
11
votes
6answers
24k views

How to write constructors which might fail to properly instantiate an object

Sometimes you need to write a constructor which can fail. For instance, say I want to instantiate an object with a file path, something like obj = new Object("/home/user/foo_file") As long as the ...
10
votes
2answers
592 views

Is it bad to create classes whose sole purpose is to be converted to another class implicitly?

Imagine a situation where we're using a library that allows you to create Circle objects, where you can specify the radius and the center of the circle to define it. However, for some reason, it also ...
10
votes
3answers
8k views

Stubbing Properties with private setters for tests

We have the object public class MyObject{ protected MyObject(){} public string Property1 {get;private set;} public string Property2 {get;private set;} public string Property3 {get;...
9
votes
4answers
2k views

Where should an object in CQRS+ES be fully initialized: in the constructor, or when applying the first event?

There appears to be widespread agreement in the OOP community that the class constructor should not leave an object partly or even fully uninitialized. What do I mean by "initialization"? Roughly ...
8
votes
5answers
53k views

Why is there no default constructor generated if you define an explicit constructor?

class Employee{ String name; int id; //No explicit constructors } Now I can invoke the following statement: Employee e1 = new Employee(); With the above code, the compiler will provide ...
8
votes
4answers
560 views

Checking the result of a constructor in C#

I'm working on a code base with a coworker who has a habit of checking the results of a constructor for a null in a fashion similar to this Person p = new Person(); if (p != null) { p.Name = "...
8
votes
4answers
2k views

Is a “object constructor” a shorter name for a “function with name `object` returning type `object`”?

I mean, it's a matter of choosing words more than there is any difference between function and constructor call. The thing which is named "constructor of an object" can also be named "function with ...
8
votes
1answer
458 views

Is a large static initializer a code smell?

I am extending SimpleExpandableListAdapter in Android. I don't think Android's adapter is implemented very well, in that its constructors have a large number of rather complicated arguments and it has ...
7
votes
4answers
4k views

Is it bad practice to read large file in constructor?

So, I am trying to create an English language trie data structure implementation in C++. I have created a Trie and TrieNode class. The TrieNode class takes in its constructor a vector<string> ...
7
votes
3answers
3k views

How to deal with constructors in large data classes [duplicate]

Several times now I have come across the situations where you have some kind of settings class that simply contains a mass of data. Often these classes are simply not valid without at least most of ...
7
votes
3answers
416 views

Avoiding side effects in immutable class constructor

I rewrote a very long method in which some data is queried from a database, based on info about a particular account, which is queried first. I split out the account info into an immutable inner ...
7
votes
3answers
493 views

Writing a good/readable constructor that needs a lot of calculation to fill its fields

I have a class that has several fields which can only be filled consecutively by a lot of calculation. The 1st field can be set very easily. To fill the 2nd field, we take the 1st field's content and ...
7
votes
4answers
863 views

Can I make my constructors less repetitive?

I'm extending a class with 10 different constructors. The new subclass, SpecialImage, is used like this: SpecialImage specialImage = new SpecialImage(..); // Leverage the Rotate() method of ...
7
votes
1answer
267 views

Is the complexity needed to prevent downcasting from constructor to overridden method worth it?

Invoking non-final instance methods in constructors risks downcasting from a constructor to an overridden method as such: public class Start { public static void main(String[] args) { try ...
6
votes
4answers
5k views

Initializing objects in Constructor

I have below constructor, where it creates a workbook in constructor. I read that, ideally, we should not create objects in Constructor, instead, we should have just assignments which are passed. ...
6
votes
3answers
7k views

Explicitly writing default empty constructor

Does it make sense to write default constructor when it has no arguments, empty body and no other constructors exist? The only benefit I can think of is reducing the risk of forgetting to add the ...
6
votes
2answers
589 views

Design pattern for too many ctor parameters within class hierarchy

Is there some design pattern for handling situation where class hierarchy constructors parameters force the most bottom classes to have too many parameters? Ideally this would be in C++, if language ...
5
votes
6answers
2k views

Should all classes have a default constructor as part of good coding convention

From the texts I have read so far, the conventions talk about organizing constructors, starting with the default, if any. I am wondering, should all classes have a default constructor anyway. This ...
5
votes
5answers
1k views

Should constructors ever be used only for side-effects?

Summary: Why is it wrong to design a constructor only for its side effects, and then to use the constructor without ever assigning its return value to a variable? I'm working on a project that ...
5
votes
3answers
2k views

Is it better to have constructors with or without parameters?

Is it better to have constructors with or without parameters and why? public NewClass( String a, String b, int c) throws IOException { //something } OR public NewClass() { //something }
5
votes
3answers
5k views

Is it okay to start a thread from within a constructor of a class

This is purely a design philosophy question in the context of C++. Is it a okay design philosophy to start a thread from within a constructor? I have a library whose sole responsibility is to ...
5
votes
2answers
475 views

Constructor Injection, Single Responsibility and List initialisation

Given the class: public class Foo : IFoo { private IBarRepository repository public Foo(IBarRepository repository) { this.repository = repository } public IList<IBar> Bars { ...
5
votes
2answers
6k views

Why multiple calls to same classes' Constructor from within a Constructor wouldn't work?

Please have a look at following snippet: public class Foo { int digit; String name; Foo (int d, String n) { this(d); // cannot do following. //compile-time error: Constructor call must ...
5
votes
1answer
482 views

Decoupling when constructors have non-contractual parameters

By non-contractual parameters, I mean parameters that are not interfaces or service dependencies, something like class Person(string name). I am writing a webpage scraping application, and so far I'...
5
votes
2answers
851 views

When to use Constructor and when to use Collection Initializer?

I am having a .Net class which has 10 properties like given below: [the datatypes of individual property is just a placeholder here and it can be anything from a primitive type to an object to a list ...
5
votes
4answers
1k views

Separation of construction and initialization

I'm confused by this post by Mark Seeman. And his comment on IInitializable below: The problem with an Initialize method is the same as with Property Injection (A.K.A. Setter Injection): it ...
5
votes
1answer
420 views

Approach for Constructing View Models in Complex MVVM Application

I'm struggling with the design in a WPF MVVM application. In a few courses I've taken, they say that having a lot of parameters in a constructor is a code smell, but they never address how to deal ...
4
votes
5answers
701 views

Requring static class setter to be called before constructor, bad design?

I have a class, say Foo, and every instance of Foo will need and contain the same List object, myList. Since every class instance will share the same List Object, I thought it would be good to make ...
4
votes
2answers
379 views

Where should I put the common code of the constructors?

I have a situation where in a class I have 2 constructors and they have very similar code. The only difference is the the call to the constructor of the super class. Where should I put this common ...
4
votes
1answer
122 views

Is it bad to access the constructor prototype within the constructor?

Most places where I have seen prototypes defined for a constructor it was done like so. var Person = function(){ this.stuff = stuff; } Person.prototype.doSomething = function(){console.log("...
4
votes
2answers
3k views

Constructor vs casting operator

I'm programming a library (so I have complete access to all the mentioned classes). Two classes (A and B) are essentially the same and differ only by their implementation, so they can easily be ...
4
votes
2answers
491 views

How do we freeze an object while constructing an object using JavaBeans pattern?

Going through Effective Java, Joshua Bloch states that the drawback of using JavaBeans pattern is that an object may be in an inconsistent state partway through the construction and with JavaBeans ...
4
votes
2answers
255 views

When to use a static method instead of a constructor?

I have a short question for you: let's imagine that we have a class similar to this one. public class StreamTradeDataProvider : ITradeDataProvider { public StreamTradeDataProvider(Stream stream) ...
4
votes
1answer
876 views

Why are SameAsClassName() constructors deprecated in PHP7?

According to the PHP5 manual, __construct() was introduced in PHP5 as a replacement for SameAsClassName() constructors, and from PHP7, the old style is marked as deprecated, so in future versions, ...