答:
I would refactor like this:</p>

```<code>        var p = null;
        var exInfo = null;

        try
        {
            p = SomeProperty;         //Line B
        }
        catch (Exception ex)
        {
            exInfo = new ExceptionMessage("The property was " + p == null ? "foo" : "bar");           //Line C
            exInfo.SomeOtherProperty = SomeOtherValue;  //Line D
        }

        exInfo.BlahBlahBlah = "Blah";
</code>```

Body:
I would refactor like this:

        var p = null;
        var exInfo = null;

        try
        {
            p = SomeProperty;         //Line B
        }
        catch (Exception ex)
        {
            exInfo = new ExceptionMessage("The property was " + p == null ? "foo" : "bar");           //Line C
            exInfo.SomeOtherProperty = SomeOtherValue;  //Line D
        }

        exInfo.BlahBlahBlah = "Blah";


问:
Building a website, want to use java
I'd like to make a simple-ish website that is essentially a small game.  Key strokes are to be processed and sent to a server (already acquired and should support SQL and JSP, I believe) which then translate to a location and written to the DB.

SQL queries are to be used to retrieve these locations and written to other clients connected to the website.  Their page is to be updated with these locations.

I have working knowledge of Java, jQuery/Ajax, SQL and JavaScript but I'm unfamiliar with JSP and how everything hooks up.  I'm aware of the MVC paradigm as well.  For my little game idea, would these technologies work?  Am I over thinking this and can make it much easier to implement?  What might be a good tutorial or example to study?

EDIT: I was just informed I will not be able to use WAR files on the server.  I'm not big on php and really don't like developing with it, can I still use Java?

答:
You can certainly do all this in Java/JSP, but personally it sounds like overkill.  I would recommend using the LAMP stack instead (Linux, Apache, MySQL, PHP).  You should be able to get this working much quicker using PHP.

If you are going to stick with Java/JSP, then I highly recommend making use of Spring MVC and JSTL tags to cut down on how much custom code you need to write just to wire everything together.

ContentLicense: CC BY-SA 3.0

Title: Building a website, want to use java


问:
How to prevent code from leaking outside work?

Possible Duplicate:

  How to manage a Closed Source High-Risk Project?

I'm working on an institution that has a really strong sense of "possession" - each line of software we write should be only ours. Ironically, I'm the only programmer (ATM), but we're planning in hiring others.

Since my bosses wouldn't count the new programmers as people they can trust, they have an issue with the copies of the source code. We use Git, so they would have a entire copy of each of the projects they work on, when they clone the repository.

We can restrict access to them to a single key with Gitolite and bind that to their PC's, but they can copy those keys to another computer and they would have the repository access in another PC. Also (and the most obvious method) they could just upload the files somewhere else, add another remote, or just copy the files to an USB drive.

Is there any (perhaps clever) way to prevent events like these?

EDIT: I would like to thank everyone for their insights in this question, since it has been not only more eye opening, but also a firm support of my arguments (since you basically think like me, and I've been trying to make them understand that) against my bosses in the near future.

I am in a difficult situation work-wise, with my coworkers and bosses (since I'm basically in the middle) being like two gangs, so all this input is greatly, greatly appreciated.

It is true that I was looking for a technical solution to a people problem - both the management and the employees are the problem, so it can't be solved that way (I was thinking about some code obfuscation, perhaps working with separate modules, etc., but that wouldn't work from my developer POV). The main problem is the culture inside and outside the company - development is not taken seriously in my country (Venezuela) so naivity and paranoia are in fact a real issue in here.

The real answer here is an NDA (something that here in Venezuela doesn't completely work), because that's the people solution, because no sane developer would work in those conditions. Things will get ugly, but I think I will be able to handle that because of your help. Thank you all a lot! <3

答:
I know someone who worked in an environment like this one.

A few measures that were taken there:

No access to the physical computer, all the computers were stored in a locked room with holes in the wall for display, keyboard and mouse.

No internet access.

Customized operating system that used an in-house-built file system with encryption (in case a computer were to get stolen somehow).

Projects were divided in static libraries, no one had access to the whole source code (this of course does not apply for all programming languages).

It was a very unpleasant workplace.


问:
How should I architect my Model and Data Access layer objects in my website?
I've been tasked with designing Data layer for a website at work, and I am very interested in architecture of code for the best flexibility, maintainability and readability.

I am generally acutely aware of the value in completely separating out my actual Models from the Data Access layer, so that the Models are completely naive when it comes to Data Access. And in this case it's particularly useful to do this as the Models may be built from the Database or may be built from a Soap web service.

So it seems to me to make sense to have Factories in my data access layer which create Model objects. So here's what I have so far (in my made-up pseudocode):

```<code>class DataAccess.ProductsFromXml extends DataAccess.ProductFactory {}
class DataAccess.ProductsFromDatabase extends DataAccess.ProductFactory {}
</code>```

These then get used in the controller in a fashion similar to the following:

```<code>var xmlProductCreator = DataAccess.ProductsFromXml(xmlDataProvider);
var databaseProductCreator = DataAccess.ProductsFromXml(xmlDataProvider);

// Returns array of Product model objects
var XmlProducts = databaseProductCreator.Products();
// Returns array of Product model objects
var DbProducts = xmlProductCreator.Products();
</code>```

So my question is, is this a good structure for my Data Access layer? Is it a good idea to use a Factory for building my Model objects from the data? Do you think I've misunderstood something? And are there any general patterns I should read up on for how to write my data access objects to create my Model objects?

答:
I am generally acutely aware of the value in completely separating out
  my actual Models from the Data Access layer, so that the Models are
  completely naive when it comes to Data Access.

This is referred to as persistence ignorance. Another concept you may wish to introduce in your data access layer is the repository. The central function of a repository is to encapsulate data access.

In an MVC architecture, the controller would reference the repository to get access to data. The specific details of data formatting should be hidden by the repository, that way your controller remains persistence ignorant as well. Repositories however are sometimes misapplied when too much abstraction is attempted. Don't try to make repositories overly generic and capable of handling any type of data access scenario because you will most likely fail and end up with lots of needless abstractions that complicate far more than they simplify.


答:
A technical solution could be to have all development sessions hosted on a server with no (or severely restricted and monitored) network access beyond that required to serve the RDP (or VNC) sessions.  That way, the source is never on a developer's machine.  It would also make it possible to work from home or a client site.

Ultimately, though, I think the whole situation is ripe for failure.  If you make it obvious to developers that you don't trust them, and make their jobs harder, then IMHO you're creating an environment where developers will find some way to make the source public, just to "stick it to the man".

Title: How to prevent code from leaking outside work?

Body:
Possible Duplicate:

  How to manage a Closed Source High-Risk Project?

I'm working on an institution that has a really strong sense of "possession" - each line of software we write should be only ours. Ironically, I'm the only programmer (ATM), but we're planning in hiring others.

Since my bosses wouldn't count the new programmers as people they can trust, they have an issue with the copies of the source code. We use Git, so they would have a entire copy of each of the projects they work on, when they clone the repository.

We can restrict access to them to a single key with Gitolite and bind that to their PC's, but they can copy those keys to another computer and they would have the repository access in another PC. Also (and the most obvious method) they could just upload the files somewhere else, add another remote, or just copy the files to an USB drive.

Is there any (perhaps clever) way to prevent events like these?

EDIT: I would like to thank everyone for their insights in this question, since it has been not only more eye opening, but also a firm support of my arguments (since you basically think like me, and I've been trying to make them understand that) against my bosses in the near future.

I am in a difficult situation work-wise, with my coworkers and bosses (since I'm basically in the middle) being like two gangs, so all this input is greatly, greatly appreciated.

It is true that I was looking for a technical solution to a people problem - both the management and the employees are the problem, so it can't be solved that way (I was thinking about some code obfuscation, perhaps working with separate modules, etc., but that wouldn't work from my developer POV). The main problem is the culture inside and outside the company - development is not taken seriously in my country (Venezuela) so naivity and paranoia are in fact a real issue in here.

The real answer here is an NDA (something that here in Venezuela doesn't completely work), because that's the people solution, because no sane developer would work in those conditions. Things will get ugly, but I think I will be able to handle that because of your help. Thank you all a lot! <3


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答: Bored team members.</p>

ContentLicense: CC BY-SA 2.5

Body: Bored team members.


答: For what you are describing, you might consider looking into node.js on the server rather than java.  Node is very good for apps that need to 'link up' multiple connected clients so that you can relay info between them.  Especially if you'll be tossing around JSON.  I'm sure you could do it in java... its certainly your call.  I just personally think node might be a better fit and overall less hassle.

Title: Building a website, want to use java

Body:
I'd like to make a simple-ish website that is essentially a small game.  Key strokes are to be processed and sent to a server (already acquired and should support SQL and JSP, I believe) which then translate to a location and written to the DB.

SQL queries are to be used to retrieve these locations and written to other clients connected to the website.  Their page is to be updated with these locations.

I have working knowledge of Java, jQuery/Ajax, SQL and JavaScript but I'm unfamiliar with JSP and how everything hooks up.  I'm aware of the MVC paradigm as well.  For my little game idea, would these technologies work?  Am I over thinking this and can make it much easier to implement?  What might be a good tutorial or example to study?

EDIT: I was just informed I will not be able to use WAR files on the server.  I'm not big on php and really don't like developing with it, can I still use Java?


问:
Designing a Database Application with OOP
I often develop SQL database applications using Linq, and my methodology is to build model classes to represent each table, and each table that needs inserting or updating gets a Save() method (which either does an InsertOnSubmit() or SubmitChanges(), depending on the state of the object).  Often, when I need to represent a collection of records, I'll create a class that inherits from a List-like object of the atomic class.

ex.

```<code>public class CustomerCollection : CoreCollection<Customer>
{

}
</code>```

Recently, I was working on an application where end-users were experiencing slowness, where each of the objects needed to be saved to the database if they met a certain criteria.  My Save() method was slow, presumably because I was making all kinds of round-trips to the server, and calling DataContext.SubmitChanges() after each atomic save.

So, the code might have looked something like this

```<code>foreach(Customer c in customerCollection)
{
   if(c.ShouldSave())
   {
       c.Save();
   }
}
</code>```

I worked through multiple strategies to optimize, but ultimately settled on passing a big string of data to a SQL stored procedure, where the string has all the data that represents the records I was working with - it might look something like this:

```<code>CustomerID:34567;CurrentAddress:23 3rd St;CustomerID:23456;CurrentAddress:123 4th St
</code>```

So, SQL server parses the string, performs the logic to determine appropriateness of save, and then Inserts, Updates, or Ignores.

With C#/Linq doing this work, it saved 5-10 records / s.  When SQL does it, I get >100 records / s, so there is no denying the Stored Proc is more efficient; however, I hate the solution because it doesn't seem nearly as clean or safe.

My real concern is that I don't have any better solutions that hold a candle to the performance of the stored proc solution.  Am I doing something obviously wrong in how I'm thinking about designing database applications?  Are there better ways of designing database applications?

答: When you're processing a list of records, instead simply calling c.Save() you should pass them to some kind of aggregator that can analyze the records and write the appropriate SQL statements (or your classes can simply support an emitDML() method that returns the SQL to execute).  Then, when you're done with the list, just tell the aggregator to persist any changes, and it can execute the SQL in a single transaction.  If you're dealing with hundreds of records it might make sense to serialize them out to disk and invoke the bulk copy program to insert them, but that's a fair amount of work.


答:
Be careful not to overestimate the value of your source code to those outside your company.

Sure - you paid a lot of engineers (Developers, QA, etc) lots of money to develop it, but that doesn't mean it's intrinsically valuable to a third party.

What exact attacks exist?

Source code is often leaked from (e.g.) games development or IT security companies. Of course, such leaks make them look bad, but otherwise, cause no real harm.

Ask yourself:

Are you so embarrassed about the quality of your source code, it would be damaging to your reputation to leak it?

Does the source code itself contain confidential secrets (e.g. hard-coded encryption keys, details of financial relationships with other companies)? Should it?

Could a competitor genuinely benefit from using your source code, despite the risk of being discovered?

As far as I know, there was a case where a member of staff at one IT security company tried to sell the source code to a competitor. The competitor immediately reported this to his employer, and he was soon dismissed. No money changed hands, but the staff member can't work easily in the IT security industry any more.


问:
Incorporating GPL Code in my Open Source Project
I have downloaded a currently inactive GPL project with a view to updating it and releasing the completed codebase as open source. I'm not really a fan of GPL though and would rather licence my project under BSD.

What are my options? Is it just a case of keeping any existing non-touched code under the GPL and any updated stuff can be BSD (messy)? The source will essentially be the same codebase i.e. there is no logical separation between the two and they certainly can't be split into anything resembling different libraries.

Are my only realistic options to either GPL the whole thing or seek the original author's permission to release everthing under BSD?

答: From your description, the answer is yes you would need to release the updated project under the GPL.</p>


答:
Effectively, yes. If you create a derived work from the original project, you're bound by the existing license. You can't relicense it without releases from any (or every) copyright holder.

You might ask the original author(s) if they would consider dual-licensing, e.g. like the Perl Artistic License, but putting a BSD-style license (which would allow other people to take their work, make changes to it, and remove it from the public good) on a program that's currently under GPL would probably be a surprising turn of events.

In the GPL v3, the relevant clause begins,

You may convey a work based on the Program, or the modifications to
  produce it from the Program, in the form of source code under the
  terms of section 4, provided that you also meet all of these
  conditions: c) You must license the entire work, as a whole, under
  this License to anyone who comes into possession of a copy.

It does (somewhat) depend upon the license under which you received the program; the net effect is similar under GPL v2, but if the author stated “or any later version,” you are permitted to “upgrade” to GPL v3.

Title: Incorporating GPL Code in my Open Source Project

Body:
I have downloaded a currently inactive GPL project with a view to updating it and releasing the completed codebase as open source. I'm not really a fan of GPL though and would rather licence my project under BSD.

What are my options? Is it just a case of keeping any existing non-touched code under the GPL and any updated stuff can be BSD (messy)? The source will essentially be the same codebase i.e. there is no logical separation between the two and they certainly can't be split into anything resembling different libraries.

Are my only realistic options to either GPL the whole thing or seek the original author's permission to release everthing under BSD?


问:
Should I try to write simple key-value storage by myself?
I need a key-value storage in a simplest form we can think of.

Keys should be some fixed-length strings, values should be some texts.

This key-value storage should have an HTTP-backed API.

That's basically it. As you can see, there is no big difference between such storage and some web application with some upload functionality.

The thing is - it'll take few hours (including tests and coffee drinking) to write something like this.
"Something like this" will be fully under my control and can be tuned on demand.

Should I, in this specific case, not try to reinvent bicycles? Is it better to use some of existing NoSQL solutions. If yes, which one exactly?

If, say, I'd needed something SQL-like, I won't ask and won't try to write something by myself. But with NoSQL I just don't know what is adequate and what is not.

答:
The problem seems basic enough to be done yourself without too much pain. Of course, you need testing, but it remains reasonable compared to, say, authentication.

When the wheel is easy, don't reinvent the wheel:

If you already know a solution which fits exactly your needs. By "know", I mean that you have already tried the product, know that it is easy to install, know the possible caveats, etc.

Or if you expect adding more features in the future, using a enterprise-scale product which provides more features than you need right now can be a better solution. Redis, by the way, comes into mind as an excellent key-value store solution.

If you don't know any existent solution and you're sure that you won't need to add features later, it would be probably faster to make your own key-value store rather than finding an existent one which will work in your context, on your platform, etc.


答:
You can't prevent code from leaking. You can limit the leak to less important code.

Normally there is only one part of the application that makes it unique. That would be some algorithm. You can interface this very well, and put this in a separate source control branch. You and only those people who need to work on it should have access to it. You provide only a binary (obfuscated) and the interface to the other developers.

Divide your code into more modules and let people only work on a particular module. The other modules are provided in binary (obfuscated). This, however, can be stretched too far that it will be unmanageable, and can lead to duplication of code.


答:
Keep in mind, once you accumulate enough data, your simple home-grown approach will be very slow when it comes to retrieval unless you then implement some sort of indexing system.  So if thats a potential issue, I'd stick with using a dbms.

In addition to using a NoSQL server, you can also use an SQL database to store key pairs.  There's nothing inherent in that type of data that prevents that. So if you already have MySQL running, that might be the simpler option.

Title: Should I try to write simple key-value storage by myself?

Body:
I need a key-value storage in a simplest form we can think of.

Keys should be some fixed-length strings, values should be some texts.

This key-value storage should have an HTTP-backed API.

That's basically it. As you can see, there is no big difference between such storage and some web application with some upload functionality.

The thing is - it'll take few hours (including tests and coffee drinking) to write something like this.
"Something like this" will be fully under my control and can be tuned on demand.

Should I, in this specific case, not try to reinvent bicycles? Is it better to use some of existing NoSQL solutions. If yes, which one exactly?

If, say, I'd needed something SQL-like, I won't ask and won't try to write something by myself. But with NoSQL I just don't know what is adequate and what is not.


问:
Check parameters annotated with @Nonnull for null?
We've begun using FindBugs and annotating our parameters with @Nonnull appropriately, and it works great to point out bugs early in the cycle. So far we have continued checking these arguments for null using Guava's checkNotNull, but I would prefer to check for null only at the edges--places where the value can come in without having been checked for null, e.g., a SOAP request.

```<code>// service layer accessible from outside
public Person createPerson(@CheckForNull String name) {
    return new Person(Preconditions.checkNotNull(name));
}

...

// internal constructor accessed only by the service layer
public Person(@Nonnull String name) {
    this.name = Preconditions.checkNotNull(name);  // remove this check?
}
</code>```

I understand that @Nonnull does not block null values itself.

However, given that FindBugs will point out anywhere a value is transferred from an unmarked field to one marked @Nonnull, can't we depend on it to catch these cases (which it does) without having to check these values for null everywhere they get passed around in the system? Am I naive to want to trust the tool and avoid these verbose checks?

Bottom line: While it seems safe to remove the second null check below, is it bad practice?

This question is perhaps too similar to Should one check for null if he does not expect null, but I'm asking specifically in relation to the @Nonnull annotation.

答:
If you dont trust FindBug, it may be an option to use an assertion. This way you avoid the problems mentioned by User MSalters but still have a check. Of course, this approach may not be applicable if such a fail-fast approach is not feasible, i.e. you have to catch any exception.

And to further answer the question whether it is bad practice. Well, this is arguable but I would not think so. I consider this FindBug annotation as a light specification following the design by contract principle.

In design by contract you establish a contract between a method and its caller. The contract consists of preconditions that the caller agrees to fulfill when calling the method and a postcondition that in turn is fulfilled by the method after execution if its precondition is fulfilled.

One of the benefits of this development method is that you can avoid a so called defensive programming style (in which you check for all invalid parameter values explicitly etc.). Instead you can rely on the contract, and avoid redundant checks to increase performance and readibility.

Contracts can be used for runtime-assertion checking which follows the above mentioned fail-first principle in which you want your program to fail if a contract is broken, giving you a clue to identify the source of error. (A failed precondition means that the caller did something wrong, a failed postcondition indicates an implementation error of the given method)

Furthermore, contracts can be used for static analysis, which tries to draw conclusions about the source code without actually running it.

The @nonnull annotation can be seen as a precondition that is used for static analysis by the tool FindBugs. If you prefer an approach such as runtime-assertion checking, i.e. the fail first strategy, you should consider using assertion statements as built-in Java. Or maybe to adapt to a more sophisticated specification strategy using a behavioral interface specification language such as the Java Modeling Language (JML).

JML is an extension of Java in which specification is embedded in special Java Comments. An advantage of this approach is that you can use sophisticated specification, even using a development approach in which you only rely on specification rather than implementation details and use different tools that make use of the specification, such as the mentioned runtime-assertion checking tools, automated generation of unit-tests or documentation.

If you share my point of view of @nonnull being a (light) contract, it would be common practice to not add additional checks because the original idea behind this principle is to avoid defensive programming.


问:
unit/integration testing web service proxy client
I'm rewriting a PHP client/proxy library that provides an interface to a SOAP-based .Net webservice, and in the process I want to add some unit and integration tests so future modifications are less risky.

The work the library I'm working on performs is to marshall the calls to the web service and do a little reorganizing of the responses to present a slightly more -object-oriented interface to the underlying service.

Since this library is little else than a thin layer on top of web service calls, my basic assumption is that I'll really be writing integration tests more than unit tests - for example, I don't see any reason to mock away the web service - the work that's performed by the code I'm working on is very light; it's almost passing the response from the service right back to its consumer.

Most of the calls are basic CRUD operations: CreateRole(), CreateUser(), DeleteUser(), FindUser(), &ct.

I'll be starting from a known database state - the system I'm using for these tests is isolated for testing purposes, so the results will be more or less predictable.

My question is this: is it natural to use web service calls to confirm the results of operations within the tests and to reset the state of the application within the scope of each test?  Here's an example:

One test might be createUserReturnsValidUserId() and might go like this:

```<code>public function createUserReturnsValidUserId() {
   // we're assuming a global connection to the service
   $newUserId = $client->CreateUser("user1");
   assertNotNull($newUserId);
   assertNotNull($client->FindUser($newUserId);
   $client->deleteUser($newUserId);
}
</code>```

So I'm creating a user, making sure I get an ID back and that it represents a user in the system, and then cleaning up after myself (so that later tests don't rely on the success or failure of this test w/r/t the number of users in the system, for example). However this still seems pretty fragile - lots of dependencies and opportunities for tests to fail and effect the results of later tests, which I definitely want to avoid.

Am I missing some options of ways to decouple these tests from the system under test, or is this really the best I can do?

I think this is a fairly general unit/integration testing question, but if it matters I'm using PHPUnit for the testing framework.

答:
Unfortunately I am not familiar with PHP or PHPUnit; so I apologize if this answer may end up not so useful.

I have experience of trying to do testing in the style you are suggesting and I found it to quickly become a large problem. Integration tests which integrate with the DB must ensure that either after every test, or before ever test that the db is in a known good state. Without this you will get lots of false results. To do it can be an annoying problem. In either case it will take time and be slow.

If your layer is in fact a thin layer which takes a some data from the web and push it to the db layer after (possibly) some modification, validation, etc - I would strongly suggest decoupling it from both the web and from the DB. Mock both ends in your tests. Your tests will be small and fast. Test separately your db layer to ensure it does the right thing when your translation layer tells it to do something.

Since I am not familiar with PHP or PHPUnit I can't help you on how to decouple and mock these items, unfortunately.


答:
Yes - if you can't find a solution that solves your problem exactly, then I would consider writing my own. As other have mentioned: consider scalability. If you foresee that it will need to scale big very soon, then perhaps it might be worth the investment to set something up that is designed to handle this.

One other thing I would mention, is I would make it as OO friendly as possible. That is, I would have a base key/value (abstract) class/interface, and extend your own key/value implementation on top of this. This is purely because later on down the line, you will find it a lot easier to (say) backup your key/value with memcached if you do it this way, or even swap it out entirely - because the interface will be the same. If you have global functions for get and set then that would seem equivalent, but you still have the issue of how quickly you can hotswap the implementation without downtime.


问:
What is the best way to create HTML in C# code?
I have a belief that markup should remain in mark-up and not in the code behind.

I've come to a situation where I think it is acceptable to build the HTML in the code behind. I'd like to have some consensus as to what the best practices are or should be.

When is it acceptable to build html in the code behind? What is the best method to create this html? (example: Strings, StringBuilder, HTMLWriter, etc)

答:
Is using something like Razor not applicable here? Because if you're doing a lot of html generation using a view engine can make it a lot easier. It was also built to be used outside of ASP.NET.

However sometimes that's not what you need. Have you considered using the TagBuilder class which is part of .net (mvc)? There is also the HtmlWriter in System.Web.UI (for web forms). I would recommend one of these if you are making Controls or Html Helpers.


答: I suggest you to look into the Play Framework, it doesn't feel like Java, you don't need to use an IDE nor Compile: It feels like Ruby on Rails: I'm liking it.</p>

Title: Building a website, want to use java


问:
Why can Perforce be a better version control system?
I've seen some people love and some loathe Perforce. As users or administrators with experience with other version control systems (free cookie to the ones with DVCS experience [git, Mercurial]), what is the main reason/feature that makes you love Perforce over other version control systems?

Edit: No, I don't sell Perforce... this is just part of my ongoing research to pitch DVCS at my company (see my question history)

答:
I have used perforce "in anger" i.e. on a project; it is very good for situations in which your source tree is extremely large- dozens to hundreds of gigabytes of source code in multiple languages, binaries (which should not have been checked in), etc.

Similar to subversion, it lets you check out only a part of a repository at a time. Unlike subversion, it has support for checking out multiple branches of a source tree, at different levels, in parallel. This is important if you have a legacy app which at one time has had different teams working on the same codebase and tests, and following different directory conventions.

After an initial period of adjustment (under a week, on and off as needed) I understood Perforce and its use cases in my scenario.

I was on the project for less than four months; the project itself was over a decade old.

I cannot think of a reasonable way for the project that I was on to move off of perforce; splitting the repository into submodules would bring all work to a halt, which is in general economically infeasible for a large company. However, individual teams can use git-to-subversion tools which help development.

Jenkins (a continuous integration tool) has plugins which fully support using perforce, so it is not incompatible with agile practices.

Perforce is very definitely an 'enterprise' tool in that most small teams don't need it unless they're working with a poorly designed file tree or with many large binary files (maybe video game developers or graphic designers would have this need, if they're sharing their version-controlled repository of binaries with one or several code projects?)


答:
While I do agree that its a recipe for disaster because no programmer will stay there long enough and you will be spending more time trying to understand other people code, some things come to mind:

Block internet access

Block any third party access (USB, card readers, etc)

Encrypt and save elsewhere any finish line of code. Thats it, turn every code into an API so programmers could not access the functions any more.

That brings: Separate programmers from debuggers.

Anyway... prepare to have some high movement of people and high salaries if you want them to stay there. You are creating a very bad working environment.

Keep in mind you could basically write much code from all the free examples that out there in the Internet. Most programming is actually re-using. You are going to block and delay your workers.


问:
Which statically typed languages support intersection types for function return values?

Initial note:

This question got closed after several edits because I lacked the proper terminology to state accurately what I was looking for. Sam Tobin-Hochstadt then posted a comment which made me recognise exactly what that was: programming languages that support intersection types for function return values.

Now that the question has been re-opened, I've decided to improve it by rewriting it in a (hopefully) more precise manner. Therefore, some answers and comments below might no longer make sense because they refer to previous edits. (Please see the question's edit history in such cases.)

Are there any popular statically & strongly typed programming languages (such as Haskell, generic Java, C#, F#, etc.) that support intersection types for function return values? If so, which, and how?

(If I'm honest, I would really love to see someone demonstrate a way how to express intersection types in a mainstream language such as C# or Java.)

I'll give a quick example of what intersection types might look like, using some pseudocode similar to C#:

```<code>interface IX { … }
interface IY { … }
interface IB { … }

class A : IX, IY { … }
class B : IX, IY, IB { … }

T fn()  where T : IX, IY
{
    return … ? new A()
             : new B();
}
</code>```

That is, the function fn returns an instance of some type T, of which the caller knows only that it implements interfaces IX and IY. (That is, unlike with generics, the caller doesn't get to choose the concrete type of T — the function does. From this I would suppose that T is in fact not a universal type, but an existential type.)

P.S.: I'm aware that one could simply define a interface IXY : IX, IY and change the return type of fn to IXY. However, that is not really the same thing, because often you cannot bolt on an additional interface IXY to a previously defined type A which only implements IX and IY separately.

Footnote: Some resources about intersection types:

Wikipedia article for "Type system" has a subsection about intersection types.

Report by Benjamin C. Pierce (1991), "Programming With Intersection Types, Union Types, and Polymorphism"

David P. Cunningham (2005), "Intersection types in practice", which contains a case study about the Forsythe language, which is mentioned in the Wikipedia article.

A Stack Overflow question, "Union types and intersection types" which got several good answers, among them this one which gives a pseudocode example of intersection types similar to mine above.

答:
In fact, the obvious answer is: Java

Whilst it may surprise you to learn that Java supports intersection types ... it does indeed through the "&" type bound operator.  For example:

```<code><T extends IX & IY> T f() { ... }
</code>```

See this link on multiple type bounds in Java, and also this from the Java API.

Body:
In fact, the obvious answer is: Java

Whilst it may surprise you to learn that Java supports intersection types ... it does indeed through the "&" type bound operator.  For example:

<T extends IX & IY> T f() { ... }

See this link on multiple type bounds in Java, and also this from the Java API.


问:
Doesn't "if (0 == value) ..." do more harm than good?
This is one of the things that I hate most when I see it in someone else's code. I know what it means and why some people do it this way ("what if I accidentally put '=' instead?"). For me it's very much like when a child goes down the stairs counting the steps out loud.

Anyway, here are my arguments against it:

It disrupts the natural flow of reading the program code. We, humans, say "if value is zero" and not "if zero is value".

Modern compilers warn you when you have an assignment in your condition, or actually if your condition consists of just that assignment, which, yes, looks suspicious anyway

You shouldn't forget to put double '=' when you are comparing values if you are a programmer. You may as well forget to put "!" when testing non-equality.

答:
It is obnoxious because it imposes a small, but noticeable mental tax.

People read left to right in virtually all programming languages (and most natural languages).

If I see 123 == x, the way I mentally parse it is:

123 - so what? incomplete info.

== - well, 123 is 123, why test it...

x - ok, so that's what we're concerned about. Only now do I have the context.

Go back to reconsider 123 and why x is compared to it.

When I see x == 123 mental parsing is:

x - Provides context, I know what the condition is about. I may choose to ignore the rest. Based on previous flow I have a good idea why and what's to come (and be surprised if it's different).

== - I thought so.

123 - Yup.

The disruption is small (in a simple example), but I always notice it.

Putting the value first may be a good idea if you want to draw attention to it, e.g. if (LAUNCH_NUKES == cmd). Normally this is not the intention.


问:
Task ownership with Wordpress - CSS - Designer or Developer?
We have a dispute regarding who owns which tasks when it comes to the CSS on our live site.

Our designer argues that he is not responsible to log-in to word press and modify the css or use ftp for any changes because that's not his job description while developer argues that since it is css, it belongs to designer and that he is to update the changes to the server and then compare and correct the output.

I'd like experienced people working in professional development environment to put a light on this scenario. I'm not sure if this is the right place to ask this question, or is there a separate forum for business development or project management specific questions?

答:
There are two separate issues.  1. Who modifies CSS?  2. Who deploys changes to production?

Of course it depends on how your team defines roles. But here is my take.

CSS defines the looks of the web page. Looks are what UI designers deal with. I'd say this is clearly the role of the UI guy.  The underlying issue may be the UI deisgner is using high level tools that automatically generate the CSS. He may not be familiar with CSS.

The task of updating files in production (regardless of CSS or not) should not fall on the UI desginer. The UI guy should just make his changes in the dev environment, check into source control, and that's it. This should not be the responsibility of the developer either. Some companies have a dedicated role for deployment to handle this.

In small companies developers tend to be the "do everything" guy because they are the only people with general computer skills in multiple domains. Developers usually can make a good looking UI.  They know how to set up and administer a website. They know how to model data in a database. And of course they can code.  It's not uncommon for a developer to be a UI designer, DBA, System administrator, and coder all in one.


问:
How to initialize object which may be used in catch clause?
I've seen this sort of pattern in code before:

```<code>//pseudo C# code

var exInfo = null;  //Line A

try
{
  var p = SomeProperty;         //Line B
  exInfo = new ExceptionMessage("The property was " + p);           //Line C
}
catch(Exception ex)
{
  exInfo.SomeOtherProperty = SomeOtherValue;  //Line D
}
</code>```

Usually the code is structured in this fashion because exInfo has to be visible outside of the try clause. The problem is that if an exception occurs on Line B, then exInfo will be null at Line D.  The issue arises when something happens on Line B that must occur before exInfo is constructed. But if I set exInfo to a new Object at line A then memory may get leaked at Line C (due to "new"-ing the object there).  Is there a better pattern for handling this sort of code? Is there a name for this sort of initialization pattern?

By the way I know I could check for exInfo == null before line D but that seems a bit clumsy and I'm looking for a better approach.

答:
It's a good idea for a variable to never contain an incorrect value, if at all possible.  That way there's no possible way, for example, for maintainers to later insert a bunch of statements between Line A and the try block, then somewhere in there accidentally use exInfo when it's null.  The general solution when you're tempted to initialize a value to null due to scope reasons is to break off the initialization code into its own function, so you would call:

```<code>var exInfo = createExInfo();
</code>```

And createExInfo would contain:

```<code>try
{
  var p = SomeProperty;
  return new ExceptionMessage("The property was " + p);
}
catch(Exception ex)
{
  var exInfo = new ExceptionMessage();
  exInfo.SomeOtherProperty = SomeOtherValue;
  return exInfo;
}
</code>```

Body:
It's a good idea for a variable to never contain an incorrect value, if at all possible.  That way there's no possible way, for example, for maintainers to later insert a bunch of statements between Line A and the try block, then somewhere in there accidentally use exInfo when it's null.  The general solution when you're tempted to initialize a value to null due to scope reasons is to break off the initialization code into its own function, so you would call:

var exInfo = createExInfo();

And createExInfo would contain:

try
{
  var p = SomeProperty;
  return new ExceptionMessage("The property was " + p);
}
catch(Exception ex)
{
  var exInfo = new ExceptionMessage();
  exInfo.SomeOtherProperty = SomeOtherValue;
  return exInfo;
}


问:
How can I get rid of just the untracked files in git?
In Mercurial I can do this with the bundled Purge Extension and executing the following command:

```<code>hg purge
</code>```

Also good to get rid of ignored files:

```<code>hg purge --all
</code>```

I'm curious about the most practical/used equivalent solution in git.

Edit: I want to just get rid of the untracked files, not reset everything (e.g. suppose I have a program generating cache files or generated code and I want to delete them with git's help)

答:
It's git reset with the option --hard:

```<code>git reset --hard
</code>```

Here is an SO answer which have more details:

https://stackoverflow.com/a/9530204/70386

And the manual:

http://www.kernel.org/pub/software/scm/git/docs/git-reset.html

Edit

To only delete untracked files, use clean

https://stackoverflow.com/questions/61212/removing-untracked-files-from-your-git-working-copy

Manual entry:

http://www.kernel.org/pub/software/scm/git/docs/git-clean.html

Body:
It's git reset with the option --hard:

git reset --hard

Here is an SO answer which have more details:

https://stackoverflow.com/a/9530204/70386

And the manual:

http://www.kernel.org/pub/software/scm/git/docs/git-reset.html

Edit

To only delete untracked files, use clean

https://stackoverflow.com/questions/61212/removing-untracked-files-from-your-git-working-copy

Manual entry:

http://www.kernel.org/pub/software/scm/git/docs/git-clean.html


答:
I would use htmltags to create HTML.

Example:

```<code>var tag = new HtmlTag("span")
    .Text("Hello & Goodbye")
    .AddClass("important")
    .Attr("title", "Greetings")
</code>```

And then CSQuery if I want to parse HTML

Example:

```<code>dom.Select("div > span")
    .Eq(1)
    .Text("Change the text content of the 2nd span child of each div");
</code>```

Title: What is the best way to create HTML in C# code?

Body:
I have a belief that markup should remain in mark-up and not in the code behind.

I've come to a situation where I think it is acceptable to build the HTML in the code behind. I'd like to have some consensus as to what the best practices are or should be.

When is it acceptable to build html in the code behind? What is the best method to create this html? (example: Strings, StringBuilder, HTMLWriter, etc)

Body:
I would use htmltags to create HTML.

Example:

var tag = new HtmlTag("span")
    .Text("Hello & Goodbye")
    .AddClass("important")
    .Attr("title", "Greetings")

And then CSQuery if I want to parse HTML

Example:

dom.Select("div > span")
    .Eq(1)
    .Text("Change the text content of the 2nd span child of each div");


问:
How do you pronounce the '...' operator
Now, in c++ '...' became a first class operator.
In speech, how do you pronounce it?

So far I've heard:

dot dot dot

triple dot

ellipsis

related: Is it OK to replace ... with ellipsis in writing?
e.g. "The ellipsis operator expands the pack"

EDIT (clarification): We are all aware that '...' as a punctuation mark is indeed called ellipsis. But in the context of C++ we don't pronounce the names of the punctuation mark. For example, the '&' operator, depends on the context is pronounced as 'and', 'bitwise and', 'address of', 'logical and' (when && is used), or 'reference'. It is rarely pronounced as 'ampersand'.

In speeches, I've a feeling that 'dot dot dot' is used more often. For example: http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Variadic-Templates-are-Funadic (an excellent presentation about variadic templates).

On the other hand, 'dot dot dot' is awkward hard to pronouce ('d' and 't' are both pronounce with the tongue).

Can we pronounce it 'unpack'?

答:
You're right; it's called an ellipsis. You can hear both the AmE and BrE pronunciation on the OALD page for "ellipsis".

Edit: I would say something like "the ellipsis represents variadic arguments."

Title: How do you pronounce the '...' operator


问:
Are there any major alternatives to Waterfall and Agile?
I am curious if anyone knows of any methodologies that are significantly different (not a recombination) and I would especially appreciate anyone who brought forward any experience with alternatives.</p>

答:
This Waterfall argument has been around for awhile and used by the agile thought leaders early on. They too encountered the "reality" of waterfall as a "red alert."

When you start working on a software development project you will quickly discover that the development methodology used will have a major part to play in the speed and quality of the code developed.Since Agile methodology is so widely used it is important that you understand the advantages and disadvantages of agile so you are able to determine whether it is the best fit for your project deliverables.

Agile software development is a conceptual framework for undertaking software engineering projects.Most agile methods attempt to minimize risk by developing software in short timeboxes, called iterations, which typically last one to four weeks. Each iteration is like a miniature software project of its own, and includes all of the tasks necessary to release the mini-increment of new functionality: planning, requirements analysis, design, coding, testing, and documentation.

It's a good process for the company because it include the customer in the development process and make it responsible for the product delivery. In the other side customers are happy because they find theirs self participating in the development of the product.

Demerits for Agile:

Agile is too programmer-centric
leaving it unclear how to balance
work across an organization.

If You Don't Know Where You're Going,
Agile Won't Get You There!

Creation of frameworks without clear
needs.

Overuse of language features
(inappropriately).

No test-first mentality.

Well for an interesting methodology which might work as an alternative for AGILE may be best viewed under these 3 links :

Kanban as Alternative Agile Implementation

Kanban software development

Lean software development on the cloud


问:
What's the benefit of Azure ACS if ASP.NET 4.5 includes OAuth and OpenID providers?
Azure ACS offers OAuth and OpenID providers, and now that ASP.NET 4.5 offers the same thing, without the added cost, is there any reason for a .NET developer to consider ACS?

(Disclaimer, I don't know what version of oauth each service provides)

答: The primary benefit to using ACS is that you can integrate login systems which are not compatible with DotNetOpenAuth; namely, that you could combine external logins with an Active Directory (including both on-premises AD as well as AD in the cloud like Office 365). Your customers could use their accustomed identities from 3rd parties, and your administrative team could use their existing domain credentials.</p>


答:
It is an ellipsis, but I'd read or pronounce it as "dot dot dot".

It's a punctuation mark, and I think of it the same as & (ampersand) which I read/pronounce as 'and'.

Title: How do you pronounce the '...' operator

Body:
Now, in c++ '...' became a first class operator.
In speech, how do you pronounce it?

So far I've heard:

dot dot dot

triple dot

ellipsis

related: Is it OK to replace ... with ellipsis in writing?
e.g. "The ellipsis operator expands the pack"

EDIT (clarification): We are all aware that '...' as a punctuation mark is indeed called ellipsis. But in the context of C++ we don't pronounce the names of the punctuation mark. For example, the '&' operator, depends on the context is pronounced as 'and', 'bitwise and', 'address of', 'logical and' (when && is used), or 'reference'. It is rarely pronounced as 'ampersand'.

In speeches, I've a feeling that 'dot dot dot' is used more often. For example: http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Variadic-Templates-are-Funadic (an excellent presentation about variadic templates).

On the other hand, 'dot dot dot' is awkward hard to pronouce ('d' and 't' are both pronounce with the tongue).

Can we pronounce it 'unpack'?


问:
What is the point to namespaces in branches in git?
So I mainly use Mercurial for my projects and I decided to sit down and learn all Git's shenanigans to discover if I'm in the right side (at least for me).

I'm learning that git uses namespaces for branches and I would like to know (in your experience) what is the point of namespaces?. In Mercurial I could just set the convention of naming branches like so:

```<code><branch name> //for "origin" branches
<username>/<branch name> //for user branches
</code>```

I imagine that there is more to it than just the name (aside from avoiding naming conflicts), but what do I get out of this seemingly more complicated (not necessarily bad) model?

答:
Never done something serious with mercurial, so I can miss something.
I'm using namespaces in git branch naming pretty much, but I'm never inserting my name into the name of the branch.

For each task that are describe in task tracker we are creating a separate branch, with number of the ticket and short description of the bug. At this point there are no spaces yet:

```<code>  remotes/origin/275-test-new-urls
  remotes/origin/283-fullscreen
  remotes/origin/299-current-menu-item
  remotes/origin/301-users-api
  remotes/origin/306-range-window-resize
  remotes/origin/307-dropdown-init-onload
</code>```

Then, say, you realize that some task need additional branches for experimenting. These branches are de-facto children to "main" task branch, i.e. after completion the should (if should at all) be merged to that very task. Here come namespaces:

```<code> remotes/origin/283-fullscreen-buggy-animation
 remotes/origin/283-fullscreen.refactor
</code>```

I've seen that slash is also used for namespacing, but personally I prefer dots, since using slashes can produce some issues.

Body:
Never done something serious with mercurial, so I can miss something.
I'm using namespaces in git branch naming pretty much, but I'm never inserting my name into the name of the branch.

For each task that are describe in task tracker we are creating a separate branch, with number of the ticket and short description of the bug. At this point there are no spaces yet:

  remotes/origin/275-test-new-urls
  remotes/origin/283-fullscreen
  remotes/origin/299-current-menu-item
  remotes/origin/301-users-api
  remotes/origin/306-range-window-resize
  remotes/origin/307-dropdown-init-onload

Then, say, you realize that some task need additional branches for experimenting. These branches are de-facto children to "main" task branch, i.e. after completion the should (if should at all) be merged to that very task. Here come namespaces:

 remotes/origin/283-fullscreen-buggy-animation
 remotes/origin/283-fullscreen.refactor

I've seen that slash is also used for namespacing, but personally I prefer dots, since using slashes can produce some issues.


问:
Should I organize my folders by business domain or by technical domain?
For example, if I'm using some MVC-like architecture, which folder structure should I use:

```<code>domain1/
    controller
    model
    view
domain2/
    controller
    model
    view
</code>```

Or:

```<code>controllers/
    domain1
    domain2
models/
    domain1
    domain2
views/
    domain1
    domain2
</code>```

I deliberately left out file extensions to keep this question language-agnostic.

Personally, I'd prefer to separate by business domain (gut feeling), but I see that most/many frameworks separate by technical domain. Why whould I choose one over the other?

答:
Microsoft ASP.Net MVC 3 has the concept of "Areas".  When you introduce "Areas" into your MVC project, they break it up like:

```<code>area1/
   models
   views
   controllers
area2/
   models
   views
   controllers
</code>```

I found this to be quite natural.  An area is a "large chunk" of a project, and working in a self-contained unit just made a lot of sense.

We used namespaces to match, FWIW.

Body:
Microsoft ASP.Net MVC 3 has the concept of "Areas".  When you introduce "Areas" into your MVC project, they break it up like:

area1/
   models
   views
   controllers
area2/
   models
   views
   controllers

I found this to be quite natural.  An area is a "large chunk" of a project, and working in a self-contained unit just made a lot of sense.

We used namespaces to match, FWIW.


问:
How do global cancel/exit commands work in bash?
As I have done multiple times before, I've written bash scripts, and just general commands that go nowhere.  They just blink the little command line cursor at me for infinity until I control+C the command.  When I do cancel the command, what exactly is going on when I do this? Am I somehow stopping and killing the current PID I'm working on?  Does it jump to a different run-level and execute something to terminate the command?

On a slightly different note, I've never been able to figure out how to set up something like this in a script or program I've worked on.  Since I mostly program in Ruby, can I setup something like a certain key press stops the program?  Every time I've looked into doing something similar, I always end up getting hung up when it comes to user input, whether that is a loop waiting for a condition, or something like this:

```<code>def Break()
  user_break = gets.strip
end

def Main()
Function1()
Break()
Function2()
Break()
[...]
end
</code>```

It seems and is incredibly bulky, and definitely isn't easily scaled up or down.

答:
I would suggest you to read:

What happens in BASH when you do Ctrl-C (hint, it's not simply sending a SIGINT).

How does Ctrl-C terminate a child process?.

You question has already been explained here well.


答:
There is another alternative and that is moving the seperate parts in plugins. CakePHP does that for example. It will allow you to generate complete MVC parts which are re-usable which you can sort by any logic you want.

Your main application will just use them and link to them.

Basically your question is also about cohesion and coupling. You want the separate parts to work as independently as possible. That way you get testable and re-usable code.

Taking that into consideration: If you split up by domain how would you re-use parts of your application? For example take a webshop: a request comes in for /orders/view/1 so you need to show order nr. 1. Goes to /orders/controllers/order_controller If you seperated domain by products and orders you would already need parts of the other "domain".

There you can start interfacing things but likely things are in most business just too cohesive. If you take the technical approach. For example you could have a plugin handling orders. You put in Product objects to it from your central application. That way you can test the plugin easily, just create some Product object with a name and price and send it in.

The plugin will do exactly what it needs to do. It will depend on it's input and not on other "parts/domains/areas".

Title: Should I organize my folders by business domain or by technical domain?

Body:
For example, if I'm using some MVC-like architecture, which folder structure should I use:

```<code>domain1/
    controller
    model
    view
domain2/
    controller
    model
    view
</code>```

Or:

```<code>controllers/
    domain1
    domain2
models/
    domain1
    domain2
views/
    domain1
    domain2
</code>```

I deliberately left out file extensions to keep this question language-agnostic.

Personally, I'd prefer to separate by business domain (gut feeling), but I see that most/many frameworks separate by technical domain. Why whould I choose one over the other?


问:
How to prevent code from leaking outside work?

Possible Duplicate:

  How to manage a Closed Source High-Risk Project?

I'm working on an institution that has a really strong sense of "possession" - each line of software we write should be only ours. Ironically, I'm the only programmer (ATM), but we're planning in hiring others.

Since my bosses wouldn't count the new programmers as people they can trust, they have an issue with the copies of the source code. We use Git, so they would have a entire copy of each of the projects they work on, when they clone the repository.

We can restrict access to them to a single key with Gitolite and bind that to their PC's, but they can copy those keys to another computer and they would have the repository access in another PC. Also (and the most obvious method) they could just upload the files somewhere else, add another remote, or just copy the files to an USB drive.

Is there any (perhaps clever) way to prevent events like these?

EDIT: I would like to thank everyone for their insights in this question, since it has been not only more eye opening, but also a firm support of my arguments (since you basically think like me, and I've been trying to make them understand that) against my bosses in the near future.

I am in a difficult situation work-wise, with my coworkers and bosses (since I'm basically in the middle) being like two gangs, so all this input is greatly, greatly appreciated.

It is true that I was looking for a technical solution to a people problem - both the management and the employees are the problem, so it can't be solved that way (I was thinking about some code obfuscation, perhaps working with separate modules, etc., but that wouldn't work from my developer POV). The main problem is the culture inside and outside the company - development is not taken seriously in my country (Venezuela) so naivity and paranoia are in fact a real issue in here.

The real answer here is an NDA (something that here in Venezuela doesn't completely work), because that's the people solution, because no sane developer would work in those conditions. Things will get ugly, but I think I will be able to handle that because of your help. Thank you all a lot! <3

答: You are working for people who simply do not understand how software engineering works.  Worse: they don't value it (only what they can get out of it).  It is not going to be possible to work productively for them; ultimately, they will punish you for this.  Find another job.</p>


答:
For all git clean commands, add -n for dry-run.

Clean all untracked files and directories, except ignored files (listed in .gitignore):

```<code>git clean -fd
</code>```

Also clean ignored files:

```<code>git clean -fdx
</code>```

Only clean ignored files (useful for removing build artifacts, to ensure a fresh build from scratch, without discarding new files/directories you haven't committed yet):

```<code>git clean -fdX
</code>```

Title: How can I get rid of just the untracked files in git?

Body:
In Mercurial I can do this with the bundled Purge Extension and executing the following command:

```<code>hg purge
</code>```

Also good to get rid of ignored files:

```<code>hg purge --all
</code>```

I'm curious about the most practical/used equivalent solution in git.

Edit: I want to just get rid of the untracked files, not reset everything (e.g. suppose I have a program generating cache files or generated code and I want to delete them with git's help)

Body:
For all git clean commands, add -n for dry-run.

Clean all untracked files and directories, except ignored files (listed in .gitignore):

git clean -fd

Also clean ignored files:

git clean -fdx

Only clean ignored files (useful for removing build artifacts, to ensure a fresh build from scratch, without discarding new files/directories you haven't committed yet):

git clean -fdX


答:
I think this depends on specific project.

For example, if the different business domains are totally independent of each other, then I'd organize by business domain.

But if there is shared code between the business domains, or rather, the business domains are different variants of the same code base, then it seems more logical to organize by technical domain.
And if you use any sort of Object Oriented language, then you can probably subclass your generic controllers, models, etc in your business-specific files to make them thinner.

There is also a (golden) mid-way between the two - strip out shared code into it's own domain and use that in other domains. This gives you your gut feeling-powered layout, but allows shared code between business domains.

```<code>Domain1              # This domain changes bits of standard MVC code
  controllers
  models
  views
Domain2              # this domain only modifies views, all else is standard
  views
Shared               # Here is the better part of code base
  controllers
  models
  views
</code>```

PS. I think that most frameworks organize by technical domain just because they tend to expect that you mix different business domains into single project only if you have shared code and otherwise would create separate projects.

EDIT:

For example, suppose there is a web app that handles a company's warehouse. In generic form this might apply to many companies, but each of them might have some specifics that aren't met and forbids them to buy in. E.g one of them has deployed tablets to the forklifts and needs special View for them while yet another wants to organize items into three levels instead of the default of two.

You could of course fork the project for each of these companies.
But if the framework/language allows, you could use subclassing or plugins etc to customize bits and pieces of the generic project to every customer's needs and organize them in the Business Domain layouts.

E.g if generic project exports to JSON only the Item itself, Domain1 can subclass the controller and make it export also recent delivery problems.

And if you later find that Domain1 has a component that is also valid for Domain2, you can extract generic version of it to Shared.

As you said, many frameworks organize by technical domain and that is what I have used for now, just because my FW of choice makes this easier. But with a little (or a lot) of elbow-grease, I think I could rewrite the include paths to support Business Domain layout too.

Body:
I think this depends on specific project.

For example, if the different business domains are totally independent of each other, then I'd organize by business domain.

But if there is shared code between the business domains, or rather, the business domains are different variants of the same code base, then it seems more logical to organize by technical domain.
And if you use any sort of Object Oriented language, then you can probably subclass your generic controllers, models, etc in your business-specific files to make them thinner.

There is also a (golden) mid-way between the two - strip out shared code into it's own domain and use that in other domains. This gives you your gut feeling-powered layout, but allows shared code between business domains.

Domain1              # This domain changes bits of standard MVC code
  controllers
  models
  views
Domain2              # this domain only modifies views, all else is standard
  views
Shared               # Here is the better part of code base
  controllers
  models
  views

PS. I think that most frameworks organize by technical domain just because they tend to expect that you mix different business domains into single project only if you have shared code and otherwise would create separate projects.

EDIT:

For example, suppose there is a web app that handles a company's warehouse. In generic form this might apply to many companies, but each of them might have some specifics that aren't met and forbids them to buy in. E.g one of them has deployed tablets to the forklifts and needs special View for them while yet another wants to organize items into three levels instead of the default of two.

You could of course fork the project for each of these companies.
But if the framework/language allows, you could use subclassing or plugins etc to customize bits and pieces of the generic project to every customer's needs and organize them in the Business Domain layouts.

E.g if generic project exports to JSON only the Item itself, Domain1 can subclass the controller and make it export also recent delivery problems.

And if you later find that Domain1 has a component that is also valid for Domain2, you can extract generic version of it to Shared.

As you said, many frameworks organize by technical domain and that is what I have used for now, just because my FW of choice makes this easier. But with a little (or a lot) of elbow-grease, I think I could rewrite the include paths to support Business Domain layout too.


问:
Minimize useless tweaking of a numeric app
I'm developing a numeric application (nonlinear optimizer), with a zillion knobs to tweak and rising.

It's not my first foray into this domain, but this time there are even more variables in the code and I'm on a tight schedule. Don't want to waste time fiddling.

Days or even months can potentially be wasted adjusting variables, recompiling, and reprocessing benchmark datasets. The resulting data is viewed and trouble spots are checked. The overall quality of the solution is reported by the program but the meaning of the report could change over time. (Numeric units for the report are one thing I'm trying to nail down.)

One main problem is organizing result files to identify each with specific code changes. Note taking can be a pain, is there software to help with this?

Are there agreed best practices to making this kind of development cycle reliably move forward? The solver package converges to its optimal solution with mechanical determination, but I'm all too familiar with the way an excess of design decisions can mire development.

答:
oh boy there is a lot going on in this question, and I'm not sure I understand all of what you are asking but lets try:

Days or even months can potentially be wasted adjusting variables, recompiling, and reprocessing benchmark datasets

at the very least I'd suggest pulling the variables out into a config file so you do not need to recompile to change them. Ideally you would also write some benchmarks and maybe use a technique such as hill climbing or GA to programatically refine the variables towards an optimal solution

(Numeric units for the report are one thing I'm trying to nail down.)

Do you mean units of measure? there are libraries available to help with these in most languages. F# even has them build into the language (though not for reporting)

One main problem is organizing result files to identify each with specific code changes. Note taking can be a pain, is there software to help with this?

the obvious solution here is to have your benchmark results committed to source control with the changes that made them, you could then even use commit hooks to signal any worsening in benchmarks


问:
How to turn on/off code modules?
I am trying to run multiple sites using single code base and code base consist of the following module (i.e. classes)

User module

Q & A module

Faq module

and each class works on MVC pattern i.e. it consist of

Entity class

Helper class (i.e. static class)

View (i.e. pages and controls)

and let's say I have 2 sites site1.com and site2.com. And I am trying to achieve following functionality

site1.com can have User, Q & A and Faq module up and running

site2.com can have User and Q & A module live while Faq module is switched off but it can be turned-on if needed, so my query here is what is the best way to achieve such functionality

Do I introduce a flag bit that I check on every page and control belonging to that module? It's more like CMS where you can turn on/off different features. I am trying to get my head around it, please provide me with an example or point out if I am taking the wrong approach.

答:
How many modules do you have? Are they hardcoded?

If you're in a case where you have only ten possible modules which are written once and require the whole update of the entire application if they need to be updated, then you can easily use checks which will propagate through the models and be used by the views to adjust the user interface (for example by showing or not the appropriate links in the web application menu).

If, instead, you're in a case of many modules developed by many developers and it is unacceptable to require the update of the whole web application in order to update any of those modules, then you should look into plugins model, like for example the one used in FogBugz.

To make a choice, consider the following elements, sorted by importance:

Maintainability: is it acceptable to modify the common code of the web application in order to change any of the modules?

Dependencies: are some modules dependent of others?

Performance: since we don't know the exact context, it's difficult to try to predict the impact of each solution. Maybe there will be none, if you use heavy, cleverly designed caching.

Overall architecture: if there are reasons to do something monolithic (because of the interdependencies), the first solution seems more appropriate; this is not the case if every module is strictly separated from others.

Title: How to turn on/off code modules?


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
When I was a student I used to put curly braces on the same line, so that there are fewer lines, and the code gets printed on fewer pages. Looking at a single bracket character printed as the only thing in a line is annoying. (environment,paper wastage)

But when coding large applications, allowing some lines with only braces in them are affordable, considering the 'grouping' feeling it gives.

Whichever style you choose, be consistent so that it does not become an overhead for your own brain to process multiple styles in related pieces of code. In different scenarios (like above) i would say it is okay to use different styles, it's easier to 'switch context' at a high level.


问:
Why are Java servers so scarce and costly?
I think "why PHP over Java" has been already discussed in other questions, the question I have is:

What makes LAMP/WAMP stacks so cheap and abundant vs a Glassfish one? What are the prime factors behind this trend?

Also, Why has no java based light weight stack come up as a competitor?

答: The answer is fairly simple: free market economics.  There are lots of people looking for cheap PHP hosting and not a lot of people looking for cheap Glassfish hosting.  This means more people will be willing to go in to the cheap PHP hosting business(less risk, more reward) than the cheap glassfish hosting business.  This creates what is known as a virtuous cycle for PHP, more hosts means less risk for trying PHP, means more people looking for PHP hosts, and around it goes. </p>


答:
What happens here is the natural lifecycle of programming languages. The languages are innovative and disruptive at the beginning, than they become mainstream and than they slowly fade out while new and better suited alternatives arise.

Java kind of disrupted C/C++, PHP with Apache &co. ate a big portion of Java's market. But I personally think tha PHP is also over it's peak and the new languages like Ruby with Rails, or the functional programming wave, are coming fast.

So, I see C/C++ and Java being on their 'legacy' or 'phase out' portion of their lifecycle when no more extraordinary new features are added but the old ones are very stable and widely used.

PHP may be only a little after it's peak. It is still fast evolving, but the downward trend can already be observed.

Title: Why are Java servers so scarce and costly?

Body:
I think "why PHP over Java" has been already discussed in other questions, the question I have is:

What makes LAMP/WAMP stacks so cheap and abundant vs a Glassfish one? What are the prime factors behind this trend?

Also, Why has no java based light weight stack come up as a competitor?


问:
What can go wrong if the Liskov substitution principle is violated?
I was following this highly voted question on possible violation of Liskov Substitution principle. I know what the Liskov Substitution principle is, but what is still not clear in my mind is what might go wrong if I as a developer do not think about the principle while writing object-oriented code.</p>

答:
Consider a classic case from the annals of interview questions: you have derived Circle from Ellipse.  Why?  Because a circle IS-AN ellipse, of course!

Except... ellipse has two functions:

```<code>Ellipse.set_alpha_radius(d)
Ellipse.set_beta_radius(d)
</code>```

Clearly, these must be re-defined for Circle, because a Circle has a uniform radius.  You have two possibilities:

After calling set_alpha_radius or set_beta_radius, both are set to the same amount.

After calling set_alpha_radius or set_beta_radius, the object is no longer a Circle.

Most OO languages don't support the second, and for a good reason: it would be surprising to find that your Circle is no longer a Circle.  So the first option is the best.  But consider the following function:

```<code>some_function(Ellipse byref e)
</code>```

Imagine that some_function calls e.set_alpha_radius.  But because e was really a Circle, it surprisingly has its beta radius also set.

And herein lies the substitution principle: a subclass must be substitutable for a superclass.  Otherwise surprising stuff happens.

Body:
Consider a classic case from the annals of interview questions: you have derived Circle from Ellipse.  Why?  Because a circle IS-AN ellipse, of course!

Except... ellipse has two functions:

Ellipse.set_alpha_radius(d)
Ellipse.set_beta_radius(d)

Clearly, these must be re-defined for Circle, because a Circle has a uniform radius.  You have two possibilities:

After calling set_alpha_radius or set_beta_radius, both are set to the same amount.

After calling set_alpha_radius or set_beta_radius, the object is no longer a Circle.

Most OO languages don't support the second, and for a good reason: it would be surprising to find that your Circle is no longer a Circle.  So the first option is the best.  But consider the following function:

some_function(Ellipse byref e)

Imagine that some_function calls e.set_alpha_radius.  But because e was really a Circle, it surprisingly has its beta radius also set.

And herein lies the substitution principle: a subclass must be substitutable for a superclass.  Otherwise surprising stuff happens.


问:
Better way to read XML
We are storing config files as XML. With that being said, when reading the XML file, is it better to use LINQ to query the XML file or would using the XMLDocument and/or XMLNode classes better to use?

To me, it would seem that in this instance, LINQ is not necessary. But then I tried to think of any value of one over the other down the road if the structure of the XML were to change.

So my question is, is one method of reading XML better or more accepted way of doing it over the other?

答:
LINQ, through XDocument is the recommended way to parse/read/query data in XML on the .NET platform.

There are many benefits including built in support for namespaces and implicit string conversions when building up a query.

Title: Better way to read XML


答: Because there is a perception that JEE containers are more "complicated", which implies more support calls and more admin training, which drives the prices up.  So hosting a JSP-based site is more expensive, so more companies go with PHP.  There are also a lot more ready-made tools and components for small business web sites (shopping carts, catalogs, etc) already written in PHP, so it's easy (read: cheap) for small companies to pull together a PHP-based site that does what they need, even if it's not as robust or scalable as a Java-based one.</p>


答:
Why are Java servers so scarce and costly?

A: Java servers are usually used by large enterprises, thus are more complex and expected to be more costly than relatively simple applications built with LAMP. Also, Java is not primary used for web application but for middleware.

Also, Why has no java based light weight stack come up as a competitor ?

A: There is Groovy language based on the Java platform (runs on JVM) and Grails a web framework. It is very easily to be learned by Java programmers and very productive.


问:
Should I try to write simple key-value storage by myself?
I need a key-value storage in a simplest form we can think of.

Keys should be some fixed-length strings, values should be some texts.

This key-value storage should have an HTTP-backed API.

That's basically it. As you can see, there is no big difference between such storage and some web application with some upload functionality.

The thing is - it'll take few hours (including tests and coffee drinking) to write something like this.
"Something like this" will be fully under my control and can be tuned on demand.

Should I, in this specific case, not try to reinvent bicycles? Is it better to use some of existing NoSQL solutions. If yes, which one exactly?

If, say, I'd needed something SQL-like, I won't ask and won't try to write something by myself. But with NoSQL I just don't know what is adequate and what is not.

答: I would make a quick review of what is out there, if you find one of the current NoSQLs get the job done then I would use one of them.  Not because you couldn't write something yourself fairly quickly but because it allows you to offload the support burden.  If all you need is key value storage one of Dynamo's children(Cassandra, Riak, ...), or redis is probably the right tool for the job. </p>


答:
In general, you should know that NoSQL databases have some characteristics to consider:

1-It does not use SQL as its query language

This will add a layer of complexity in your solution if you are already using a SQL database in the same solution.

2-It may not give full ACID guarantees

That may be undesirable in critical applications.

3-It has a distributed, fault-tolerant architecture

This is very cool, but do you really need it?

4-Additional Security Model

If you are already using another RDBMS, you will have to build/use another security mechanism.

In my opinion, and as @MainMa, already mentioned, for common database applications, the task should be trivial if you already have an RDBMS database in your solution. Do the work required on your own, it is almost trivial. However, if your solution has no database already, then it may be worthwhile because some vendors offer hosting (and virtually installing) the database for you. That saves you resources and possibly money.


问:
Is there an opposite for the term "Backporting"?
As I understand, the term "Backporting" is used to describe a fix which is applied in a future version which is also ported to a previous version. Wikipedia definition is as follows:

Backporting is the action of taking a certain software modification (patch) and applying it to an older version of the software than it was initially created for. It forms part of the maintenance step in a software development process...

For example:

A problem is discovered and fixed in V2.0. The same fix is ported and applied to V1.5.

What is the term when this is done in the opposite direction?

The problem is discovered and fixed in V1.5. The same fix is ported and applied to V2.0.

Would the term "Backporting" still apply? Or is there a term such as "Forwardporting" (which amusingly sounds a lot like "Port Forwarding")?

答: This does not generally happen as you would fix said issue in the V2.0 codebase, and optionally backport it. :) In terms of version control, this is simply called merging.


问:
What are best practices for testing programs with stochastic behavior?
Doing R&D work, I often find myself writing programs that have some large degree of randomness in their behavior. For example, when I work in Genetic Programming, I often write programs that generate and execute arbitrary random source code.

A problem with testing such code is that bugs are often intermittent and can be very hard to reproduce. This goes beyond just setting a random seed to the same value and starting execution over.

For instance, code might read a message from the kernal ring buffer, and then make conditional jumps on the message contents. Naturally, the ring buffer's state will have changed when one later attempts to reproduce the issue.

Even though this behavior is a feature it can trigger other code in unexpected ways, and thus often reveals bugs that unit tests (or human testers) don't find.

Are there established best practices for testing systems of this sort? If so, some references would be very helpful. If not, any other suggestions are welcome!

答: One reasonable thing to do is to seed the random number generator with a constant value for the tests, so that you get a deterministic behavior. </p>


问:
Switch or a Dictionary when assigning to new object
Recently, I've come to prefer mapping 1-1 relationships using Dictionaries instead of Switch statements. I find it to be a little faster to write and easier to mentally process. Unfortunately, when mapping to a new instance of an object, I don't want to define it like this:

```<code>var fooDict = new Dictionary<int, IBigObject>()
{
    { 0, new Foo() }, // Creates an instance of Foo
    { 1, new Bar() }, // Creates an instance of Bar
    { 2, new Baz() }  // Creates an instance of Baz
}

var quux = fooDict[0]; // quux references Foo
</code>```

Given that construct, I've wasted CPU cycles and memory creating 3 objects, doing whatever their constructors might contain, and only ended up using one of them. I also believe that mapping other objects to fooDict[0] in this case will cause them to reference the same thing, rather than creating a new instance of Foo as intended. A solution would be to use a lambda instead:

```<code>var fooDict = new Dictionary<int, Func<IBigObject>>()
{
    { 0, () => new Foo() }, // Returns a new instance of Foo when invoked
    { 1, () => new Bar() }, // Ditto Bar
    { 2, () => new Baz() }  // Ditto Baz
}

var quux = fooDict[0](); // equivalent to saying 'var quux = new Foo();'
</code>```

Is this getting to a point where it's too confusing? It's easy to miss that () on the end. Or is mapping to a function/expression a fairly common practice? The alternative would be to use a switch:

```<code>IBigObject quux;
switch(someInt)
{
    case 0: quux = new Foo(); break;
    case 1: quux = new Bar(); break;
    case 2: quux = new Baz(); break;
}
</code>```

Which invocation is more acceptable?

Dictionary, for faster lookups and fewer keywords (case and break)

Switch: More commonly found in code, doesn't require the use of a
Func<> object for indirection.

答:
That's an interesting take on the factory pattern.  I like the combination of the Dictionary and the lambda expression; it made me look at that container in a new way.

I'm ignoring the concern in your question about CPU cycles as you mentioned in the comments that the non-lambda approach doesn't provide what you need.

I think either approach (switch vs. Dictionary + lambda) is going to be fine.  The only limitation is that by using the Dictionary, you are limiting the types of inputs you could receive in order to generate the returned class.

Using a switch statement would provide you more flexibility on input parameters.  However, if this got to be an issue, you could wrap the Dictionary inside of a method and have the same end result.

If it's new for your team, comment the code and explain what's going on.  Call for a team code review, walk them through what was done and make them aware of it.  Other than that, it looks fine.


答:
In general, I would prefer neither.

Whatever is consuming this should work with a Func<int, IBigObject>. Then the source of your mapping can be a Dictionary or a method that has a switch statement or a web service call or some file lookup... whatever.

As for implementation, I'd prefer the Dictionary since that is more easily refactored from 'hard code dictionary, lookup key, return result' to 'load dictionary from file, lookup key, return result'.

Title: Switch or a Dictionary when assigning to new object

Body:
Recently, I've come to prefer mapping 1-1 relationships using Dictionaries instead of Switch statements. I find it to be a little faster to write and easier to mentally process. Unfortunately, when mapping to a new instance of an object, I don't want to define it like this:

```<code>var fooDict = new Dictionary<int, IBigObject>()
{
    { 0, new Foo() }, // Creates an instance of Foo
    { 1, new Bar() }, // Creates an instance of Bar
    { 2, new Baz() }  // Creates an instance of Baz
}

var quux = fooDict[0]; // quux references Foo
</code>```

Given that construct, I've wasted CPU cycles and memory creating 3 objects, doing whatever their constructors might contain, and only ended up using one of them. I also believe that mapping other objects to fooDict[0] in this case will cause them to reference the same thing, rather than creating a new instance of Foo as intended. A solution would be to use a lambda instead:

```<code>var fooDict = new Dictionary<int, Func<IBigObject>>()
{
    { 0, () => new Foo() }, // Returns a new instance of Foo when invoked
    { 1, () => new Bar() }, // Ditto Bar
    { 2, () => new Baz() }  // Ditto Baz
}

var quux = fooDict[0](); // equivalent to saying 'var quux = new Foo();'
</code>```

Is this getting to a point where it's too confusing? It's easy to miss that () on the end. Or is mapping to a function/expression a fairly common practice? The alternative would be to use a switch:

```<code>IBigObject quux;
switch(someInt)
{
    case 0: quux = new Foo(); break;
    case 1: quux = new Bar(); break;
    case 2: quux = new Baz(); break;
}
</code>```

Which invocation is more acceptable?

Dictionary, for faster lookups and fewer keywords (case and break)

Switch: More commonly found in code, doesn't require the use of a
Func<> object for indirection.


答:
Stylistically I think the readability is equal between them. It's easier to do dependency injection with the Dictionary.

Don't forget that you must check whether the key exists when using the Dictionary, and must provide a fallback if it does not.

I would prefer the switch statement for static code paths, and the Dictionary for dynamic code paths (where you might add or remove entries). The compiler might be able to perform some static optimizations with the switch that it cannot with the Dictionary.

Interestingly, this Dictionary pattern is what people sometimes do in Python, because Python lacks the switch statement. Otherwise they use if-else chains.


问:
REST - Tradeoffs between content negotiation via Accept header versus extensions
I'm working through designing a RESTful API.  We know we want to return JSON and XML for any given resource.  I had been thinking we would do something like this:

```<code>GET /api/something?param1=value1
Accept:  application/xml (or application/json)
</code>```

However, someone tossed out using extensions for this, like so:

```<code>GET /api/something.xml?parm1=value1 (or /api/something.json?param1=value1)
</code>```

What are the tradeoffs with these approaches?  Is it best to rely on the accept header when an extension isn't specified, but honor extensions when specified?  Is there a drawback to that approach?

答:
This, "However, philosophically - the first approach is the only approach.", and this "The proper official RESTful approach is to use Accept: header." are widely perceived to be the case, but are also absolutely incorrect.

Here's a brief snippet from Roy Fielding (who defined REST)...

"section 6.2.1 does not say that content negotiation should be
used all the time." cite

That particular conversation is in the context of the 'Accept-Language:' header, but the same applies equally to the 'Accept:' header, as made clear later in his response...

"I have no idea why people can't see
the second and third link on the top page

http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

that point to the two PDF editions."

What he means there is that there's no issue in using different endpoints for different representations of the same source data.  (In this case one .html endpoint and two different .pdf endpoints.)

Also in a similar discussion, this time regarding the virtues of using query parameters vs. using file extensions for different media types...

"That's why I always prefer extensions.
Neither choice has anything to do with REST." cite

Again, that's slightly different to Accept vs. filename extensions, but Fielding's stance is still clear.

Answer - it really doesn't much matter.
The trade-offs between the two aren't very significant and both are acceptable styles.

ContentLicense: CC BY-SA 4.0


问:
Do non-manager coders in their forties or older out there sometimes regret about not being managers?
And why do most programmers quit coding and become managers so early compared to other areas? You can work as a construction worker, a lawyer, researcher, writer, architect, movie director for decades if not your whole life, without quitting the favorite thing you are doing. And yet most programmers think being a manager, or better, a non-coding manager is a cool thing and the ultimate goal of the software career. It's so rare to see an ordinary coder in his 40s or 50s (or 60s!) in a typical software company. Why?

(And I am for being a coder for as long as you love doing it.)

答:
Not me - and I'm 52!

I went down that road for about ten years, struggled the whole time, and finally woke up to the fact that I hate managing other people and really suck at it. So in 2002, I went back to just programming. Now, I make way more money and really enjoy what I do, and I have zero regrets about it.

There are usually only a few standard career tracks for technical people, no matter what the field. Unfortunately, in most organizations, the purely technical track has a salary ceiling, and has limited influence on the organization. A lot of programmers who jump to the management track don't do it because they really want to stop coding, but because they want to keep progressing in income and authority.

I've been successful with a very different approach: become proficient in technologies I think are cool, and take jobs or contracts to work with them. Those positions then expose me to more cool technologies which I become proficient at, and the cycle continues.

There is certainly some age discrimination against older programmers - but there are ways to combat this, too. The first time somebody sees how fast my reflexes are from my ongoing practice of martial arts, they stop paying attention to my white beard.


答:
I agree that many frameworks separate by technical domain and so I often start this way when using a new framework. However, I consistently settle on using business domain as the primary level of folder organization.

Personally, I think it's much easier to keep my Foo Controller and Foo Repository or whatever together than going back and forth between the Controller's folder and the Repository's folder as often I need to work on both when adding features around Foo. In larger projects this is even more important as the distance between technical folders can be great and become a noticeable waste of time while developing.


问:
Useful git commit messages for merged branches
As a follow-up to this question:

If I'm working on a team by myself, I can maintain useful commit messages when merging branches by squashing all the commits to a single diff and then merging that diff. That way I can easily see what changes were introduced in the branch, and I have a single summary describing the feature/change/whatever that was accomplished in that branch when browsing the master branch.

My question now is, how can I accomplish this when working with a team? In that situation, the branches will  be pushed to a remote repository, meaning that I can't squash all the commits in the branch down to a single commit. If the branch is public, can I still have a single useful merge commit in the master branch? (By "useful" I mean that the commit in the master line tells me (1) a useful summary of what was done in the branch and (2) diffs of the same.)

答:
This turns out to be pretty simple to do, using some git merge flags I wasn't familiar with.

The -e flag allows you to edit the message that occurs when you merge.

The --log flag appends the one-line commit message from all commits in the branch to be merged to the commit message, making it easier to remember what you've done.