问:
Eliminating Dependencies vs Eliminating Redundancy
Upon my assignment to a project, I discovered that many message classes were received and then kept intact and passed around inside the receiving application. When these messages changed, code throughout the entire application had to be changed. Since this problem, I have gotten into the habit of converting messages to a new format upon reception.

However, it feels like I am directly violating DRY (don't repeat yourself): I have these near-identical internal classes that I create from external messages.

Where is the line between eliminating dependencies and eliminating redundancy? Should each module have their own data formats?

答:
I would say this is a break between information and data. Consider this:

Your client has a choice of files they can send you. Either a csv file full of rows with username,id,address and so on, or a pdf with the same stuff on a form. Which one do you want to read? Which one do you want to have a program use?

Data is the fundamental values you are talking about, ID=1 and USERNAME=SRR. Information is data and context. Put the username here, drop the id. Your message classes should be data repositories, holding all the information anyone may require and having methods to collect the raw data.

Then, you pass pointers to these objects around to the various different things that need access to the data. One of the methods will be a simple wrapper around the method calls necessary to produce the data you need, then combine it with the current context to get the information desired.

However, data does require a method of collecting it, and this requires a clearly defined interface. Then you are into interface design, with the requirements therein. If new data may need to be added later on, then the interface needs to account for that. Perhaps your get method has a parameter that lists the various items desired, or a get method is added for each data variable. Whatever you pick must scale, or you are destined to go in and rebuild all the different pieces each time.


答:
To avoid violating the DRY principle you need to figure out the one place information about the messages goes.  You also don't want dependencies from other modules.

How about putting the information in the message itself?  Not just the data, but how to use the data.  That way all the code that uses the message can still use it, but changes to the message don't have to propagate beyond it.

Unless of course changes are to the external interface of the message.  But in that case it's difficult to say how to limit the ripple effect, especially without more specific information.  But the question indicates it's a format issue, which should be taken care of by making the message a "real" object.

ContentLicense: CC BY-SA 3.0

Title: Eliminating Dependencies vs Eliminating Redundancy

Body:
Upon my assignment to a project, I discovered that many message classes were received and then kept intact and passed around inside the receiving application. When these messages changed, code throughout the entire application had to be changed. Since this problem, I have gotten into the habit of converting messages to a new format upon reception.

However, it feels like I am directly violating DRY (don't repeat yourself): I have these near-identical internal classes that I create from external messages.

Where is the line between eliminating dependencies and eliminating redundancy? Should each module have their own data formats?


答:
I'm assuming that an "external message" is something that's coming over a network protocol, e.g. RPC, SOAP, Protocol Buffers, etc.

In that case, it's absolutely a good thing to maintain two separate models. One for messaging, one for domain. It's not unusual to have yet another model for presentation and another model for data.

It seems awfully repetitive, but there are plenty of automapping tools that can reduce the effort to near-nil; in .NET we have AutoMapper, in Java there's Dozer, etc.

More importantly, the alternative is an obnoxious, bloated canonical model which forces everything that touches it to deal with all of the bizarre idiosyncracies of everything else that touches it. When you need to map between models, you usually have the ability to do versioning (choose sane defaults for new fields), but when you have a single shared model... forget about recompiling just one application, you have to rebuild and redeploy your entire architecture. This sucks when you have a distributed system.

Just because two classes have very similar structures does not mean one of them is redundant:

Domain models are "thick" models, meant to accurately model the real world and contain all or most of the business logic for your application. Encapsulation is king and domain objects emphasize behaviour over data.

Messaging models are by definition "thin" models containing nothing but data; in many cases a message has already been validated (in the case of an event message) or will have to be re-validated anyway (in the case of a command), so validation tends to be limited to the format of the message. In addition, the structure of one of these message models is almost always optimized for transmission efficiency (no unnecessary fields) and there may be several "metadata" attributes (like security headers) that would make no sense at all in any other model.

Data models are (traditionally) intended to provide a bridge to a DAL or ORM. Modern tools have gotten pretty good at aligning these with domain models but not nearly all of the way there. Generally there are a lot of annoying restrictions on a data model that also make no sense in a domain model, such as ID properties on every class, bidirectional references, setters on every property, and in some cases every member has to be virtual. The last two are especially problematic; most often you want your domain models to be immutable and sealed (not inheritable).

And finally the presentation model is likely to be much flatter than the domain model, have all sorts of formatting code, and mostly string properties (which have all manner of validation attached to them). Which fields are read-only will depend on the features that the UI is supposed to provide.

It's really, really hard, bordering on impossible, to keep all of these conflicting requirements in sync when trying to maintain an architecture-wide or even application-wide shared model.

Ultimately you will end up doing less work by having custom models with very few dependencies, as opposed to one model with a very high number of dependencies.


问:
Interacting With Data Using Multiple Databases/Servers
All of the projects that I've had to deal with so far have only required a single database on a single server. I'm interested in learning more about how projects that need to scale move to  multiple databases and/or servers to help manage the load. I'm aware of High Scalability, but I'm particularly interested in some code examples or additional resources where I could read more on the subject.

For instance:

How are joins constructed between two tables on multiple databases? (A code example here would be helpful).

Are there any special strategies for tracking which tables are in which database?

Does the application code need to know that one or more databases are spread across multiple servers? If not, at what level are the requests filtered?

When is it time to move beyond a 1 database/1 server setup? How common is it to need to do this?

答: The primary way I've encountered multiple database servers in the web-world (since the question is tagged PHP) is setups where there was one 'master' (write) database, and then one or more replicated 'slave' (read) databases.  Database writes are performed against the 'master' database.  The contents of that database are replicated to the 'slave' servers in near real-time.  Queries - particularly intensive reports - are then run against one of the 'slave' databases to shift the load to those servers.  Keep in mind, that particular setup is best for applications that have a lot of reads, but not a lot of writing.  It is by no means the only way to arrange things.


答:
How are joins constructed between two tables on multiple databases? (A code example here would be helpful).

They're not. NoSQL databases don't do "joins" at all, and even if you could do a SQL join across RDBMS servers, you wouldn't want to if you value performance (c.f. fallacies of distributed computing).

Are there any special strategies for tracking which tables are in which database?

In a relational/SQL database, partitioning is normally done within the confines of a single server/database, using different files placed on different disks. Almost by definition a horizontal scaling solution means that all databases have all the tables and you have some sort of transactional mirroring, replication, or custom eventual-consistency solution to make sure all the data gets to where it's supposed to.

If you're actually splitting the database up logically and not just physically, then the mappings defined in your DAL or ORM will declare which tables are in which database.

NoSQL databases are a mix of partitioning solutions. Sometimes it's the "tables" (or more commonly, "collections") that get partitioned. Other times it's the "rows" (or "documents"). In some cases it's actually the columns, as in a column-oriented database like HBase. It totally depends on the technology you're using. The one thing that these all have in common is that the engine itself keeps track of it all, so all you have to do is request a document or row.

That is of course assuming you're actually making use of the sharding features and not just creating a bunch of different databases. If you're doing the latter, then you're on your own.

Does the application code need to know that one or more databases are spread across multiple servers? If not, at what level are the requests filtered?

If they are different logical databases, yes. If they are only physically distributed then no - assuming that either your specific database natively supports sharding or you use a load balancing solution (for SQL databases). Also assuming that all of your operations are stateless; if you want horizontal scaling, you're going to have to give up ACID.

When is it time to move beyond a 1 database/1 server setup? How common is it to need to do this?

It's time when you've optimized everything you possibly can on the one server and still can't squeeze out enough performance due to constraints on the I/O load. If you have to ask the question, then it's too early.

Note that performance problems in a decent RDBMS product (Oracle, SQL Server) are more frequently due to poor design, poor indexing, poor queries, lock contention, and so on; these products can scale vertically to a ridiculous degree. So again, you should consider "moving beyond a 1 database/1 server setup" when you are absolutely certain that your performance problems are due to hardware limitations and not just a sub-par design/implementation.

Or, I guess, another reason some people switch to distributed databases is when they're not prepared to pay much (or any) money in licensing fees and want to ditch SQL as a conscious choice to trade the low cost for increased application complexity. Totally valid reason if you're a software startup but usually not applicable in the corporate sector.

Title: Interacting With Data Using Multiple Databases/Servers

Body:
All of the projects that I've had to deal with so far have only required a single database on a single server. I'm interested in learning more about how projects that need to scale move to  multiple databases and/or servers to help manage the load. I'm aware of High Scalability, but I'm particularly interested in some code examples or additional resources where I could read more on the subject.

For instance:

How are joins constructed between two tables on multiple databases? (A code example here would be helpful).

Are there any special strategies for tracking which tables are in which database?

Does the application code need to know that one or more databases are spread across multiple servers? If not, at what level are the requests filtered?

When is it time to move beyond a 1 database/1 server setup? How common is it to need to do this?


问:
How large is ok for a Class?
I’m a long time developer (I’m 49) but rather new to object oriented development. I’ve been reading about OO since Bertrand Meyer’s Eiffel, but have done really little OO programming.

The point is every book on OO design starts with an example of a boat, car or whatever common object we use very often, and they start adding attributes and methods, and explaining how they model the state of the object and what can be done with it.

So they usually go something like "the better the model the better it represents the object in the application and the better it all comes out".

So far so good, but, on the other hand, I’ve found several authors that give recipes such as “a class should fit in just a single page” (I would add “on what monitor size?" now that we try not to print code!).

Take for example a PurchaseOrder class, that has a finite state machine controlling its behavior and a collection of PurchaseOrderItem, one of the arguments here at work is that we should use a PurchaseOrder simple class, with some methods (little more than a data class), and have a PurchaseOrderFSM “expert class” that handles the finite state machine for the PurchaseOrder.

I would say that falls in the “Feature Envy” or “Inappropriate Intimacy” classification of Jeff Atwood's Code Smells post on Coding Horror. I’d just call it common sense. If I can issue, approve or cancel my real purchase order, then the PurchaseOrder class should have issuePO, approvePO and cancelPO methods.

Doesn’t that goes with the “maximize cohesion” and “minimize coupling” age old principles that I understand as cornerstones of OO?

Besides, doesn’t that helps toward the maintainability of the class?

答: A class should use the Single Responsibility Principle. Most very large classes I have seen do to many things which is why they are too large. Look at each method and code decide should it be in this class or separate, duplicate code is a hint. You might have an issuePO method but does it contain 10 lines of data access code for example? That code probably shouldn't be there.</p>

Title: How large is ok for a Class?

ContentLicense: CC BY-SA 2.5


问:
Is it a good practice set connection strings in a web config?
Recently I have a discussion with some of my colleagues at my work because they said that it's better have in a .DLL a string connection encrypted. And I said why just don't use the string connection defined in the web.config encrypted? it's the same and it's better because entity framework, for example looks for the name of the connection in the web config of the application, Now i want to know from a security point what's better or what's the best practice??</p>

答:
There's no substantive difference, except that you'll have to actually build a binary if you wanted to make a configuration change if you put it in a DLL, whereas an admin could just modify the configuration with well-understood off-the-shelf tools if it's in the config. There's already a mechanism for encrypting configuration strings and additional guidance on MSDN. Current versions of Asp.Net may have alternative mechanisms, so do some additional research before committing to an approach.

Just because something is sitting in a DLL, doesn't make it any more secure. A text editor can open binary files just as well, tools like Reflector can provide a nicer interface to navigating a .Net DLL; a DLL won't provide any "extra" encryption.


答:
It doesn't matter where the encrypted data is stored, it matters how it's encrypted.

Encrypted sections in an web.config are normally encrypted with the Data Protection API, which is extremely difficult to crack without compromising the entire machine. You can also use an RSA key container, which is similar (difficult to get those off the machine).

If you want to store the encrypted string in the DLL, that's fine, I guess, although it's not inherently any more secure than an encrypted web.config (anybody can peek into that DLL with Reflector), and is obviously harder to change (you'd need to recompile).  But again, what's a lot more important is how that encrypted string was generated; presumably you're not using the same providers as you would for an encrypted web.config, so what are you using?

An encryption scheme is only as strong as the private key or shared secret. If that key is also stored in your assembly, then you might as well have no encryption at all. If it's stored in some external database, then it raises the question of how that database's connection string is secured. This can really only lead to weaker security overall.

On the other hand, if you were a service provider and the connection string were encrypted with a user password, then that would be more secure than using a static machine key. Then again, if you're using user passwords to encrypt, it's pretty unlikely that you'd be hard-coding the encrypted data in your assembly, since it needs to be generated and stored in response to user (not developer) action.

Really I can't think of too many situations where hard-coding an (encrypted) connection string in the DLL is any more secure than encrypting the relevant web.config section. At best it's just adding inconvenience, at worst it's relying on some clumsily-written custom security riddled with holes. Do yourself a favour and do what Microsoft recommends - just encrypt your web.config if there's sensitive data in there.

Title: Is it a good practice set connection strings in a web config?

Body: Recently I have a discussion with some of my colleagues at my work because they said that it's better have in a .DLL a string connection encrypted. And I said why just don't use the string connection defined in the web.config encrypted? it's the same and it's better because entity framework, for example looks for the name of the connection in the web config of the application, Now i want to know from a security point what's better or what's the best practice??</p>


答:
The best practice for ASP.NET is put all configurations/settings in the web.config file or app.config file (for other project types).

About encryption and the reason to use it on your connection strings have to be a very special case. Because most cases up to 99% you don't need to encrypt your connection strings. Microsoft own enterprise applications have their connection string exposed in the web.config/app.config file. I think you are over complicating security.

One more thing, hard-coding your connection strings is bad practice. For instance, do not put any connection string (aka connectionstring) in a DLL or .aspx/.ascx/.cshtml or code-behind.


问:
Write a directory structure (pseudo code)
I am writing a wiki article and wondering what is the proper way to write a directory scheme?

I am doing something like

```<code>main folder
- sub folder
- sub folder
...
</code>```

But I'm stuck after that.

Any help?

答:
```<code>root
  - sub1
    - sub1a
    - sub1b
  - sub2
  - sub3
</code>```

keep the indention consistent ( I used 2 spaces ) and use a
 or  block in your html

you can try and make it look more like a tree control with a | if you want to stick to ASCII characters

```<code>root
  |- sub1
  | |- sub1a
  | |- sub1b
  |- sub2
  |- sub3
</code>```

or use Unicode Characters from the Character Map Software provided by your Operating System

```<code>root
  ├ sub1
  | ├ sub1a
  | └ sub1b
  ├ sub2
  └ sub3
</code>```

Body:
root
  - sub1
    - sub1a
    - sub1b
  - sub2
  - sub3

keep the indention consistent ( I used 2 spaces ) and use a <pre/> or <code/> block in your html

you can try and make it look more like a tree control with a | if you want to stick to ASCII characters

root
  |- sub1
  | |- sub1a
  | |- sub1b
  |- sub2
  |- sub3

or use Unicode Characters from the Character Map Software provided by your Operating System

root
  ├ sub1
  | ├ sub1a
  | └ sub1b
  ├ sub2
  └ sub3


问:
Collaborate on UML online
Some friends and I are starting up a hobby programming project.
I wonder if there is any good method/tool/service which lets us collaborate on UML diagrams online.
This can be in any form (online direct edit, source-control style, etc.) as long as we can make changes independent of each other.</p>

答:
What I do is to share my model and my diagrams directly on CVS inside my project.
After each major change I commit.

Anyone in the team can change the model or the diagrams. It works pretty well because the class diagram is synchronized with the code and no offline out of box code generation is used.

Title: Collaborate on UML online


问:
What options are there if an SVN repository becomes unavailable?
A project I'm working on was hosted on a svn repository at bettercodes.org. This was under another user's name and that repository is now unavailable.

The person responsible for the project was sent an export from Eclipse and I had a more or less up-to-date project on my machine. I could see no other option than to commit my copy of the project to another repository. It is now possible that some of the most recent changes by another programmer are missing.

Now, what options do I have to bring this project together? Is some of the necessary metadata saved on Eclipse or are all the changes on the original repository? What tools could I use to check what is missing in terms of classes, config files and code?

答:
If all else fails and there aren't any nifty Eclipse tricks (I don't use Eclipse, so I have no idea :P)...

Do you know who worked on the project? If so, if you stick your repo up somehwere, you could get diff patches from other developers and apply them to your project.

How to create and apply an SVN patch


答:
What kind of project is this? Why is the repo unavailable?

In the case of SVN, all the changes and diffs are in the server repository and not on the clients. You're going to somehow need to get access to the original repo if you want all the other data.

Some of the distributed version control systems, like Git and Mercurial, store all the metadata on all machines using the repository. In the future, it might be a wise idea to use one of those. Or, use an SVN server under your direct control.

Title: What options are there if an SVN repository becomes unavailable?

Body:
A project I'm working on was hosted on a svn repository at bettercodes.org. This was under another user's name and that repository is now unavailable.

The person responsible for the project was sent an export from Eclipse and I had a more or less up-to-date project on my machine. I could see no other option than to commit my copy of the project to another repository. It is now possible that some of the most recent changes by another programmer are missing.

Now, what options do I have to bring this project together? Is some of the necessary metadata saved on Eclipse or are all the changes on the original repository? What tools could I use to check what is missing in terms of classes, config files and code?


答:
If at all possible, ask that programmer what his last change was (or get him to review the code you do have). As far as I am aware Eclipse will not have kept history or actual source, as SVN is the place to keep that. At best it will have reference to SVN commit numbers - now useless to you.

Going foward - (and OT but I thinks is worth mentioning) When choosing another rev. control tool, consider a distributed tool such as GIT or Mecurial. With these you have the entire history stored locally, so the lose of the "master" repo is not a big deal, you still have all of the history, and you can pull changes from any other repo, so you could recover the most recent changes provided the commiter of those still has his local repo. These tools can still operate in a similar fashion to the SVN concept of a master repo if thats how you want them to.

(OT)Thank you for this question - it adds fire-power to an argument that "the cloud" is not a suitable/reliable repository to store mission critical data.


答:
As whatsisname says, in a separate answer, in SVN all history information is in the server repository and not on local clients.

I'd say your best bet is to try really hard to make contact with bettercodes.org - see their "About us" Contact Page, and:

Explain the situation

Provide documentation/evidence as to why you, or your organisation has rights to use the code.

Request a downloadable copy of the code, with history


问:
strcpy memcpy reason for parameter order
Answering a question about order of parameters it struck me that strcpy (and family) are the wrong way round. Copy should be src -> destination.

Is there a historical or architectural reason for the dest,src order in these 'C' functions? Something to do with optimization of the stack on the PDP-8 or something?

答:
I don't think anyone will know for certain the true answer, although many will speculate why, and now we can no longer ask Dennis Ritchie, the definitive answer is probably not possible. (Can anyone provide an evidence based answer?)

However, I do belive you assertion that the order is "wrong" is wrong. It is what it is.  On the right in the UK: there is no right or wrong, it's just because it's that way - as long as everyone does it the same way around.


问:
Why scalability issues cannot be solved by more servers ?
I know that big websites suffer from scalability issues and I guess that more servers (hardware) can help to handle scalabililty issues but I see that big websites are stuck about scalability even if they can handle the cost of new servers.

So why can big companies not handle scalability issues by more servers?

答:
"More servers" is fine - and that's what a lot of companies actually do.
However, unless your software is designed to scale that way, you hit diminishing returns very fast.

Most architectures have at least one bottleneck that just can't scale by adding more servers - wether it's a database, an authentication service, network, logging... 'Throw more hardware at it' works until you move the bottleneck to that place where it doesn't work any more.

You drain a pond faster by using more pumps or more buckets, but at some point you'll have so many workers they can't all access the pool at the same time and your power company won't be able to provide enough juice to all your pumps.


问:
How to introduce Agile to a team that uses rigid non-Agile methods?
Consider a company that is proudly certified for some non-Agile methodology, uses it as a selling point to its customers to demonstrate accountability.

How do you go about introducing Kanban or Scrum progressively without breaking their whole system and still making them confident that it can still be just as accountable / auditable?

I know this is possibly related to "How would you introduce an agile methodology like Scrum", but here I am wondering about ways to circumvent/work around the fact that the company imposes a certain way of managing the SDLC under the false pretense that it's the only way to have an audit trail.

答:
I'm a Agile coach and one of the keys to change initiatives is buy-in at all levels!  This includes executives, development teams, managers, ...etc.  Before announcing a large or small change effort I would suggest getting individuals on board with you first.  Doing this through a third person conversation is the easiest way for individuals to start cranking on new ideas.  What is third person?  A blog, youtube video, presentation, ...etc.  This way those folks can start coming up with their own ideas and with your influence will jump on board with a change initiative.

Here are two crafty videos I have used to spark interest at all levels in the food chain.

Kanban: http://www.youtube.com/watch?v=0EIMxyFw9T8

Scrum:  http://www.youtube.com/watch?v=Q5k7a9YEoUI


问:
Why have minimal user/handwritten code and do everything in XAML?
I feel the MVVM community has become overzealous like the OO programmers in the 90's - it is a misnomer MVVM is synonymous with no code. From my closed StackOverflow question:

Many times I come across posts here about someone trying to do the equivalent in XAML instead of code behind. Their only reason being they want to keep their code behind 'clean'. Correct me if I am wrong, but is not the case that:

XAML is compiled too - into BAML - then at runtime has to be parsed into code anyway.
XAML can potentially have more runtime bugs as they will not be picked up by the compiler at compile time - from incorrect spellings - these bugs are also harder to debug.
There already is code behind - like it or not
InitializeComponent();
has to be run and the .g.i.cs file it is in contains a bunch of code though it may be hidden.
Is it purely psychological? I suspect it is developers who come from a web background and like markup as opposed to code.

EDIT: I don't propose code behind instead of XAML - use both - I prefer to do my binding in XAML too - I am just against making every effort to avoid writing code behind esp in a WPF app - it should be a fusion of both to get the most out of it.

UPDATE: Its not even Microsoft's idea, every example on MSDN shows how you can do it in both.

答:
I've never heard of anyone suggesting to put everything in XAML.

In fact, that would be a terrible idea, IMO.

The problem, historically, came from Winforms apps having logic in their code behind that didn't belong there, because it was logic. That's where the importance of VM comes from.  It allows you to isolate the parts that tie together the View to the Model.

Therefore, the View is left to only handle what is does best, which is UI.

Now, if you happen to have situations where your UI requires code, then by all means go for it and put it in your code behind.  However, I would say that for 95% of the scenarios out there, you will most likely be better off leaving the UI in the markup file, and if you need some code behind, it's probably some logic that you're trying to write out that is more appropriately left to the View Model.  Exceptions to this are things such as Behaviors, but they are separate animals entirely, and require a special place (i.e. not in your code behind).


问:
Why would I learn C++11, having known C and C++?
I am a programmer in C and C++, although I don't stick to either language and write a mixture of the two. Sometimes having code in classes, possibly with operator overloading, or templates and the oh so great STL is obviously a better way. Sometimes use of a simple C function pointer is much much more readable and clear. So I find beauty and practicality in both languages. I don't want to get into the discussion of "If you mix them and compile with a C++ compiler, it's not a mix anymore, it's all C++" I think we all understand what I mean by mixing them. Also, I don't want to talk about C vs C++, this question is all about C++11.

C++11 introduces what I think are significant changes to how C++ works, but it has introduced many special cases, exceptions and irregularities that change how different features behave in different circumstances, placing restrictions on multiple inheritance, identifiers that act as keywords, extensions of string literals, lambda function variable capturing, etc.

I know that at some point in the future, when you say C++ everyone would assume C++11. Much like when you say C nowadays, you most probably mean C99. That makes me consider learning C++11. After all, if I want to continue writing code in C++, I may at some point need to start using those features simply because my colleagues have.

Take C for example. After so many years, there are still many people learning and writing code in C. Why? Because the language is good. What good means is that, it follows many of the rules to create a good programming language. So besides being powerful (which easy or hard, almost all programming languages are), C is regular and has few exceptions, if any. C++11 however, I don't think so. I'm not sure that the changes introduced in C++11 are making the language better.

So the question is: Why would I learn C++11?

答:
Learning is always beneficial. Knowledge is power.

That's the answer, basically. Everything else is just details as to how exactly you can benefit from it and what powers you have by knowing it, and they're so many that any enumeration would be incomplete.

One example is your own question. You wouldn't be able to even ask it without learning at least a bit of it.

And as I commented - the real concern is not why to learn, but why to use. And that's an entirely different question.

OwnerDisplayName: anon


答:
After so many years, there are still many people learning and writing
  code in C. Why? Because the language is good.

First, most students these days are learning Java or .NET, not C.  Second, people are still using C not only because of its advantages as a language, but mainly because there is a huge amount of existing software written in C that needs to be maintained and extended, and because in many cases (e. g. embedded platforms) a C compiler is all there is. Incidentally, these are some of the reasons why people still write COBOL.

It is very rare for a programmer in the industry to start working on a brand-new project that is not tied to an existing code base, and to continue working alone.  So, the reason to learn C++11 is that you are likely to have to deal with code written by other people, that uses the new features. Also, the features that were added were added for a reason. Once you learn them and use them, you might come to appreciate them.

Title: Why would I learn C++11, having known C and C++?

Body:
I am a programmer in C and C++, although I don't stick to either language and write a mixture of the two. Sometimes having code in classes, possibly with operator overloading, or templates and the oh so great STL is obviously a better way. Sometimes use of a simple C function pointer is much much more readable and clear. So I find beauty and practicality in both languages. I don't want to get into the discussion of "If you mix them and compile with a C++ compiler, it's not a mix anymore, it's all C++" I think we all understand what I mean by mixing them. Also, I don't want to talk about C vs C++, this question is all about C++11.

C++11 introduces what I think are significant changes to how C++ works, but it has introduced many special cases, exceptions and irregularities that change how different features behave in different circumstances, placing restrictions on multiple inheritance, identifiers that act as keywords, extensions of string literals, lambda function variable capturing, etc.

I know that at some point in the future, when you say C++ everyone would assume C++11. Much like when you say C nowadays, you most probably mean C99. That makes me consider learning C++11. After all, if I want to continue writing code in C++, I may at some point need to start using those features simply because my colleagues have.

Take C for example. After so many years, there are still many people learning and writing code in C. Why? Because the language is good. What good means is that, it follows many of the rules to create a good programming language. So besides being powerful (which easy or hard, almost all programming languages are), C is regular and has few exceptions, if any. C++11 however, I don't think so. I'm not sure that the changes introduced in C++11 are making the language better.

So the question is: Why would I learn C++11?


答:
C++11 is not a new language; it is only an extension/modification of C++ that you already know . C++11 just like any other programming language consists of features.  A lot of them were there from before, some of them are new.  But your question really is, should I learn all features of the language (in this case C++11), or only familiarize myself with 90% of it?

IMO even if you are not using all of the language, you should at least read up on what the new features do for you.  A lot of them were introduced to make library/framework code (especially templates) easier to write (for example, before C++11 perfect forwarding was impossible), but if you never had the need for those feature before, chances are you won't notice that these features were added in C++11.

On the other hand, if you've previously dabbled in writing library/core code that mimics some of STL/Boost functionality and found yourself being limited by the language because you've come 95% to having a very cool, elegant solution but then you were stopped because you found out language simply doesn't support what you want, you will realize the truly awesome power of C++11.  Ever since our team upgraded to VS2010 (and we've discovered Boost in the process), I've been able to crank out some crazy awesome code, that would simply be impossible prior to things like r-value references and template parameter forwarding.

Also things like lambda's may look foreign, but they don't introduce a new construct.  Instead they make what we used to have before so much easier to write.  Previously every lambda function would have to be a separate class.  Now it's just {...code...}. Love it.

The key is don't look at these features and think how daunting the list is.  Instead, use C++ as you normally do and when you come across some scenario where these new C++11 features come in handy (more than 90% of people will never get to that point), you'll be very happy that the extension to the language was done.  For now, I'd suggest you just learn enough about the language to know what's there, not necessarily how to use all of it.


问:
Is this agile? Scrum? How to improve agility?
Is this agile?  Scrum?  Any suggestions on how this can be made more agile under the circumstances?  Which points are positives and which can be improved?

The product is developed for a customer who will re-sell it while paying us royalty.

The team does not get to talk directly to the end user.  Only to the reseller.

A product requirements document was created before starting development.

The requirements are rigid and do not change.

A delivery schedule was agreed on with milestones such as "alpha", "beta" etc. and features/times attached to those milestones.

All developers on the Scrum team report to the product owner, a software manager.

Testers on the team report to a QA manager.

The product owner has directed the team towards certain high risk technical tasks.  The output of those tasks is not usable by the end user but rather some technology/code that will eventually be used in the product.

The product owner has created a backlog based on the requirements.

The product owner is unable to answer some questions regarding the product.  He refers to others or to the documented requirements.

The team goes through the motions of Scrum.  Daily Scrum, Sprint Planning, Retrospective etc.  There is a ScrumMaster.

Every sprint the product owner and management decide what backlog items the team works on.

There is a burndown chart.  Scrum board with stories and tasks.  The estimates on those come from the team.

The team sits in an open floor "bull pen" shared with other teams, all visible and audible.  There is cross-team noise and there is foot traffic around the team area.

The team may be required to attend various meetings not directly related to the goals of the sprint.

There are pressures to select certain technical solutions.  Some tools and processes are mandated.

答:
No.  This is not Scrum, nor is it Agile.  Specifically:

The requirements are rigid and do not change.

Scrum is designed to make it easy to change the requirements.  You may have a Scrum project where the requirements happen to remain unchanged, but you can't go into a Scrum project with the restriction that they cannot change.

A delivery schedule was agreed on with milestones such as "alpha",
  "beta" etc. and features/times attached to those milestones.

This wouldn't be possible in a real Scrum project.

All developers on the Scrum team report to the product owner, a
  software manager. Testers on the team report to a QA manager.

This is a problem if the issue of "who manages who" gets in the way of team synergy.  The fact that it's mentioned here is probably an indication that this is happening.

The product owner has created a backlog based on the requirements.

One of the fundamental rules of Scrum is that anyone can add anything to the backlog at any time.  The backlog is a fluid, living thing that represents the evolving knowledge of the people involved in the project.

The product owner is unable to answer some questions regarding the
  product. He refers to others or to the documented requirements.

This is a massive red flag that this isn't Scrum.  The PO is the one person in the organization with OWNERSHIP of the product.  He can make all decisions about the deliverables of the project.  If he can't, then you've got the wrong person in the PO role.

Every sprint the product owner and management decide what backlog
  items the team works on.

This is the biggest issue.  In Scrum, the PO get's to decide what the relative priorities of the items in the backlog are, the Team has the sole right provide estimates and decide how many items will be worked on in each Sprint.  No one is allowed to tell the Team how many items will be in the Sprint.

This feels like incremental development, but it's not iterative.  Iterative implies that you re-evaluate the project, feature set, requirements, design and delivery schedule at the beginning of each iteration - putting it in front of the customer and working what you've learned back into the project.


答:
I find the output of the tree command very readable. Here's an example that uses Jarrod's directory structure:

```<code>root
├── sub1
│   ├── sub1a
│   └── sub1b
├── sub2
└── sub3
</code>```

Title: Write a directory structure (pseudo code)

Body:
I am writing a wiki article and wondering what is the proper way to write a directory scheme?

I am doing something like

```<code>main folder
- sub folder
- sub folder
...
</code>```

But I'm stuck after that.

Any help?

Body:
I find the output of the tree command very readable. Here's an example that uses Jarrod's directory structure:

root
├── sub1
│   ├── sub1a
│   └── sub1b
├── sub2
└── sub3


答:
It's simple. C++11 makes code dramatically easier, cleaner to write, and faster.

nullptr is a VAST improvement over the old 0. It's type-safe and doesn't convert when it shouldn't- unlike 0. It's a good thing that nullptr won't convert to an int. It doesn't make sense for that to happen at all. Do you know what the C++ Committee found when they tried to consider #define NULL nullptr? Stuff like char c = NULL;. How terrible is that? The only reason there's an exception here is because bool is considered an integral type, which is quite wrong- but that was there in C++ before, and in C. The fact that nullptr doesn't convert is good, it's great and you should love it.

Or how about rvalue references and variadic templates? Faster, more generic code. That's a total win right there.

How about the library improvements? Stuff like function, unique_ptr and shared_ptr are so much better than what was there before, it's impossible to argue that the C++03 way was better.

```<code>#define adding_func(x, y) ((x)+(y))
</code>```

Not even remotely equivalent. Macros are bad for six billion reasons. I'm not going to quote all of them here, but it's well known that macros should be avoided for pretty much all purposes that they can possibly be avoided for. What are you going to do when it's

```<code>#define add_twice(x) (x + x)
</code>```

Oh wait, I hope you didn't increment or something on x. Which the template function version is totally immune to. I also hope that you don't appreciate namespaces, for example.

Then you open yourself to a world of undefined behavior for using
  external variables whose scopes are already finished.

In a functional API, e.g. STL algorithms, then reference is fine. If it's a stored callback, then you need to capture by value. Whatever documentation you have on the function should clearly indicate which is necessary. The fact that the code is written in a lambda is irrelevant to the problem of referring to local variables- if you pass a regular function object, then you're going to have the exact same trouble. And it's not a trouble. At all. Because it's inherently obvious when you can and can't refer to local variables.

Take C for example. After so many years, there are still many people
  learning and writing code in C. Why?

There are many people who don't brush their teeth in the morning. There are many murderers, and rapists, and prostitutes. And politicians. People who commit suicide. Would you argue that that therefore makes these activities good or useful? Of course not. It's a logical fallacy that just because someone did it, therefore it must be good or useful.

C is still being written for three reasons: because C++ is a bitch to implement, for example on embedded or kernel mode; because legacy codebases are written in C and would cost too much to upgrade, although even that's questionable given C++'s excellent C interop; and because the people writing it don't know how to program. That's it. There's no other reason to write C.

If you take C or the old style C++, you wouldn't find many exceptions.

How about the pathetic C-style arrays, for a simple example? The number of people who can't get arrays and pointers straight in their head is obscene. Not to mention the fact that the C Standard library is incredibly unsafe.

Your core arguments are full of logical fallacies and misunderstandings.

Body:
It's simple. C++11 makes code dramatically easier, cleaner to write, and faster.

nullptr is a VAST improvement over the old 0. It's type-safe and doesn't convert when it shouldn't- unlike 0. It's a good thing that nullptr won't convert to an int. It doesn't make sense for that to happen at all. Do you know what the C++ Committee found when they tried to consider #define NULL nullptr? Stuff like char c = NULL;. How terrible is that? The only reason there's an exception here is because bool is considered an integral type, which is quite wrong- but that was there in C++ before, and in C. The fact that nullptr doesn't convert is good, it's great and you should love it.

Or how about rvalue references and variadic templates? Faster, more generic code. That's a total win right there.

How about the library improvements? Stuff like function, unique_ptr and shared_ptr are so much better than what was there before, it's impossible to argue that the C++03 way was better.

#define adding_func(x, y) ((x)+(y))

Not even remotely equivalent. Macros are bad for six billion reasons. I'm not going to quote all of them here, but it's well known that macros should be avoided for pretty much all purposes that they can possibly be avoided for. What are you going to do when it's

#define add_twice(x) (x + x)

Oh wait, I hope you didn't increment or something on x. Which the template function version is totally immune to. I also hope that you don't appreciate namespaces, for example.

Then you open yourself to a world of undefined behavior for using
  external variables whose scopes are already finished.

In a functional API, e.g. STL algorithms, then reference is fine. If it's a stored callback, then you need to capture by value. Whatever documentation you have on the function should clearly indicate which is necessary. The fact that the code is written in a lambda is irrelevant to the problem of referring to local variables- if you pass a regular function object, then you're going to have the exact same trouble. And it's not a trouble. At all. Because it's inherently obvious when you can and can't refer to local variables.

Take C for example. After so many years, there are still many people
  learning and writing code in C. Why?

There are many people who don't brush their teeth in the morning. There are many murderers, and rapists, and prostitutes. And politicians. People who commit suicide. Would you argue that that therefore makes these activities good or useful? Of course not. It's a logical fallacy that just because someone did it, therefore it must be good or useful.

C is still being written for three reasons: because C++ is a bitch to implement, for example on embedded or kernel mode; because legacy codebases are written in C and would cost too much to upgrade, although even that's questionable given C++'s excellent C interop; and because the people writing it don't know how to program. That's it. There's no other reason to write C.

If you take C or the old style C++, you wouldn't find many exceptions.

How about the pathetic C-style arrays, for a simple example? The number of people who can't get arrays and pointers straight in their head is obscene. Not to mention the fact that the C Standard library is incredibly unsafe.

Your core arguments are full of logical fallacies and misunderstandings.


问:
How do you run a sprint retrospective to maximize participation and honesty? And what about follow up on action items?
I've seen it done as a free-for-all where the scrum master just asks everyone to throw out comments. Or a time-boxed session where "anonymous" comments are posted on the walls bucketed by category. My current team is constrained by being spread out, so it has be done online/over the phone. What is everyone's best experience with soliciting constructive feedback? And how do you follow through on action items for improvement?</p>

答:
A good start is to make note of issues that arise during the daily stand-up meetings.  Also useful is to build a time-line of Sprint just completed, asking team members to bring up events and issues that occurred through the time-line - things that went right as well as things that went wrong.

Once items have been raised, it's up to the Team to figure out what they want to address and how they want to address it.

It's also important to understand that Sprint retrospectives aren't about "feedback".  What the are about is implemented "continuous improvement" through the process of inspect and adapt.  How does the Team make the things that worked well work even better in the future, and how do they fix the things that didn't work well?

The Scrum Master's role is to ensure that the Retrospective is held, and to coach the Team and keep them focused on the purpose of the Retrospective.  Follow-through is really the responsibility of the Team, although it often helps to review the effects of prior action items in future retrospectives.


问:
What metrics do you use on your Scrum project?
We are starting a new project and the board/stakeholders are asking for metrics to check the team performance.

As a junior ScrumMaster I told them:

about the Velocity and BurndownChart

that we can chose any type of metrics as long as they are team based and not individual, they do not push people to act awkwardly / counter productive (as you get what you reward)

Is there any other thing I can provide them in this regards? Have you got metrics other than velocity?

答: From a customer perspective, there's only one productivity metric that counts:  business value delivered over time.  Presumably, the Product Owner is already evaluating the relative business value of each backlog item when the backlog is prioritized.  So it should be relatively easy to have a numeric value assigned to each backlog item representing its business value.</p>


问:
Should a programmer fix someone else's failed build?
One programmer committed some work to the SVN repository, then went home. After he left, the Hudson automatic build failed. Another programmer saw this, and after looking through the code changes, detected that the problem was the absence of one library. He added this library to SVN and the next build completed successfully.

Did the second programmer do the right thing or should he have just waited until the first programmer fixed the issue?

答: It depends on Team dynamics, but in an ideal world everyone on the Team would "own" the whole project, all of the code, and consequently, all of the bugs jointly.  So if you find a problem you fix it, and communicate with the originator of the bug only if there's some specific added value to the code in doing so.</p>


答:
Think of it like an assignment operation.

```<code>A = B;  //copies the contents of B into A
</code>```

Same order when using memcpy to copy an array.

```<code>memcpy(A, B, sizeof(B));  //copies the contents of B into A
</code>```

Title: strcpy memcpy reason for parameter order

Body:
Answering a question about order of parameters it struck me that strcpy (and family) are the wrong way round. Copy should be src -> destination.

Is there a historical or architectural reason for the dest,src order in these 'C' functions? Something to do with optimization of the stack on the PDP-8 or something?

Body:
Think of it like an assignment operation.

A = B;  //copies the contents of B into A

Same order when using memcpy to copy an array.

memcpy(A, B, sizeof(B));  //copies the contents of B into A


答:
Not all necessarily "Scrum Specific" but keep in mind Scrum is a framework, and not a substitute for good Project Management practice :-)
I'd suggest:

Features added/demo'ed since last report - Very compelling to tell stakeholders what is already part of the product!

Defects that "slip" out of the iteration - this is the rate of defects that get added to the system.  Ideally, it will be zero, indicating that both testing is happening before existing the iteration boundary and any tech debt that either the product owner has accepted as part of the iteration or has crept into the system as tech debt.  Hard to measure this and "fake it"

Team's definition of done - report any changes the team makes as they progress the sprint.  This is less "number-y" but is a good indication that a Scrum team is learning as they develop the product and are adjusting their way of working.  Less "intrusive" than asking for a report of "what went well/what needs to change"

Burndown against backlog for the release - Picture a stacked area chart (in Excel) the number of points the release starts with might be 100, and each sprint 10 (for example) get closed and maybe 5 get added.  I like about 5-6 stacked areas : Accepted (closed), Removed (closed), Original (open), New-missed (open), New-from customers (open).  Show this each iteration and you'll rapidly see how the team is doing.

Risk board - always always always report on the top risks the team identifies.  I like showing the Top 5 risks in a quadrant view -  http://yfrog.com/g0qy8p

Projected ship date - Prep the stakeholders that the first 2-3 iterations are going to have wide swings until the team settles on a velocity.

hth

Title: What metrics do you use on your Scrum project?

Body:
We are starting a new project and the board/stakeholders are asking for metrics to check the team performance.

As a junior ScrumMaster I told them:

about the Velocity and BurndownChart

that we can chose any type of metrics as long as they are team based and not individual, they do not push people to act awkwardly / counter productive (as you get what you reward)

Is there any other thing I can provide them in this regards? Have you got metrics other than velocity?


问:
C++ XML Parsing: Suggestions on Approach for Parsing and Storing data
I am looking into developing a C++ application to parse xml (using the rapidxml framework), and I would like some advice on how to approach this.

The file I want to parse is a XML game file that defines a set of addons for a starship ('outfits'), which have several attributes in common (like name and cost), but also fall into various categories.

For example:
Fixed weapons: range, rate of fire

Turret weapons, range, rate of fire, turret slew speed

Afterburners: acceleration modifier, fuel burn speed

etc etc etc

There are at least 5 classifications of outfits (and say 3 or 4 outfits that fall into each category), and some, like the weapons, have a few attributes in common with each other, but not with other categories like afterburners.

I want to write parsing code to handle each type of object and store its data in objects. I also want to minimize how much code I have to retype (i.e. make use of good OOP style so I can add new categories or tweak existing ones in the future).

What is the best way to approach this? I have already started the program, but I would like to have some input on the best approach.

Since this is a really broad question, I will give you some of my thoughts/specific questions so you can see what I am looking for:

Should I have a basic class called 'outfit' and use inheritance to customize the parsing for each specific category (i.e. 'fixed-weapons')? Should I have multiple levels of inheritance for similar categories (i.e. 'weapons'). How can I minimize code retyping so I only have to write the specific routines for each category?

Where should I handle the errors: in 'outfit', or in the derived classes? How much error handling do I need?

How can I easily access these objects later? Should I make a list-object with a vector containing each object? How can I access each object by name?

Any input is appreciated; you don't have to give a complete and comprehensive rundown on how to do this (though that would be nice :P).

答:
Each of your object types - Weapons for example should form a class hierarchy using inheritance. The attributes of this are known - and they must share the common attribute in the right way. (some times they are referred as entity objects).

There should be only one class call it something like arsenal which will take up XML as an input and produce a list of objects as per the above definition.
The output is constructed entity objects like any other object - you don't have to touch XML after that.

Output of the arsenal can be a vector (template) to be able to access easily.

Error handling : You haven't specified much about it, but as general rule, you should try to handle exceptions on per class basis i.e. each class should have its own rule set for type of exception they can generate.
E.g. if rate_of_fire >MAX rate_of_fire = MAX : this should be done inside core class and application should not have to worry about it.


答:
Is it so hard to write a function, that you have to write the content of the function inline with the code, besides giving it no name?

When you do that you scroll up, or open a new source file and add the definition of the function there. Then you have to go back and continue on what you were working on, which distracts you to some degree.

Other than that, when other people are reading you code a lambda may be more self-documenting in some cases, instead of saying "Oh, what does this function do?" and jumping to its declaration you can just have a look at what it is doing in its own place.

There is a nice talk by Herb Sutter about lambdas, maybe he can convince you better:

http://channel9.msdn.com/events/PDC/PDC10/FT13

Well, why don't you just write the code there instead of making it a lambda-function?

Because you can't do it when you are using STL algorithms, or any function that you are using which requires you to pass a function.

#define adding_func(x, y) ((x)+(y))

There is no way to justify this usage instead of lambdas, you cannot fill your code with macros everywhere. Macros and functions have different purposes, and one, in general, is not a replacement for the other.

```<code>template<class Lhs, class Rhs>
auto adding_func(const Lhs &lhs, const Rhs &rhs)
                -> decltype(lhs+rhs) {return lhs + rhs;}
</code>```

I agree, this is ugly. However I remember myself saying "why the hell should I figure the type of this expression even though the compiler can infer this?" in lots of cases. This might help a lot during those moments.

To sum up:

Even though the new features of C++11 seem ugly in their syntax, I think one can get used to them in a short time. Every new language construct is difficult to learn at first; imagine the first time you learned to write a whole class: Putting the declaration in the header file, not forgetting the extra semicolon at the end, putting the definitions in the source file, including the header file while ensuring that it has a guard for preventing multiple inclusions, not forgetting the scope resolution operator in the member function declarations and so on...

But I am pretty sure that after writing a few classes you get used to it, and you don't think about the complexity of this process: Because you know that a class makes your job as a programmer a lot easier, and the utility you are earning from this new construct is a lot greater than the utility loss during the time you were trying to learn the language. I think this can be the reason why one should try to learn, or use C++11 in a similar manner.

Body:
Is it so hard to write a function, that you have to write the content of the function inline with the code, besides giving it no name?

When you do that you scroll up, or open a new source file and add the definition of the function there. Then you have to go back and continue on what you were working on, which distracts you to some degree.

Other than that, when other people are reading you code a lambda may be more self-documenting in some cases, instead of saying "Oh, what does this function do?" and jumping to its declaration you can just have a look at what it is doing in its own place.

There is a nice talk by Herb Sutter about lambdas, maybe he can convince you better:

http://channel9.msdn.com/events/PDC/PDC10/FT13

Well, why don't you just write the code there instead of making it a lambda-function?

Because you can't do it when you are using STL algorithms, or any function that you are using which requires you to pass a function.

#define adding_func(x, y) ((x)+(y))

There is no way to justify this usage instead of lambdas, you cannot fill your code with macros everywhere. Macros and functions have different purposes, and one, in general, is not a replacement for the other.

template<class Lhs, class Rhs>
auto adding_func(const Lhs &lhs, const Rhs &rhs)
                -> decltype(lhs+rhs) {return lhs + rhs;}

I agree, this is ugly. However I remember myself saying "why the hell should I figure the type of this expression even though the compiler can infer this?" in lots of cases. This might help a lot during those moments.

To sum up:

Even though the new features of C++11 seem ugly in their syntax, I think one can get used to them in a short time. Every new language construct is difficult to learn at first; imagine the first time you learned to write a whole class: Putting the declaration in the header file, not forgetting the extra semicolon at the end, putting the definitions in the source file, including the header file while ensuring that it has a guard for preventing multiple inclusions, not forgetting the scope resolution operator in the member function declarations and so on...

But I am pretty sure that after writing a few classes you get used to it, and you don't think about the complexity of this process: Because you know that a class makes your job as a programmer a lot easier, and the utility you are earning from this new construct is a lot greater than the utility loss during the time you were trying to learn the language. I think this can be the reason why one should try to learn, or use C++11 in a similar manner.


答: Putting the target as the second argument would be inconsistent with other functions that write things to strings and have the target in the first argument.  memset(3) and sprintf(3) come to mind.


答:
Assembly was created because people didn't like writing machine code

C was created because people didn't like writing assembly

C++ was created because people didn't like writing C

C++11 was created because people didn't like writing C++

You are going to come to a point in your C++ career where you say to yourself, "I sure wish functors were simpler," or "Why is NULL an int?" and then you will understand C++11.


问:
Why did javascript libraries like knockoutjs, backbonejs, and angularjs only come out in 2010?
Being a relatively new web-developer I am surprised that these libraries didn't exist before.  Is there a particular technical or historical reason that at around Sep 2010, a sudden development and interest in client-side javascript RIA applications and libraries?

http://www.google.com/insights/search/#q=backbonejs%2Cangularjs%2Cknockoutjs%2Cjquery%20tmpl&cmpt=q

答:
I would say its just a matter of enough developer mindshare, combined with node.js invigorating the JavaScript community, combined with html5 hitting its stride. The fact is that these libraries are certainly not the first, even if they do have a sort of new breed feel to them.

Not that it matters because it's still closed source, but my company created a rich client side JavaScript framework with many of the same ideas as the ones you mention - client side templating, data binding, MVC, REST based data services, automatic lazy loading, build tools, etc. And we've been doing it since 2008. Other frameworks have certainly cropped up in that time period as well before backbone, too. JavaScriptMVC has been around forever, and sproutcore too.


问:
complex numbers in programming?
Are complex numbers used in programming? If they are what is their significance? What IDEs and languages use them? And would it be recommended to learn how to implement them for a programming job (if so please specify what job)?

I've been working in Eclipse and just studied the importance of complex numbers in math and wondered if it correlated.

答:
Complex Numbers show up all over the place in Computer Science and Engineering as well as Scientific Computing. Examples include Fast Fourier Transforms for Signal Processing, Circuit Simulation (Complex Numbers are very common in Electrical Engineering), and Fractals which get used in Graphics and various other fields. They also show up a lot in Physics programming as Complex Numbers have some very interesting relations to vectors and trigonometry. This linkage is critical to Euler's Identity:

You'd cover complex numbers in a huge variety of courses ranging from Electrical Engineering to Numerical Analysis. Most modern or even many older languages can handle Complex numbers, usually by use of a library. C99 for instance has complex.h. Haskell on the other end of the spectrum also does with the Complex Module.

As far as importance, I'd learn them and well if you do anything with hardware, embedded systems, physics, graphics, computer vision, signal processing, computational mathematics, data compression or simulation. Anything that leans hardware or scientific really.

Title: complex numbers in programming?


答:
Yes, but only in some of those languages popular with physicists, electrical engineers, and anyone of the sort who would have a beer with them.  Complex numbers are especially useful in electronics, optics, and quantum theory for describing waves and any periodic phenomena.   Fourier transforms use complex numbers and are the key to working with wavefunctions, designing filters, signal integrity in digital electronics, radio astronomy, and on and on...

The languages "D" (from Digital Mars), Python, IDL, Matlab (and Octave), APL, J, C (since C99), and Fortran have complex numbers built in.  There are probably more.  By "built in" we mean that one can write mathematical expressions with the same ease as when using plain floating point values, declare arrays of that type, and not having to work through some API or set of classes and methods even if syntactic sugar hides it.   The compiler can optimize in ways not possible with a library.

Python is especially good to EEs by using "j" as the unit imaginary instead of the usual "i" used in math and physics.

Most other languages allow one to use complex numbers in the form of libraries.  These include C, C++, Java, Ruby, perl, at least, among languages scientists and engineers have some likelihood of using.

I don't know about functional languages such as Haskell, in what manner they support complex numbers.

Programming for business, web apps, smartphones, and games rarely has any use for complex numbers.  When they do, it's probably for some sort of audio or image analysis - science and engineering stuff - as part of some app.  Languages that cater only to these industries might have complex libraries, but more likely don't support them at all.   OTOH, it wouldn't surprise me if some smartass in the past had created a complex numbers library for COBOL.

Title: complex numbers in programming?

Body:
Are complex numbers used in programming? If they are what is their significance? What IDEs and languages use them? And would it be recommended to learn how to implement them for a programming job (if so please specify what job)?

I've been working in Eclipse and just studied the importance of complex numbers in math and wondered if it correlated.

ContentLicense: CC BY-SA 4.0


答:
In some environments, this is very rude, and for good reasons. In other environments, it's expected, and for good reasons.

In still other environments, it's very rude or expected for very bad reasons.

It largely depends how critical a broken build is versus how critical a verified correct build. And to some extent, it depends on how obvious it was that the fix was the right fix and the only one needed.

Title: Should a programmer fix someone else's failed build?

Body:
One programmer committed some work to the SVN repository, then went home. After he left, the Hudson automatic build failed. Another programmer saw this, and after looking through the code changes, detected that the problem was the absence of one library. He added this library to SVN and the next build completed successfully.

Did the second programmer do the right thing or should he have just waited until the first programmer fixed the issue?


问:
increasing productivity - mastering a language vs. selecting efficient tools
I'm looking for advice from experienced developers on this question.

In my work there's a need for a lot of one-off code. It's tempting to just dip into the right python/perl library calls to do these little tasks as quickly as possible.

I used to be of the philosophy of - "use most efficient tool for the task". However, I'm afraid that over time, this means that I won't have a deeper experience and expertise, so recently I've been forcing myself to use C++ (w/ Boost and STL) for everything, even if I could do the task in python or perl much more quickly. I'm hoping that in the long run, this will make me a more productive developer. I hope to reach a level of familiarity that I can do things in C++ as quickly as I can in python (and also have the practice to work on bigger projects that would require C++).

Is this a good strategy towards long-term productivity and deeper skills? Or am I unnecessarily wasting time / torturing myself?

答:
"use most efficient tool for the task" - don't completely throw away this principle. You won't be able to achieve the same level of efficiency in C++ as in Python and Perl, simply because they are high-level languages. But there will be reasons you will want to choose C++ in spite of development efficiency.

But, by all means, do choose C++ over the others for the sake of practicing it. Getting familiar with it is a good start, and won't be a waste of time. But note that there will be limitations to how proficient you can get by writing the C++ equivalent of a script. You'll eventually need to move beyond that to actually get proficient.


问:
Evaluating PHP namespaces
I'm at the pre-release stage of an open-source PHP project, one which I hope will be used by other developers in their own projects. The project doesn't currently support namespaces  and I'm trying to evaluate if it should use namespaces or the PEAR naming convention of Dir_Subdir_Class, which seems to have all of the same technical benefits without some of the drawbacks. To be honest, it's not an easy choice.

Some points of consideration against namespaces:

One of the ways that my project is trying to differentiate itself by providing a simpler API than other similar projects. Because namespaces are new and also because they are more complicated than the PEAR naming convention, introducing them into the codebase will make my project less simple to use. By implementing them, I lose some differentiation in terms of ease-of-use.

While I can see some benefits to namespaces, they don't seem to solve a problem that needs to be solved in a modern PHP product that uses the PEAR naming convention. Naming conflicts while using my project should be minimal if not non-existent.

This article gives me some pause in adopting namespaces as their implementation has been less than stellar.

I'm also hesitant to jump on a bandwagon that may not go anywhere. As namespaces are a new feature to PHP, I'm not convinced yet that they will become standard.

Compatibility. Almost all of the PHP code that has ever been written does not use namespaces as it's a new feature. Other libraries would be incompatible without a conversion.

Some points for using namespaces:

Perception. If namespaces become standard and a best-practice, my project could quickly become viewed as unprofessional and obsolete without them.

Competition. While some competing PHP projects are beginning to use namespaces in their latest versions, many have yet to make the leap. Doing so now could give my project a leg-up on other projects.

Future work would be easier if I made the switch now before the project goes public rather than after, where I would have to support two versions of it for a while.

I want to support best-practices and if namespaces become a best practice for PHP, my project should make use of them.

From what I can tell, you must choose one way or the other; you can't do both. Are there any points that I haven't considered? Are there any objective signs (no flamewars, please) that point toward or against namespaces becoming the professional standard for PHP? I would appreciate any insight or resources that you would be willing to share as I need to make a decision soon.

答:
Two signs that namespaces in PHP are here to stay:

The PEAR naming scheme was abandoned in favor of namespaces in PEAR2.

One of the stated goals of Zend Framework 2.0 is to be an exemplar of PHP 5.3 usage, by fully utilizing namespaces, amongst other things. I consider this as a strong indication that Zend is fully committed to namespaces and will continue to support and evolve them (hopefully to the better).

I fully agree with you that the current implementation of namespaces is lacking, to say the least, but your arguments against using them are not that solid. Even in their current form, namespaces provide for:

Better code organization,

Avoiding naming collisions,

Context for classes, functions and constants.

Keep in mind that most arguments against PHP namespaces are by comparison to implementations in other languages and not against their actual merits as a feature.

Title: Evaluating PHP namespaces


问:
How large is ok for a Class?
I’m a long time developer (I’m 49) but rather new to object oriented development. I’ve been reading about OO since Bertrand Meyer’s Eiffel, but have done really little OO programming.

The point is every book on OO design starts with an example of a boat, car or whatever common object we use very often, and they start adding attributes and methods, and explaining how they model the state of the object and what can be done with it.

So they usually go something like "the better the model the better it represents the object in the application and the better it all comes out".

So far so good, but, on the other hand, I’ve found several authors that give recipes such as “a class should fit in just a single page” (I would add “on what monitor size?" now that we try not to print code!).

Take for example a PurchaseOrder class, that has a finite state machine controlling its behavior and a collection of PurchaseOrderItem, one of the arguments here at work is that we should use a PurchaseOrder simple class, with some methods (little more than a data class), and have a PurchaseOrderFSM “expert class” that handles the finite state machine for the PurchaseOrder.

I would say that falls in the “Feature Envy” or “Inappropriate Intimacy” classification of Jeff Atwood's Code Smells post on Coding Horror. I’d just call it common sense. If I can issue, approve or cancel my real purchase order, then the PurchaseOrder class should have issuePO, approvePO and cancelPO methods.

Doesn’t that goes with the “maximize cohesion” and “minimize coupling” age old principles that I understand as cornerstones of OO?

Besides, doesn’t that helps toward the maintainability of the class?

答:
I’ve found several authors that give
  recipes such as “a class should fit in
  just a single page”

In terms of just the physical size of a class, seeing a large class is an indication of a code smell, but doesn't necessarily mean that there always are smells.  (Usually they are though)  As the pirates in the Pirates of the Caribbean would put it, this is more what you'd call "guidelines" than actual rules.  I'd tried strictly following the "no more than one hundred LOC in a class" once and the result was a LOT of unnecessary over-engineering.

So they usually go something like "the
  better the model the better it
  represents the object in the
  application and the better it all
  comes out".

I usually start my designs with this.  What does this class do in the real world?  How should my class reflect this object as stated in its requirements?  We add a bit of state here, a field there, a method to work on those fields, add a few more and voila!  We've got a working class.  Now fill in the signatures with the proper implementations and we're good to go, or so you think.  Now we've got nice big class with all the functionality we need.  But the problem with this is, it doesn't take the way the real world works into account.  And by that I mean it doesn't take into account, "CHANGE".

The reason why classes are preferably split into smaller parts is that it's hard to change large classes later on without affecting the existing logic or introducing a new bug or two unintentionally or just make everything hard to reuse.  This is where refactoring, design patterns, SOLID, etc come in to play and the end result is usually a small class working on other smaller, more granular sub classes.

Also, in your example, adding IssuePO, ApprovePO and Cancel PO into the PurchaseOrder class seems illogical.  Purchase Orders don't issue, approve or cancel themselves.  If PO should have methods, then the methods should be working on its state not on the class as a whole.  They really are just data/record classes that other classes work on.

Title: How large is ok for a Class?


问:
Non-OOP Design Patterns?
I have only heard the term "design pattern" being used for object oriented code, and the GoF patterns include only OOP design patterns, but design patterns are elegant solutions for commonly occuring programming problems, right? There is nothing in there saying that they must be limited to OOP, is there?

I would like to see some examples of design patterns outside the realm of object oriented programming. Do you have any? Do such even exist (no book, like the GoF book, must necessarily have been written, they should just be used; that is enough)?

They can be specific to some programming language(s), but general (paradigm-level) patterns are preferred, of other paradigms than the object oriented one.

答:
"Design pattern" is actually an euphemism for "workaround". The design patterns were invented to work around shortcomings and flaws in OO languages. For example take the iterator pattern which eventually led to the introduction of the collections in Java. Groovy got rid of many more patterns by converting them into language features: You no longer need the decorator pattern because you can add methods to existing classes in Groovy.

This means you can find design patterns everywhere. In fact every "best practice" can be considered a simple form of a design pattern.

Title: Non-OOP Design Patterns?


问:
What are the dangers of setting an unlimited database transaction life timeout?
We have a process that may last between a few seconds and a few minutes. As such, we may update just a few records or thousands of them. The process can be committed only when everything has been done correctly.

Recently we have begun having problems when attempting to commit transaction as they were marked as "rollbackOnly". I've discovered that in fact the transaction had been marked "rollbackOnly" because it had timed out a bit earlier (not clear to see in the log files as our application server is Websphere and its transaction manager just gives a one-line warning), and as such it could not be committed. Of course it makes sense that you cannot commit a transaction that has timed out.

The problem is in fact that we never set the transaction timeout in transaction definitions, and that in that case the value of the timeout is the one set at the application server level (see Websphere's transaction settings, the paragraph on "Total transaction lifetime timeout"). That value is 2 minutes and sometimes we exceed it.

Now, that explains the setting (and in case somebody encounters a "rollbackOnly" transaction, I've provided here a possible explanation).

I'm tempted to increase the timeout, but I've also seen in the documentation that the timeout can be set to 0, meaning there is no timeout.

As such, my question is: what are the dangers of setting an unlimited transaction life timeout ?

Note that I'm aware of programmatic/database solutions to my problem like for example working on temporary tables, and reversing data from temporary tables to the real tables when we know everything has been done right (using PL/SQL for example). I'm just curious about the transaction timeout thing.

答: Most databases don't have automatic deadlock detection, so the timeout is the only way to stop those. A timeout does harm long running transactions, too, but without this, the first deadlock would stop your application.</p>


问:
Where did the notion of "one return only" come from?
I often talk to programmers who say "Don't put multiple return statements in the same  method." When I ask them to tell me the reasons why, all I get is "The coding standard says so." or "It's confusing." When they show me solutions with a single return statement, the code looks uglier to me. For example:

if (condition)
   return 42;
else
   return 97;
```

<p>"<em>This is ugly, you have to use a local variable!</em>"</p>

<pre class="lang-c prettyprint-override"><code>int result;
if (condition)
   result = 42;
else
   result = 97;
return result;
</code>```

How does this 50% code bloat make the program any easier to understand? Personally, I find it harder, because the state space has just increased by another variable that could easily have been prevented.

Of course, normally I would just write:

return (condition) ? 42 : 97;
```

But many programmers eschew the conditional operator and prefer the long form.

Where did this notion of "one return only" come from? Is there a historical reason why this convention came about?

答:
This notion of Single Entry, Single Exit (SESE) comes from languages with explicit resource management, like C and assembly. In C, code like this will leak resources:

void f()
{
  resource res = acquire_resource();  // think malloc()
  if( f1(res) )
    return; // leaks res
  f2(res);
  release_resource(res);  // think free()
}
```

In such languages, you basically have three options:

Replicate the cleanup code.

Ugh. Redundancy is always bad.

Use a goto to jump to the cleanup code.

This requires the cleanup code to be the last thing in the function. (And this is why some argue that goto has its place. And it has indeed – in C.)

Introduce a local variable and manipulate control flow through that.

The disadvantage is that control flow manipulated through syntax (think break, return, if, while) is much easier to follow than control flow manipulated through the state of variables (because those variables have no state when you look at the algorithm).

In assembly it's even weirder, because you can jump to any address in a function when you call that function, which effectively means you have an almost unlimited number of entry points to any function. (Sometimes this is helpful. Such thunks are a common technique for compilers to implement the this pointer adjustment necessary for calling virtual functions in multiple-inheritance scenarios in C++.)

When you have to manage resources manually, exploiting the options of entering or exiting a function anywhere leads to more complex code, and thus to bugs. Therefore, a school of thought appeared that propagated SESE, in order to get cleaner code and less bugs.

However, when a language features exceptions, (almost) any function might be exited prematurely at (almost) any point, so you need to make provisions for premature return anyway. (I think finally is mainly used for that in Java and using (when implementing IDisposable, finally otherwise) in C#; C++ instead employs RAII.) Once you have done this, you cannot fail to clean up after yourself due to an early return statement, so what is probably the strongest argument in favor of SESE has vanished.

That leaves readability. Of course, a 200 LoC function with half a dozen return statements sprinkled randomly over it is not good programming style and does not make for readable code. But such a function wouldn't be easy to understand without those premature returns either.

In languages where resources are not or should not be managed manually, there is little or no value in adhering to the old SESE convention. OTOH, as I have argued above, SESE often makes code more complex. It is a dinosaur that (except for C) does not fit well into most of today's languages. Instead of helping the understandability of code, it hinders it.

Why do Java programmers stick to this? I don't know, but from my (outside) POV, Java took a lot of conventions from C (where they make sense) and applied them to its OO world (where they are useless or outright bad), where it now sticks to them, no matter what the costs. (Like the convention to define all your variables at the beginning of the scope.)

Programmers stick to all kinds of strange notations for irrational reasons. (Deeply nested structural statements – "arrowheads" – were, in languages like Pascal, once seen as beautiful code.) Applying pure logical reasoning to this seems to fail to convince the majority of them to deviate from their established ways. The best way to change such habits is probably to teach them early on to do what's best, not what's conventional. You, being a programming teacher, have it in your hand. :)

Body:
This notion of Single Entry, Single Exit (SESE) comes from languages with explicit resource management, like C and assembly. In C, code like this will leak resources:

void f()
{
  resource res = acquire_resource();  // think malloc()
  if( f1(res) )
    return; // leaks res
  f2(res);
  release_resource(res);  // think free()
}

In such languages, you basically have three options:

Replicate the cleanup code.

Ugh. Redundancy is always bad.

Use a goto to jump to the cleanup code.

This requires the cleanup code to be the last thing in the function. (And this is why some argue that goto has its place. And it has indeed – in C.)

Introduce a local variable and manipulate control flow through that.

The disadvantage is that control flow manipulated through syntax (think break, return, if, while) is much easier to follow than control flow manipulated through the state of variables (because those variables have no state when you look at the algorithm).

In assembly it's even weirder, because you can jump to any address in a function when you call that function, which effectively means you have an almost unlimited number of entry points to any function. (Sometimes this is helpful. Such thunks are a common technique for compilers to implement the this pointer adjustment necessary for calling virtual functions in multiple-inheritance scenarios in C++.)

When you have to manage resources manually, exploiting the options of entering or exiting a function anywhere leads to more complex code, and thus to bugs. Therefore, a school of thought appeared that propagated SESE, in order to get cleaner code and less bugs.

However, when a language features exceptions, (almost) any function might be exited prematurely at (almost) any point, so you need to make provisions for premature return anyway. (I think finally is mainly used for that in Java and using (when implementing IDisposable, finally otherwise) in C#; C++ instead employs RAII.) Once you have done this, you cannot fail to clean up after yourself due to an early return statement, so what is probably the strongest argument in favor of SESE has vanished.

That leaves readability. Of course, a 200 LoC function with half a dozen return statements sprinkled randomly over it is not good programming style and does not make for readable code. But such a function wouldn't be easy to understand without those premature returns either.

In languages where resources are not or should not be managed manually, there is little or no value in adhering to the old SESE convention. OTOH, as I have argued above, SESE often makes code more complex. It is a dinosaur that (except for C) does not fit well into most of today's languages. Instead of helping the understandability of code, it hinders it.

Why do Java programmers stick to this? I don't know, but from my (outside) POV, Java took a lot of conventions from C (where they make sense) and applied them to its OO world (where they are useless or outright bad), where it now sticks to them, no matter what the costs. (Like the convention to define all your variables at the beginning of the scope.)

Programmers stick to all kinds of strange notations for irrational reasons. (Deeply nested structural statements – "arrowheads" – were, in languages like Pascal, once seen as beautiful code.) Applying pure logical reasoning to this seems to fail to convince the majority of them to deviate from their established ways. The best way to change such habits is probably to teach them early on to do what's best, not what's conventional. You, being a programming teacher, have it in your hand. :)


问:
Does Java promote a separation between class definitions and implementations, as is  C++?
I have a homework assignment and I need to evaluate which approach is better according to GRASP "Protected Variation". I found a question on Stack Overflow about the separation of header and code files in C++.

However, what I want to know why Java does not follow C++ in promoting the separation between class definitions and class implementations. Are there any advantages with the Java method, over the C++ method?

答:
How many lines of code are in the following program?

```<code>#include <iostream>

int main()
{
   std::cout << "Hello, world!\n";
   return 0;
}
</code>```

You probably answered 7 (or 6 if you didn't count the blank line, or 4 if you didn't count the braces).

Your compiler, however, sees something very different:

```<code>~$ cpp hello.cpp | wc
  18736   40822  437015
</code>```

Yes, that's 18.7 KLOC just for a "Hello, world!" program.  The C++ compiler has to parse all that.  This is a major reason why C++ compilation takes so long compared to other languages, and why modern languages eschew header files.

A better question would be

Why does C++ have header files?

C++ was designed to be a superset of C, so it had to keep header files for backwards compatibility.

OK, so why does C have header files?

Because of its primitive separate compilation model.  The object files generated by C compilers don't include any type information, so in order to prevent type errors you need to include this information in your source code.

```<code>~$ cat sqrtdemo.c
int main(void)
{
    /* implicit declaration int sqrt(int) */
    double sqrt2 = sqrt(2);
    printf("%f\n", sqrt2);
    return 0;
}

~$ gcc -Wall -ansi -lm -Dsqrt= sqrtdemo.c
sqrtdemo.c: In function ‘main’:
sqrtdemo.c:5:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
sqrtdemo.c:5:5: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
~$ ./a.out
2.000000
</code>```

Adding the proper type declarations fixes the bug:

```<code>~$ cat sqrtdemo.c
#undef printf
#undef sqrt

int printf(const char*, ...);
double sqrt(double);

int main(void)
{
    double sqrt2 = sqrt(2);
    printf("%f\n", sqrt2);
    return 0;
}

~$ gcc -Wall -ansi -lm sqrtdemo.c
~$ ./a.out
1.414214
</code>```

Notice that there are no #includes.  But when you use a large number of external functions (which most programs will), manually declaring them gets tedious and error-prone.  It's much easier to use header files.

How are modern languages able to avoid header files?

By using a different object file format that includes type information.  For example, the Java *.class file format includes "descriptors" that specify the types of fields and method parameters.

This was not a new invention.  Earlier (1987), when Borland added separately-compiled "units" to Turbo Pascal 4.0, it chose to use a new *.TPU format rather than Turbo C's *.OBJ in order to remove the need for header files.

Body:
How many lines of code are in the following program?

#include <iostream>

int main()
{
   std::cout << "Hello, world!\n";
   return 0;
}

You probably answered 7 (or 6 if you didn't count the blank line, or 4 if you didn't count the braces).

Your compiler, however, sees something very different:

~$ cpp hello.cpp | wc
  18736   40822  437015

Yes, that's 18.7 KLOC just for a "Hello, world!" program.  The C++ compiler has to parse all that.  This is a major reason why C++ compilation takes so long compared to other languages, and why modern languages eschew header files.

A better question would be

Why does C++ have header files?

C++ was designed to be a superset of C, so it had to keep header files for backwards compatibility.

OK, so why does C have header files?

Because of its primitive separate compilation model.  The object files generated by C compilers don't include any type information, so in order to prevent type errors you need to include this information in your source code.

~$ cat sqrtdemo.c
int main(void)
{
    /* implicit declaration int sqrt(int) */
    double sqrt2 = sqrt(2);
    printf("%f\n", sqrt2);
    return 0;
}

~$ gcc -Wall -ansi -lm -Dsqrt= sqrtdemo.c
sqrtdemo.c: In function ‘main’:
sqrtdemo.c:5:5: warning: implicit declaration of function ‘printf’ [-Wimplicit-function-declaration]
sqrtdemo.c:5:5: warning: incompatible implicit declaration of built-in function ‘printf’ [enabled by default]
~$ ./a.out
2.000000

Adding the proper type declarations fixes the bug:

~$ cat sqrtdemo.c
#undef printf
#undef sqrt

int printf(const char*, ...);
double sqrt(double);

int main(void)
{
    double sqrt2 = sqrt(2);
    printf("%f\n", sqrt2);
    return 0;
}

~$ gcc -Wall -ansi -lm sqrtdemo.c
~$ ./a.out
1.414214

Notice that there are no #includes.  But when you use a large number of external functions (which most programs will), manually declaring them gets tedious and error-prone.  It's much easier to use header files.

How are modern languages able to avoid header files?

By using a different object file format that includes type information.  For example, the Java *.class file format includes "descriptors" that specify the types of fields and method parameters.

This was not a new invention.  Earlier (1987), when Borland added separately-compiled "units" to Turbo Pascal 4.0, it chose to use a new *.TPU format rather than Turbo C's *.OBJ in order to remove the need for header files.


答: Headers exist, quite frankly, as a historical accident. It's an incredibly poor system, no other language has anything so terrible, and anyone who doesn't have to deal with them should rejoice.</p>

Title: Does Java promote a separation between class definitions and implementations, as is  C++?

Body:
I have a homework assignment and I need to evaluate which approach is better according to GRASP "Protected Variation". I found a question on Stack Overflow about the separation of header and code files in C++.

However, what I want to know why Java does not follow C++ in promoting the separation between class definitions and class implementations. Are there any advantages with the Java method, over the C++ method?


问:
UML to portray SQL objects
I am delving into the science of UML.  The tool I am using is ArgoUML.  I feel very confident portraying OO designs through this tool.  But what still vexes me is the incorporation of the database.  What does one do in UML to show table structure?  Stored procedures?  So on and so forth.

答:
I think that there are two opposite visions of UML and databases.

On one side you have traditional and old methodology using Model Driven Development and books such as Scoot Ambler.

On the other hand you have new initiative where UML is reversing Java annotations and adding this information in the code. I mean that UML is synchronized with the java code persistence annotations used by the EJB3 specifications (e.g. hibernate annotations). These annotations are created by using a Database profile composed by database stereotypes. This database modeling at the same stage as the object UML model modeling is only possible because of the use of JDK 5..7 annotations with ORM mappers. It means that you have to know not only UML but also the way the mapper will be working. Pretty hard but really powerful and time saving approach.

Title: UML to portray SQL objects


答:
Java does promote the separation of class definition and implementation, it just depends where you're looking from.

When you're the author of a Java class you get to see the definition of the class as well as its implementation in one file. This simplifies the development process as you've only gor to go to one place to maintain the class, you don't have to switch between two files (.h and .cpp as you would in C++). However, when you're the consumer of the class you only deal with the definition, via a .class file that is either packaged in a .jar or a standalone .class

C++ allows you to separate the definition and implementation, but it's ad-hoc. For example, there's nothing to stop you writing the method inline within the header file, and for template classes this is mandatory. The header file also lists out any member variables, which are visible to anyone who looks at the header file, even though they're an implementation detail of the class and irrelevant to a consumer.