Stack Exchange Network

Stack Exchange network consists of 174 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

The tag has no usage guidance.

4
votes
2answers
152 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
200 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
108 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
348 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
503 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
98 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
525 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
128 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
70 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
162 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
62 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
587 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
210 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
115 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 = ...
3
votes
2answers
84 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 ...
2
votes
2answers
60 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
351 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 ...
0
votes
1answer
178 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 ...
27
votes
3answers
4k 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 ...
0
votes
0answers
36 views

Is it bad practice to not separate the class definition and constructor into separate files? (specifically in R package development)

I am developing an R package and for some reason all of the current packages I have looked at put the class definition and class constructor in separate files. Usually a myClass--class.R file and a ...
35
votes
7answers
10k 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
2k 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 ...
1
vote
4answers
2k 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
182 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
1k 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
118 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
541 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
0answers
37 views

Best practice for populating an object instance with remote data on construction? [duplicate]

I've recently gone from mostly client side javascript programming to lots of back end c# that communicates with multiple databases. I've designed a packing list generator, however I'm unsure of the ...
0
votes
1answer
67 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
2k 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
914 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
101 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
223 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
2k 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
458 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
578 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
103 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 ...
2
votes
3answers
5k 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
576 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
64 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
211 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 ...
19
votes
5answers
3k 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 ...
3
votes
1answer
114 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("...
7
votes
3answers
452 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 ...
0
votes
6answers
624 views

why can't class directly take arguments instead of using a constructor?

I referred this page for understanding about constructors in Java: http://www.javatpoint.com/constructor So, I pretty much got it as in my own words: constructor has no return value and is used to ...
-2
votes
2answers
221 views

Why is the syntax for a new object creation is little bit long in java? [duplicate]

After trying to write small programs with out reading much of the concepts in Java, the following syntax bugs me a little: Car volvo = new Car("Sweden"); class Car { String country; // ...
-2
votes
1answer
379 views

When is Memory allocated to a constructor? [closed]

When is memory allocated to a constructor in a program run? I Don't know it. I think it may be when the instance(object) of the class is created or so. Is it correct?
0
votes
0answers
82 views

validating arguments in javascript constructors

In many cases, it is useful to have a constructor or factory method that validates arguments before instantiating an object, returning a new object if the arguments are valid and null otherwise. But ...
10
votes
2answers
581 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 ...