Questions tagged [constructors]
Member functions of a class which initializes objects of the given class.
147
questions
-1
votes
1
answer
516
views
How are parameters values passed into a MVC controller constructor?
For this MS sample code, I have checked Program.cs, Startup.cs, and other config files, don't see how the two parameters sqlQueryService and sqlCommandService are populated. Appreciate if someone can ...
-2
votes
3
answers
221
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 ...
-1
votes
1
answer
117
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'...
2
votes
5
answers
364
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
110
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()
{
...
-1
votes
1
answer
159
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 ...
-2
votes
1
answer
211
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/...
0
votes
2
answers
91
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 ...
0
votes
1
answer
223
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
290
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 &...
0
votes
1
answer
78
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,...
1
vote
1
answer
560
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
235
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
112
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
1k
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....
1
vote
2
answers
885
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 ...
9
votes
6
answers
1k
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
1k
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 ...
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
319
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
725
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
206
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 {...
-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
275
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;
...
9
votes
4
answers
19k
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
466
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
9k
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
235
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
2
answers
943
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 ...
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
votes
1
answer
553
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 ...
1
vote
3
answers
637
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
4
answers
621
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 ...
2
votes
4
answers
687
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
1
answer
182
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
330
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
279
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
0
answers
506
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 ...
1
vote
1
answer
274
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
1
answer
141
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
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
172
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
522
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
195
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 ...
32
votes
3
answers
17k
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 ...
42
votes
7
answers
17k
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 ...
12
votes
2
answers
8k
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 ...