答:
There can't be any proper inheritance of constructors in C++, because the constructor of a derived class needs to perform additional actions that a base-class constructor does not have to do and does not know about. These additional actions are the initialisation of the data members of the derived class (and in a typical implementation, also setting the vpointer to refer to the derived classes vtable).

When a class gets constructed, there are a number of things that always need to happen: The constructors of the base class (if any) and the direct members need to be called and if there are any virtual functions, the vpointer must be set correctly. If you don't provide a constructor for your class, then the compiler will create one that performs the required actions and nothing else.
If you do provide a constructor, but miss out on some of the required actions (for example, the initialisation of some members), then the compiler will automatically add the missing actions to your constructor. This way, the compiler ensures that each class has at least one constructor and that each constructor fully initializes the objects it creates.

In C++11, a form of 'constructor inheritance' has been introduced where you can instruct the compiler to generate a set of constructors for you that take the same arguments as the constructors from the base class and that just forward those arguments to the base class.

Although it is officially called inheritance, it isn't truly so because there still is a derived-class specific function. Now it just gets generated by the compiler instead of explicitly written by you.

This feature works like this:

```<code>struct Base {
    Base(int a) : i(a) {}
    int i;
};

struct Derived : Base {
    Derived(int a, std::string s) : Base(a), m(s) {}

    using Base::Base; // Inherit Base's constructors.
    // Equivalent to:
    //Derived(int a) : Base(a), m() {}

    std::string m;
};
</code>```

Derived now has two constructors (not counting copy/move constructors). One that takes an int and a string and one that takes just an int.

Title: Why are constructors not inherited?

Body:
I am confused as to what the problems could be if a constructor was inherited from a base class. Cpp Primer Plus says,

Constructors are different from other class methods in that they
  create new objects, whereas other methods are invoked by existing
  objects. This is one reason constructors aren’t inherited. Inheritance
  means a derived object can use a base-class method, but, in the case
  of constructors, the object doesn’t exist until after the
  constructor has done its work.

I understand  the constructor is called before object construction is completed.

How can it lead to problems if a child class inherits (By inheriting I mean the child class is able to override the parent class method etc. Not just accessing the parent class method) the parent constructor?

I understand there is no necessity of explicitly calling a constructor from within a code[not that I am aware of as yet.] except while creating objects. Even then you can do so using some mechanism to invoke the parent constuctor [ In cpp, using :: or using member initialiser list, In java using super]. In Java there is an enforcement to call it in the 1st line, I understand that is to ensure the parent object is created first and then the child object construction proceeds.

It can overrride it. But, I can't come up with situations where this can pose a problem. If the child does inherit the parent constructor what can go wrong?

So is this just to keep away from inheriting unecessary functions. Or is there more to it?

Body:
There can't be any proper inheritance of constructors in C++, because the constructor of a derived class needs to perform additional actions that a base-class constructor does not have to do and does not know about. These additional actions are the initialisation of the data members of the derived class (and in a typical implementation, also setting the vpointer to refer to the derived classes vtable).

When a class gets constructed, there are a number of things that always need to happen: The constructors of the base class (if any) and the direct members need to be called and if there are any virtual functions, the vpointer must be set correctly. If you don't provide a constructor for your class, then the compiler will create one that performs the required actions and nothing else.
If you do provide a constructor, but miss out on some of the required actions (for example, the initialisation of some members), then the compiler will automatically add the missing actions to your constructor. This way, the compiler ensures that each class has at least one constructor and that each constructor fully initializes the objects it creates.

In C++11, a form of 'constructor inheritance' has been introduced where you can instruct the compiler to generate a set of constructors for you that take the same arguments as the constructors from the base class and that just forward those arguments to the base class.

Although it is officially called inheritance, it isn't truly so because there still is a derived-class specific function. Now it just gets generated by the compiler instead of explicitly written by you.

This feature works like this:

struct Base {
    Base(int a) : i(a) {}
    int i;
};

struct Derived : Base {
    Derived(int a, std::string s) : Base(a), m(s) {}

    using Base::Base; // Inherit Base's constructors.
    // Equivalent to:
    //Derived(int a) : Base(a), m() {}

    std::string m;
};

Derived now has two constructors (not counting copy/move constructors). One that takes an int and a string and one that takes just an int.


问:
Is garbage collection necessary?
Do any languages really need garbage collection? Is there not a way to figure out when a object should be destroyed? I haven't had leaks in C++ and i dont use smart pointers or reference counters or anything special. I confirm this by attaching something for leak detection: whether its built in to the IDE or a header that uses magic (defines) to overloads new/free.

Is garbage collection necessary, or is it possible to have a leak-free application in a language without placing the memory burden on the programmer?

答:
Garbage collection is not necessary to provide. In java, you can create only objects you never destroy that. That destruction system will taken care-of.
Just you can close that objects never destroy.

In C++ construction and destruction  is manually not in java.

if suppose your applying the garbage collection. There is no surety that objects are destroyed or not.

Not only me any one also told this one for this question.

ContentLicense: CC BY-SA 3.0

Title: Is garbage collection necessary?


问:
Why are constructors not inherited?
I am confused as to what the problems could be if a constructor was inherited from a base class. Cpp Primer Plus says,

Constructors are different from other class methods in that they
  create new objects, whereas other methods are invoked by existing
  objects. This is one reason constructors aren’t inherited. Inheritance
  means a derived object can use a base-class method, but, in the case
  of constructors, the object doesn’t exist until after the
  constructor has done its work.

I understand  the constructor is called before object construction is completed.

How can it lead to problems if a child class inherits (By inheriting I mean the child class is able to override the parent class method etc. Not just accessing the parent class method) the parent constructor?

I understand there is no necessity of explicitly calling a constructor from within a code[not that I am aware of as yet.] except while creating objects. Even then you can do so using some mechanism to invoke the parent constuctor [ In cpp, using :: or using member initialiser list, In java using super]. In Java there is an enforcement to call it in the 1st line, I understand that is to ensure the parent object is created first and then the child object construction proceeds.

It can overrride it. But, I can't come up with situations where this can pose a problem. If the child does inherit the parent constructor what can go wrong?

So is this just to keep away from inheriting unecessary functions. Or is there more to it?

答:
It's not clear what you mean by "inheriting the parent constructor".  You use the word overriding, which suggests you may be thinking about constructors that behave like polymorphic virtual functions.  I deliberately do not use the term "virtual constructors" because that is a common name for a code pattern where you actually require an already existing instance of an object to create another one.

There is little utility to polymorphic constructors outside of the "virtual constructor" pattern, and it's difficult to come up with a concrete scenario where an actual polymorphic constructor might be used.  A very contrived example that is in no way even remotely valid C++ :

```<code>struct Base {
  virtual Base(unsigned p1, unsigned p2) {...}
};

struct Derived: public Base {
  Derived(unsigned p1, unsigned p2) : Base(p1, p2) override {...}
};

int main(void) {
  unsigned p1 = 0;
  unsigned p2 = 42;
  Derived *p_d1 = new Base(p1, p2); // This might call Derived(unsigned, unsigned).
  Derived *p_d2 = nullptr;
  p_d2 = new Base(p1, p2); // This might call Derived(unsigned, unsigned) too.
}
</code>```

In this case the constructor called depends on the concrete type of the variable being constructed or assigned.  It is complex to detect during parsing / code generation and has no utility: you know the concrete type you are constructing and you have written a specific constructor for the derived class.  The following valid  C++ code does exactly the same, is slightly shorter and is more explicit in what it does:

```<code>struct Base {
  Base(unsigned p1, unsigned p2) {...}
};

struct Derived: public Base {
  Derived(unsigned p1, unsigned p2) : Base(p1, p2) {...}
};

int main(void) {
  unsigned p1 = 0;
  unsigned p2 = 42;
  Derived *p_d1 = new Derived(p1, p2);
  Derived *p_d2 = nullptr;
  p_d2 = new Derived(p1, p2);
}
</code>```

A second interpretation or perhaps additional question is - what if the Base class constructors were automatically present in all derived classes unless explicitly hidden.

If the child does inherit the parent constructor what can go wrong?

You would have to write additional code to hide a parent constructor that is incorrect to use in constructing the derived class.  This can happen when the derived class specializes the base class in a way that certain parameters become irrelevant.

The typical example is rectangles and squares (Note that squares and rectangles are generally not Liskov-substitutable so it's not a very good design, but it highlights the issue).

```<code>struct Rectangle {
  Rectangle(unsigned width, unsigned height) {...}
};

struct Square : public Rectangle {
  explicit Square(unsigned side) : Rectangle(side, side) {...}
};
</code>```

If Square inherited the two-value constructor of Rectangle, you could construct squares with a different height and width... That's logically wrong, so you'd want to hide that constructor.

Title: Why are constructors not inherited?

Body:
It's not clear what you mean by "inheriting the parent constructor".  You use the word overriding, which suggests you may be thinking about constructors that behave like polymorphic virtual functions.  I deliberately do not use the term "virtual constructors" because that is a common name for a code pattern where you actually require an already existing instance of an object to create another one.

There is little utility to polymorphic constructors outside of the "virtual constructor" pattern, and it's difficult to come up with a concrete scenario where an actual polymorphic constructor might be used.  A very contrived example that is in no way even remotely valid C++ :

struct Base {
  virtual Base(unsigned p1, unsigned p2) {...}
};

struct Derived: public Base {
  Derived(unsigned p1, unsigned p2) : Base(p1, p2) override {...}
};

int main(void) {
  unsigned p1 = 0;
  unsigned p2 = 42;
  Derived *p_d1 = new Base(p1, p2); // This might call Derived(unsigned, unsigned).
  Derived *p_d2 = nullptr;
  p_d2 = new Base(p1, p2); // This might call Derived(unsigned, unsigned) too.
}

In this case the constructor called depends on the concrete type of the variable being constructed or assigned.  It is complex to detect during parsing / code generation and has no utility: you know the concrete type you are constructing and you have written a specific constructor for the derived class.  The following valid  C++ code does exactly the same, is slightly shorter and is more explicit in what it does:

struct Base {
  Base(unsigned p1, unsigned p2) {...}
};

struct Derived: public Base {
  Derived(unsigned p1, unsigned p2) : Base(p1, p2) {...}
};

int main(void) {
  unsigned p1 = 0;
  unsigned p2 = 42;
  Derived *p_d1 = new Derived(p1, p2);
  Derived *p_d2 = nullptr;
  p_d2 = new Derived(p1, p2);
}

A second interpretation or perhaps additional question is - what if the Base class constructors were automatically present in all derived classes unless explicitly hidden.

If the child does inherit the parent constructor what can go wrong?

You would have to write additional code to hide a parent constructor that is incorrect to use in constructing the derived class.  This can happen when the derived class specializes the base class in a way that certain parameters become irrelevant.

The typical example is rectangles and squares (Note that squares and rectangles are generally not Liskov-substitutable so it's not a very good design, but it highlights the issue).

struct Rectangle {
  Rectangle(unsigned width, unsigned height) {...}
};

struct Square : public Rectangle {
  explicit Square(unsigned side) : Rectangle(side, side) {...}
};

If Square inherited the two-value constructor of Rectangle, you could construct squares with a different height and width... That's logically wrong, so you'd want to hide that constructor.


问:
MVC View Question
In my PHP web page (index.php), I have a simple script that calls a "page" class, and then builds the page from it.

Index.php executes methods within an instance of the 'page' class, such as "add_to_body("bla bla bla")". It can then call a "build()" method, where the page class will return a string with the user input and some other HTML elements pre-added in, that index.php can echo. Essentially the page class is a template of sorts.

I'm trying to have some kind of MVC hierarchy here (I'm a student learning about programming 'best practices' in my own time), my question is: would 'index.php' be a view? Or, would the instance of the page class be the view (as it constructs the page, but it doesn't actually show it, it returns a string), or: would the 'page' class be a controller?

Also, is a view 'allowed' to talk to (eg: get data from) a controller (for example: by calling a method that controller owns)?

Many thanks for your help!

答:
There are different approaches to MVC. An MVC architecture always consists of at least four parts.

Dispatcher. Decides which controller is used.

Controller. Makes decisions about models and views.

Model. Does the data handling.

View. Generates the output.

The two main approaches to MVC differ in the place, where the business logic comes in. One puts it into the model (Thin Controller / Fat Model), the other into the controller (Fat Controller / Thin Model).

In your current implementation, index.php is the Dispatcher, and seems to contain the Controller, too. The Page class is the View. From your description I cannot tell, where the Model is; it should be in index.php, but likely there are parts of it in the Page class. It takes some experience to create a proper separation.

Title: MVC View Question


问:
Migration to embedded systems
My company has so far been developing a medical device, which is connected via USB to a desktop system (running x64 Windows 7) to run the image analysis and do everything GUI related.

I am familiar with both Windows and Linux programming, C, C++, C++11 and C#, but now our new project coming from management would be a handheld, embedded system, and since I am the only software engineer, I have absolutely no idea how embedded systems work.

Is it totally different from the "normal" programming job, should I recommend hiring someone with embedded experience, are there good ressources for introduction to embedded computing?

I am at a loss here, since I do not know what exactly to expect (it'll be in theory the same as with the desktop systems, a sensor acquiring an image, and the software doing analysis).

Can someone help me get an idea what I would have to expect for this?

Edit: there is no framework, as to what hardware to use. We can use whatever we want, as long as it is small enough to be handheld. We will be using a third party sensor (either photo-sensor, or acoustic sensor, thats not been established yet), but again, we are pretty much free to decide, so my guess will be that it will have a well established API. I don't even really know what embedded systems are, I have experimented privately with an Arduino, does that count as embedded already?

答:
The term embedded system is extremely large and covers just about anything from the chip that controls your microwave to systems that give dynamic, road-side traffic information. Generally speaking, you have an embedded system if there is a computer chip in it that communicates with some purpose-built hardware.

There are roughly tow types of embedded systems, which I will term here as 'small' and 'large' systems.

In a 'small' embedded system, there is usually very little available in terms of resources (RAM/ROM/Flash) and it has no OS to speak of. Usually, all software running on such a device gets compiled into one big executable that also includes the OS kernel. These kernels only provide you with scheduling and task synchronization primitives.

In a 'large' embedded system, you are writing software to run under the control of a regular OS (often Linux, but not always). As a software developer, there is usually not much difference with writing software for a desktop environment, except in the tooling you use for compiling/deploying/debugging and that some of the heavier processes (like X windows) might not be available.

If this is the company's first step in the embedded world, I would advise them to look as much as possible for stock hardware that fits their needs as best as possible and for which there already is an OS implementation available. Porting an OS to new hardware and writing device drivers are not the easiest of tasks, especially for people unfamiliar with embedded development.

Title: Migration to embedded systems


问:
Is the algorithm more important than the programming language?
During the current (2013) Google Code Jam contest, there was a problem that took C++ and Java people 200+ lines of code as compared to Python people that solved the same problem only using 40 lines of code.

Python is not directly comparable with C++ and Java but the difference in verbosity I thought might perhaps have an influence on the efficiency of the algorithm.

How important is knowing the right algorithm compared to the choice of language? Could an excellently implemented Python program be implemented in C++ or Java in a better way (using the same algorithm) and does this have any relation to the natural verbosity of certain programming languages?

答:
Any algorithm can be implemented in any programming language. After all, its not the syntax that matters. But using a high level language like Python do have its own advantages. Less work and less amount of coding. So to implement an algorithm in Python, you shall need fewer lines than what is required in a low level language like C.

Python have most of the data structures built into its library. But in C, we need to start from scratch and use a structure to built it all up. Certainly there are differences between the high level and low level language, but the language shouldn't stop you from implementing any algorithm.


答:
Embedded is a LARGE field, and ranges from really little stuff to things that are really just a desktop machine in a funny box.

I'm going to go with 3 categories of embedded systems, to correspond with my experience, then I'll make some recommendations.

Small embedded systems are things run by micro-controller type devices. They don't have any OS, scheduler, etc, etc. You're running code running directly on the CPU, and in general you'll have main loop that gets started at power on and never exits. There are a lot of options for micro-controllers, ranging from things like the venerable 8051 to the really tiny PIC up and a lot of products based on the ARM cores. These are nice because you have complete and direct control over every facet of the system's operation. Of course, that also means you need to be careful about things like timing and latency of operations, and how long you can spend on any one thing before you go back to your main loop.

Medium embedded systems are bigger things, and which will have an embedded OS such as Wind River's pSOS (there are MANY choices for this, I happen to have used pSOS once upon a time). I'm calling it medium because at this point you're NOT running a single main loop, and actually have a scheduler. The hardware may not be much different from the higher end of the previous group, but the presence of a scheduler and a more formalized driver architecture really improves your ability as a programmer to get stuff done. On the downside, it might be more trouble to meet really tight timing because you can easily introduce more unexpected delays from the scheduler. Also, you have to be careful that your hardware does things that make sense for the OS you are using - for instance, not all interrupt strategies work with all embedded OSs. At the larger end of this group I'll put in Windows CE, the embedded offering from Microsoft. This segment is getting squeezed out to some degree as more and more processing power is becoming available for less and less money.

Big embedded systems are even bigger and run an OS that a desktop user might well recognize. Linux is common here, as is the embedded (or even the regular!) version of MS Windows. There's a lot of this going around in the medical field (look at a lot of ultrasound machines). The advantage here is that you can run a full bore installation of Linux, with all the useful stuff that a real OS brings on very small and very cheap hardware anymore.

Now, being your first foray into embedded, and given that it's medical (where I suspect you have margins to support reasonable hardware budgets), I recommend that you use some small computer like a rasberry pi, a beaglebone, or something else based on one of the multitude of ARM cores out there. Run Linux on it, and build your app on top of that. In fact, you probably want to simply leave your device as-is, package it into a box with the small computer and communicate via USB. Effectively, just port your existing app to Linux and go.

Title: Migration to embedded systems

Body:
My company has so far been developing a medical device, which is connected via USB to a desktop system (running x64 Windows 7) to run the image analysis and do everything GUI related.

I am familiar with both Windows and Linux programming, C, C++, C++11 and C#, but now our new project coming from management would be a handheld, embedded system, and since I am the only software engineer, I have absolutely no idea how embedded systems work.

Is it totally different from the "normal" programming job, should I recommend hiring someone with embedded experience, are there good ressources for introduction to embedded computing?

I am at a loss here, since I do not know what exactly to expect (it'll be in theory the same as with the desktop systems, a sensor acquiring an image, and the software doing analysis).

Can someone help me get an idea what I would have to expect for this?

Edit: there is no framework, as to what hardware to use. We can use whatever we want, as long as it is small enough to be handheld. We will be using a third party sensor (either photo-sensor, or acoustic sensor, thats not been established yet), but again, we are pretty much free to decide, so my guess will be that it will have a well established API. I don't even really know what embedded systems are, I have experimented privately with an Arduino, does that count as embedded already?


问:
How should I behave as a developer in a project that's headed for failure?
I am a developer in a 5-member team and I believe our project is headed for disaster. I'll describe why in a moment, but my question is: how should I behave?

The deadline is in 1.5 months, and I feel no matter what we do, this project will fail. I'm of the opinion that we should just terminate the project and stop wasting our time, but politically I think it's impossible for our manager to do that.

What should I do in this case? Should I put in extra effort, or should I just take it easy? And what should I say to the manager?

Reasons this project is headed for failure:

With deadline approaching many of the must-have features are not finished

Application is unstable and very difficult to use

System is very convoluted, code very hard to understand, very difficult to change - Data model is too driven by a complex relational database (100+ tables)

Unclear leadership; the manager responds to new information with major changes

Almost no automated tests or unit test

Heavily depends on other systems, but no integration tests yet

In fact, we actually just inherited this project (along with the mess) around 1-2 months ago from another dev team under the same manager, who has worked on it for a few months.

答:
What I've found most effective is Robert L. Read's recommendation on how to fight schedule pressure. Here's what Read writes:

The key to fighting schedule pressure is simply to turn it into time-to-market pressure. The way to do this to give visibility into the relationship between the available labor and the product. Producing an honest, detailed, and most of all, understandable estimate of all the labor involved is the best way to do this. It has the added advantage of allowing good management decisions to be made about possible functionality tradeoffs.

The key insight that the estimate must make plain is that labor is an almost incompressible fluid. You can't pack more into a span of time anymore than you can pack more water into a container over and above that container's volume. In a sense, a programmer should never say ‘no’, but rather to say ‘What will you give up to get that thing you want?’ The effect of producing clear estimates will be to increase the respect for programmers. This is how other professionals behave. Programmers' hard work will be visible. Setting an unrealistic schedule will also be painfully obvious to everyone. Programmers cannot be hoodwinked. It is disrespectful and demoralizing to ask them to do something unrealistic.

When you say that the project is "headed for failure," that's based on your assessment of what tasks need to be done and how much effort each one of them will require. Make that assessment explicit, understandable, and detailed. Separate tasks into their component parts; explain in as much detail as you can how development time will be spent.

Once you do that, you have a solid foundation for discussing concerns with management. In all probability, once you've broken down your assessment into all the specific tasks that need to be completed, you will be able to demonstrate that the job takes more time than you have - possibly much, much more.

Once you're discussing this detailed schedule with your manager, be prepared to be flexible. Your manager might say "Task X won't take a month; it'll take a week at most," or "Task Y is entirely unnecessary, cut that from the schedule." You can certainly discuss these points, but what's far more important is to reach an understanding between you and your manager on some realistic version of a schedule. That way, if you're not being allocated time for, say, testing, then you've got an explicit directive not to test, rather than just running out of time "unexpectedly". And it's definitely possible that your manager is legitimately willing to explicitly cut certain corners in order to ship on time - there's plenty of cases where that's a perfectly reasonable call!

The estimate gives you concrete substance to debate and discuss. It puts you on the same page; it helps you feel confident that your manager has taken your concerns into account. And it brings you to the point where if your manager is plainly asking the impossible, it will be perfectly evident to both of you. If the project is well and truly doomed, you will have made that clear, and it will be up to your manager to decide precisely how he wants you to spend your time.


问:
How to document a project which is already developed?
I would like to know what options are available for documenting a project which has already been developed, as the developers who worked on didn't write even a single page of documentation.

The project has no other details other than many pages of scripts with functions written and modified by developers who worked on this project from the past 2 years. All I have is the database schema and project files. I would like to know if there is any way to organize this project and document it so that it could be helpful for the developers who will be working on this project in the future.

The project was developed with PHP and MySQL. The functions are poorly commented so I can't get good results when I run it with doxygen.

答:
In the past I have managed a situation like this by sitting down with the various product owners or power users, going through their primary use cases and documenting these with a set of tests. You can use these as a baseline for the system when you begin to make changes in the future. This can also help identify areas of the system that do not have an owner or use case and are may potentially be deleted.

It all depends on the size of the system really. If this is a complex system with many different stakeholders you could create a high-level component diagram detailing what capabilities exist and where they are satisfied. This can be very helpful to identify architectural issues in the system design.

In general I suggest avoiding old-fashioned documentation because it will get out-dated and it will miss-lead developers in the future. I always try to produce living documentation in the form of tests that will be maintained as the system evolves.


问:
Is mysql_* deprecated after PDO was introduced?
I have been noticing for a long time on Stack Overflow that most users recommend to use PDO instead of mysql_*, because PDO is more secure than mysql_*. But my question is if websites which are already running with mysql_* will stops working? Or what exactly does "deprecating" mean here? So should we have never used  mysql_*? From which PHP version is is deprecated?

答:
The websites written with mysql_* functions shall continue to work until PHP removes the functionality altogether. As of now, the functions are merely depreciated.

Deprecated means that those functions are no longer recommended, and are replaced with better functions. They may have no support either.

It's recommended to switch over to PDO mainly because of the security that it provides with injection based attacks.


答:
First things first, who is your target audience? Future developers or other businessy people? With the answer to that question in mind:

As others have said, a high level description is the first thing you need. Explain what the system is trying to do in the broader scheme of things. Explain what it runs on, how it fits into the network and talks to any other system.  Then I would go through each screen, screenshot it and give a quick explanation of what the screen does, and how it interacts with any other parts of the system. If its for developers, keep it conversational like you are explaining the app to them for the first time. After all, that's the point of the doc (I assume).

Any complicated processing or logic I'd use a  state diagram, data flow diagram or sequence diagram. Definitely do an entity diagram, then a DB schema design (two different things!).  Maybe a basic class diagram but keep it simple, only note the main stuff that's of interest, devs can figure that stuff out by looking at the code.

If you're having troubles getting started, just pretend there's another developer there in the room right next to you, who doesn't know the first thing about the system, I relatively impatient and just needs to know the gist of it. Then start explaining, and write down what you say :)

Title: How to document a project which is already developed?

Body:
I would like to know what options are available for documenting a project which has already been developed, as the developers who worked on didn't write even a single page of documentation.

The project has no other details other than many pages of scripts with functions written and modified by developers who worked on this project from the past 2 years. All I have is the database schema and project files. I would like to know if there is any way to organize this project and document it so that it could be helpful for the developers who will be working on this project in the future.

The project was developed with PHP and MySQL. The functions are poorly commented so I can't get good results when I run it with doxygen.


问:
Registration: Email hash and verifying only one account per email
I'm using a registration function that hashes the email in PBKDF2 with a random and unique Salt each time. The hashes email and his salt are saved in the DB. No problem with that.
The problem is that now I want to make sure that users only create one single account per email. Obviously to verify that I need to check my DB and that's where the problem starts. I either lose in security or in time.

Because as I see it I have 2 choices:

1 - I change my hash method and use a common Salt for all emails. Which make me lose a bit of security.

Or

2 - I hash the email with all the Salts from the DB and check for matches. My guess is that this will be horribly slow.

So my question are:

What should I do? Optimize security or "time"?

Maybe hashing emails with unique and random salts in PBKDF2 is too much? If yes, what hashing method should I use?

Is there any other solution?

PS: I didn't post any code because I think this is more of a theory discussion but if code is needed let me know, I will add it.

答:
If your purpose is to merely protect the emails, a simple hashing algorithm is all that is required. There is no point in even adding a random salt for making the system more secure, as you are not storing sensitive information.

For most hashing algorithms, the chance for a collision is negligent. So no two emails should be able to create the same hash. That way, you just need to make that column unique to detect duplicate emails.


答:
Who will be reading the documentation? What will the documentation be used for? These are the most important questions to answer. For example, documentation for maintenance developers would focus more on structure whereas documentation for developers integrating with the product would focus more on web services and database structure.

In general, do as much documentation as is required and no more. Many organizations require documentation because someone insisted it is best practice but the documentation ends up gathering dust.

Assuming that people will actually use the documentation, do not try to capture the code and database to the smallest level. Developers will look at the code for minutiae. Instead, focus on details that are not apparent in the code, for example:

The use cases the product meets. This may be difficult considering the age of the product but capturing what the product is meant to do gives vital context to non-technical readers and testers. Who are the competitors in the market (if any)? Is there anything excluded from the product's scope?

Any clear non-functional requirements. For example, was the product written to handle a certain volume? How old can the data be? Where is caching used? How are users authenticated? How does access control work?

A context diagram showing interaction with other systems, such as the database, authentication sources, backup, monitoring and so on.

(If known) Risks and how they were mitigated along with a decision register. This is probably difficult in retrospect but there are often critical decisions that influence a design. Capture any that you know.

Common design patterns or design guidelines. For example, is there a standard way of accessing the database? Is there a coding or naming standard?

Critical code paths, usually using flow charts or UML activity or sequence diagrams. There may not be any in the project but these are usually ones business users have articulated.

Even if all this information is not available, start now. The developers that come after you will thank you.

Good automated unit tests or test cases can also be useful documentation, albeit hard to access for less technical people.

It also sounds like you need to make a cultural change to include documentation. Start small but, ideally, the project should not be "done" until it has at least a minimal level of documentation. This is probably the hardest step because the above are things you can control. This is something others must buy into. However, it can also be the most rewarding, particularly if the next project you do comes with good documentation.

ContentLicense: CC BY-SA 4.0


答:
Constructors are fundamentally different from other methods:

They are generated if you do not write them.

All base class constructors are called implicitly even if you don't do it manually

You do not call them explicitly but by creating objects.

So why are they not inherited? Simple answer: Because there is always an override, either generated or written manually.

Why does every class need a constructor? That is a complicated question and I believe the answer is compiler dependent. There is such a thing as a "trivial" constructor for which the compiler does not mandate that it will be called it seems. I think that is the closest thing to what you mean by inheritance but for the three reasons stated above I think comparing constructors to normal methods is not really useful. :)

Title: Why are constructors not inherited?


问:
I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?
My day job is  java/web developer. I have been using eclipse for ~5years. I think its excellent and I also use Webstorm for javascript and html/jsp.

I do on occasion need to ssh into server and mess around with config files; for this I use vi and it pains me. I have to get up a webpage listing the syntax/commands : press escape, then asterix, turn around three times and the text will be entered two lines above your cursor. Its so unintuitive to me, and I imagine anyone who grew up in the late eighties nineties.

Here are the main reasons I think eclipse is brilliant(and I assume other IDE's), and do not switch to emacs and/or vim.

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

availablity of 3rd party plugins - eg
findbugs/checkstyle.

One of the arguments I hear is that with emacs/vim you can create your own plugins - well OK, but you can do that in eclipse too. But you don't need to as everything is already there!  Its like saying buy this half built car, you can build the rest yourself.

Why are people using emacs/vim ? Do people who use it actually work on complex object-oriented projects in large organisations ?

What are the reasons to switch to vim/emacs. How would my productivity increase if I did switch?

答: Use whatever tool fits your needs. Knowing VIM or Emacs is a good thing if you ever have to login into a remote server and edit a config file or something similar. I know VIM reasonably well, but I wouldn't use it to develop in Java. That's what Eclipse, Netbeans etc. are made for.</p>

ContentLicense: CC BY-SA 2.5


问:
Is this a Best Practice with Enum in C#
When Enum is used as below, say if we have

```<code>enum Designation
{
    Manager = 0,
    TeamLead = 1,
    Associate = 2
}
</code>```

then write the below code

```<code>if (designation == Designation.TeamLead) //somecode
</code>```

Now if we decide to change the enum element from "TeamLead" to "Lead" then we have to modify the above line of code as well i.e. designation == Designation.TeamLead to designation == Designation.Lead. So what is the best practice.

答: Just use a refactoring tool. You cannot circumvent the fact that if you rename something you have to rename it everywhere but a refactoring tool will make that easy.</p>

Title: Is this a Best Practice with Enum in C#


答:
Renaming an element of an enum is not a problem: Visual Studio does that for you, while ensuring that every reference to it will be renamed as well.

On the other hand, other issues may arise when "reusing" the elements in such way:

Business behavior

Imagine that TeamLead is a team lead, while Lead is a lead developer in a team. Imagine the following piece of code:

```<code>if (role != Designation.TeamLead)
{
    // The user cannot fire a member of a team: only a team lead can do it.
    this.DenyFiringTeamMember();
}
</code>```

If you rename the role, you will miss the business rules, i.e. the fact that only a team lead can fire a team member. Now, lead developer can fire other developers, while only team lead is expected to be able to do it.

Dependencies

Unless you're Google, you may have dependencies in external projects. Visual Studio won't be able to find those, so the problem will arise the next time you open a solution which is referencing the old TeamLead.

ToString

Sometimes, and this is an extremely bad practice, the item from the enum is converted to string, and then used in a comparison, or stored in database, etc. Example:

```<code>if (role.ToString() == "TeamLead")
{
    // I never understood how to compare variables, and I don't care.
}
</code>```

Renaming the element will break those pieces of code. Maybe it's better: you'll be able to find them and rewrite them correctly.

Title: Is this a Best Practice with Enum in C#

Body:
When Enum is used as below, say if we have

```<code>enum Designation
{
    Manager = 0,
    TeamLead = 1,
    Associate = 2
}
</code>```

then write the below code

```<code>if (designation == Designation.TeamLead) //somecode
</code>```

Now if we decide to change the enum element from "TeamLead" to "Lead" then we have to modify the above line of code as well i.e. designation == Designation.TeamLead to designation == Designation.Lead. So what is the best practice.

Body:
Renaming an element of an enum is not a problem: Visual Studio does that for you, while ensuring that every reference to it will be renamed as well.

On the other hand, other issues may arise when "reusing" the elements in such way:

Business behavior

Imagine that TeamLead is a team lead, while Lead is a lead developer in a team. Imagine the following piece of code:

if (role != Designation.TeamLead)
{
    // The user cannot fire a member of a team: only a team lead can do it.
    this.DenyFiringTeamMember();
}

If you rename the role, you will miss the business rules, i.e. the fact that only a team lead can fire a team member. Now, lead developer can fire other developers, while only team lead is expected to be able to do it.

Dependencies

Unless you're Google, you may have dependencies in external projects. Visual Studio won't be able to find those, so the problem will arise the next time you open a solution which is referencing the old TeamLead.

ToString

Sometimes, and this is an extremely bad practice, the item from the enum is converted to string, and then used in a comparison, or stored in database, etc. Example:

if (role.ToString() == "TeamLead")
{
    // I never understood how to compare variables, and I don't care.
}

Renaming the element will break those pieces of code. Maybe it's better: you'll be able to find them and rewrite them correctly.


答:
Most refactoring tools can easily help with this. It allows mass renaming based on language semantics, not only text-replace.

But if you use complex enums for business logic, I would start thinking if you shouldn't be using proper OOP.

Title: Is this a Best Practice with Enum in C#


答:
The most basic answer to your question is this: Most C# IDEs I know of have a Refactoring option that easily lets you rename variables and references, such as enum types. If you highlight TeamLead, anywhere it's used, right-click it and look for a Rename option, you should be able to change references in all code files of your project. If you reference it as a string at some point, it may be good to do a full text search and handle individual cases.

However, my full answer, which I can only hope you care about, is that this is the wrong way of going about things in an object-oriented language. You should especially take note of times when you're seperating large blocks of logic by an if-else/switch, and even using part of one block in another, as a time when object-oriented design would help you. Here's how I'd do it, in incomplete pseudo-code:

```<code>abstract class ProjectMember {
    public abstract void reassignTask(Task t);
}

class Manager : ProjectMember {
    public void reassignTask(Task t) {
        // TODO: manager case
    }
}

class TeamLead : ProjectMember {
    public void reassignTask(Task t) {
        // TODO: TeamLead case
    }
}

class Associate : ProjectMember {
    public void reassignTask(Task t) {
        // TODO: associate case
    }
}

// this is the function where you'd be getting rid of a switch statement, by way of the above code.
void reassignMemberTask(ProjectMember mem, Task t) {
    mem.reassignTask(t);
}
</code>```

Title: Is this a Best Practice with Enum in C#

Body:
The most basic answer to your question is this: Most C# IDEs I know of have a Refactoring option that easily lets you rename variables and references, such as enum types. If you highlight TeamLead, anywhere it's used, right-click it and look for a Rename option, you should be able to change references in all code files of your project. If you reference it as a string at some point, it may be good to do a full text search and handle individual cases.

However, my full answer, which I can only hope you care about, is that this is the wrong way of going about things in an object-oriented language. You should especially take note of times when you're seperating large blocks of logic by an if-else/switch, and even using part of one block in another, as a time when object-oriented design would help you. Here's how I'd do it, in incomplete pseudo-code:

abstract class ProjectMember {
    public abstract void reassignTask(Task t);
}

class Manager : ProjectMember {
    public void reassignTask(Task t) {
        // TODO: manager case
    }
}

class TeamLead : ProjectMember {
    public void reassignTask(Task t) {
        // TODO: TeamLead case
    }
}

class Associate : ProjectMember {
    public void reassignTask(Task t) {
        // TODO: associate case
    }
}

// this is the function where you'd be getting rid of a switch statement, by way of the above code.
void reassignMemberTask(ProjectMember mem, Task t) {
    mem.reassignTask(t);
}


问:
Distinguishing between UI command & domain commands
I am building a WPF client application using the MVVM pattern that provides an interface on top of an existing set of business logic residing in a library which is shared with other applications.  The business library followed a domain-driven architecture using CQRS to separate the read and write models (no event sourcing).  The combination of technologies and patterns has brought up an interesting conundrum:

The MVVM pattern uses the command pattern for handling
user-interaction with the view models. .NET provides an ICommand
interface which is implemented by most MVVM frameworks, like MVVM
Light's RelayCommand and Prism's DelegateCommand.  For example, the view model would expose a number of command objects as properties that are bound to the UI and respond when the user performs actions like clicking buttons.

Many implementations of the CQRS use the command pattern to isolate
and encapsulate individual behaviors.  In my business library, we have implemented the write model as command / command-handler pairs.  As such, when we want to do some work, such as create a new order, we 'issue' a command (CreateOrderCommand) which is routed to the command-handler responsible for executing the command.

This is great, clearly explained in many sources and I am good with it.  However, take this scenario:

I have a ToolbarViewModel which exposes a CreateNewOrderCommand
  property.  This ICommand object is bound to a button in the UI.  When
  clicked, the UI command creates and issues a new CreateOrderCommand
  object to the domain which is handled by the CreateOrderCommandHandler.

This is difficult to explain to other developers and I am finding myself getting tongue-tied because everything is a command.

I'm sure I'm not the first developer to have patterns overlap like this where the naming/terminology also overlap.  How have you approached distinguishing your commands used in the UI from those used in the domain?

(Edit: I should mention that the business library is UI-agnostic, i.e. no UI technology-specific code exists, or will exists, in this library.)

答:
I tend to resolve these naming conflicts by simply choosing different names.

Perhaps you have already started calling these things by different names internally, if so, have the codebase reflect that. If not, think of something (UserCommand vs WriteCommand, Command vs Request, Action vs Command...)

Basically, the overloading of the word "command" creates confusion, so change your terminology. It means deviating from the standard design pattern names, but that's better than constant confusion.

Terminology is not gospel. The terminology used by design patterns is supposed to make talking about the software easier. If it does the opposite, change it (and document that and why you did it)


问:
Do Windows Installers for internal business applications make sense?
I'm trying to build a general understanding for what's common in this situation so that I can decide if it makes sense to pursue it further.

Are installers welcome in a typical corporate environment with the following?

Change control process

Dev/QA/Production environments

Designated deploy teams for various areas (firewall, database, windows, etc.).

Is there a "litmus test" that could be applied to an application to see if it is a good candidate for creating an installer? *

Are installers simple enough that every application should have one?

Are installers even the right tool?

Is it reasonable to expect developers to learn something like WiX to support installers?

Maintainability in general is a concern, i.e., is creating an installer a niche skill?

*

For example, I have a set of winform applications that are in a shared directory on a production server.  Specific groups can run the applications from this directory but only system admins can modify the executables.  The current deploy process involves having an admin copy/paste the executables and libraries to the shared directory.

Since the applications are not installed on the individual users' machine, does it make sense to create an installer for deploying new versions of these applications to the shared directory?

Edit--

I felt that the answers here gave some solid advice so I wanted to share what I came up with for my current project where I needed to build a large number of applications and deploy them to individual folders.

I found a NuGet package called _PublishedApplications that mimics the behavior of _PublishedWebsites for web projects.  The idea is you install the NuGet package to your projects and it adds a target that will copy the build artifacts to a _PublishedApplications directory in the output path.  This behavior is activated by running MSBuild from the command line and specifying an outdir property:

```<code>msbuild /p:Configuration=Release /p:outdir=C:\path\to\outdir MySolution.sln
</code>```

This will give you a directory structure similar to the following:

C:\path\to\outdir

_PublishedApplications\

Project1\

dlls, exes, etc.

Project2\

...

From there, creating a zip that can be extracted in the various environments is fairly painless.

答:
As with all engineering decisions, it depends.

Probably the most important factor is to understand who the consumer of your installation process is and what skillset the development team has.

Since it's internal, I assume it's deployed by an internal IT department.  They are probably no strangers to command shells.

Graphical install wizards are useful for software that is distributed to external customers directly because simple assumptions about your configuration are no longer valid, such as file server locations, security policies, etc.  Therefore, you need to guide each user through picking settings themselves.

In your environment, this stuff is probably dictated by either development or IT and rarely change.  Therefore, I recommend using shell scripts to copy files around to the appropriate place.  The scripts should live within your product as part of the package that is released.  It should also be version controlled along with your app.

Where I work, our entire web application is installed via an InstallShield wizard, which asks a bunch of questions, most of which are file system locations, db connection information and other settings that just end up in config files.  It's difficult to automate.  Since the web app installation at its core just created a couple of databases and copies files, I am writing a new installer using either Ant or Powershell which simply runs .sql files and copies files.

Then everybody can understand how it works and maintain it more effectively.


问:
How to run C++ code in browser using asm.js?
An asm.js application is very fast (near native C++ speed):

http://kripken.github.io/mloc_emscripten_talk/micro4b.png

But how is it possible to write one in C++, convert it to LLVM code, then do some trick with emscripten/asm.js ? I haven't found any tutorial about it.

And if I write the code in C++, then how to use the js API-s, for example XMLHttpRequest, WebSockets, Canvas or WebGL?

答:
I believe you are mistaken in your understanding of asm.js.

First off, from their FAQ

Q. Is asm.js a new language?

  A. No, it's just (a subset of) JavaScript.

And you asked clarification added :

But how is it possible to write one [an asm.js application] in C++

You don't write an "asm.js application", rather asm.js is a target1 to compile your C++ code to.

This article by John Resig provides a number of details that may better explain how asm.js would be used.

Starting with this image:

 clang / LLVM => emscripten => JS engine">

you can see that asm.js is a translation target of emscripten.  Emscripten handles translating the LLVM bytecode into JavaScript, and asm.js is a subset of JavaScript.  Staying within asm.js' restricted subset of JavaScript allows the code to be optimized and run faster.

You also asked:

And if I write the code in C++, then how to use the js API-s

Again, you're kind of missing the point.  Asm.js enables porting existing C/C++ applications into JavaScript so they can be run within a browser.  You wouldn't normally be able to use JS APIs within your C/C++ code, and there's nothing magical about asm.js to allow that.

If you have a new application to write that needs JS APIs then you should write the application in JS and not futz with trying to write in C++ and then port to JavaScript.

And going back to Resig's article, there are two key quotes for your question:

the kind of applications that are going to target Asm.js, in the near future, are those that will benefit from the portability of running in a browser but which have a level of complexity in which a direct port to JavaScript would be infeasible

and

As you can probably see from the code above Asm.js isn’t designed to be written by hand. ... The most common use case for Asm.js right now is in applications complied from C/C++ to JavaScript. Almost none of these applications interact with the DOM in a meaningful way, beyond using WebGL and the like.

What you might want to consider doing instead is having a JavaScript program that calls the JS APIs that you need along with making calls to the C++ that you compiled to JavaScript.  Have a look at this emscripten tutorial to see how to call C++ code from JavaScript.

For some additional research, emscripten has a tutorial that might help you get started with understanding how to take C++ code, run it through LLVM, and then target asm.js.

1 Strictly speaking, that's not true.  The C/C++ code is unaware of what it's going to be compiled to, so I can't really call asm.js a target. Another tool (emscripten) takes the LLVM output and then translates to asm.js compliant JavaScript.  But I'm going to call it a target because it's easier to understand.

Body:
I believe you are mistaken in your understanding of asm.js.

First off, from their FAQ

Q. Is asm.js a new language?

  A. No, it's just (a subset of) JavaScript.

And you asked clarification added :

But how is it possible to write one [an asm.js application] in C++

You don't write an "asm.js application", rather asm.js is a target1 to compile your C++ code to.

This article by John Resig provides a number of details that may better explain how asm.js would be used.

Starting with this image:

you can see that asm.js is a translation target of emscripten.  Emscripten handles translating the LLVM bytecode into JavaScript, and asm.js is a subset of JavaScript.  Staying within asm.js' restricted subset of JavaScript allows the code to be optimized and run faster.

You also asked:

And if I write the code in C++, then how to use the js API-s

Again, you're kind of missing the point.  Asm.js enables porting existing C/C++ applications into JavaScript so they can be run within a browser.  You wouldn't normally be able to use JS APIs within your C/C++ code, and there's nothing magical about asm.js to allow that.

If you have a new application to write that needs JS APIs then you should write the application in JS and not futz with trying to write in C++ and then port to JavaScript.

And going back to Resig's article, there are two key quotes for your question:

the kind of applications that are going to target Asm.js, in the near future, are those that will benefit from the portability of running in a browser but which have a level of complexity in which a direct port to JavaScript would be infeasible

and

As you can probably see from the code above Asm.js isn’t designed to be written by hand. ... The most common use case for Asm.js right now is in applications complied from C/C++ to JavaScript. Almost none of these applications interact with the DOM in a meaningful way, beyond using WebGL and the like.

What you might want to consider doing instead is having a JavaScript program that calls the JS APIs that you need along with making calls to the C++ that you compiled to JavaScript.  Have a look at this emscripten tutorial to see how to call C++ code from JavaScript.

For some additional research, emscripten has a tutorial that might help you get started with understanding how to take C++ code, run it through LLVM, and then target asm.js.

1 Strictly speaking, that's not true.  The C/C++ code is unaware of what it's going to be compiled to, so I can't really call asm.js a target. Another tool (emscripten) takes the LLVM output and then translates to asm.js compliant JavaScript.  But I'm going to call it a target because it's easier to understand.


问:
What best practices should be employed in a PHP login script?
I am wanting to re-write my login scripts for clients websites to make them more secure. I want to know what best practices I can implement into this. Password protected control panels are in their abundance, but very few seem to impliment best practices in terms of code writing, speed and security.

I will be using PHP and a MYSQL database.

I used to use md5, but I see that sha256 or sha512 would be better (together with secure hash and salt).

Some login scripts log the ip address throughout the session or even the user agent, but I want to avoid that as it isn't compatible with proxy servers.

I am also a little behind the best practice in using sessions in PHP 5 (last time I read up was PHP 4) so some best practices with this would be helpful.

Thanks.

答:
Never use MD5 or SHA1 hashing algorithms. Always stick to newer ones like SHA512

Always use a strong random generated salt

Never email your users their passwords, even in case of "Forgot Password"

Never use the mysql_* functions. They are long depreciated. Stick to PDO

Never store passwords in sessions or cookies


答:
Yes, you can write C++ code and compile it to asm.js, using emscripten. I haven't tried it myself, and I'm not sure how ready this is for prime time. It seems to be good enough to run a bunch of games though.

Here is a tutorial: http://kripken.github.io/emscripten-site/docs/getting_started/Tutorial.html . Looking at the tutorial, it seems quite easy to compile C++ code:

```<code>// hello.cpp
#include<stdio.h>

int main() {
  printf("hello, world!\n");
  return 1;
}
</code>```

```<code>$ ./emcc tests/hello.cpp -o hello.html
</code>```

Title: How to run C++ code in browser using asm.js?

Body:
An asm.js application is very fast (near native C++ speed):

http://kripken.github.io/mloc_emscripten_talk/micro4b.png

But how is it possible to write one in C++, convert it to LLVM code, then do some trick with emscripten/asm.js ? I haven't found any tutorial about it.

And if I write the code in C++, then how to use the js API-s, for example XMLHttpRequest, WebSockets, Canvas or WebGL?

Body:
Yes, you can write C++ code and compile it to asm.js, using emscripten. I haven't tried it myself, and I'm not sure how ready this is for prime time. It seems to be good enough to run a bunch of games though.

Here is a tutorial: http://kripken.github.io/emscripten-site/docs/getting_started/Tutorial.html . Looking at the tutorial, it seems quite easy to compile C++ code:

// hello.cpp
#include<stdio.h>

int main() {
  printf("hello, world!\n");
  return 1;
}

$ ./emcc tests/hello.cpp -o hello.html


问:
Programming Style in Large Scale C++ Applications
Recently I've been browsing source code of large applications written in C++ to learn a bit but I couldn't help but notice that most if not all use a lot of IFDEFs and class-less functions (where they could have been class members/methods).

An example is Qt Creator IDE source code:

http://qt.gitorious.org/qt-creator/qt-creator/blobs/master/src/app/main.cpp

If you notice, it has a bunch of functions around the main() function; one of them, for example, is:

```<code>static inline void toHtml(QString &t)
</code>```

the above method is defined outside while I think it could have been part of some utility class maybe.

Also, I think IFDEFs make the programs messy (again my opinion).

My question is: is it just an accepted practice in C++ world to mix procedural and OO code like that?

答:
It is generally accepted in many worlds. In fxCop for C# for example, it will flag you for not making methods static when they use no member variables. The idea is that a class should only define enough of a public interface to protect its invariants; the rest is the responsibility of the consumer, who knows best how the class will be consumed.

I'm not sure I would go so far as to consider it universally accepted, but it is a common practice.


答:
Sometimes the "class" part of a utility class does nothing more than act as a pseudo-namespace. There is no instance state needed, just parameters passed into a function. For example the Math class in C#. In that case  you may as well just have free functions in a namespace.

Sometimes behavior should be a property of the "environment" not the object. For example a save() function may be layer/environment specific and should be a free function in that layer. The object may visit many layers (physical or logical) where saving may not be relevant.

Title: Programming Style in Large Scale C++ Applications

Body:
Recently I've been browsing source code of large applications written in C++ to learn a bit but I couldn't help but notice that most if not all use a lot of IFDEFs and class-less functions (where they could have been class members/methods).

An example is Qt Creator IDE source code:

http://qt.gitorious.org/qt-creator/qt-creator/blobs/master/src/app/main.cpp

If you notice, it has a bunch of functions around the main() function; one of them, for example, is:

```<code>static inline void toHtml(QString &t)
</code>```

the above method is defined outside while I think it could have been part of some utility class maybe.

Also, I think IFDEFs make the programs messy (again my opinion).

My question is: is it just an accepted practice in C++ world to mix procedural and OO code like that?


问:
VPS vs Web Hosting: Which one is good for java web services
I have some questions about VPS and web hosting.

As far as I understand, VPS is a virtual machine on which we can do anything as we can do with our local machine. Install software, change settings etc.

Web hosting is where we have only a folder in which we place our web site in.

However, most of the provider currently advertise their service as "VPS web hosting". This confuses me, does that mean they are selling VPS service which can only host web sites?

I need a virtual machine which host one RESTful Java service using Tomcat and Jersey and MYSQL at the backend. My plan was to hire a VPS machine, install Tomcat 7 and MySQL on that machine. Is this the right way to go?

Many thanks.

答:
VPS hosting

You get a virtual machine which is all your own, you run whatever software you can on the supported OS. An example is AWS, which runs heavy JVM apps just fine, provided you create instances with enough RAM.

You are responsible for your own OS (security and all).

A VM is just like a physical machine (it fails, etc), it just can be replaced faster.

You have full control over your OS, and can freely tweak JVM flags.

You can add any native components you might need.

Usually lower tier is cheap or even free (AWS) but rather resource-constrained.

JVM-enabled hosting

Some providers don't give you your own machine but give you enough JVM access to run whatever jars/wars you might upload.

You don't need to bother about maintaining the OS, the JVM, etc.

You have less control over things beyond JVM, and even JVM flags.

You still got only one instance of your app, but possibly with redundancy higher than on a VPS.

Google AppEngine

It further limits your contact with OS and JVM.

It is easy to have more instances of your app.

Your app is redundantly deployed (not on one machine).

You are limited to Google-supported data store options (fortunately a MySQL-compatible option exists).

The lower tier is free, but free resource access quotas may end soon unless you're careful.

Take a look at another relevant SO thread, too.


答:
It is a rather subjective question - there are many schools of practice for writing C++ code.

C++ affords you the ability to pick and choose what paradigms you want to use for writing your code. The language allows you to use procedural, object-oriented, generic, and functional constructs (especially with C++11 features).

You don't necessarily need to build utility classes (unlike, say, in Java, where everything has to be in a class), as static functions in a class may not be required and can just be standalone free functions.

Conditional compilation is a necessity because of disparate platforms. I worked in defense, and have written code using Qt, boost, libraries for video games, and have worked on a variety of platforms including Linux, HP-UX, AIX, Windows, IRIX, and Mac OSX - platforms are different enough that code written for one does not necessarily work on a different platform. Some easy examples are:

Endianess - Some architectures (like x86) are little endian, but many other architectures (like SPARC) are big endian. Networking is also reliant on big endian addressing. When you write code across different architectures, sometimes you need to conditionally compile in code that supports such endian differences.

Different library calls - Windows uses winsock as its networking API, and it's similar to BSD Sockets used by Unix and Unix-derivatives. However, it is different enough that the function calls aren't similar. Additionally, there are library calls that exist in some flavors of Unix that don't exist in other flavors, or derivatives, so conditional compilation is needed for that too.

Compiler differences or versioning differences - Different versions of compilers, or different compilers altogether, may support functionality/libraries that aren't supported by other compilers.

Even if you use a library like Qt, which aims to be cross-platform, there is still conditional compilation happening, as you found out. These cross-platform libraries are there to reduce your own needs to do conditional compilation.

Additionally, coding styles and standards may be influencing how code is written.

http://qt-project.org/wiki/Coding-Conventions - These are Qt's coding conventions for developers and contributors to the library.

Boost Coding Conventions - The Boost library's conventions for contributors.

Compare with the Joint Strike Fighter C++ Coding Standards - I have not had to read this, but it's vastly different to most standards I've had to follow and very stringent in regards to what C++ features can and can't be used, and how to structure code.

Just more anecdotes from my past - C++ can be written in many ways as influenced by internal standards. For example, some organizations restrict the use of the C++ Standard Library, especially in regards to using the standard containers (like std::vector and std::list) - this may be due to the environment involved (like embedded systems).

Ultimately, it does come down to this: there are many ways to write C++, and it is acceptable to mix and match different paradigms in a single C++ program and code base, because there may be better/simpler ways to express something in one paradigm than to be locked into using a single pattern for an entire code base.

If you want to look at large C++ code bases that have high code quality, I will say that Boost and Qt are among the better examples.

Generally and widely accepted conventions and idioms for C++ programming are provided in books like Effective C++ and More Effective C++


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
Mix Up the Workweek by Setting Your Own "20-Percent Time"

Many large companies have policies that allow employees to spend some of their time working on their own projects. These programs are often used to entice high-caliber job applicants, as well as encourage innovation. For example, Google has what it calls “20-Percent Time”, where its employees spend one day each workweek on project they’re passionate about.

Why?

Innovation and creativity

Exploration

Opportunity

Motivation


答:
Wyatt takes off his programmer hat and puts on his Director of IT hat

If this is an internal line of business application then you only need aim at one environment -- said business. I would call the head of IT and ask him how they would like to manage deployment. IT departments have been dealing with this for a while so they might have a strong preference for xcopy or MSI-based options or something else entirely such as your current option.

I'll add that department would at the very least appreciate the gesture and could likely become a valuable ally as chances are they know more about the existing line of business app and problems than you realize.

Title: Do Windows Installers for internal business applications make sense?

Body:
I'm trying to build a general understanding for what's common in this situation so that I can decide if it makes sense to pursue it further.

Are installers welcome in a typical corporate environment with the following?

Change control process

Dev/QA/Production environments

Designated deploy teams for various areas (firewall, database, windows, etc.).

Is there a "litmus test" that could be applied to an application to see if it is a good candidate for creating an installer? *

Are installers simple enough that every application should have one?

Are installers even the right tool?

Is it reasonable to expect developers to learn something like WiX to support installers?

Maintainability in general is a concern, i.e., is creating an installer a niche skill?

*

For example, I have a set of winform applications that are in a shared directory on a production server.  Specific groups can run the applications from this directory but only system admins can modify the executables.  The current deploy process involves having an admin copy/paste the executables and libraries to the shared directory.

Since the applications are not installed on the individual users' machine, does it make sense to create an installer for deploying new versions of these applications to the shared directory?

Edit--

I felt that the answers here gave some solid advice so I wanted to share what I came up with for my current project where I needed to build a large number of applications and deploy them to individual folders.

I found a NuGet package called _PublishedApplications that mimics the behavior of _PublishedWebsites for web projects.  The idea is you install the NuGet package to your projects and it adds a target that will copy the build artifacts to a _PublishedApplications directory in the output path.  This behavior is activated by running MSBuild from the command line and specifying an outdir property:

```<code>msbuild /p:Configuration=Release /p:outdir=C:\path\to\outdir MySolution.sln
</code>```

This will give you a directory structure similar to the following:

C:\path\to\outdir

_PublishedApplications\

Project1\

dlls, exes, etc.

Project2\

...

From there, creating a zip that can be extracted in the various environments is fairly painless.


答:
An installer always makes sense, if deployment requires anything more complicated than copying the relevant file(s) to some folder and running the EXE.  If there are additional steps that need to be taken to set the product up properly, there's two ways to go about it.

You can write out a list for someone to follow.  Humans being humans, someone's bound to screw it up, and then call you up asking for help because your program isn't running right.

You can write out a list for a computer to follow (an install script).  This makes it much less likely that user error will screw up deployment.

On the other hand if you don't have any setup tasks that need to be performed, then just give them a zipfile.  That's simpler than running an installer.


问:
Is Domain Entity violating Single Responsibility Principle?
Single responsibility ( reason to change ) of an entity should be to uniquely identify itself, in other words, its responsibility is to be findable.

Eric Evan's DDD book, pg. 93:

most basic responsibility of Entities is to establish continuity so
  that behavior can be clear and predictable. They do this best if they
  are kept spare. Rather than focusing on the attributes or even the
  behavior, strip the Entity object's definition down to the most
  intrinsic characteristics, particularly those that identify it or are
  commonly used to find or match it. Add only behavior that is essential
  to the concept and attributes that are required by that behavior.

Beyond that, look to remove behavior and attributes into other objects
  associated with the core Entity .Beyond identity issues, Entities tend
  to fulfill their responsibilities by coordinating the operations of
  objects they own.

1.

... strip the ENTITY object's definition down to the most intrinsic
  characteristics, particularly those that identify it or are commonly
  used to find or match it. Add only behavior that is essential to the
  concept ...

Once an entity is assigned a unique ID, its identity is established and so I would assume such  an entity doesn't need any behavior to maintain its identity or to help it identify itself. Thus, I don't understand what kind of behavior is author referring to ( besides find and match operations ) with "behavior that is essential to the concept"?

2.

... strip the ENTITY object's definition down to the most intrinsic
  characteristics, particularly those that identify it or are commonly
  used to find or match it. ... Beyond that, look to remove behavior and
  attributes into other objects associated with the core ENTITY.

So any behavior that doesn't help identify the entity, but we'd still characterize that behavior as being an intrinsic characteristic of that entity ( i.e. barking is intrinsic to dogs, flying is intrinsic to airplanes, laying eggs is intrinsic to birds ... ), should be put into other objects associated with that entity ( example: we should put barking behavior into an object associated with a dog entity )?

3.

Beyond that, look to remove behavior and attributes into other objects
  associated with the core ENTITY.

a) MyEntity delegates responsibilities A_resp and B_resp to objects a and b, respectively.

Even though most of A_resp and B_resp work is done by a and b instances, clients are still served A_resp and B_resp through MyEntity, which means that from the client's perspective the two responsibilities belong to MyEntity. Thus, doesn't that mean MyEntity also has A_resp and B_resp responsibilities and as such is violating SRP?

b) Even if we assume that A_resp and B_resp don't belong to MyEntity, MyEntity still has a responsibility AB_resp of coordinating the operations of objects a and b. So doesn't MyEntity violate SRP since at minimum it has two responsibilities – to uniquely identify itself and also AB_resp?

```<code>class MyEntity
{
    private A a = ...
    private B b = ...

    public A GetA()
    { ... }

    public B GetB()
    { ... }

    /* coordinates operations of objects a and b */
    public int AworkB()
    { ... }
}

/* A encapsulates a single responsibility resp_A*/
/* A is value object */
class A
{ ... }

/* B encapsulates a single responsibility resp_B*/
/* B is value object */
class B
{ ... }
</code>```

UPDATE:

1.

Behavior in this context is refering to semantic behavior. For
  example, a Property on a class (i.e. attribute on a domain object)
  that is used to uniquely identify it has a behavior. While this is not
  represented in code directly. The expected behavior is that there will
  not be any duplicate values for that property.

So in code we would almost never need to actually implement a behavior ( i.e. an operation ) that would somehow maintain entity's identity, since as you explained such a behavior only exist as a concept in a domain model ( in the form of a ID attribute of an entity), but when we translate this ID attribute into code, part of its semantics is lost ( i.e. the part which implicitly makes sure the ID value is unique is lost )?

2.

Furthmore, a property such as Age has no context outside of a Person
  Entity, and as such, makes no sense to move into a different object
  ... However that information could easily be stored in a separate
  location that the unique identifier, hence the confusing reference to
  behavior. Age could be a lazy loaded value.

a) If Age property is lazy loaded, then we may call it a behavior, even though semantically Age is just an attribute?

3.

You could easily have operations specific to Address such as
  verification that it is a valid address. You may not know that at
  design time, but this whole concept is to break down objects into
  their smallest parts

While I agree that we'd lose context by moving Age into different object, the context wouldn't be lost if we moved DateOfBirth property into a different object, but we usually don't move it.

What is the main reason that we'd move Address into another object, but not DateOfBirth? Because DateOfBirth is more intrinsic to Person entity or because there are less chances that somewhere in the future we may need to define operations specific to DateOfBirth?

4.
I must say I still don't know whether MyEntity also has A_resp and B_resp responsibilities and why MyEntity also having AB_resp isn't considered a violation of SRP

EULERFX

1)

The behaviors that the author is referring to are behaviors associated
  with the entity. These are the behaviors that modify the state of the
  entity

a) If I understand you correctly, you're saying that entity should only contain those behaviors that modify its attributes ( i.e. its state )?

b) And what about the behaviors that don't necessarily modify the state of the entity, but are still  considered as being an intrinsic characteristic of that entity ( example: barking would be intrinsic characteristic of a Dog entity, even if it didn't modify Dog's state )? Should we include these behaviors in an entity or should they be moved to other objects?

2)

As far as moving behavior to other objects, the author is referring to
  value objects specifically.

Though my quote doesn't include it, but author does mention in the same paragraph  that in some cases behaviors ( and attributes ) will also get moved into other entities ( though I understand the benefits of moving behaviors to VOs )

3) Assuming MyEntity ( see question 3. in my original post ) doesn't violate SRP, would we say that a responsibility of MyEntity is among other things also comprised of:

a. A_resp + B_resp + AB_resp ( AB_resp coordinates objects a and b )

or

b.  AB_resp + delegating A_resp and B_resp to objects ( a and b ) associated with MyEntity?

4)
Eric Evan's DDD book, pg. 94:

CustomerID is the one and only identifier of the Customer ENTITY (
  figure 5.5 ), but  phone number and address would often be used to
  find or match a Customer. The name does not define a person's
  identity, but it is often used as part of the means of determining it.

In this example, the phone and address attributes moved into Customer,
  but on a real project, that choice would depend on how the domain's
  customers are typically matched or distinguished. For example, if a
  Customer has many contact phone numbers for different purposes, then
  the phone number is not associated with identity and should stay with
  the Sales Contact.

a)

CustomerID is the one and only identifier of the Customer ENTITY (
  figure 5.5 ), but  phone number and address would often be used to
  find or match a Customer. The name does not define a person's
  identity, but it is often used as part of the means of determining it.

Quote states that only attributes associated with identity should stay in an entity.  I assume author means that entity should contain only those attributes that are often used to find or match this entity, while ALL other attributes should be moved?

b) But how/where should other attributes be moved? For example ( assumption here is that address attribute isn't used to find or match Customer and thus we want to move address attribute out of Customer ):

if instead of having Customer.Address ( of type string ) we create a property Customer.Address of type Address, did we move the address attribute into an associated VO object ( which is of type Address ) or would we say that Customer still contains address attribute?

c)

In this example, the phone and address attributes moved into Customer,
  but on a real project, that choice would depend on how the domain's
  customers are typically matched or distinguished. For example, if a
  Customer has many contact phone numbers for different purposes, then
  the phone number is not associated with identity and should stay with
  the Sales Contact.

Isn't author in the wrong here, since if we assume each of the many contact phone numbers that Customer has only belong to that particular Customer, then I'd say these phone numbers are associated with identity just as much as when Customer only had one phone number?

5)

The reason the author suggests stripping the entity down is that when
  one initially creates a Customer entity, there is a tendency to
  populate it with any attribute that one can think of being associated
  with a customer. This is a data-centric approach that overlooks
  behaviors ultimately leading to an anemic domain model.

Off topic, but I thought anemic domain model results from moving behavior out of an entity, while your example is populating an entity with lots of attributes, which would result in Customer having too much behavior ( since we'd probably also include in Customer the behaviors which modify these additional attributes ) and thus in violation of SRP?

thanks

答:
Behavior in this context is refering to semantic behavior. For example, a Property on a class (i.e. attribute on a domain object) that is used to uniquely identify it has a behavior. While this is not represented in code directly. The expected behavior is that there will not be any duplicate values for that property. Something such as an Address  which may have its own identity, but does not exist outside of the context of a Person Entity should still be moved out into it's own object. Thus promoting the Entity into an Aggregate Root.

Furthmore, a property such as Age has no context outside of a Person Entity, and as such, makes no sense to move into a different object. The context would be lost, and therefore you can safely determine that it is a value that is essential to the Person Entity. You could not locate the value otherwise. However that information could easily be stored in a separate location that the unique identifier, hence the confusing reference to behavior. Age could be a lazy loaded value.

So to answer your question. No, it does not violate the Single Responsibility Principle. It is mearly stating that a Person should have only person stuff, and not something like Address, which is more complex and related to a person, should exist as its own entity.

You could easily have operations specific to Address such as verification that it is a valid address. You may not know that at design time, but this whole concept is to break down objects into their smallest parts so that something like this is relatively simple when done after the fact.

Update:
1) In most cases this identity validation is done upon saving an object out to a data store. Which means that the code representing the entity validation exists, but it exists elsewhere. It usually exists with the code that is responsible for issuing the identity value. Which is why I state that the uniqueness is not represented directly in the code for the entity.

2) The correct statement would be that Age is an attribute that has behavior. You would need to document the fact that Age is lazy loaded so that a developer consuming that property can make an accurate decision on how to consume that property

3) DateOfBirth usually is a different object; A date object that already has predefined operations on it. In some languages the date object already has a whole domain model defined on it. For example in c# you can specifiy the timezone, if the date is UTC, add and subtract dates to get a timespan. So your assumption about moving DateOfBirth would be correct.

4) If the only thing that MyEntity does is delegation and cooridination then no it does not violate SRP. Its single responsibility is to delegate and coordinate and is refered to as the Facade pattern

OwnerDisplayName: EdvRusj


答:
Very good question. The SRP shouldn't be taken quite so literrally. Identification/lookup isn't the responsibility of the entity in the regards to the SRP. Someone else is responsible for giving it an ID (namely the store) and for looking it up (namely the Repository).

The primary purpose of an entity is to represent the concepts uncovered by the model. The only difference between an Entity and a Value Object is that the Entity has meaning beyond its non-identifying attributes. For example if a Person changes his Name, he's still the same person, just with a different name.

Title: Is Domain Entity violating Single Responsibility Principle?

Body:
Single responsibility ( reason to change ) of an entity should be to uniquely identify itself, in other words, its responsibility is to be findable.

Eric Evan's DDD book, pg. 93:

most basic responsibility of Entities is to establish continuity so
  that behavior can be clear and predictable. They do this best if they
  are kept spare. Rather than focusing on the attributes or even the
  behavior, strip the Entity object's definition down to the most
  intrinsic characteristics, particularly those that identify it or are
  commonly used to find or match it. Add only behavior that is essential
  to the concept and attributes that are required by that behavior.

Beyond that, look to remove behavior and attributes into other objects
  associated with the core Entity .Beyond identity issues, Entities tend
  to fulfill their responsibilities by coordinating the operations of
  objects they own.

1.

... strip the ENTITY object's definition down to the most intrinsic
  characteristics, particularly those that identify it or are commonly
  used to find or match it. Add only behavior that is essential to the
  concept ...

Once an entity is assigned a unique ID, its identity is established and so I would assume such  an entity doesn't need any behavior to maintain its identity or to help it identify itself. Thus, I don't understand what kind of behavior is author referring to ( besides find and match operations ) with "behavior that is essential to the concept"?

2.

... strip the ENTITY object's definition down to the most intrinsic
  characteristics, particularly those that identify it or are commonly
  used to find or match it. ... Beyond that, look to remove behavior and
  attributes into other objects associated with the core ENTITY.

So any behavior that doesn't help identify the entity, but we'd still characterize that behavior as being an intrinsic characteristic of that entity ( i.e. barking is intrinsic to dogs, flying is intrinsic to airplanes, laying eggs is intrinsic to birds ... ), should be put into other objects associated with that entity ( example: we should put barking behavior into an object associated with a dog entity )?

3.

Beyond that, look to remove behavior and attributes into other objects
  associated with the core ENTITY.

a) MyEntity delegates responsibilities A_resp and B_resp to objects a and b, respectively.

Even though most of A_resp and B_resp work is done by a and b instances, clients are still served A_resp and B_resp through MyEntity, which means that from the client's perspective the two responsibilities belong to MyEntity. Thus, doesn't that mean MyEntity also has A_resp and B_resp responsibilities and as such is violating SRP?

b) Even if we assume that A_resp and B_resp don't belong to MyEntity, MyEntity still has a responsibility AB_resp of coordinating the operations of objects a and b. So doesn't MyEntity violate SRP since at minimum it has two responsibilities – to uniquely identify itself and also AB_resp?

```<code>class MyEntity
{
    private A a = ...
    private B b = ...

    public A GetA()
    { ... }

    public B GetB()
    { ... }

    /* coordinates operations of objects a and b */
    public int AworkB()
    { ... }
}

/* A encapsulates a single responsibility resp_A*/
/* A is value object */
class A
{ ... }

/* B encapsulates a single responsibility resp_B*/
/* B is value object */
class B
{ ... }
</code>```

UPDATE:

1.

Behavior in this context is refering to semantic behavior. For
  example, a Property on a class (i.e. attribute on a domain object)
  that is used to uniquely identify it has a behavior. While this is not
  represented in code directly. The expected behavior is that there will
  not be any duplicate values for that property.

So in code we would almost never need to actually implement a behavior ( i.e. an operation ) that would somehow maintain entity's identity, since as you explained such a behavior only exist as a concept in a domain model ( in the form of a ID attribute of an entity), but when we translate this ID attribute into code, part of its semantics is lost ( i.e. the part which implicitly makes sure the ID value is unique is lost )?

2.

Furthmore, a property such as Age has no context outside of a Person
  Entity, and as such, makes no sense to move into a different object
  ... However that information could easily be stored in a separate
  location that the unique identifier, hence the confusing reference to
  behavior. Age could be a lazy loaded value.

a) If Age property is lazy loaded, then we may call it a behavior, even though semantically Age is just an attribute?

3.

You could easily have operations specific to Address such as
  verification that it is a valid address. You may not know that at
  design time, but this whole concept is to break down objects into
  their smallest parts

While I agree that we'd lose context by moving Age into different object, the context wouldn't be lost if we moved DateOfBirth property into a different object, but we usually don't move it.

What is the main reason that we'd move Address into another object, but not DateOfBirth? Because DateOfBirth is more intrinsic to Person entity or because there are less chances that somewhere in the future we may need to define operations specific to DateOfBirth?

4.
I must say I still don't know whether MyEntity also has A_resp and B_resp responsibilities and why MyEntity also having AB_resp isn't considered a violation of SRP

EULERFX

1)

The behaviors that the author is referring to are behaviors associated
  with the entity. These are the behaviors that modify the state of the
  entity

a) If I understand you correctly, you're saying that entity should only contain those behaviors that modify its attributes ( i.e. its state )?

b) And what about the behaviors that don't necessarily modify the state of the entity, but are still  considered as being an intrinsic characteristic of that entity ( example: barking would be intrinsic characteristic of a Dog entity, even if it didn't modify Dog's state )? Should we include these behaviors in an entity or should they be moved to other objects?

2)

As far as moving behavior to other objects, the author is referring to
  value objects specifically.

Though my quote doesn't include it, but author does mention in the same paragraph  that in some cases behaviors ( and attributes ) will also get moved into other entities ( though I understand the benefits of moving behaviors to VOs )

3) Assuming MyEntity ( see question 3. in my original post ) doesn't violate SRP, would we say that a responsibility of MyEntity is among other things also comprised of:

a. A_resp + B_resp + AB_resp ( AB_resp coordinates objects a and b )

or

b.  AB_resp + delegating A_resp and B_resp to objects ( a and b ) associated with MyEntity?

4)
Eric Evan's DDD book, pg. 94:

CustomerID is the one and only identifier of the Customer ENTITY (
  figure 5.5 ), but  phone number and address would often be used to
  find or match a Customer. The name does not define a person's
  identity, but it is often used as part of the means of determining it.

In this example, the phone and address attributes moved into Customer,
  but on a real project, that choice would depend on how the domain's
  customers are typically matched or distinguished. For example, if a
  Customer has many contact phone numbers for different purposes, then
  the phone number is not associated with identity and should stay with
  the Sales Contact.

a)

CustomerID is the one and only identifier of the Customer ENTITY (
  figure 5.5 ), but  phone number and address would often be used to
  find or match a Customer. The name does not define a person's
  identity, but it is often used as part of the means of determining it.

Quote states that only attributes associated with identity should stay in an entity.  I assume author means that entity should contain only those attributes that are often used to find or match this entity, while ALL other attributes should be moved?

b) But how/where should other attributes be moved? For example ( assumption here is that address attribute isn't used to find or match Customer and thus we want to move address attribute out of Customer ):

if instead of having Customer.Address ( of type string ) we create a property Customer.Address of type Address, did we move the address attribute into an associated VO object ( which is of type Address ) or would we say that Customer still contains address attribute?

c)

In this example, the phone and address attributes moved into Customer,
  but on a real project, that choice would depend on how the domain's
  customers are typically matched or distinguished. For example, if a
  Customer has many contact phone numbers for different purposes, then
  the phone number is not associated with identity and should stay with
  the Sales Contact.

Isn't author in the wrong here, since if we assume each of the many contact phone numbers that Customer has only belong to that particular Customer, then I'd say these phone numbers are associated with identity just as much as when Customer only had one phone number?

5)

The reason the author suggests stripping the entity down is that when
  one initially creates a Customer entity, there is a tendency to
  populate it with any attribute that one can think of being associated
  with a customer. This is a data-centric approach that overlooks
  behaviors ultimately leading to an anemic domain model.

Off topic, but I thought anemic domain model results from moving behavior out of an entity, while your example is populating an entity with lots of attributes, which would result in Customer having too much behavior ( since we'd probably also include in Customer the behaviors which modify these additional attributes ) and thus in violation of SRP?

thanks