Questions tagged [constructors]

Member functions of a class which initializes objects of the given class.

Filter by
Sorted by
Tagged with
-2 votes
3 answers
215 views

How to signal a dealbreaker error from a c-tor?

Context: 128kB RAM, freeRTOS. Considered solutions: Exceptions. Discouraged by both the memory size and the code style guide. Late bool init(...);. Has worked for a decade but has it's problems - can ...
  • 6,955
-1 votes
1 answer
115 views

Smart pointer class choice: Simplicity vs. right tool for the job

I'm wrestling with a design choice question here. I've got a class that needs a couple of semaphores. Semaphores are non-movable objects. Objects of this class however need to go into a vector (there'...
  • 1,049
2 votes
5 answers
346 views

Do db calls in constructors lead to more DRY code?

It recently came to my attention that its best practice to avoid database calls in constructors. I feel like this means you end up repeating unnecessary code, thus the code is less DRY? For example, ...
1 vote
1 answer
92 views

Constructor initializer list too bloated?

I noticed that my Member initializer list is not really readable. My main.cpp files looks like this: #include "Application.hpp" using Pathfinding::Core::Application; int main() { ...
  • 161
-1 votes
1 answer
155 views

Conversion methods: from_xxx() or to_xxx(), is there a reason I shouldn't stick with to_xxx()?

I have a C++ library that I'm converting to Python. In the C++ library I have multiple constructors and many different types of conversion functions (think radians to degrees, and different types of ...
  • 1,208
-2 votes
1 answer
194 views

Why aren't constructors atomic? [closed]

If thrown exceptions in constructors can lead to memory leaks or partially-constructed objects, then why we don't make them atomic? so neither an object nor it's local variables will get created/...
  • 99
0 votes
2 answers
87 views

Can and should constructors do more work than merely assigning values to fields? [duplicate]

A typical introductory example to OOP, classes, and constructors is object Car, with properties such as float fuel, bool is_engine_running, etc etc, and a class and constructor definition might be as ...
  • 219
0 votes
1 answer
221 views

Is a "wrong" to return anything else besides `this` in a constructor?

Is a "wrong" to return anything else besides this in a constructor? Take this TypeScript Queue sample: class Queue { private buffer: string; constructor(buffer: string = "&...
-1 votes
3 answers
117 views

When and how to check input parameters

My SmsRecipientDetails class constructor accepts String value as recipient phone number. I would like to accept number with spaces: assertDoesNotThrow(() -> new SmsRecipientDetails("123456789 &...
  • 289
0 votes
1 answer
63 views

Composition without direct instantiation through constructor

I have 2 classes that independently operate on specific file formats: class FileWriterA and class FileWriterB. Each class has some shared methods (e.g., __enter__, __exit__, __str__, closed, is_closed,...
  • 999
1 vote
1 answer
440 views

(UML) Can parameter variables be omitted in a lengthy constructor?

I have the following constructor in a class for a code I'm writing an assignment on for school: public Plant(int xPos, int yPos,int width,int height, int hp,String imageLocation,String audioLocation,...
2 votes
0 answers
202 views

How to handle a bunch of nested ValueObjects?

I'm writing a PHP web application (or actually a Symfony module). One part of it is a nested structure of ValueObjects (meaning: they are immutable and have to be validated on the creating). Such an ...
-1 votes
1 answer
111 views

Doing work when passing constructor arguments

This is very closely linked to the question Legitimate "real work" in a constructor? but not quite the same. I am interested in having feedback on whether this is acceptable or has any risks....
1 vote
2 answers
887 views

Default value for constructor dependency injection

I have class A that depends on interfaces B & C. I use constructor injection to inject them into A: class A { let b: B let c: C init(b: B, c: C) { self.b = b self....
  • 69
1 vote
2 answers
612 views

Is passing arguments to a constructor always considered DI?

Starting to explore using DI more in my project design and I find myself asking the same question: "If I pass this object to that constructor, does that new object now have a dependency?" For ...
  • 999
9 votes
6 answers
959 views

How do you decide if a parameter should go to the constructor of the method it relates to?

I use Python but I guess my question applies to OOP in general. Whenever I create a class I am never sure whether I should put a parameter/attribute in the constructor or in the method the parameter ...
0 votes
3 answers
803 views

Unit Testing: Constructor Injection with Fake Objects - Bad Tests?

In The Art of Unit Testing, 2nd Ed., the author gives the following example for injecting a stub using constructor injection and a "fake object". The goal of the "fake object" is to inherit the ...
  • 1,349
22 votes
4 answers
4k views

Constructing an object: should I expose or hide parameters passed to the constructor?

I've a habit I just mechanically do without even thinking too much about it. Whenever a constructor is waiting for some parameters, I consider this a public information that should be available by ...
-2 votes
2 answers
216 views

C# Static & Constructor Logic [closed]

I learn C# and try to understand the logic between static and Constructor right now. One thing I need ask you about an example which I will give at below. (please ignore the quality of code or how ...
7 votes
3 answers
655 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 ...
-3 votes
1 answer
2k views

Why constructor inheritance is not supported in Python? [closed]

Consider the case where I have the following classes, class A: def __init__(self): print("Class A") class B(A): def __init__(self): print("Class B") b = B() The expected ...
1 vote
1 answer
161 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 {...
  • 23
-1 votes
2 answers
199 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
1 answer
235 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; ...
  • 433
9 votes
4 answers
18k 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
1 answer
380 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 ?
5 votes
3 answers
8k 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
2 answers
208 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 ...
  • 281
4 votes
2 answers
813 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 ...
's user avatar
3 votes
3 answers
3k 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:...
  • 2,000
2 votes
1 answer
506 views

Is using the copy constructor in an object's construction is 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 ...
's user avatar
1 vote
3 answers
600 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....
's user avatar
8 votes
4 answers
610 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 = "...
6 votes
1 answer
1k 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 ...
  • 169
2 votes
4 answers
671 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 ...
  • 181
1 vote
1 answer
180 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 ...
1 vote
1 answer
294 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
1 answer
254 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 ...
's user avatar
1 vote
0 answers
505 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
4 answers
4k 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 ...
  • 147
1 vote
1 answer
272 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:...
's user avatar
-4 votes
1 answer
138 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 = ...
  • 1
4 votes
2 answers
2k 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
2 answers
170 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
2 answers
498 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
1 answer
194 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 ...
  • 455
32 votes
3 answers
16k 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 ...
's user avatar
42 votes
7 answers
16k 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
2 answers
7k 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 ...
  • 6,865
2 votes
4 answers
19k 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 ...
  • 468