问:
What are the benefits of using comments
I just accepted a new job. Our application is in the 50,000 lines of code area. None of which is commented. I am finding it difficult to understand how the application works. Id like to prevent this for the next person that joins the project by getting the team to start to use comments.

Forget about if you support comments or consider them code duplication. What are some of the benefits of using comments that I can use as reasons for the team to start using them. What arguments are there in favor of comments (Not looking for opposing arguments). Are there any publications or studies done that show that using comments improves code quality or something like that?

答:
When you analyze a piece of code you can't tell if it is correct
or not unless you know what it is supposed to do.  You can only
tell what it does do.  A good comment can tell you what the code
is supposed to accomplish.  If it is redundant, it is a good thing
because it means the code is meeting it's objective.

Comments can also tell you why it does it.

'we kept lines under 128 bytes because there is a legacy
component that breaks when they exceed that'

Someone who might argue 'put that in the unit test instead of
a comment' fails to grasp that it then needs to be commented in the
unit test, and that when someone changes the value and the regression
test fails, he will discover that he wasted his time because
the comment that he needed to see was in the wrong place.

Would you propose this?

'write_but_do_not_exceed_the_limits_that_the_legacy_component_can_handle()'

'Good naming suffices' is naive, an idea that comes from lazy people
who never learned how to comment properly in the first place.

Title: What are the benefits of using comments


问:
Ways of marking changes being made to a file
I am looking for a lightweight way to notate changes made to a file. The obvious answer to this is a version control system. But this is more robust than necessary for what I would like to do. All I want is the functionality to compare an edited file to its original in a lightweight manner.</p>

答: You might want to check the set of tools diff, cmp, sdiff, diff3, etc. These will provide you with easy to parse text output, making them usable from another program. diff in particular would probably do what you want.

ContentLicense: CC BY-SA 3.0


问:
Why do PHP variables need to be preceded with a dollar sign?
I understand that all PHP variables need to be preceded by a dollar sign (e.g. $someValue = 1), but why is this the case?  Why was this design choice made?

The reason I ask is my girlfriend asked why when I mentioned that PHP variables need to begin with a dollar sign, and I realized I had no idea why this syntactic choice was made.

Any ideas?

答:
PHP Was originally a meta-syntax that was parsed and simply dynamically called-into a compiled  c-programs functions.

In this way you can think of it similar to a "shell" program for the "web"...

It's no wonder variables with $dollarsigns were used similar to shell variables.

When I was all of 12, and I was learning PHP 3... as my first programming language - having the $ made life so much easier.  I knew what a variable was, but having a reminder in all of the source code I read made learning possible... not sure I'd be here today if I didn't start on PHP.

Here's an example from -> http://www.php.net/manual/en/history.php.php

```
<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hey, you are using Netscape!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Sorry, that record does not exist<p>
<!--endif exit-->
  Welcome <!--$user-->!<p>
  You have <!--$index:0--> credits left in your account.<p>

<!--include /text/footer.html-->
```

Body:
PHP Was originally a meta-syntax that was parsed and simply dynamically called-into a compiled  c-programs functions.

In this way you can think of it similar to a "shell" program for the "web"...

It's no wonder variables with $dollarsigns were used similar to shell variables.

When I was all of 12, and I was learning PHP 3... as my first programming language - having the $ made life so much easier.  I knew what a variable was, but having a reminder in all of the source code I read made learning possible... not sure I'd be here today if I didn't start on PHP.

Here's an example from -> http://www.php.net/manual/en/history.php.php

<!--include /text/header.html-->

<!--getenv HTTP_USER_AGENT-->
<!--ifsubstr $exec_result Mozilla-->
  Hey, you are using Netscape!<p>
<!--endif-->

<!--sql database select * from table where user='$username'-->
<!--ifless $numentries 1-->
  Sorry, that record does not exist<p>
<!--endif exit-->
  Welcome <!--$user-->!<p>
  You have <!--$index:0--> credits left in your account.<p>

<!--include /text/footer.html-->


答:
For a complete list of text/source editors that produce "Diffs" see:

https://stackoverflow.com/questions/12625/best-diff-tool

I would suggest using Meld if you are on Linux, and Netbeans if you aren't.  Both compare files in a graphical way.  Netbeans does Realtime-Data-Protection...  If you are interested in that... (It keeps track of all of your file-changes and allows you to compare any two versions for the last N* days)

Title: Ways of marking changes being made to a file

Body: I am looking for a lightweight way to notate changes made to a file. The obvious answer to this is a version control system. But this is more robust than necessary for what I would like to do. All I want is the functionality to compare an edited file to its original in a lightweight manner.</p>


答:
Several answers have already been provided and more exist if you search this site. What I want to bring your attention to is as follows:

Before you ask people to do comments - Come up with a set of rules and examples of what comments should look like (format), length, content, scope and when to use them.

Avoid describing business rules inside the application as much as possible. Code may reference business rules in outside documents but should not verbally state them inside the code.

Title: What are the benefits of using comments

Body:
I just accepted a new job. Our application is in the 50,000 lines of code area. None of which is commented. I am finding it difficult to understand how the application works. Id like to prevent this for the next person that joins the project by getting the team to start to use comments.

Forget about if you support comments or consider them code duplication. What are some of the benefits of using comments that I can use as reasons for the team to start using them. What arguments are there in favor of comments (Not looking for opposing arguments). Are there any publications or studies done that show that using comments improves code quality or something like that?


问:
Why are SQL databases still used with ORM?
ORMs and persistence ignorance make perfect sense: if I am programming in a language, then I want to use the language's native implementation of objects and data structures to drive my program. I shouldn't need to worry about SQL or a database, and I always thought that inline SQL strings in a program was very cumbersome.

Why is SQL still used as a backend? Why doesn't the ORM just persist objects to XML or a binary file(s) and avoid all the overheads and difficulties of administering a database server?

答:
The big problem is that OO Objects present a strictly hierarchical view of the data.

Take a typical OO "Order" object it consists of:

Some customer details.

Some Delivery details.

A collection of order items.

A product code.

A quantity.

A price.

Some tax data.

Total amount payable

Some payment details.

This is all well and good and can be mapped into six or seven relational tables via the ORM or one serialized object via an Object store, XML or plain text file.

This works fine for vanilla order processing. But consider what happens when purchasing want to know how many of each product were ordered today so they can manage their inventory.

With the SQL backend they can fire off a simple SQL query against the items table and get a total for each product in product id sequence.

With serialized objects they need a custom program to read all the orders, step through each order item, sort the items into the right sequence and summarize the quantities.

In any normal sales situation marketing will want to know sales volumes by product, area and channel. Warehousing will want products and quantities, accounts will want to know prices and taxes, credit control will want to track outstanding amounts by customers etc. etc.

Relational data bases were designed from the outset allow different views on the same data.
By basing your tables on a conceptional Entity Relationship model that satisfies the needs of all the potential users of the data an efficient and flexible data store is created.

With the current crop of OO databases you can only design for a small set of use cases, other potential uses are excluded.


问:
Is code commonly generated from UML?
So when I was at university I was educated on the benefits of UML and its future in code development.

But from my industry experience, I've found that while we do use diagrams—ranging from ER diagrams, class diagrams, state diagrams, to work flow diagrams—all of it is for communication purposes.

That is, I've never generated code automatically from diagrams, and from a communication standpoint, I generally try to keep my diagrams as simple and easy to understand as possible.

But when I look at Visio and Enterprise Architect, it seems they have many different types of graphs, shapes, properties objects, most of which I don't use.

Do people use UML to do more sophisicated things such as code or database generation?

答:
Been there, didn't find it too useful.

Generally the diagrams specific enough to generate some code from them, mainly class diagram, don't add much in the way of actually understanding the program and you can't generate code from the overview diagrams like use case or overview-level activity that are crucial for documentation. One diagram that is useful for understanding and can have code generated from is state chart, which comes in handy when you really need state machine. But generally you should try to avoid those, because they are inherently error prone.

On one project we were required to design the code in UML modeller (Rhapsody) and generate it from there. It kind of worked and was probably very slightly easier than typing the headers (it was C++) and prototypes by hand. The ability to keep those two consistent automatically was somewhat handy.

The method bodies still had to be filled in by hand, because the diagrams can't really represent that with exception of state machine skeletons.

On the other hand it is rather complex, so you have to learn a lot of extra stuff and more importantly it was pain to merge. Merging is well researched for text files and works with them, but nobody invented easy way to merge changes to diagrams yet. Rhapsody actually keeps part of the information in the generated code and parses it back, so it was not totally unusable, but it was still serious complication.

Title: Is code commonly generated from UML?


问:
How should I go about learning new technologies?
In a career of software engineer, you need to learn new technologies very often and always in less time due to deadlines. So just need to know how programmers should go about learning the technologies really quick still thoroughly. What approaches do you follow?</p>

答:
In my eyes it's quick XOR thorough.

The key point here might be that you figure out just enough of the new framework, e.g. Spring's dependency injection, to get the project going, because most often you won't need the complete framework, but just a few pieces of it.

I usually write vertical prototypes to get familiar with the technology. They might be helpful to explain things to the developer as well later.


问:
How do I improve my coding skills?
Here's a bit information about me, before starting with the question.

I am a Computer Science Undergraduate, Java being my primary coding language.

The basic problem in my University are the teaching standards. No one is concerned about teaching coding knowledge to students, rather than just theoretical knowledge.

The effect being, most of my fellow college mates don't understand programming at all.

Even I haven't been able to come out of the traditional programming environment, which limits my coding to an extent.

What are the possible ways by which I can develop and expand my programming/coding skills.

Also, can you suggest the sources for the same?

Edited:
Sources suggesting development of coding skills.

答: Peer reviews really help improve the quality of your code. If you have no real mentor, you can post your code [after you reduce it to necessary minimum] at StackOverflow or RefactorMyCode or mailing lists and people will help you with improving the quality of your code.</p>

ContentLicense: CC BY-SA 2.5

Title: How do I improve my coding skills?


答:
Yes, UML CASE tools were one of the hot items of the 90s... and then failed to deliver.

The fundamental reason for this is that UML (or most any other kinds of) diagrams help to understand the problem and/or the program solving it only insofar the diagram is abstracting away the implementation details of the actual code. Thus (for any nontrivial piece of code), a diagram which is easy to understand is inherently useless for code generation, because it lacks the necessary details. And vice versa, a diagram which is directly usable for code generation doesn't help you much to understand the program any better than code itself. If you have ever seen a UML class diagram reverse engineered from production code, you probably know what I mean.

The only potential exception to this I know of is Entity-Relationship diagrams, which don't encompass code per se, only (as their name implies) pieces of data and their relationships. But I have never heard of a successful attempt to use any kind of UML diagrams for real code generation [Update] - i.e. more than class skeletons and trivial code like getters/setters -, except in special purpose tools/areas like ORM, as testified by Doc Brown below [/Update], and I think this is no accident.

I personally do not hate UML - I think that UML diagrams can be a great tool of communication - to show your intent and ideas during design discussions, or to visualize the architecture of your app. But it's best to keep them to this, and not try to use them for things they aren't good in.

Title: Is code commonly generated from UML?

Body:
So when I was at university I was educated on the benefits of UML and its future in code development.

But from my industry experience, I've found that while we do use diagrams—ranging from ER diagrams, class diagrams, state diagrams, to work flow diagrams—all of it is for communication purposes.

That is, I've never generated code automatically from diagrams, and from a communication standpoint, I generally try to keep my diagrams as simple and easy to understand as possible.

But when I look at Visio and Enterprise Architect, it seems they have many different types of graphs, shapes, properties objects, most of which I don't use.

Do people use UML to do more sophisicated things such as code or database generation?


答:
This is a sort of trade-off: you either learn something "thoroughly" or "really quick".

In many cases you don't have to learn everything "from scratch". If you want to learn a new technology, for example ORM, you can still learn it using your favorite programming language (Java or C#), just learning how to perform abstraction from your data model. If you learn a new language, for example Python, you can just try to implement something you know how to implement in other language/framework already, for example you can try to implement the page you previously programmed in ASP.NET MVC using Django to see the differences between those languages and approaches.

As long as you know a similar technology you can find a tutorial where you can just learn the difference. This is true, for example, for functional languages: you can find many Haskell tutorials for Ocaml or Java users etc.

Title: How should I go about learning new technologies?

Body: In a career of software engineer, you need to learn new technologies very often and always in less time due to deadlines. So just need to know how programmers should go about learning the technologies really quick still thoroughly. What approaches do you follow?</p>


问:
What about ALM systems, ERPs, and embedded products?
We are working on getting a new application lifecycle management (ALM) system, including a bug tracker, a documentation system, project management, etc.

The concern is that we deal with quite complex embedded systems and we would like to have the best possible integration of the different services (project management, issue/task tracking, documentation, etc.). If it was software only, I'd just buy something like JIRA, but the fact that we would hope to manage software, firmware (no big problem there), and hardware in the same system makes me doubt a little bit.

I'm looking for advice regarding these points:

What about managing "bugs" with embedded products? In software, you have the versions of the affected module(s). In embedded products, you have different software driving often times different firmware operating sometimes different hardware. Is it good in practice to simply consider hardware parts as if they were software modules in a software-intended system? I tend to believe it will add many custom fields to the bug tracking interface and consequently won't promote its systematic use.

Some would like to push integration to the level where you have hardware inventory integrated to the rest. This means that a project in the ALM (think JIRA) would have to reserve its hardware components based on the sub-components. It would also mean that, for example, the ALM in question would have to be able to manage part providers and offer facilities to easy purchase order creation, sending, and management in general.

I'm wondering, at that point, if everything in an embedded project management process can be integrated in one management system, or if a line has to be drawn between 1) bug/task tracking (possibly software and hardware) and project management and 2) high level project management, inventory tracking, sale/buy orders, etc. What is ultimately wished for seems to be nothing less than an integrated JIRA and ERP. Or is it possible to do proper ALM in an existing ERP or have a decent ERP in an ALM system already?

My personal opinion, from what I know right now, would be to split issues and project management (ALM + documentation + ...) from the ERP. The problem with that is that there's documentation about a project both in the ERP and in the project management of the ALM (which would be used for software, firmware, hardware, ...). What's funny in this is that some things might seem very unrelated at first, like the time sheets (ERP) and an issue (bug tracker in ALM), but in the end, it might very well be interesting, wanted, or even required to know how much time was spend on a bug, or a project altogether (bugs, issues, features, other tasks). This gives a point toward total unification of ERP/ALM...

At this point, you should get a feel of my questioning. Any helpful input is greatly appreciated. Thanks!

答:
I worked for the company developing embedded devices for seismic recording, including custom hardware, firmware and software.

It turned out that just a conventional issue-tracking system, like RedMine (what we used) or JIRA (as you suggest) already perfectly do.

I am not competent in JIRA, but in RedMine you can define the "areas" of your project, so we just split the complete project into three big parts: hardware, firmware and software. RedMine allows you to change the area "on the fly", that is especially handy if you notice a bug and don't know its origin, you can just post it as a general bug and then developers in charge of firmware or hardware engineers can assign it to the appropriate section.


答:
In my latest project I am using UML-Lab(https://www.uml-lab.com). This is a nice tool which allows the model to be reverse engineered as well. The tool generates java code and even the JPA annotations which are fairly accurate.

The challenge to that is when working in a team. The model is static and is in a single resource which makes keeping it in sync with multiple developer changes a little difficult. There is trial version that is available for 1 month which is a good time to explore and compare with others if you are investigating.

This is the first time I seen a product doing Object modelling and data modelling in one shot along with code generation as well.

Otherwise in my past projects, I have always seen stale models which are inaccurate or either too detailed.

In my past projects I sometimes generated diagrams by reverse engineering. Most of the time I found the diagrams are cluttered and I preferred to draw them manually filtering all the noise.

Title: Is code commonly generated from UML?


问:
Single or multiple files for unit testing a single class?
In researching unit testing best practices to help put together guidelines for my organization, I've run into the question of whether it is better or useful to separate test fixtures (test classes) or to keep all tests for a single class in one file.

Fwiw, I am referring to "unit tests" in the pure sense that they are white-box tests targeting a single class, one assertion per test, all dependencies mocked, etc.

An example scenario is a class (call it Document) that has two methods: CheckIn and CheckOut.  Each method implements various rules, etc. that control their behavior.  Following the one-assertion-per-test rule, I will have multiple tests for each method.  I can either place all of the tests in a single DocumentTests class with names like CheckInShouldThrowExceptionWhenUserIsUnauthorized and CheckOutShouldThrowExceptionWhenUserIsUnauthorized.

Or, I could have two separate test classes: CheckInShould and CheckOutShould. In this case, my test names would be shortened but they'd be organized so all tests for a specific behavior (method) are together.

I'm sure there are pro's and con's to either approach and am wondering if anyone has gone the route with multiple files and, if so, why?  Or, if you've opted for the single file approach, why do you feel it is better?

答:
In general I would recommend thinking about tests as testing a behaviour of the class rather than a method. I.e. some of your tests may need to call both methods on the class in order to test some expected behaviour.

Usually I start out with one unit test class per production class, but may eventually split that unit test class into several test classes based on the behaviour they tests. In other words I would recommend against splitting the test class into CheckInShould and CheckOutShould, but rather splitting by behaviour of the unit under test.


问:
In a "Revisional Data Model," where does code that preserves a previous record's state belong?
When I say "Revisional Data Model", I mean a data model where information is never lost: Deletes never destroy any rows, and updates always cause an insert somewhere else to preserve a row's previous state before the update.

There are a few I've read about, and heard from colleagues:

Triggers in the database. The main reason why I don't like this approach is because if you depend on triggers to enforce revision integrity, the application becomes tied to the database server. If using an ORM with different providers (Oracle, MySQL, T-SQL, etc), you may need to alter some SQL to switch between them.

Human-readable trace logs. Last year I played Business Analyst for a project with a new developer because one of our sister departments was slammed with important deadlines.  She insisted that, despite the requirements I gathered and the schemas I modeled, she would insert a stored procedure to be executed with each create/update/delete statement. This sproc would just write out the old data as a formatted string, and save it to a ERRORS_LOG table in the database. Her goal was to help her with debugging the application in case anything went wrong: she wanted a trace.

Creating sister tables. This approach is like having 2 databases living in the same context. For the table Person there would be a PersonHistory table, for Product there would be ProductHistory, and so on. The schemas would be identical, and each time a change happened in the entity table, the previous state would be inserted into ProductHistory.

If you have an application where you want to allow users to "undelete" or "restore previous version" of an entity, only #3 seems like a workable solution. However, since each pair (entity and its history) have the same model/schema, they can in fact be combined. By adding bool/bit properties like IsCurrentVersion and IsDeleted, you can slice a single entity set into different states within the WHERE clause. Consider this example #4.

One disadvantage of #4 is that the database tables become hard to read when you select all rows. Mining data from a db server ide would require pretty extensive use of views, which causes the same problem as in option #1. Looking at all of the different states together in the same table makes it much more difficult to read. With approach #3, you need to look in a different table to find previous versions & deletes.

We've been using approach #4 with success. We have a RevisableEntity supertype with properties that indicate when data was changed, who changed it, whether it was deleted, archived, or modified. Updates occur on rows just as they would under normal circumstances. However as part of the same action, a corresponding insert is made into the same table / entity set. The insert contains the same values as the update before it was updated. The updated row, in addition to whatever changes were made by the user, also updates the when and who properties.

Now for my question: Where does this code belong? In the domain, or in the repository implementation? There are certain aspects of this that are storage dependent, which hint at putting the code where your ORM coupling is. However there are other aspects that the domain / application layers should be able to trust. Maybe the domain entities should manage their own revisional integrity, or maybe there should be a factory to coordinate?

答:
There is no clear-cut answer to this I'm afraid. It depends on what you want to do, how strict your requirements are and what tools you have available or want to use. To give an extreme example, banks don't just write a log on a file somewhere, but actually print that log line onto real paper...

What I did for one of my applications was your suggestion #3, where the live-data sits in optimized-for-access tables residing entirely in memory while the data for 'undeletes'/'rollbacks' is stored on traditional tables that have just an index on the entry-id.

But that's just me, because I have a lot of searches per second, but only few changes and rollbacks. Your requirements might differ. Maybe your application is more GoogleDocs-like where you expect changes to happen often, and even simultaneously, but don't need that fast lookups/searches. Then it might be better to store the base-document and keep track of change-deltas that happen over time.

Others again, that are already using an enterprise-DBMS like Oracle, might feel much more comfortable 'outsourcing' this to the database. Be it by using triggers, or specialized versioning Add-Ons available from the DBMS vendor directly. This could also be the right choice for your personally if the versioning and traceability is vital to the data and you want to offload the responsibilty of doing it properly to someone else.

And so on...

So you see, it really depends on your requirements


问:
Does not testing internals entail diligent refactoring and/or rely on developer talent?
I'm not asking here what the arguments are for/against testing
internal methods (though I'll restate some, and don't mind hearing
others). My questions relate to the implications of only testing
public interface.  Especially, whether I understand the extent of the
"refactor" part of Red-Green-Refactor in by-the-book TDD, and if there
are non TDD techniques TDD practitioners use that address the problems
that make me want to test internals.

My question is: If you write the most straightforward code possible to
get the light green, and if you don't test internal methods, does it
follow that from time to time you allow yourself to start off by
writing a class that does far more than it should with a bunch of
member variables you know will not survive refactoring?  And wind up
after refactoring with a bunch of methods that aren't explicitly
tested?

As I get familiar with TDD, it feels like anyone would at least be tempted to
test internal methods.  And many practitioners flatly say you shouldn't.
E.g. (of about 23 million results):

Item 2 here and it's comments and this StackOverflow post

Given an implementation will involve more than one non-trivial
problem, if you only test the public interface, there are two
possibilities: 1) non-trivial logic winds up getting tested only
indirectly, AND tested in the same calls as other non trivial logic.  2) you make methods
public that you don't expect clients other than the SUT and the tests
to call.  I think what I hear from the advocates of by-the-book TDD is
"1 is right.  Yes, a lot of non trivial code is tested only
indirectly, and that isn't a problem.  After all, you don't want your
tests to start failing when you improve the implementation.  Even if
they don't fail, it's not innocuous if tests keep passing when they're
targetting a bunch of no-longer-used code, because the tests show how
to use your class. You Should Only Test the Public Interface."  And
that sounds like a reasonable thing to say, but I haven't seen it said
explicitly.

But even though it sounds reasonable -- if I don't test internals I
feel like I lose part of what helps keep the tests DRIVING the coding
(maybe part of my difficulty applying the precepts is that I don't
distinguish between coding and developing).  If there's some internal
logic that has to turn a String to a valid int32, int64 or decimal
value depending on what's in the string and the type of some other
object, I want to test that little bit of logic, not just find out
that the whole method failed.  I want one test to pinpoint those few
lines of code and exercise what should fail.

The thinking in the doubly downvoted answer here seems so obviously attractive that I have to wonder if the
by-the-book fellows are neglecting to mention some
instrumentation/tracing/logging code they use in addition to TDD, or
if they watch it work in a symbolic debugger.  Or do they just
recognize that as a failure point and write a test with input that
will cause a failure pinpointing those few lines of code?  If they do
that it's testing the implementation though.  It seems so natural to
want to test that code in isolation, and verify it fails where it
should, even though it's an implementation detail.

I suppose that with talent and experience you can classify bigger chunks
of code as "non-trivial" but I haven't seen anyone bluntly saying or condescendingly implying that
that's why they don't have to test implementation details.

Lots of time it makes perfect sense to me to test the public
interface, lots of methods really are like what you see in TDD
examples.  But for the feel of where I wonder if purists are doing
something more than writing tests on a public member: Say you want to
put data from an ISAM file into a database.  There is one public
method to the envisioned consumer of the code: public void
LoadIt(SqlConnection c).  "Loadit" has a bunch of other dependencies
that will be resolved using configuration files and environment
variables: some code has to determine that it can find the name of the
folder where the ISAMs live; to find, load and parse the schema file
for the isams using the ISAM vendor's DDL library; so forth+so on.
But none of that is of any interest to any envisioned calling code.

My only reason for moving the dependency resolvers out of the
Loadit class would be so I could test them OR to make the code easier
to understand/maintain.

Moving to another class to make them testable is Doing It Wrong --
they're really just implementation details of LoadIt.  And in my first
implementation, I am just trying to write enough code to get the light
to turn green.  So I won't write anything with reasonable
maintainability if it's easier to just manhandle a bunch of variables
in a big method or two.  I won't write helper classes.  Instead, I'll
get the light green and then do the Refactor part diligently.  Even
when I clean it up, any classes introduced keep "internal/friend"
accessibility, and only get tested via the call to LoadIt.

Thanks for reading this far; as a reminder, my question is in the
second paragraph.

答:
If you have no problem writing a good set of test cases, and no problem getting the tests to pass, so that each line of code is critical to at least one test, then you have no problem.

If you are having difficulty creating test cases to cover all the logic needed in some internal method, then you need to test that method separately.  If it should not be a public method in it's current class, then make it a public method in some new class.  At first you may think "It's a waste of time to create all those little classes".  Soon you will find that all those little classes are quite handy, easy to understand, and are reused more than you might expect.

OwnerDisplayName: MakeMinePanacea

ContentLicense: CC BY-SA 4.0


问:
confusion between SVN and code backup by month/date/time whenever i make major or important update to the code
I am working on two different project simultaneously where whenever the changes are made we use

Tortoise SVN for project A

Backed up by folder for Project B (this is done by me on my system)

I find SVN good for maintaining the latest code server machine and update it whenever necessary.

For Project A, I happen to make alot of changes to the project A and I am advice not to commit the changes again and again but just a major change all at once.

But since in not alone on project A I tend to make code backs by folder every time I make an important change so I can go back and return if some conflict occurs.

But what should I do in case of the project B?

where most I am on the project (as of now).

Should it be SVN or folder backups?

The reason I do folder backups for the project B is that

sometimes the build given to the client fails/buggy so instead of making them wait for it to fix

I just go and open the project and compile the last working build and give the executable so they can carry on their work and not wait for me to fix it (may take long).

I am working with Delphi on both the projects.

答:
im advice not to commit the changes again and again but just a major change all at once

It's wrong advice.

project B where most im on the project (as of now) should it be SVN or folder backups

You should use version control in any project.

Backups and version control are not the same thing, although an external  repository (centralized, or distributed in another computer) is a backup in itself, and backups (e.g. dated folders or zip files) together with some diff tool (e.g. WinMerge) could serve as a very rudimentary version control tool. But since excellent version control systems are available for free, there's absolutely no excuse not to use them.

Of course, backups must be taken in addition to using a version control system.


问:
Where are programming languages published?
I have read that a number of new programming languages are created each year, however I have never seen a single one. Where exactly are these things published? Is there some site out there that keeps track of them?

(I don't have any intention to learn such languages - I am only interested)

答: Felix is described at felix-lang.org, but the source is on GitHub.com. So even one language can't be said to be published in one place :)</p>


答:
I still don't understand why the business intelligence with tools like Business Object is able to analyse and take advantages of all company information while at technological level we are still working at code level only or at abstract level with UML !!

The problem is not UML but model transformation between UML and MOF and code generation from a clas diagram or xmi using templates. UML is said to give an abstract view of the real world therefore you only see what is really important.
Having said that how to generate accurate code if the UML diagram is just a view of the real world ? It is impossible and therefore model driven development which would generate code from a model has failed.

The solution is to transform to map the real world and therefore all project code to a single UML model. Having a single model and the project full logic you can then generate views from the model and not from the code each time. There is a courageous initiative made by Omondo within the Java / Jee technology.
The concept is live synchronized MOF and UML directly with the code and ORM. UML diagram are now just a high level view of the model which is mapping the entire project. You can create hundred of views, add hundred of notes etc.... to have a better understanding of the project. The code will be generated only if the element is changed or created. Marvelous technology where the Java Id is mapped to the UML id without the traditional transformation bridge between MOF and UML. The Model is becoming a kind of project datawarehouse inside which you can navigate and take accurate decision.

What is also fantastic is to be able to model my domain at UML level and get my ORM annotations directly in the code and therefore using Hibernate I can create, erase, create my database, deploy etc... in a permanent continuous integration in which UML is piece of the all architecture and not the architecture itself of the project.

I have never been disappointed by UML as  high level viewer if live syncrhonization with the code but was absolutely devastated by traditional using MDA with Model driven development templates code generation. Code generation from a model is like an HTML page coming from a word document. How to change it once it is generated ? It is just impossible to update and you spend more time to clean the code than to write from scratch !

Title: Is code commonly generated from UML?


问:
What modern alternatives to Numerical Recipes exist?
In the past, the Numerical Recipes book was considered the gold standard reference for numerical algorithms.  The earliest Fortran Edition was followed by editions in C and C++ and others, bringing it then more up-to-date.  Through these, it provided reference code for the state-of-the-art algorithms of the day.

Older editions are available online for free nowadays.

Unfortunately, I think it is now mostly useful only as a historic tome.  The "software engineering" practices seem to me to be outdated, and the actual content hasn't kept pace with the literature.

What similarly comprehensive yet approachable references should the modern programmer look at instead?

答:
Numerical Recipes is still, IMO, a useful book. It describes the algorithms really well, including their derivation, the situations in which they're useful, and alternatives to consider when they aren't. I've been using the book for years.

One thing I have never used is their code. I always write my own implementation based on the algorithms they describe. In that respect the quality of their code doesn't matter (and it is indeed questionable: in the 2nd edition C book, they define a collection of functions and macros to make arrays unit-indexed because the authors come from a Fortran background). As an example: I once had to implement FFT in Objective-C, so I used NR in Fortran to understand what FFT did and how the code should look.

Think of NR the same way you think of Knuth: you would never paste code from that book into your project.


答:
The reason I do folder backups for the project B is that
  sometimes the build given to the client fails/buggy so instead of making them wait for it to fix
  I just go and open the project and compile the last working build and give the executable

This is precisely the problem source control is meant to solve (using branches/tags). You would do yourself a favor in the long term by switching to SVN. You will realise how wise such a movement was (would have been) the first time you need to provide a hotfix to a bug in an older version while you are in the middle of developing a new feature in the latest version, which must not be deployed yet. With SVN, merging between different branches is way easier and safer than manual diff & merge between different backup directories.

Title: confusion between SVN and code backup by month/date/time whenever i make major or important update to the code

Body:
I am working on two different project simultaneously where whenever the changes are made we use

Tortoise SVN for project A

Backed up by folder for Project B (this is done by me on my system)

I find SVN good for maintaining the latest code server machine and update it whenever necessary.

For Project A, I happen to make alot of changes to the project A and I am advice not to commit the changes again and again but just a major change all at once.

But since in not alone on project A I tend to make code backs by folder every time I make an important change so I can go back and return if some conflict occurs.

But what should I do in case of the project B?

where most I am on the project (as of now).

Should it be SVN or folder backups?

The reason I do folder backups for the project B is that

sometimes the build given to the client fails/buggy so instead of making them wait for it to fix

I just go and open the project and compile the last working build and give the executable so they can carry on their work and not wait for me to fix it (may take long).

I am working with Delphi on both the projects.


答:
You could switch to mercurial (distributed version control). This way you can commit as often as you want (on both projects).

In project A once you have reached a critical mass of commits that are acceptable you can all push them to the subversion repository (using HgSubversion*). If the number of commits is a Problem you can use either mercurial queues (Tutorial) or make a little home-made fix by rewriting all your commits into one. For example export them all as patches -- easily done with TortoiseHg -- and then import them into the repository again. Then commit and you have all your changes in one commit.

*To use HgSubversion you need the Python SVN bindings. In TortoiseHg (Windows mercurial client) these are included so you just download the HgSubversion source, include the path in the hgrc file and are ready to go.


答:
Use a source repository for all of your projects, as @JoonasPulakka and @PéterTörök wrote.

Backup your entire source repository daily on another server/drive. Corruption/loss of source repositories may happen, and it is the only way to recover the the whole history of your changes, not only the last version. There is a question on SO on what is the best way to backup an SVN repository.

Tag/Branch your minor/major changes. If one of these builds is released to the client, and fails, you should be able to fix that branch and release a fix, and report the change to the HEAD branch. Sometimes, though, there may be valid reasons to not fix a previous version (as you mentioned), and releasing the latest version that already fixed the problem may be the best solution. Anyway, this is your choice, and the only way to be able to fix a previous version is to have it in the repository, AND to tag it appropriately.

Edit: on the subject of SVN, as @PéterTörök wrote, merging branches is way easier than with some other source repositories, you already made a good choice there.


问:
Does any programming language use variables as they're in maths?
In maths, a variable means you can put any number there, and an equation will still be true:

```<code>root(square(x)) = abs(x)
</code>```

In programming languages, this is not so: a var can change. In Python:

```<code>y = (x**2)**.5
x *= 2
assert y == abs(x)
</code>```

will raise an exception, since x in the last line is not the same.

Are there programming languages that use immutable variables?

答:
The = sign used in programming languages is misleading.
 <-, meaning "store", or even COBOL MOVE should be used instead.

As an addition, Prolog uses variable like math: Variables cannot change, and the Prolog engine will fill in the variables to see if the solutions exist.

Also, Curry is a mix of Haskell and Prolog.


答:
In my view, learning all things will take time.
What all i do is search for new technologies, by subscribing Microsoft website or any leading platform blogs or website, so if they introduce any new things, we will automatically come to know and then for the next time when u think to do something new, think of these new technologies.

Because you can only learn if you use it..


问:
How can I retain knowledge about new technologies I don't use every day?
At work we mostly do WinForms development and it’s not a secret that it is already very outdated. I have a passion to learn new stuff like WPF, MVVM and want to use full advantages of C# 4.0. There is no way I can push my bosses to change “well-recommended” and “proven” technologies like WinForms to something else.

I have up to two hours a day which I can dedicate to self-learning but I simply don’t know the most efficient way to study. I tried to read couple of books and even wrote a simple WPF application but think that it’s not enough.

How can I manage my time learning new things in a way that sticks, even if I don't use it on a daily basis?

答:
In my view, learning all things will take time. What all i do is search for new technologies, by subscribing Microsoft website or any leading platform blogs or website, so if they introduce any new things, we will automatically come to know and then for the next time when u think to do something new, think of these new technologies.

Because you can only learn if you use it..


问:
Do you find languages with indentation requirements cumbersome?
Thoughts on these?  Python is one example, and no this is not a stab against Python I like the language.

What languages have a indentation requirement?

答:
This seems to me purely a matter of preference.

I personally don't like significant whitespace for the following reasons:

Mentally, whitespace to me is a "no-op". I don't like the fact that it changes behaviour.

Tabs and spaces look the same in an editor, but can have different meanings if whitespace is significant. Nasty!

I like the freedom to format my code however I like. Worrying if this will change the semantics of the program is not helpful.

I think that visible block delimiters, whether they are {} in C/Java or () in Lisp, are useful additional visual clues as to the structure of the code.


答:
"Practice!" That is a cliche.

You should review what you've learned in the math classes, and make some programs that deal with the problems.
Also, implement an elevator program, a vending machine (that calculates changes in coins), to sharpen your logic skills.
Think of everything in the everyday life, and implement them.

Title: How do I improve my coding skills?

Body:
Here's a bit information about me, before starting with the question.

I am a Computer Science Undergraduate, Java being my primary coding language.

The basic problem in my University are the teaching standards. No one is concerned about teaching coding knowledge to students, rather than just theoretical knowledge.

The effect being, most of my fellow college mates don't understand programming at all.

Even I haven't been able to come out of the traditional programming environment, which limits my coding to an extent.

What are the possible ways by which I can develop and expand my programming/coding skills.

Also, can you suggest the sources for the same?

Edited:
Sources suggesting development of coding skills.


答:
Soft deletes such as these are a performance killer. The main reason for this is that each table needs to have a "IsDeleted" column, and because this will only contain 1 of 2 possible values, indexing this column is pointless as the selectivity is way too low.  This means that each query against the table turns into a table scan to find all of the "Current" rows.

See the following article for more details about why this is a bad idea.

http://weblogs.asp.net/fbouma/archive/2009/02/19/soft-deletes-are-bad-m-kay.aspx

Title: In a "Revisional Data Model," where does code that preserves a previous record's state belong?

Body:
When I say "Revisional Data Model", I mean a data model where information is never lost: Deletes never destroy any rows, and updates always cause an insert somewhere else to preserve a row's previous state before the update.

There are a few I've read about, and heard from colleagues:

Triggers in the database. The main reason why I don't like this approach is because if you depend on triggers to enforce revision integrity, the application becomes tied to the database server. If using an ORM with different providers (Oracle, MySQL, T-SQL, etc), you may need to alter some SQL to switch between them.

Human-readable trace logs. Last year I played Business Analyst for a project with a new developer because one of our sister departments was slammed with important deadlines.  She insisted that, despite the requirements I gathered and the schemas I modeled, she would insert a stored procedure to be executed with each create/update/delete statement. This sproc would just write out the old data as a formatted string, and save it to a ERRORS_LOG table in the database. Her goal was to help her with debugging the application in case anything went wrong: she wanted a trace.

Creating sister tables. This approach is like having 2 databases living in the same context. For the table Person there would be a PersonHistory table, for Product there would be ProductHistory, and so on. The schemas would be identical, and each time a change happened in the entity table, the previous state would be inserted into ProductHistory.

If you have an application where you want to allow users to "undelete" or "restore previous version" of an entity, only #3 seems like a workable solution. However, since each pair (entity and its history) have the same model/schema, they can in fact be combined. By adding bool/bit properties like IsCurrentVersion and IsDeleted, you can slice a single entity set into different states within the WHERE clause. Consider this example #4.

One disadvantage of #4 is that the database tables become hard to read when you select all rows. Mining data from a db server ide would require pretty extensive use of views, which causes the same problem as in option #1. Looking at all of the different states together in the same table makes it much more difficult to read. With approach #3, you need to look in a different table to find previous versions & deletes.

We've been using approach #4 with success. We have a RevisableEntity supertype with properties that indicate when data was changed, who changed it, whether it was deleted, archived, or modified. Updates occur on rows just as they would under normal circumstances. However as part of the same action, a corresponding insert is made into the same table / entity set. The insert contains the same values as the update before it was updated. The updated row, in addition to whatever changes were made by the user, also updates the when and who properties.

Now for my question: Where does this code belong? In the domain, or in the repository implementation? There are certain aspects of this that are storage dependent, which hint at putting the code where your ORM coupling is. However there are other aspects that the domain / application layers should be able to trust. Maybe the domain entities should manage their own revisional integrity, or maybe there should be a factory to coordinate?


问:
Agile,Waterfall and requirement changes
Has anyone had this issue of a project defined as 'Agile' being overrun by requirement changes ? I work on a development project which is run in 4 weeks Sprint but there are always changes in between these Sprints . Is it still defined as Agile then ? I feel it's sort of a sub Agile process - The requirements of an Agile process should be defined at the beginning of a sprint and reviewed towards its end. Am I right in this? Please let me know your experiences in this .</p>

答:
The requirements of an Agile process should be defined at the
  beginning of a sprint and reviewed towards its . Am I right in this?

No, this depends on the nature of the project (and the process).

There are some agile development models where requirements are meant to be fixed during a sprint, and should only change for the next sprint (a prominent example is Scrum).

However, there are also processes where changes can happen almost any time (as long as the customer accepts the delays and the extra work which the change causes). Kanban is often used to manage these workflows (although Kanban can also be combined with Scrum).

Which model you follow depends on the details of each project.

So yes, if the customer feels they need the possibility of constantly changing the requirements, then an agile process can accommodate this. However, the customer should be aware of the consequences of constant changes, and should understand that they will slow down the project.

This boils down to the principles from the agile manifesto - "Individuals and interactions over processes and tools", and "Responding to change over following a plan".

Title: Agile,Waterfall and requirement changes


答:
I answered a similar question on SO some time ago. Here's something that might work.

One method that is used by a few wiki platforms is to separate the identifying data and the content you're tracking revisions for.  It adds complexity, but you end up with a history of complete records.

So for example, if you had a table called Opportunities to track sales deals, you would actually create two separate tables:

Opportunities

Opportunities_Content (or something like that)

The Opportunities table would have information you'd use to uniquely identify the record and would house the primary key you'd reference for your foreign key relationships.  The Opportunities_Content table would hold all the fields your users can change and for which you'd like to keep an audit trail.  Each record in the Content table would include its own PK and the modified-by and modified-date data.  The Opportunities table would include a reference to the current version as well as information on when the main record was originally created and by whom.

Here's a simple example based on ScrewTurn's data schema:

```<code>CREATE TABLE dbo.Page(
    ID int PRIMARY KEY,
    Name nvarchar(200) NOT NULL,
    CreatedByName nvarchar(100) NOT NULL,
    CurrentRevision int NOT NULL,
    CreatedDateTime datetime NOT NULL
</code>```

And the contents:

```<code>CREATE TABLE dbo.PageContent(
    PageID int NOT NULL,
    Revision int NOT NULL,
    Title nvarchar(200) NOT NULL,
    User nvarchar(100) NOT NULL,
    LastModified datetime NOT NULL,
    Comment nvarchar(300) NULL,
    Content nvarchar(max) NOT NULL,
    Description nvarchar(200) NULL
</code>```

I would probably make the PK of the contents table a multi-column key from PageID and Revision provided Revision was an identity type.  You would use the Revision column as the FK.  You then pull the consolidated record by JOINing like this:

```<code>SELECT * FROM Page
JOIN PageContent ON CurrentRevision = Revision AND ID = PageID
</code>```

There might be some errors up there...this is off the top of my head.  It should give you an idea of an alternative pattern, though.

Josh

Body:
I answered a similar question on SO some time ago. Here's something that might work.

One method that is used by a few wiki platforms is to separate the identifying data and the content you're tracking revisions for.  It adds complexity, but you end up with a history of complete records.

So for example, if you had a table called Opportunities to track sales deals, you would actually create two separate tables:

Opportunities

Opportunities_Content (or something like that)

The Opportunities table would have information you'd use to uniquely identify the record and would house the primary key you'd reference for your foreign key relationships.  The Opportunities_Content table would hold all the fields your users can change and for which you'd like to keep an audit trail.  Each record in the Content table would include its own PK and the modified-by and modified-date data.  The Opportunities table would include a reference to the current version as well as information on when the main record was originally created and by whom.

Here's a simple example based on ScrewTurn's data schema:

CREATE TABLE dbo.Page(
    ID int PRIMARY KEY,
    Name nvarchar(200) NOT NULL,
    CreatedByName nvarchar(100) NOT NULL,
    CurrentRevision int NOT NULL,
    CreatedDateTime datetime NOT NULL

And the contents:

CREATE TABLE dbo.PageContent(
    PageID int NOT NULL,
    Revision int NOT NULL,
    Title nvarchar(200) NOT NULL,
    User nvarchar(100) NOT NULL,
    LastModified datetime NOT NULL,
    Comment nvarchar(300) NULL,
    Content nvarchar(max) NOT NULL,
    Description nvarchar(200) NULL

I would probably make the PK of the contents table a multi-column key from PageID and Revision provided Revision was an identity type.  You would use the Revision column as the FK.  You then pull the consolidated record by JOINing like this:

SELECT * FROM Page
JOIN PageContent ON CurrentRevision = Revision AND ID = PageID

There might be some errors up there...this is off the top of my head.  It should give you an idea of an alternative pattern, though.

Josh


问:
Emphasizing the importance of TDD to customers
The importance of TDD needs to be propagated but there's always a gap in the project timeline and time needed for developing a TDD project.  Customers usually do not understand the importance of code maintenance or TDD and want the project to be finished as soon as possible.

The result would be a Test After Development which would be very basic minimal tests to please the coverage tools and let the project analyzers have a great Graph.

Do projects developed using TDD take longer, or is that just an unfounded fear?

答: As a project leader and if possible in any way, I would not even talk about TDD with the customer. The customer cares that the project is finished at the deadline you agreed on before. They probably don't care whether you write your project using AWT or Swing, sometimes not even whether you use Java or .NET. Why should they care about TDD or no-TDD?</p>


问:
Multiple Dispatch vs. Function Overloading
I'm trying to understand the difference (if any) between the two.

According to the Wikipedia page for Multiple Dispatch it is synonymous with Function Overloading, but then later on goes on to say:

In a language with only single dispatch, such as Java […]

which seems like a contradiction, since Java does support function overloading.

So which is it? Is Multiple Dispatch different from Function Overloading, or is the article wrong in claiming that Java does not support Multible Dispatch?

答:
Multiple dispatch is not (always) the same as function overloading, although they do bear some similarities. And Java does not support multiple dispatch.

In statically typed languages, including Java, the biggest difference between dispatch and overloading is that overloading  is based on the static type of parameters (i.e. the choice of which method is actually called is decided compile-time), while dispatch is based on the dynamic types (i.e. the decision is made runtime). (Such languages usually don't support multiple dispatch.)

But then again, this may be a question of terminology. In dynamically typed languages, dispatch and overloading indeed seem to boil down to the same thing.


问:
How do you solve large dependencies among files?
So basically I make several programs. Of course one program often used code from another. So I have my own personal "library"

Well, I do write jerk codes. Then When I open a project, the project will require another file. I add that file and that file require another file, then I add that file and that file requires another file. Then, I ended up with so many files the program doesn't need. I ended up having to correct really really old codes that are no longer used on files I do not need. Why? Because I don't bother structure dependency. Well, subject for another question.

What do you do to avoid this problem.

答:
You modularize and make libraries.  Each library may contain much more than you will need in a project, but it is a single atomic unit that is easy to handle.

For starters, keep the library version number in the file name.

Remember to use a SCM like git.  It will be very helpful in the long run.


答:
I think the question you should be asking is: Why are you overrun by requirements changes? Common causes include:

The developers don't have (enough) contact with end users so they can't understand the users' needs. Instead they treat requirements like an abstract Rubik's cube - they follow the letters of the requirements without even trying to understand their spirit

Somebody (e.g. from marketing) is adding requirements that don't make any sense for the end user (but e.g. sound good on a brochure). So there's a battle between "real" requirements and "other" requirements that's fought on the backs of developers

The scope of the project is undefined ("Well, if you're implementing a word processor anyway, couldn't you just add a small module that does our payroll accounting? Oh, and Bill from the other development team asked how hard it would be to make the word processor compile C++ code, too?")

Whatever the root problem is, you need to fix that. Drowning it under layers of "Agile" (or any other methodology) won't work.

Title: Agile,Waterfall and requirement changes

Body: Has anyone had this issue of a project defined as 'Agile' being overrun by requirement changes ? I work on a development project which is run in 4 weeks Sprint but there are always changes in between these Sprints . Is it still defined as Agile then ? I feel it's sort of a sub Agile process - The requirements of an Agile process should be defined at the beginning of a sprint and reviewed towards its end. Am I right in this? Please let me know your experiences in this .</p>


答:
I agree with Raku that you better not talk about TDD with your customer.  Maybe tell them about TDD after you completed the project and they ask you how you did it so well :-)

I don't think that TDD projects always take more time.  They certainly will take more time if the team has not learned to do TDD well.  I would suggest that first, you take the time to learn TDD on your own, until you can do it well and without effort; then you share the technique with your team only when you can do it well yourself.

Title: Emphasizing the importance of TDD to customers

Body:
The importance of TDD needs to be propagated but there's always a gap in the project timeline and time needed for developing a TDD project.  Customers usually do not understand the importance of code maintenance or TDD and want the project to be finished as soon as possible.

The result would be a Test After Development which would be very basic minimal tests to please the coverage tools and let the project analyzers have a great Graph.

Do projects developed using TDD take longer, or is that just an unfounded fear?


答:
While Raku's answer is correct - these decisions/implement details don't concern your clients/customers, you don't seem to appreciate the business factors facing your customers.

It's likely they understand the importance of maintenance, but other factors take priority.

Another answer on another question highlighted the time to market factor for mobile games. It is better for business to have software that to sell today than tomorrow, especially if competition is developing something similar.

It is better for business to have usable software in the wild than something sitting in the lab being re-tested and re-tested.

Your customers will decide whether the investment is worth it and if their product is successful they can reinvest in maintainability, but based on those decisions you have to toe the line to get it done for the cost/budget quoted (if you use TDD, then time for your development is factored in estimates for these quotes). If you've got time to do TDD within that quote and your estimates, you should use TDD, but if you don't have time then you can't afford to do it.


答:
"Very basic minimal tests" sounds like you aren't concerned about product quality. This has nothing to do with TDD versus non-TDD, it has to do with the quality standards of your team.

TDD isn't a magic bullet, but I think it's safe to say that if you think you can cut the amount of testing you do so that you can deliver earlier, the only thing that does for your customer is to potentially give them a lower quality product. Only you can say whether that is an acceptable risk. Delivering a clone of tetris for an android tablet? It's acceptable. Writing software for medical equipment, not so much.

So, before you discuss TDD or non-TDD you need to decide whether quality is something you care about or not. Once you decide to commit to delivering a quality product rather than one that has "minimal tests", then you can start to discuss whether TDD is the appropriate way to do your testing. TDD isn't about how much testing you do, it's about when you do it. From the sound of your question you're more concerned about how much testing to do.


问:
Which languages use "paired" header/implementation files?
C is ubiquitous, and C++ nearly as much, but I'm curious which other languages follow a similar model of header files.  Specifically, in which other languages is it idiomatic to edit pairs or groups of "header" and "implementation" files?  (A group as in multiple headers with one corresponding implementation file or a single header with multiple implementation files, as also seen in C.)  For example, the pair "blah.h" and "blah.c".

C's header files are tied into the C preprocessor, but that's not the detail I'm focusing on here.  For example, PHP has various include mechanisms, but you don't have a pair/group of "blah-header.php" plus "blah-notheader.php".

Some languages generate a file from source in a one-to-one mapping, such as Java, but that's not what I'm talking about either.  I'm interested in cases where the programmer directly edits both/all files in the pair/group.

Perhaps to put it another way: which languages have a declaration file ("header") and definition file ("implementation") such that a person would generally edit both files in tandem?

答:
F#: It optionally allows a .fsi file to declare the symbols like C headers.
See http://en.wikibooks.org/wiki/F_Sharp_Programming/Modules_and_Namespaces#Module_Signatures

OwnerDisplayName: Roger Pate

LastEditorDisplayName: Roger Pate


问:
Is code commonly generated from UML?
So when I was at university I was educated on the benefits of UML and its future in code development.

But from my industry experience, I've found that while we do use diagrams—ranging from ER diagrams, class diagrams, state diagrams, to work flow diagrams—all of it is for communication purposes.

That is, I've never generated code automatically from diagrams, and from a communication standpoint, I generally try to keep my diagrams as simple and easy to understand as possible.

But when I look at Visio and Enterprise Architect, it seems they have many different types of graphs, shapes, properties objects, most of which I don't use.

Do people use UML to do more sophisicated things such as code or database generation?

答:
We use Software Architect to do high-level designs and to document some of the more arcane component interactions in our stuff.  We sometimes generate the skeleton of the app from the diagrams, but once that's done we maintain both separately, we don't try to reverse-engineer the code back into a diagram after it's complete.  I used to use a tool called Rational XDE that worked pretty well for small programs, but it would get lost when you started adding in Swing event handlers or tried working with Struts.

I think a big part of the reason why people don't write in UML is that it takes a lot more work to completely specify everything in UML and then generate the code from your diagram.  I know the US DoD is working with the OMG to develop some tools that will generate "proven" code from diagrams that have been verified correct, but my impression is that you will wind up with an order of magnitude more metadata than actual code.  Which is probably good (it's documentation, after all), but generating metadata is no quicker than writing code, so you wind up spending proportionally more time.

Title: Is code commonly generated from UML?


答:
In Scrum at least, which seems to be the Agile process that's most popular with management types these days, the scope of a Sprint is fixed. If your Sprint Backlog is changing during the sprint, that's not Scrum, it's chaos. The Sprint Backlog should be created at the start of the sprint and remain fixed until the end of the sprint (at which point you create a new Sprint Backlog for the next sprint).

If your Product Backlog is changing during a sprint, it's no big deal. The changes just become new work that's prioritized, estimated, and selected like any other requirement for the next sprint. If the requirements change so much that the Product Owner has to cancel the sprint on a regular basis, though, you've got Trouble with a capital 'T'.

Maybe you need shorter sprints?

Title: Agile,Waterfall and requirement changes


答: UML itself is a notation system, so that it is of cause for communication and documenting. It is rare case to generate code from UML model, but yes there are guys doing it. Rhapsody users do it more often than Rose. The difficult part is to keep the model and code synchronized, for most of real projects, the cost is just too high.</p>

Title: Is code commonly generated from UML?


问:
Why aren't there automated translators from one programming language to another?
Most programming languages are Turing complete, which means that any task that can be solved in one language can be solved in another one, or even on Turing machine. Then why aren't there automatic translators that can convert programs from any given language to any other language? I've seen couple attempts for two languages, but they always work only on a limited subset of a language and can hardly be used for converting real projects.

Is it possible, at least in theory, to write 100% correct translator between all languages? What are the challenges in practice? Are there any existing translators that work?

答:
The biggest problem is not the actual translation of program code, but the porting of the platform API.

Consider a PHP to Java translator. The only feasible way to do that without embedding part of the PHP binary is to reimplement all of PHP's modules and API's in Java. This involves implementing over 10.000 functions. Compared to that the job of actually translating the syntax is easy as pie. And even after all that work you wouldn't have Java code, you'd have some sort of monstrosity that happens to run on the Java platform, but that was structured like PHP on the inside.

This is why the only such tools that come to mind are all about translating code to deploy it, not to maintain it afterwards. Google's GWT "compiles" Java to JavaScript. Facebook's hiphop compiles PHP into C.


答:
I think customers like to know that you follow solid practices. Sometimes they understand TDD. You may be working on a side project outsourced by an IT manager and prefer consultants who have the same standards.

I don't think you can use this as a reason to bill for more hours compared to your commpetition. The client wants results. The risks of not following sound practices are absorbed by you and not the client. Otherwise, they'll go where someone else can convince them they'll deliver. Imagine a carpenter wanting to charge you double because they "measure twice and cut once."


答:
The result would be a Test After Development which would be very basic
  minimal tests to please the coverage tools and let the project
  analyzers have a great Graph .

That's not the point of testing. Testing in itself adds no value. If done properly, various types of testing can improve correctness, flexibility and usability of a software. You are selling a product, not the process.

Unless a project is so extremely small, that it can be properly implemented without iterations, you can make good use of the flexibility that robust code adds (TDD being one of the more popular and easy ways to achieve robustness). There is a little overhead in the first iteration of a functionality, but you can respond to changes quickly and the overhead is amortized long before the last iteration. So on a grander scale of things, you're probably going to be faster.


问:
Will I ever be able to code client-side browser code in a language of my choice?
I'll be brutally honest: I hate writing client side code in JavaScript. I'm not a fan of this language, to say the least.

It seems silly to me that browsers support a programming language, rather than an intermediate virtual machine (like CIL or JVM). The latter would allow programmers to write in a language of their choice (to some extent), rather than in one fixed pre-set language. This language could evolve more rapidly, because only changes to the CIL/JVM/whatever would require every major browser to upgrade. Language features could be added without affecting old browser experience.

The massive savings of effort that intermediate langauges bring about are well known. Are there any initiatives out there to promote browser "scripting" in something other than JavaScript, and especially in an already designed, developed and optimized virtual machine? Do they have any momentum?

答:
To answer your question, yes there are efforts being made to deprecate Javascript in favour of a more cohesive language for web scripting. Google have been putting a lot of thrust behind their Dart language. Dart has it's own VM which is already embedded into Chrome, but I'm not sure if the other browsers have adopted it yet. There is also a fairly promising language called CoffeeScript.

There's also a very ambitious looking project called HaXe which aims to unify a whole host of development platforms with a single language..

Believe me you're not alone in disliking Javascript, but I'm afraid it's not going anywhere soon - in fact it seems to be gaining a lot of momentum what with Windows 8 HTML5/JS apps etc.. but alternatives like the ones I mentioned are starting to spring up :)


答:
In fact you're not hating javascript, as described in Ecma standards, but you're hating the awful implementation across various browsers, with they quirks, bugs and wtfs. Server-side Javascript is quite enjoyable actually. Also the DOM Model is the cause of 80% of the pain of client-side javascript.

If you still want to use another language, you can use GWT, which basically let you write Java, then compile it into (ugly) javascript, or CoffeeScript, which is a syntactic sugar over JS, that compiles into JS.

Title: Will I ever be able to code client-side browser code in a language of my choice?

Body:
I'll be brutally honest: I hate writing client side code in JavaScript. I'm not a fan of this language, to say the least.

It seems silly to me that browsers support a programming language, rather than an intermediate virtual machine (like CIL or JVM). The latter would allow programmers to write in a language of their choice (to some extent), rather than in one fixed pre-set language. This language could evolve more rapidly, because only changes to the CIL/JVM/whatever would require every major browser to upgrade. Language features could be added without affecting old browser experience.

The massive savings of effort that intermediate langauges bring about are well known. Are there any initiatives out there to promote browser "scripting" in something other than JavaScript, and especially in an already designed, developed and optimized virtual machine? Do they have any momentum?


问:
Do I need an IDE to develop Android apps?
After reading some articles on Google, I decided to start working on Android apps since it's an open source platform from Google.

So I wanted to create some apps.I have Android 2.2 Os So I just googled it to find the things and I finally found this link to create Android apps.

Is this the link that enables me to create apps or does we need any other IDE? Like we have gcc for c and VC++ for C++. What other things to do I need to set up to get going on this?

答:
Google's Android Development tutorials teach you how to set up Eclipse for Android development. Most of the Android developers that I know use this configuration. If you are more comfortable with NetBeans, you might want to look at the NBAndroid plugin, which is designed to support Android app development in the NetBeans IDE. I don't know anyone who uses NBAndroid, and I've never tried, so I can't comment on how well it works.

It is possible to develop Android applications using only command-line tools, but I'm not aware of anyone who actually develops using this type of environment.


问:
How do quick & dirty programmers know they got it right?
If you ask programmers why they should write clean code, the number one answer you get is maintainability.  While that's on my list, my main reason is more immediate and less altruistic:  I can't tell if my new code is correct if it's too dirty.  I find that I have focused on individual functions and lines of code so much that when I finish my first draft and step back to look at the big picture again it sometimes doesn't fit together very neatly.  Spending an hour or two refactoring for cleanliness frequently uncovers copy/paste errors or boundary conditions that were very difficult to detect in the rough draft.

However, some people feel it's occasionally okay to intentionally check in dirty code in the interest of shipping software, with a plan to "clean it up later."  Is there is some practicable technique that gives them confidence in the correctness of their code when the readability is less than ideal?  Is it a skill worth trying to develop?  Or is a lack of confidence in the code something some people just find easier to accept?

答:
Good programmers (Quick & Dirty and otherwise) do not have the hubris to assume they have got it right.  They assume that all large systems have bugs and flaws, but that at some point might be well enough tested and reviewed to have a sufficiently low risk or low enough cost of failure that the code can ship.

So why do these, so called Quick & Dirty, programmers, exist?  My hypothesis is Darwinian selection.  Programmers who ship workable code fast, occasionally ship before the competition ships, or the budget runs out, or the company goes bankrupt.  Therefore their companies are still in business employing new programmers to complain about the mess that has to be cleaned up.  So called clean code ships as well, but not differentially well enough to drive Quick & Dirty coders into extinction.


答:
You should also try IntelliJ Idea. Now community version has Android support and after dealing with Eclipse and NetBeans for years I find this IDE to be the one for me.
Truth is, you don't need any IDE. But if you want to focus on development rather than on typing then you should definitely consider using one.</p>

Title: Do I need an IDE to develop Android apps?

Body:
After reading some articles on Google, I decided to start working on Android apps since it's an open source platform from Google.

So I wanted to create some apps.I have Android 2.2 Os So I just googled it to find the things and I finally found this link to create Android apps.

Is this the link that enables me to create apps or does we need any other IDE? Like we have gcc for c and VC++ for C++. What other things to do I need to set up to get going on this?


答: You could develop without a IDE for android has the Android SDK supports command line arguments.  And you could use a your code editor of choice to write your code in.  In my experience though the preferred way is to use the Eclipse ADT plugin.</p>


答:
How do they know they got it right?  Testing is the simple answer.

If their code has been tested thoroughly by a good QA team and it passes, then I would say they got it right.

Writing quick and dirty code is not something that should be done as a habit but at the same time there are occasions when you can spend 20 mins writing code that may be classed as dirty or 4 hours refactoring a lot of code to do it right. In the business world sometimes 20mins is all that is available to do the job and when you face deadlines quick and dirty may be the only option.

I have myself been on both ends of this, I have had to fix the dirty code and have had to write my own in order to work around the limitations of a system I was developing in. I would say I had confidence in the code I wrote because although it was dirty and a bit of a hack sometimes I did make sure it was thoroughly tested and had a lot of built in error handling so if something did go wrong it wouldnt destroy the rest of the system.

When we look down on these quick and dirty programmers we do need to remember one thing, a customer generally doesnt pay till they have the product, if it ships and they go into UAT testing and find the bugs from quick and dirty code it is a lot less likely they will pull out when they have an almost working product infront of them, yet if they have nothing and you are telling them "you will have it soon we are just fixing x" or "it was delayed because we had to get y working just perfectly" they are more likely to give up and go with a competitor.

Of course as this image demonstrates no one should underestimate the danger of quick and dirty code!

Title: How do quick & dirty programmers know they got it right?

Body:
If you ask programmers why they should write clean code, the number one answer you get is maintainability.  While that's on my list, my main reason is more immediate and less altruistic:  I can't tell if my new code is correct if it's too dirty.  I find that I have focused on individual functions and lines of code so much that when I finish my first draft and step back to look at the big picture again it sometimes doesn't fit together very neatly.  Spending an hour or two refactoring for cleanliness frequently uncovers copy/paste errors or boundary conditions that were very difficult to detect in the rough draft.

However, some people feel it's occasionally okay to intentionally check in dirty code in the interest of shipping software, with a plan to "clean it up later."  Is there is some practicable technique that gives them confidence in the correctness of their code when the readability is less than ideal?  Is it a skill worth trying to develop?  Or is a lack of confidence in the code something some people just find easier to accept?


答:
Essentially, no.  You're pretty much stuck with Javascript.

Having said that, there have been efforts in the past to bring other languages on board (java applets, vbscript, etc.)  Each of these never really gained the traction that javascript has because javascript is integrated.

The only way to build what you are referring to would be to create a scripting language that runs on a virtual machine, compiled client side, and then executed.  Then each browser would have to implement the virtual machine into its own codebase so that all the code ran on all the browsers.  Then you'd have to make sure to have some sort of standards so that all the browsers executed the commands the same way.  Of course, browsers being independently created, there would probably be quirks that the developers would have to keep in mind.

But now we've just described Javascript.

So in the end, your choices are:

get used to Javascript

try to use some language that compiles down to Javascript.  (Keep in mind that you will still want to verify the Javascript, which puts back to option 1.)

use a language that exists as a plug-in to the browser, such as actionscript (Flash), ActiveX, java applet, .Net (SilverLight).  This avoids the problem with multiple vendors/implementations of the language, but doesn't integrate the language.

Essentially, if you want an integrated language, you're stuck with Javascript.


问:
Is there another meaning to prototype?
I am reading Pro C#.  It says

do be aware that the value 0 is automatically returned, even if you construct a Main() method prototyped to return void.

What does prototyped mean in this context?

The only C# related definition of a prototype I'm aware of has to do with a model or test program tossed together without the intention to go to production.

答:
In this context, I believe the phrase is used a as synonym to a method signature.

You can call any method signature the prototype of the actual call.

A bit of a throwback to c and header files.

See wikipedia - Function prototype:

A function prototype in C, Perl or C++ is a declaration of a function that omits the function body but does specify the function's return type, name, arity and argument types. While a function definition specifies what a function does, a function prototype can be thought of as specifying its interface.

Title: Is there another meaning to prototype?


问:
How do you include Support in your Sprint?
Our company moved to Scrum recently on a product that was almost coded by a single person (Joe). We have support to do with our exising customers that we try to integrate in our process.

For now we tried the following approach:

We do a rotation on a person in charge each week.

The person in charge for the week may spend up to 8 hours on support.

But we failed to have it work:

Joe always does the support because he knows the code better, and it's always faster for him to do it than to explain it.

We (the rest of us) tend to focus on what's on the Sprint board aka new stories instead of support tasks.

Joe has too much work, he can't handle all the support by himself because he has to do things outside of the Sprint as well.

Have you already faced similar situation? How did you manage to get out of it?

Note: We can't dedicate a single person on the support right now. We hope to in the future.

答:
In my mind, there are two different kinds of "support" work. The first kind is an emergency that has to get fixed NOW. It's really more operations-type work, fire-fighting stuff that can't really be planned for and estimated as part of a sprint. The second kind is a bug report, which gets estimated, prioritized, and planned into a sprint. It's treated like any other story. Often, the first kind will result in the second kind; you'll put out the fire, and create a bug report to do a real fix so it doesn't happen again. For the rest of this post, I'm talking about the former: un-planned, emergency work that has to be done NOW.

Taking time away from the Team to do support work reduces the Team's velocity. You should be using your historical velocity to determine your capacity for the next sprint. The context-switching required to go from release work to support work means that there is some overhead, but since the work you bite off for a sprint should take into account how much work you historically get done in a sprint, the typical amount of time you put into support, and the context-switching overhead, should automatically be accounted for.

I don't consider this to be sprint work. It's separate, and should  be prioritized above sprint work. Thus, it eats into the velocity of the team, and is "planned for" by using that reduced velocity when deciding how much work can get done during the next sprint.


问:
How do you find errors related to undeclared variables in php?
If I copy a piece of code from somewhere that looks like so

```<code>$blah = array(1,2,3,4);
foreach ($blah as $i)
       echo ($i);
</code>```

and rename the variables but forget to do it correctly like so

```<code>$apple = array(1,2,3,4);
foreach ($blah as $i) <--- notice $blah instead of $apple
       echo ($i);
</code>```

Then my NetBeans IDE doesn't complain and I get an error at runtime when I run this.
Is there a way to catch errors like this without running the code? Which IDE does it? Which plugin? Or the whole PHP development world is living without this?

答:
PhpStorm from jetBrains does it.

PhpStorm is a lightweight and smart PHP IDE focused on developer
  productivity that deeply understands your code, provides smart code
  completion, quick navigation and on-the-fly error checking. It is
  always ready to help you shape your code, run unit-tests or provide
  visual debugging.


答:
I think the command-line tools for Android development are deprecated for the new (ICS) features, but you should be able to use them for 2.x development.  That said, I'd certainly recommend setting up Eclipse or another IDE if you can.  It'll be easier to follow the tutorials, and also easier to get help on the forums (since people will be less likely to try to reproduce your problems if you're working in a "different" environment).

In addition to the Android SDK you'll need a Java SDK.  I haven't tried using Java 7 with the Android SDK yet, but it should be fine.  If you're going to be using the emulator, you'll want a fast machine with plenty of memory -- the emulator emulates a complete Android device, right down to an ARM CPU, so it gets better the more power you can throw its way.


答:
No, you don't. You don't need one for developing programs in any other language or for any other platform either, but it will give you a productivity boost if you are using one.

Your favorite editor or your favorite IDE are tools for your programming craft. You can always work with bare hands (Notepad), but having a proper tool makes life easier.

Use your tools once you know what they're doing for you.


问:
How can I find own replacement when the company wants someone far less experienced?
I told the company I work for that I want to phase myself out, but that I would stick around for a couple months before applying anywhere to help in the recruitment of my replacement. I offered this because I am the sole web developer and I didn't want to leave them helpless.

The problem is, they want to hire someone very under qualified to avoid having to pay a high salary.

As far as I'm concerned, it's their company and they can run it how they want. However, when it comes to me helping find and train someone before I go, I'm in a position where I don't know what to do.

To give a little perspective, I built them a medium sized e-commerce system using an MVC framework; there's more to it, but I'll leave it at that. The candidates they are finding me to review are people who have never worked as a programmer, have made a couple really crappy static websites using a WYSIWYG program and are calling themselves web designers.

I know these people have no chance at success. I have tried to explain it to the company, but they don't want to hear it; they think one of these people can be trained and be up and running at my level in about a year. The reality is, I don't think their site will last a year if they go this route.

I think maybe they think I am just trying to make myself look good and the new candidates look bad for some reason, which is not the case at all. I would like to leave what I have worked hard on in capable hands.

So what is the ethical and professional thing to do here? Just keep telling them that these candidates are no good until they actually find a decent one, up until its time for me to leave, at which point I leave them with no one? Or just accept that they are going to destroy themselves and do the best I can to pick the best out of the candidates and teach him/her what I can before I go?

I really just want to do the right thing here, so I can leave on good terms. And if a year down the road they fail, I can have a clean conscience.

答: If you are interviewing just keep rejecting the people who are not qualified to do the work. If you have left who is going to train these people?  JUst document the reasons why you think the rejected candidates are unqualified and then leave with a clear concience. You tried your best to get them to understand what they were doing wrong, you owe them no loyalty later if they do not listen to your advice.</p>


答:
My opinion from reading this (only an opinion): different mindset.

By doing some "reverse engineering" on some similar situations
I can (only) assume that you work for a place which believes developers are interchangeable, which is unfortunately the common conception outside IT shops (and even some IT ones). Viewing the work under that prism, you are paid "more", not based on capability/skills but only on the knowledge of the system's internals (emphasis to "only"). In this mindset any other (preferably cheaper) developer would do, only if he is given enough time to learn on how the application works.

Based on your question, it is difficult to change such perception to someone who has not engaged with IT operations a lot. Your conscience should be clear, you cannot do anything

That's what I thought from reading your question and associating it with previous experience.

Title: How can I find own replacement when the company wants someone far less experienced?

Body:
I told the company I work for that I want to phase myself out, but that I would stick around for a couple months before applying anywhere to help in the recruitment of my replacement. I offered this because I am the sole web developer and I didn't want to leave them helpless.

The problem is, they want to hire someone very under qualified to avoid having to pay a high salary.

As far as I'm concerned, it's their company and they can run it how they want. However, when it comes to me helping find and train someone before I go, I'm in a position where I don't know what to do.

To give a little perspective, I built them a medium sized e-commerce system using an MVC framework; there's more to it, but I'll leave it at that. The candidates they are finding me to review are people who have never worked as a programmer, have made a couple really crappy static websites using a WYSIWYG program and are calling themselves web designers.

I know these people have no chance at success. I have tried to explain it to the company, but they don't want to hear it; they think one of these people can be trained and be up and running at my level in about a year. The reality is, I don't think their site will last a year if they go this route.

I think maybe they think I am just trying to make myself look good and the new candidates look bad for some reason, which is not the case at all. I would like to leave what I have worked hard on in capable hands.

So what is the ethical and professional thing to do here? Just keep telling them that these candidates are no good until they actually find a decent one, up until its time for me to leave, at which point I leave them with no one? Or just accept that they are going to destroy themselves and do the best I can to pick the best out of the candidates and teach him/her what I can before I go?

I really just want to do the right thing here, so I can leave on good terms. And if a year down the road they fail, I can have a clean conscience.


答:
Here's what you do:

Let them know that the candidates they are sending you are all unqualified

Give them your minimum qualifications

Reject anyone who does not meet those qualifications.

If they refuse to give you resumes of anyone who meets your qualifications, then you have done your part.

Regarding ethics, you don't have a responsibility to replace yourself--that's the hiring manager's job.  If you want to go beyond ethics into kindness, then offering to help out is great, but stick to your guns on what the job really requires.

Finally, set a deadline for leaving the company, don't languish in this job.  They could very well be sending you unqualified candidates so that you will stick around (although that is unlikely).  But once you set that deadline, let them know so that the expectations are understood.


答:
You've said it yourself - You have given them more than a fair amount of notice, offered to stay for a few months to get the new recruit up to speed so far as you can, and told them that their current potential candidates are not good enough.

That is above and beyond what is required of you. Just keep being honest with them up until you leave, whether you find a good candidate or not, and your terms of leaving should be fine.

(and as HLGEM says, you owe them no loyalty once you're gone)


问:
What performance can we expect from std::string's c_str()? Always constant time?
I've been doing some needed optimizations lately. One thing I've been doing is changing some ostringstreams -> sprintfs. I'm sprintf'ing a bunch of std::strings to a c style array, ala

```<code>char foo[500];
sprintf(foo, "%s+%s", str1.c_str(), str2.c_str());
</code>```

It turns out that Microsoft's std::string::c_str() implementation runs in constant time (it just returns an internal pointer). It appears that libstdc++ does the same. I realize the std makes no guarantees for c_str, but its hard to imagine another way of doing this. If, for example, they copied into memory they'd either have to allocate memory for a buffer (leaving it up to the caller to destroy it -- NOT part of the STL contract) OR they'd have to copy to an internal static buffer (probably not threadsafe, and you have no guarantees on its lifetime). So simply returning a pointer to an internally maintained null terminated string seems to be the only realistic solution.

答:
In theory C++03 doesn't require that, hence the string can be an array of char where the presence of the null terminator is added just at the time c_str() is called. This may require a reallocation (it doesn't violate the const-ness, if the internal private pointer is declared as mutable).

C++11 is stricter: it requires time constantness, so no relocation can be done and the array must always be wide enough to store the null at the end.
c_str(), by itself, can still do "ptr[size()]='\0'" to ensure the null is really present. It doesn't violate the const-ness of the array since the range [0..size()) is not changed.