Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Questions tagged [constructors]

The tag has no usage guidance.

0
votes
0answers
29 views

Neural Networks object creation from OOP perspective [duplicate]

Let's say that I have a class representing the Neural Network. The neural network is composed of three bigger units: a subpart_1, subpart_2 and subpart_3, being called in such a way, that the output ...
1
vote
1answer
61 views

ES6 - Where is it better to initialize a member - parent class or derived class?

I am trying to figure out if there is a better practice for initializing class members of derived classes in ES6 - in the child or the parent, and why? For example: Option 1: class AbstractAnimal {...
0
votes
2answers
179 views

Java Constructor Syntax and Design [closed]

With regards to object-oriented Java constructor syntax and design, specifically parameterized or specific constructors, it is the accepted process, as describe in books, to build a parameterized ...
0
votes
1answer
82 views

Unit testing for a method in a class which uses constructor DI (prism)

I have a class that uses constructor DI for IEventAggregator public SomeViewModel(IEventAggregator eventAggregator) { this.eventAggregator = eventAggregator; ...
5
votes
3answers
2k 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 ...
-4
votes
1answer
120 views

Inheritance of Constructors from parent into child class [closed]

Is the Default Constructor of Super or Parent class Can be Inherited into Child class ?
2
votes
3answers
256 views

What is the best practice for initializing variables: outside or inside of the constructor?

I try to use the best coding standards/practices, however in all of my googling and classes I have never learned which is proper form for declaring/defining variables like the examples below. I have ...
1
vote
2answers
98 views

Performing serial communication in constructor to initialize an object

I have a class UnitInfo which represents a collection of unit information with methods to get the unit information in a structured way, such as a specific encoding, etc. This unit info consists of ...
4
votes
2answers
194 views

Verifying Parameters in Constructor or Service

I was reading on this SO page about when to check parameters when constructing an object. The accepted answer suggests throwing the exception from the constructor so that an invalid object cannot be ...
2
votes
3answers
414 views

Should a class constructor ever create objects of other classes? [duplicate]

Is it ever good or bad to have a constructor create new instances of classes that it needs versus passing in a reference that you want the new class to have ? So basically it's the difference between:...
1
vote
1answer
186 views

Is using the copy constructor in an object constructor bad? [duplicate]

I was reading this page about using the new keyword in the constructor, and I was wondering if it applies to copy constructors for collections. Suppose I have a Book class and a collection to store a ...
1
vote
3answers
385 views

Is calling .sort() in the constructor a violation of the guideline that a constructor shouldn't do work?

Suppose I have the following List to hold a list of fruits. Example: def fruits = ["Apple", "Orange", "Grapes"] def fruitsBowl = ["Apple", "Grapes", "Orange"] // Will print false println(fruits....
8
votes
4answers
548 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 = "...
5
votes
1answer
333 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 ...
2
votes
4answers
546 views

What do OOP languages gain from having constructors that always return an object?

In what seems like a deliberate design decision, C++ does not have a null value for objects and references. This makes using objects and references very elegant since we don't have to perform null ...
1
vote
1answer
160 views

Am I waiting for the new C# 8 'record' feature?

I'd like an immutable class, or rather a class whose properties are initialised (whether they have public/private setters or not), in the constructor: public class MyClass { public string ...
0
votes
1answer
113 views

Can I use Dependency Injection to test my class when a parameterless constructor is needed?

I want to use PowerArgs for a console application I am writing. It offers some nice features I'd like to try. My root looks like this: public static void Main(string[] args) { try ...
3
votes
1answer
173 views

Does adding values to a dictionary in the constructor violate that “a constructor shouldn't do work”?

Some what of a followup to this question. Suppose I have a Player class with a dictionary call attributes that holds the Health and Mana of the player. In this example, I'll use Python, but my ...
1
vote
0answers
156 views

Are constructors with complex initialization logic always bad? [duplicate]

I've recently read this blog post regarding what a constructor should do and I am also reading Eric Evans' book on Domain Driven Design. Both the blog post and the book state that a constructor ...
3
votes
4answers
1k views

Public static method calls private constructor

I'm working in a C# codebase that was largely written by a former developer and this pattern is used extensively... public class AuditInserter { public static void Insert( DataContext ...
1
vote
1answer
235 views

Does creating a list in the constructor violate the guideline that a constructor shouldn't do work?

I was reading these pages (1,2,3), but I'm still unsure if this violates the guideline. I have the following data being read from a website: Date: July 13, 2018 Type: Partial Solar Eclipse Location:...
-4
votes
1answer
124 views

Can a constructor look like this in Java?

I wonder if a constructor in Java can look like this: public double[] values; I'm not sure if the constructor can look like this, or should it be public values (double[] values){ values = ...
4
votes
2answers
285 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
103 views

How to separate construction and runtime logic in iOS?

I've been reading Robert Martin's Clean Code book where it suggests we should separate a programs startup/construction process from its run time logic. In Java (the language the book uses) this ...
4
votes
2answers
365 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 ...
1
vote
1answer
182 views

Passing 0's (literals) to a constructor

I have a function that creates a new object by passing to it's constructor integer ids primarily with values of 0. This function is called when saving a newly created record (not an edit). public ...
28
votes
3answers
8k 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 ...
37
votes
7answers
11k 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 ...
11
votes
2answers
3k 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 ...
2
votes
4answers
9k views

When to call the constructor and when to call the method in Java?

I am struggling to fully understand the usage of constructors in Java. What I have learned so far about constructors is the following: same name as class abbreviation ctor overloading no return type ...
-1
votes
3answers
312 views

Constructor from interface with minimal repetition

Preface In an application that is separated by layers or distributed by services it is common to have classes that are very closely related data-wise, but which we wish to have loosely coupled. My ...
0
votes
1answer
2k views

Object constructors with dynamic parameter lists

I had a quick question and I was hoping someone could help me figure this out. I'm new to Java and I'm trying to learn about classes and objects and I see you can call parameters in the constructor of ...
0
votes
1answer
150 views

Constructors or setters for entity classes? [duplicate]

I know this has been asked a lot of times but we are talking about entity classes here. Plain dumb objects containing nothing but primitives for properties. The purpose here is to store data. Our ...
3
votes
1answer
1k views

List initialization by empty braced-init-list (value-initialization or by initializer_list) vs explicit default initialization, for “list” types

Background Based on Item 4 in Scott Mayers Effective C++, when appropriate, it can be good practice to initialize all member properties of custom types via the member initialization list (in same ...
0
votes
1answer
68 views

Identifying the use case for instantiation only through existing instances

I was in my CS class when my instructor presented me the following classes: public class UninstantiableTest { private static Uninstantiable uninstantiable; public static void ...
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> ...
4
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 ...
1
vote
1answer
120 views

Instance of other class within class, instead of constructor instance variables?

I was watching an OOP lesson with such code: class UsersConstroller { protected $userService protected $logger public function __construct { UserService $userService, ...
4
votes
2answers
242 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) ...
6
votes
4answers
4k 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. ...
4
votes
3answers
543 views

Tell don't ask vs constructor doing work

When you browse for the phrase "constructors must not do work", then in various blog posts you will find the advice to not let the constructor do work. Despite this, I am having some trouble ...
3
votes
1answer
799 views

Handle Named constructors with factory pattern

In my current project I'm refactoring the code to get a DBAL. I have a class Entity that is the base class for all classes that model a database table. So there are several classes that inherit from ...
0
votes
3answers
109 views

Constructor containing class dependencies

Is it a best practice to initialize class dependencies in a constructor or should a class be initialized in the method where it is used. Let's say we have the following situation, and PriceCalcService ...
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 ...
3
votes
3answers
10k views

C++ derived class copy constructor

If I have an abstract class Drink which has a derived class Coffee, what would the copy constructor for Coffee look like? If it accepts a reference of Type Coffee as a parameter then I wouldn't be ...
-1
votes
1answer
2k views

Reuse base() constructor argument in this() constructor

Let's say I have two classes Base and Derived : Base. Derived shall be able to use a DerivedComponent : BaseComponent, just like all other derivates of Base use their own derivate specific component. ...
0
votes
2answers
68 views

Use XmlDeserializer in factory method?

I have the following class representing an XML configuration stored in the DB: using System.IO; using System.Xml; using System.Xml.Serialization; [XmlRoot("ModalConfiguration")] public class ...
2
votes
1answer
224 views

Must constructors of value objects not do work, even when class invariants prescribe so?

Today I had a discussion with a colleague. It is my understanding that a class has the responsibility to ensure that its objects have a valid state when interacted with from outside the class. The ...
23
votes
5answers
7k 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 ...
4
votes
1answer
121 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("...