java – Why aren’t constructors atomic?

Usually, it is a best practice to write constructors so that they should not have any side effects and external interactions. Just initialize the members of the object using only the parameters passed to them and do all of the complex operations in a separate function once the object was safely constructed.
Or even better, let the only way for constructing an object be a factory function, that can check the parameters for correctness and only create the object if it can be sure it will be valid/consistent/safe to use.

Allowing constructors to do much more than that might have its roots both in history and in offering powerful options to developers (though these overlap a lot).

On the “being powerful” side:
Most programming languages prefer to offer many possibilities for developers, instead of restricting what they can do for a simple reason: If you would need to do something the language does not support you will use a different language … but if you have much more power than needed, you can always decide to be careful and not use it.

On the “historical” side:
Technically, constructors have been just simple functions for a long-long time with some additional rules. This made them easy to implement for compiler developers (other some extra checks they could just reuse the usual procedures used for functions), but also offered all of the powers of “normal” functions.

haskell – State monad and pattern matching on data constructors

I am writing a Settlers of Catan server in Haskell for fun. Currently I am passing around state manually. I want to learn more about the State monad and want to incorporate it into my project.

However, my GameState has multiple data constructors that I pattern match on to yield different functionality. Three of such data constructors are for the WaitingLobby (when people can still join over the internet), the SetupPhase (before the game has really started and people have to build their initial settlements), and one for the RunningGame (when you can play the game turn by turn normally). Code:

data GameState = WaitingLobby ... | SetupPhase ... | RunningGame ...

Lots of functions pattern match on the type of data constructor used. For example the function that handles building a settlement after it has been decided that the player is indeed allowed to do so:

doConstructBuilding :: GameState -> Building -> VertexCoordinate -> GameState 
doConstructBuilding gs@(SetupPhase _ _ board _ _ _) building coord          = gs { board = placeBuilding building coord board,
                                                                                   _placedSettlement = True }
doConstructBuilding gs@(RunningGame playerList cur board _) building coord  = gs { board = placeBuilding building coord board, 
                                                                                   playerList = map payIfCur playerList}
                                    where payIfCur p | cur == playerId p = playerPays p $ constructionCost building
                                                     | otherwise         = p

So the different GameState dataconstructors have different implementations: In the SetupPhase the building is placed and it is noted that the player has placed a settlement in the state, while in the RunningGame the building is also placed, but here the player also pays resources for it.

The question: My understanding is that with the state monad you only pull out the state once you’re in the monadic context on the right side of the =. So How would I implement something like this?

Note: Maybe there are other solutions for this particular method, but I have a lot of these data constructor pattern match cases.

object oriented – Can and should constructors do more work than merely assigning values to fields?

It very much depends on your class, what it does, how you expect to use it, and what kind of performance optimization you’re looking for.

If you’re looking for the constructor to trigger some external work, e.g. a cleanup of the file server, that is not appropriate. But I suspect you’re thinking more along the lines of calculations of values that are relevant to the currently constructed class’ lifetime.

The first approach is to calculate your values once, in the beginning. This means that you don’t have to repeat the same calculation whenever the data is requested.

For the examples, I’m going to use taking the first letter of a string as “the calculation”. It’s of course a trivial amount of effort, but it’s merely intended as a simple example of a value calculation of any level of complexity.

public class Person
    public string Name { get; private set; }

    public char FirstLetterOfName { get; private set; }

    public Person(string name)
        this.Name = name;
        this.FirstLetterOfName = name(0);

This is straightforward, and leads to increased performance on repeated usage, at the cost of initial performance when initializing the object.

The second approach is to defer the execution of the value until it is asked. This means you don’t waste time during initialization, especially if you never end up fetching this specific value. But if you fetch the specific value multiple times, you’ll lose performance by redoing the same calculation.

public class Person
    public string Name { get; private set; }

    public char FirstLetterOfName
        get { return this.Name(0); }

    public Person(string name)
        this.Name = name;

The third approach tries to have it both ways: deferred execution, and caching the result so the execution is not repeated.

public class Person
    public string Name { get; private set; }

    private char? _firstLetterOfName;
    public char FirstLetterOfName
            if(_firstLetterOfName == null)
                _firstLetterOfName = this.Name(0);

            return _firstLetterOfName;

    public Person(string name)
        this.Name = name;

This approach maximizes performance both during initialization and during repeated usage, but it comes at the cost of a more complex implementation, which affects readability and maintainability, in a “straw that broke the camel’s back” sense.

So, depending on which approach you take, you can enhance:

  1. Performance during initialization
  2. Performance during repeated usage
  3. Code readability and maintainability

You can’t have it all, but you can have two out of three. Take your pick.

  • 1 + 2 => third approach
  • 1 + 3 => second approach
  • 2 + 3 => first approach

haskell – What is the idiomatic way to represent algebraic datatype constructors in Scheme (R6RS)?

I’m wondering what is the best way to translate Haskell-like datatypes to Scheme. My current plan is to represent constructors with vectors, with the first element being a label representing the variant. So, for example, the following Haskell program:

data Bits       = O Bits | I Bits | E deriving Show
data Nat        = S Nat  | Z          deriving Show
inc (O pred)    = I pred
inc (I pred)    = O (inc pred)
inc E           = E
dup (S pred)    = let (x,y) = dup pred in (S x, S y)
dup Z           = (Z, Z)
bus Z        bs = inc bs
bus (S pred) bs = let (x,y) = (pred,pred) in (bus pred (bus pred bs))
o32             = (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O E))))))))))))))))))))))))))))))))
n26             = (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S Z))))))))))))))))))))))))))
main            = print (bus n26 o32)

Would be translated as:

(define (O pred)   (vector 'O pred))
(define (I pred)   (vector 'I pred))
(define E          (vector 'E))
(define (S pred)   (vector 'S pred))
(define Z          (vector 'Z))
(define (Inc bits) (case (vector-ref bits 0) ('O (I (vector-ref bits 1))) ('I (O (Inc (vector-ref bits 1)))) ('E E)))
(define (Dup val)  (case (vector-ref val 0) ('S (let ((xy (Dup (vector-ref val 1)))) (cons (S (car xy)) (S (cdr xy))))) ('Z (cons Z Z))))
(define (Bus n bs) (case (vector-ref n 0) ('Z (Inc bs)) ('S (let ((xy (Dup (vector-ref n 1)))) (Bus (car xy) (Bus (cdr xy) bs))))))
(define O32        (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O (O E)))))))))))))))))))))))))))))))))
(define N26        (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S Z)))))))))))))))))))))))))))
(display (Bus N26 O32))

To my surprise, this actually performs quite well (Scheme is faster than Haskell here). But I wonder if this is the best way to do it? Is this reasonable, or is there some more “idiomatic” translation, which would be expected to perform better?

design – Custom datatype and their constructors – should you clone, or just copy?

Suppose we have the following C snippet, implementing a tree data structure:

typedef struct node {
    char* data;
    struct node** children;
    unsigned int num_children;
} node;

Then we could create a leaf constructor that looks like the below,

node* make_leaf(char* data) {
    node* res = malloc(sizeof(*res));
    res->data = malloc(sizeof(*(res->data)) * strlen(data) + 1);
    strcpy(res->data, data); 

    res->children = NULL;
    res->num_children = 0;

Now suppose you have a few leaves, and you want to build them into a larger tree. You could do something like the following:

node *make_tree_1(char *data, unsigned int num_children, node *children) {
  node *res = malloc(sizeof(*res));
  res->data = malloc(sizeof(*(res->data)) * strlen(data) + 1);
  strcpy(res->data, data);

  res->num_children = num_children;
  res->children = malloc(sizeof(*(res->children)) * res->num_children);
  for (int i = 0; i < num_children; ++i) {
    *(res->children + i) = children + i;
  return res;

void shallow_cleanup(node *nd) {
  nd->children = NULL;
  nd->data = NULL;
  nd = NULL;

So users can create trees with make_tree_1 and for every such tree created with this function, there needs to be a corresponding call to shallow_cleanup. This feels natural, but has the property that editing a subtree will change the larger tree. Intuitively, this feels like a big onus to put on the user, to remember not to touch certain trees once they have been included in a larger tree. Conversely, this may be what the user wants. Of course, they could just clone the subtrees before passing them to make_tree_1, but this potentially just adds more line noise to your code. Additionally, if a user is building a large tree, then there will be a lot of corresponding calls to shallow_cleanup at the end of the function.

So another alternative is to clone the subtrees for the user, and do something like the following:

node *make_tree_2(char *data, unsigned int num_children, node *children) {
  node *res = malloc(sizeof(*res));
  res->data = malloc(sizeof(*(res->data)) * strlen(data) + 1);
  strcpy(res->data, data);

  res->num_children = num_children;
  res->children = malloc(sizeof(*(res->children)) * res->num_children);
  for (int i = 0; i < num_children; ++i) {
    *(res->children + i) = children + i;
  return res;

void deep_cleanup(node *nd) {
  if (nd->num_children > 0) {
    for (int i = 0; i < nd->num_children; ++i) {
      deep_cleanup(*(nd->children + i));
  nd->children = NULL;
  nd->data = NULL;
  nd = NULL;

To me, this seems even more natural – you can now chain calls without worrying about memory leaks, and you will probably need fewer cleanup calls at the end. But this could potentially invoke a massive memory overhead, as we are repeatedly copying everything.


  1. Are either of these two ways outlined above idiomatic C? If not, why not? Is there a third way of doing things? What is most commonly found ‘in the wild’, when managing memory on custom data structures?

  2. In the second case, is the memory overhead ‘worth it’?

  3. Is the idiomatic way of handling this language dependent? Would you copy in some languages vs cloning in others?

  4. What is the most friendly/natural of the above two options for end users?

I asked a philosophically similar question here, but I feel this (new) question is more oriented around design principles rather than details of C. I also appreciate that the above question may not be entirely well-formed, but I feel I’m in a position where I don’t know what I don’t know. Any help would be very much appreciated – thank you in advance.

object oriented – I want java coding OOP mean I want code using Classes, Encapsulation, Constructors, Inheritance and Array list

The second level of training contains practical work on programming using Java, and ‎focuses on implementing basic algorithms in code using IDE, your training should go ‎as follows:‎
‎1.‎ To start the technical part, you should start by showing a suitable IDE for your ‎trainees
‎2.‎ Then, create a discussion with the attendees to criticize development using IDEs ‎in comparison with not using one.‎

Now, you’ll give them practical training by giving them a small programming project, ‎the following is the project description: ‎
Create a library system with the following specifications: the library has a name, number ‎of employees, manager name, and location. Also, the library consists of five sections: ‎human studies, science, mathematics, information technology, and history. Every ‎section contains books, every book has a serial number (number), title, number of ‎pages, author name, and publisher name. Identify and Implement all the needed ‎classes according to the mentioned requirements.‎
After you make sure all the project details are clear, you need to help your attendees to ‎implement a sorting algorithm to sort books (Ascending) in every section, implement the ‎algorithm in two ways, sort by serial number, and sort by book title. ‎

public static library(){

**package library;

public static ‎human studies {


magento2 – Why Magento 2 Injecting Interfaces to the constructors?

See the link:

Magento 2 use oops concepts of PHP.

. As the interface is not able to provide a method (function) definition, So, at Magento, every interface is overridden by a PHP class.

Let me give an example, If you want get an order data then you have to use MagentoSalesApiOrderRepositoryInterface::get()

If you check at this interface class you will find that only method signature is exiting that interface.

 * Loads a specified order.
 * @param int $id The order ID.
 * @return MagentoSalesApiDataOrderInterface Order interface.
public function get($id);

That interface is overridden by PHP class MagentoSalesModelOrderRepository where you find the function definition and it business logic.

This write is managed from di.xml.

<preference for="MagentoSalesApiOrderRepositoryInterface" type="MagentoSalesModelOrderRepository"/>

If you want to create object of class at core php then you r write like

$object = new MyClass;

Adding an interface to __construct() means you are creating an object of a class/interface.


public function __construct(
ConfigInterface $config,

You have created an object of class ConfigInterface which is $config.

So you can access all public methods of ConfigInterface using $config .

As at di.xml ‘s MagentoFrameworkIndexerConfigInterface override by MagentoIndexerModelConfig,So basically you can access of all public MagentoIndexerModelConfig

<preference for="MagentoFrameworkIndexerConfigInterface" type="MagentoIndexerModelConfig" />

Adding Interfaces/classes to __construct() method you are creating an object of that class/interface which required for your work.

And this is the concept of use interfaces at contract().

Also, interface only expose public method NOT your private and protected methods that make your code Core more secure.

c ++ 11 execution without definition of C ++ constructors

a query.

I created a little code that shows the values ​​that an object's data takes without initializing it in the main or constructor.

using namespace std;

class Cuenta{
  int saldo;
  float interes;
  string nombre;
  int obtenerSaldo(){return saldo;}
  float obtenerInteres(){return interes;}
  string obtenerNombre(){return nombre;}

int main(){

  Cuenta cuenta1;
  Cuenta cuenta2;
  cout << "Cuenta 1: " << cuenta1.obtenerSaldo() << " - " << cuenta1.obtenerInteres() << " - " << cuenta1.obtenerNombre() << endl;
  cout << "Cuenta 2: " << cuenta2.obtenerSaldo() << " - " << cuenta2.obtenerInteres() << " - " << cuenta2.obtenerNombre() << endl;

  return 0;


I understand that with the exception of the string, the other data is not initialized with a certain value, but with "garbage".
Running Account1 gives me completely random values ​​(except for the string, which is always empty), but Account2 always gives me the same output 2 - 0 - . Even when I comment on the output from Account1, it always gives me the same values.
Is it special that this happens, or is it just a coincidence that these types of values ​​came out?

I hope you understood. Thanks a lot

Java – using enum constructors, rewritable getters, or both in combination?

At the moment, an enumeration in our project takes on properties in the constructor. It is practically guaranteed that they are completely different in every enumeration.

Now I want to add a property that is a simple Boolean – and only differs from the default in a few cases.

There are two sensible approaches that I can see here:

  1. Revise the constructor to take the Boolean parameter and set it to true for the parameters required. While this is the most consistent one with the current status quo, it also adds a lot of unnecessary mess as it rarely deviates from the standard.

  2. Define a rewritable Get method that uses the default method and override the method in the enumerations where it varies. I like that because it keeps the constructor "clean", but it starts to introduce "magic" that successors may overlook or forget in the future – especially since it hides the implementation.

Only because of the clarity of implementation, option 1 should win by far. But I'm not sure if Clairty can be sacrificed for a in this case little slightly more readability.