答:
What everyone seems to be missing is that a single address can be used by several users.

So you need something like:

```<code>User  Usage Addr
   1      1    1
   1      2    2
   2      1    3
   2      2    2
   3      1    1

Id  Number     Street        Town
1   23         Accai Drive   Hoboken
2   15         Wall Street   N.Y.C
3   99         First Street  Armonk
</code>```

In this way can share office locations between colleges and home addresses between cohabitants. It also solves the problem of what you put in the "work" address for people who work from home.

Title: How to model an address type in DDD?

Body:
I have an User entity that has a Set of Address where Address is a value object:

```<code>class User{
    ...
    private Set<Address> addresses;
    ...
    public setAddresses(Set<Address> addresses){
        //set all addresses as a batch
    }
    ...
}
</code>```

A User can have a home address and a work address, so I should have something that acts as a look up in the database:

tbl_address_type

```
------------------------------------------------
|    address_type_id       | address_type      |
------------------------------------------------
|            1             |      work         |
------------------------------------------------
|            2             |      home         |
------------------------------------------------
```

and correspondingly tbl_address

```
-------------------------------------------------------------------------------------
|    address_id       |     address_description      |address_type_id|    user_id   |
-------------------------------------------------------------------------------------
|          1          |      123 main street         |      1        |      100     |
-------------------------------------------------------------------------------------
|          2          |      456 another street      |      1        |      100     |
-------------------------------------------------------------------------------------
|          3          |      789 long street         |      2        |      200     |
-------------------------------------------------------------------------------------
|          4          |      023 short street        |      2        |     200      |
-------------------------------------------------------------------------------------
```

Should the address type be modeled as an Entity or Value type? and Why?

Is it OK for the Address Value object to hold a reference to the Entity AdressType (in case it was modeled as an entity)? Is this something feasible using Hibernate/NHibernate?

If a user can change his home address, should I expose a User.updateHomeAddress(Address homeAddress) function on the User entity itself? How can I enforce that the client passes a Home address and not a work address in this case? (a sample implementation is most welcomed)

If I want to get the User's home address via User.getHomeAddress() function, must I load the whole addresses array then loop it and check each for its type till I find the correct type then return it? Is there a more efficient way than this?

Body:
What everyone seems to be missing is that a single address can be used by several users.

So you need something like:

User  Usage Addr
   1      1    1
   1      2    2
   2      1    3
   2      2    2
   3      1    1

Id  Number     Street        Town
1   23         Accai Drive   Hoboken
2   15         Wall Street   N.Y.C
3   99         First Street  Armonk

In this way can share office locations between colleges and home addresses between cohabitants. It also solves the problem of what you put in the "work" address for people who work from home.


问:
What is the benefit of switching on Strings in Java 7?
When I was starting to programme in Java, the fact that switch statements didn't take strings frustrated me. Then on using Enums, I realised the benefits that you get with them rather than passing around raw values — type safety (which brings easier refactoring) & also clarity to other developers.

I'm struggling to think of a situation where with SE7 I'll now decide to use a switch with strings as inputs rather than Enums. If they are implemented via switching on whole strings (e.g. rather than partial or regex matches), it doesn't seem to offer less reason for the code to change.

And with IDE tools and the read-write ratio of coding, I'd be much happier auto-generating an extra Enum than passing around string values.

What benefit do they bring to us as programmers? Less boiler-plate?

It doesn't feel like the language was crying-out for this feature. Though maybe there's a use-case I'm overlooking.

答:
As far as I can tell, the question is why wrapping String constants into enum hasn't been considered sufficient to cover the needs of language users. This has been addressed in the official feature proposal announced at JDK 7 (project Coin) mailing list.

Per my reading of the proposal, alternative of using enums has been dismissed on the ground that it introduces types bloat. For your convenience, relevant part of the proposal is quoted below, with the statement addressing enums quoted in bold:

MAJOR ADVANTAGE: What makes the proposal a favorable change?

More regular coding patterns can be used for operations selected on the
  basis of a set of constant string values; the meaning of the new
  construct should be obvious to Java developers.

MAJOR BENEFIT: Why is the platform better if the proposal is adopted?

Potentially better performance for string-based dispatch code.

MAJOR DISADVANTAGE: There is always a cost.

Some increased implementation and testing complexity for the compiler.

ALTERNATIVES: Can the benefits and advantages be had some way without a
  language change?

No; chained if-then-else tests for string equality are potentially
  expensive and introducing an enum for its switchable constants, one per
  string value of interest, would add another type to a program without
  good cause...

OwnerDisplayName: anotherdave

ContentLicense: CC BY-SA 3.0


问:
Backbone/JQuery, ExtJs 4.... is there something else worth looking?
Im currently evaluating a front-end architecture for a big app that will be developed by a team of about 6 developers + 1 web designer so that said, having a robust SVN friendly architecture is a must. So far I'm evaluating this two options:

A mixture of JQuery/UI/Mobile + Backbone/Underscore + Require JS + Twitter-Bootstrap

ExtJS 4

This are the requirements the architecture needs to meet:

SVN Fiendly (or Friendly depending on you previous experiences)

Active community and extensive documentation

Extensible

Easy to learn and to maintain (nice to have)

Cross-browser support (most of the time at least)

Support for Mobile devices

Easy to maintain (MVC, MVVM)

OpenSource (nice to have)

The previously mentioned ones meet most of the requirements in different levels and so far they are the only ones I've found about, am I missing any others?

答:
I'm writing in ExtJS and using Sencha stack since 2008. I also use jQuery, YUI, Twitter Bootstrap and tried EmberJS.
I love component-based approach that is promoted by Sencha. You create your UI from a set of ready-made controls. You put your data in models and tie them using controllers. If you introduce additional layers like global AJAX call handling, error processing and i18n, you've got a great foundation for a lot of projects. CRUD-based ones like admin panel or CRM can be done really quickly.
There are certain dos and donts that you should keep in mind, but overall ExtJS allows you to be very efficient.
However there are significant drawbacks:

It uses quite heavy DOM. In modern browser it doesn't matter a lot, but if you are writing for devices, this will be paintful. On a flip side, it's easy to override, say, Ext.Button's method that produces DOM and put DIV instead of table structure.

It's not that easy to customize the appearance. We ended up creating our own set of overrides and SASS mixins that we use in the projects. However, creating such foundation takes significant time, I admit. Styling jQuery app with lightweight DOM and Bootsrap is faster and easier. On the flip side, if you are fine with common themes, you have no problems and you get your product really fast.

ExtJS is for desktops. Sencha Touch is for devices. You cannot create product that works fine for both device and desktop. Good approach is use Sencha Touch and let it scale on desktop and tablet. But, hey, guys, approach to touch-based and click-based interfaces are REALLY different. So, yes, it's a problem, but you will get this problem anyway :-)

ExtJS is large. Yes, but you can customize the build. It would still be larger that jQuery, but it can do way more than jQuery for you :-) Minimize and serve it from CDN and you'll be fine

Custom components are not easy to create. Yes, if you need to extend ExtJS components, that's usually quick. However if you need your custom one or want to change existing component significantly, you'll get a headache. However, building GOOD jQuery plugin that does something useful is a pain too. I did both components for ExtJS and plugins for jQuery. When you use right approaches, both are complex enough, but I can't say that Ext is harder.

ExtJS doesn't have good routing. No excuse for that. Modern framework and modern app should provide it.

As a conclusion, I'd say that if your UI is large, but consists of a components youcn find in ExtJS palette and you don't need significant design updates, ExtJS is definitely the way to go. If you have something really customized, scaled from android phone to macbook pro retina screen, using custom controls and having completely unique look&feel, then check out jQuery, but combine it with structural framework like EmberJS and with CSS/component framework like Bootstrap. Given you learn that stack really good, you'll be quite efficient with that.

And never, never, never write in jQuery with ExtJS mindset and vice versa. Framework is a code+philosophy behind it's architecture and it's way. Learn it, follow it and you'll get good results.


答:
Should the address type be modeled as an Entity or Value type? and
  Why?

I think that address is a candidate for a domain model. It's common for address objects to have validation behaviour. For example, you might want check that certain fields are set or that the postcode is valid prior to setting it.  Some might argue that postcode validation shouldn't be done in the address object. This can be debated.

Is it OK for the Address Value object to hold a reference to the
  Entity AdressType (in case it was modeled as an entity)? Is this
  something feasible using Hibernate/NHibernate?

I'm assuming that AddressType is defined in your data access layer. If this is the case, then at some point you will want to expose your address in the presentation or service layers. All of a sudden your data layer logic is leaking into presentation and service layers.

If a user can change his home address, should I expose a
  User.updateHomeAddress(Address homeAddress) function on the User
  entity itself? How can I enforce that the client passes a Home address
  and not a work address in this case? (a sample implementation is most
  welcomed)

I don't think that User.updateHomeAddress(Address homeAddress) is a right way forward. I'm assuming that in your system user plays a major role. I wouldn't pile up user related concerns into a single User class. The more responsibilities you give to the user, the harder it will become to maintain your code.

One of the solutions is to have a command class for updating address.

E.g.

```<code>public class UpdateHomeAddressCommand
{
   private User _user;
   private Address _address;

   public UpdateHomeAddressCommand(User user, Address address)
   {
      _user = user;
      _address = address;
   }

   public void Execute()
   {
       // Update logic
   }
}
</code>```

In the example above, I'm using a simple command to update address. If you find that logic for updating home and work address is very similar, than you can move it into an abstract class and then make UpdateHomeAddressCommand to inherit from abstract UpdateAddressCommand.

If I want to get the User's home address via User.getHomeAddress()
  function, must I load the whole addresses array then loop it and check
  each for its type till I find the correct type then return it? Is
  there a more efficient way than this?

Ideally your data layer should return only the data that you need. Otherwise it's unnecessary data travelling over the wire.

Title: How to model an address type in DDD?

Body:
Should the address type be modeled as an Entity or Value type? and
  Why?

I think that address is a candidate for a domain model. It's common for address objects to have validation behaviour. For example, you might want check that certain fields are set or that the postcode is valid prior to setting it.  Some might argue that postcode validation shouldn't be done in the address object. This can be debated.

Is it OK for the Address Value object to hold a reference to the
  Entity AdressType (in case it was modeled as an entity)? Is this
  something feasible using Hibernate/NHibernate?

I'm assuming that AddressType is defined in your data access layer. If this is the case, then at some point you will want to expose your address in the presentation or service layers. All of a sudden your data layer logic is leaking into presentation and service layers.

If a user can change his home address, should I expose a
  User.updateHomeAddress(Address homeAddress) function on the User
  entity itself? How can I enforce that the client passes a Home address
  and not a work address in this case? (a sample implementation is most
  welcomed)

I don't think that User.updateHomeAddress(Address homeAddress) is a right way forward. I'm assuming that in your system user plays a major role. I wouldn't pile up user related concerns into a single User class. The more responsibilities you give to the user, the harder it will become to maintain your code.

One of the solutions is to have a command class for updating address.

E.g.

public class UpdateHomeAddressCommand
{
   private User _user;
   private Address _address;

   public UpdateHomeAddressCommand(User user, Address address)
   {
      _user = user;
      _address = address;
   }

   public void Execute()
   {
       // Update logic
   }
}

In the example above, I'm using a simple command to update address. If you find that logic for updating home and work address is very similar, than you can move it into an abstract class and then make UpdateHomeAddressCommand to inherit from abstract UpdateAddressCommand.

If I want to get the User's home address via User.getHomeAddress()
  function, must I load the whole addresses array then loop it and check
  each for its type till I find the correct type then return it? Is
  there a more efficient way than this?

Ideally your data layer should return only the data that you need. Otherwise it's unnecessary data travelling over the wire.


问:
DDD, creating an aggreagate from outside the application service layer
I have a service(webservice) that is used to access to the domain logic. One of the methods of the webservice is createFoo, where Foo is my aggregate. So the class that implements the webservice's method calls my application service that contains the createFoo method which is responsible of doing some stuff and persisting the new Foo instance.

This new Foo instance the is returned by the application service to the class that implements the web service's method. Finally, the Foo instance is converted to something like FooWsResponse and then the web service returns the FooWsResponse instance.

Right now all this is more or less implemented like this:

```<code>public class CreateFooService{

    private FooService appService;

    private Converter<Foo, FooWsResponse> converter;

    public FooWsResponse createFoo(CreateFooParams params){
        Foo foo = FooFactory.createFoo(params);
        foo = appService.createFoo(foo);
        return converter.converter(foo);
    }
}
</code>```

The problem with the code above is that the Application Service method is misleading because is not creating a Foo instance, is only working on the domain logic associated to the creation of Foo and persisting the instance.

So, the things that I want to know are:

Is it ok create the aggregate outside the service layer?. I know that I can pass the CreateFooParams as parameter appService.createFoo but I don't want to do this because my service layer will be coupled to the web service framework. Also, I don't want to pass all the properties of the class CreateFooParams as parameters of appService.createFoo because I will end with a method with 15 parameters!. Finally, creating the Foo instance before calling appService.createFoo method but now the method's name is not accurate and also all clients of my appService should need to create how to create an instance of Foo to pass it as parameter of appService.createFoo which is very bad and may lead to many issues.

Should I create a FooDto that receives all the data of CreateFooParams and pass it to appService.createFoo method?. This looks like a better option but having 3 different classes with almost the same properties feels very redundant

I want to know what is the right thing to do according to the DDD guidelines.

Thanks for your help.

答:
Generally, I'd say no. Aggregates should not leave your domain model boundary and any business logic related to creating that aggregate should reside within that aggregate.
I'd advise you to add a factory method to that aggregate class which takes in all the necessary parameters to create a new instance of that aggregate. If there's business logic related to that creation, it should reside in that factory method.

If you feel that you need way to many parameters for that factory method, then maybe that's a sign that that aggregate could be too big (maybe).

I don't really understand why you would create and then immediately return that instance though. Usually, you separate your reads and writes, because your read and write model are usually very different.


问:
How does a chess engine decide what move to make?
I'm writing a simple chess engine in LISP. I actually know how the engine decide the move, it evaluates and reads some opening books. But that's not what i mean. This is my design.

```<code>57 58 59 60 61 62 63 64
49 50 51 52 53 54 55 56
41 42 43 44 45 46 47 48
33 34 35 36 37 38 39 40
25 26 27 28 29 30 31 32
17 18 19 20 21 22 23 24
09 10 11 12 13 14 15 16
01 02 03 04 05 06 07 08
</code>```

I looked at more  complicated solutions but i came out with what i believe is the simplest one. Say the bishop is on the square 23, it could move 4 possible moves, (to  16 or 14 or 32 or 30), so  it moves -7 or +7 or +9 or -9.

I create an array

```<code>(make-array '(8 8) :initial-contents
'((R B N Q K B N R)
 (P P P P P P P P)
(NIL NIL NIL NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL NIL NIL NIL)
          (P P P P P P P P))
          (R B N Q K B N R)))
</code>```

And move the pieces from index to index. My question is, i cannot simply tell the bishop to move +7 or whatever, if it's an open diagonal. I need to tell it to move +9 * 1  or +9 * 2 etc. and you bishop have to decide which one to go to. I cannot write a condition and a loop for every possible square

答:
Imagine you've got a function that evaluates the game board and returns a score, where large positive scores mean you're doing well and large negative scores means you're doing badly.

Now imagine that for each possible position that a piece can move to, for each piece on the board, you calculate what the score would become and choose the move that results in the best score. This isn't too hard to do and results in an AI opponent that's roughly equivalent to a novice human chess player.

Now; instead of finding the best score after you've made one move, you could find the score after you've made a move and the opponent has also made a move.

More importantly you can do this to "n levels" - e.g. find the score after you've made n moves and the opponent has made n moves. In this case "n = 3" is about equivalent to a decent human player, and extremely good human players may be equivalent to about "n = 7".

Computers are fast enough to do up to "n = 7" relatively quickly; so that's all relatively easy to implement.

If you want to completely and utterly destroy the game (by making it impossible for a human player to win or enjoy playing); you can go further than this. In this case you have to worry about the "pruning" stuff other people have mentioned to reduce processing time and memory consumption. My advice here is don't bother - there's already been far too many smart/stupid people ruining "player vs. machine" chess.


问:
DDD Proper aggregates division and getting rid of too many references
I am designing an application, which will aid designing electric installations. I went for Domain Driven Design, as the topic is complex and the application will be growing with gained knowledge. However, I am newbie to this concept. For now, I have a problem to properly model the domain, especially to divide entities into aggregates.

I have defined wiring - Installation as a set of ConnectionPoints and Cables, which connect them. One ConnectionPoint has one or more Cables. Each Cable has a set of wires. I consider end of a wire as a Terminal, which we can connect to another Terminal creating a Junction. Terminals differ one from another, as wires have different colours and purpose. Junctions are made of two or more Terminals and can be done only inside a ConnectionPoint. I have illustrated it for a better understanding:

Besides Cables there are also Devices, which also have Terminals. They are also connected in a ConnectionPoint and their Terminals are treated the same way as Cable's  Terminals. For each Device I must be able to track, where the Terminal is connected to (it might be a list of end points).

The problem, with the design, is the need of having references to Terminals outside of a Cable and Device entities to create Junctions and track connections. I could consider a Cable and a Device as aggregates of Terminals, as Terminals cannot exist without them and as a knowledge of Terminal's parent is important. However, each Terminal has also an identity outside of a Cable / Device and I have no idea how later in code and database I could keep knowledge of the connections made.

Do you have any ideas how could I model it? What questions should I ask myself to define a correct model and avoid keeping references everywhere?

答:
An aggregate is an entity or group of entities that must remain consistent within any given transaction.

E.g. consider an electrical cable that has multiple wires: if you send current accross it, the current travels in the same direction on each of the wires. In a DDD app, you would have a method on the cable "TransferCurrent". That method would reside on the aggregate root (cable) and not on the wires, because current can't travel in different directions on wires of the same cable, that would make the cable inconsistent.

I hope that example somewhat makes sense, your domain is rather alien to me. But the gist is: look for entities or groups of entities that need to remain consistent within a given transaction.

Also keep in mind that aggregate roots can only reference by id other aggregate roots, not entities that may reside within an aggregate. The other way around is possible though.


答:
A bishop can go to the field numbered +7 or +9, and possibly from there to the fields numbered +14 and +18. That last part you can check with a loop: how often can you do a +7, how often a +9?

There are two limits to this: other pieces (which can be captured, but must be then removed) and the board edges. For the bishop, that means you can't do a +7 from board position N*8+1, as that would wrap, you can't do a +9 from board position N*8, and you can't do any + from board position >=57. And obviously there's also -7 and -9 with similar constraints.

Other pieces have other rules, but they're pretty much the same: can't cross other pieces, can't cross edges. Some can perform only one step at a time. E.g. knights have a +15 move, but no +30, and the +15 move can only originate from fields withing the 02-08-48-42 rectangle.

Title: How does a chess engine decide what move to make?

Body:
I'm writing a simple chess engine in LISP. I actually know how the engine decide the move, it evaluates and reads some opening books. But that's not what i mean. This is my design.

```<code>57 58 59 60 61 62 63 64
49 50 51 52 53 54 55 56
41 42 43 44 45 46 47 48
33 34 35 36 37 38 39 40
25 26 27 28 29 30 31 32
17 18 19 20 21 22 23 24
09 10 11 12 13 14 15 16
01 02 03 04 05 06 07 08
</code>```

I looked at more  complicated solutions but i came out with what i believe is the simplest one. Say the bishop is on the square 23, it could move 4 possible moves, (to  16 or 14 or 32 or 30), so  it moves -7 or +7 or +9 or -9.

I create an array

```<code>(make-array '(8 8) :initial-contents
'((R B N Q K B N R)
 (P P P P P P P P)
(NIL NIL NIL NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL NIL NIL NIL)
(NIL NIL NIL NIL NIL NIL NIL NIL)
          (P P P P P P P P))
          (R B N Q K B N R)))
</code>```

And move the pieces from index to index. My question is, i cannot simply tell the bishop to move +7 or whatever, if it's an open diagonal. I need to tell it to move +9 * 1  or +9 * 2 etc. and you bishop have to decide which one to go to. I cannot write a condition and a loop for every possible square


问:
PHP SplFixedArray How To Deal With billions of indexes?
I've built a flatfile db system that will work like mini-noSQL system
and it split db to smaller files, and I did a SplFixedArray wrapper for it
with a method for searching usage built on preg_grep.

Everything working very good till now, but if the array became more than billions of indexes how to handle it? When searching it, it will iterate over the small files then get the matches and put it in a temporary fixedArray so, what if it found very large matches?

How the noSQL dbms do that?

NOTE: If you wonder why I do that without a real noSQL solution, I'll say because I want to know more.

答:
You basically stumbled upon the whole OS idea of paging/virtual memory...what you are thinking about is really only a little different from the issue that OS developers have been dealing with system memory requirements becoming too large to handle in physical memory.

Lots of really smart people have been working on this idea for a very long time...you could do well by researching the various solutions.


问:
Can you be Agile without doing TDD (test driven development)?
Is is possible to correctly call yourself (or your team) "Agile" if you don't do TDD (Test-Driven Development)?</p>

答:
Yes, yes, yes, a million times yes.

Agile is a philosophy, TDD is a specific methodology.

If I wanted to be really picky I could simply point out that there are quite a few variations of xDD - which their advocates will explain in depth are not TDD - but those are still substantially bound up with test first so that would be cheating.

So lets says this - you can be agile without doing "test first" development (look at the way scrum works - nowhere in there are there specifics about how you write code). Look at a kanban board, look at all sorts of agile methodologies.

Do you want unit tests? Of course you do, for all kinds of reasons - and you might well make an argument that you can't be agile without unit tests (although I suspect that you can be) - but you don't have to write them first to be agile.

And finally, its equally true that you could do Test First without being Agile and strong arguments for doing test first regardless of your overall dev philosophy.

It seems that others (with a more SOLID rep) have a similar opinion...

http://www.twitter.com/unclebobmartin/status/208621409663070208

@unclebobmartin: http://t.co/huxAP5cS Though it's not impossible to do
  Agile without TDD and OOD, it is difficult.  Without TDD the iteration
  rate of...

(The link in the tweet is to the full answer on LinkedIn)

ContentLicense: CC BY-SA 2.5


问:
Fastest way to check if two square 2D arrays are rotationally and reflectively distinct
The best idea I have so far is to rotate first array by {0, 90, 180, 270} degrees and reflect it horizontally or/and vertically. We basically get 16 variations [1] of first array and compare them with second array. if none of them matches the two arrays are rotationally and reflectively distinct.

I am wondering if there is more optimal solution than this brute-force approach?

[1]

```
0deg, no reflection
0deg, reflect over x
0deg, reflect over y
0deg, reflect over x and y
90deg, no reflection
...
```

答:
To devise an appropriate strategy, it is useful to know how the input is likely to be.  For instance if you have large arrays full of zeroes containing a hand of ones, then computing the checksum will quickly lead you to negative answers, but if your arrays are full of random data, the checksum will not be that helpful, comparing the first coefficient will usually be enough to tell one array apart from the other.

I am wondering if there is more optimal solution than this brute-force approach?

For general input, there is no better solution. However, note that you can avoid to copy the array by defining a custom accessor, i.e. a function taking coordinates in the array and one of our 16 permutations as well as arguments, to access the checked array.


答:
Break this into two problems:

How would you compare two square arrays - I'll call these matrices - that cannot be rotated or reflected, and

How would you compare an item that can be rotated and reflect against another item

Implementing the first problem with a naive approach gives a very simple answer - walk the matrices in parallel, stopping once you find non-equal values. If you walk the entire matrix without non-equal values then the matrices are equal. To walk the matrix, loop through columns, inner loop through each row, and compare values. Note that walking the matrix allows us to enumerate over all items in the matrix as if they were a single linear collection.

For the second problem, there are eight different ways to rotate and reflect a matrix. There are four corners to be used as a starting point, and an algorithm can walk from each corner in two directions (i.e. horizontally or vertically). Thus we will need to perform 'problem 1' over each of the eight perspectives of the original matrix.

How would I implement this? We can walk the eight matrices in parallel or sequentially; I'll implement this sequentially as potentially faster (if the first matrix checked is a match, no other checks are required) but more importantly it will be simpler.

Each of the eight matrices to check should be represented by a walking function f(x) to retrieve the xth value. For instance, in an n by n square array A,

```<code>f1(x) = A[x % n, x / n]; // walking rows first, then columns
f2(x) = A[x / n, x % n]; // walking columns first, then rows

// using a different starting point
f3(x) = A[n - (x / n), x % n];
f4(x) = A[n - (x % n), x / n];
</code>```

and so on. Now simply,

```<code>foreach walking function
    foreach value in walking function
        if value not equal to corresponding value in target
            next walking function
    return true // not non-equal values found
return false // none of the functions matched
</code>```

Title: Fastest way to check if two square 2D arrays are rotationally and reflectively distinct

Body:
The best idea I have so far is to rotate first array by {0, 90, 180, 270} degrees and reflect it horizontally or/and vertically. We basically get 16 variations [1] of first array and compare them with second array. if none of them matches the two arrays are rotationally and reflectively distinct.

I am wondering if there is more optimal solution than this brute-force approach?

[1]

```
0deg, no reflection
0deg, reflect over x
0deg, reflect over y
0deg, reflect over x and y
90deg, no reflection
...
```

Body:
Break this into two problems:

How would you compare two square arrays - I'll call these matrices - that cannot be rotated or reflected, and

How would you compare an item that can be rotated and reflect against another item

Implementing the first problem with a naive approach gives a very simple answer - walk the matrices in parallel, stopping once you find non-equal values. If you walk the entire matrix without non-equal values then the matrices are equal. To walk the matrix, loop through columns, inner loop through each row, and compare values. Note that walking the matrix allows us to enumerate over all items in the matrix as if they were a single linear collection.

For the second problem, there are eight different ways to rotate and reflect a matrix. There are four corners to be used as a starting point, and an algorithm can walk from each corner in two directions (i.e. horizontally or vertically). Thus we will need to perform 'problem 1' over each of the eight perspectives of the original matrix.

How would I implement this? We can walk the eight matrices in parallel or sequentially; I'll implement this sequentially as potentially faster (if the first matrix checked is a match, no other checks are required) but more importantly it will be simpler.

Each of the eight matrices to check should be represented by a walking function f(x) to retrieve the xth value. For instance, in an n by n square array A,

f1(x) = A[x % n, x / n]; // walking rows first, then columns
f2(x) = A[x / n, x % n]; // walking columns first, then rows

// using a different starting point
f3(x) = A[n - (x / n), x % n];
f4(x) = A[n - (x % n), x / n];

and so on. Now simply,

foreach walking function
    foreach value in walking function
        if value not equal to corresponding value in target
            next walking function
    return true // not non-equal values found
return false // none of the functions matched


问:
Is there a way to created nested computation expressions?
In F#, I want to build a hierarchical data structure in a way with a minimum
amount of language noise. The actual problem is trying to build an RSpec
inspired framework using F#. RSpec allows the construction of tests in a nested way. For example.

describe Order do
  context "with no items" do
    it "behaves one way" do
      # ...
    end
  end

  context "with one item" do
    it "behaves another way" do
      # ...
    end
  end
end
```

<p>I have something working here, but there are some
potential problems with the current solution. In particular general
setup/teardown code can become somewhat ugly.</p>

<p>My primary concern is to write an API that allows the user to write
tests/specifications in a way, where the language gets as little in the way as
possible.</p>

<p>I think that using computation expressions could allow my to create a better
API, but I am struggling with implementing nested contexts.</p>

<p>Currently I do have a builder that allows me to write:</p>

<pre class="lang-fs prettyprint-override"><code>let specs =
    describe "Some feature" {
        it "has some behavior" (fun () ->
            // Test code goes here
        )
    }
</code>```

But in order to have nested contexts I need to be able to write something like
this:

let specs =
    describe "Some feature" {
        describe "in some context" {
            it "has some behavior" (fun () ->
                // Test code goes here
            )
        }
        describe "in some other context" {
            it "has some behavior" (fun () ->
                // Test code goes here
            )
        }
    }
```

<p>I have no idea how to implement the nested context. Or even if it is possible to
bend F# in a way to allow me to create such a builder.</p>

<p>I did make an experiment, that allowed me to write this:</p>

<pre class="lang-fs prettyprint-override"><code>let specs =
    desribe "Some feature" {
        child (describe "in some other" {
            it "has some behavior" (fun () ->
                // Test code goes here
            )
        })
        child (describe "in some context" {
            it "has some behavior" (fun () ->
                // Test code goes here
            )
        })
    }
</code>```

But the added parenthesis and explicit builder construction is exactly what I
want to avoid in the first place.

type DescribeBuilder(name : string) =
    [<CustomOperation("it")>]
    member __.It (x, name, test : unit -> unit) =
        let t = TestContext.createTest name test
        x |> TestContext.addTest t
    [<CustomOperation("child")>]
    member __.Child(x, child :TestContext.T) =
        x |> TestContext.addChildContext child
    member __.Yield y =
        TestContext.create name
    member __.Delay (x) =
        x()
let describe name = new DescribeBuilder(name)
```

答:
For this, I don't see why would you want to use computation expressions, a simple discriminated union with single case would suffice:

type Hierarchy = Hierarchy of Hierarchy list

let h = Hierarchy [ Hierarchy []; Hierarchy [ Hierarchy [] ] ]
```

It's possible you need something more, but it's not clear from your example.

Body:
For this, I don't see why would you want to use computation expressions, a simple discriminated union with single case would suffice:

type Hierarchy = Hierarchy of Hierarchy list

let h = Hierarchy [ Hierarchy []; Hierarchy [ Hierarchy [] ] ]

It's possible you need something more, but it's not clear from your example.


问:
Use cases sequentialy related, how to deal with this?
I'll express my doubt with an example. Suppose I have the following requirement:

The customer needs a page in his website that displays all the products he has with a quantity field on the side of each product. The visitor of the website must be able to fill in the quantities desired, select one location and ask for the budgeting. After asking for the budgeting, the visitor must be taken to a page with the summary of the products asked, together with the prices and fields to fill in contact informations to proceed the negotiation if desired

To organize this I've decided on building two use cases: "Require budgeting" and "Ask for products". The first one is:

Title: Require budgeting

Actor: Website visitor

Scenario:

The visitor selects to see the products

While the visitor want to add products to the budgeting

The visitor fills the desired quantity of a product in the corresponding field

The visitor selects his location to estimate shipping price

The visitor sends the requirement

After that, the visitor will be redirected to the page with the information about what he asks and the fields to require the products. This is another use case, but there is a close connection with the first one, because it is in the sequnce. I didn't know exactly how to deal with this. So I thought of using precondition:

Title: Ask for products

Actor: Website visitor

Precondition: the visitor has asked for a budgeting

Scenario:

The visitor reviews the products and prices

If he wants to ask for the products

The visitor fills his contact information and sends to the sales department

If not, he exits the page

But I'm unsure this is the right way to do so, I think that "extension" was the right way to express that, but I think I didn't get this yet.

How should we proceed when use cases are closely related like that?

答:
The way I see it, you can argue two 'right' ways of doing this: A) the whole thing is one large use case (primarily considering the 'ask for products' case to be the dominant one you're writing for), or B) the way you've got set up, where you have a short case for each atomic action (requiring budgeting, asking for products), and specifying a precondition where necessary (asking for products requires that budgeting already exists, which requires other stuff, etc.)

If I had to implement this using something like SpecFlow, keeping it the way you've posted is beneficial because I can do something like this:

```<code>Given the user has added budgeting
And the user views Review Products & Pricing
When the user enters their contact information
Then a request is sent to the sales department
</code>```

...The first given step would likely be a call-forward macro for that first story, whcih would probably be written as such:

```<code>Given the user views Manage Budgeting
When the user requests Item [X] in Quantity [Y]
Then the requirement is saved
</code>```

The ability to do it like this, in my opinion validates how you organized these two related test cases.

Body:
The way I see it, you can argue two 'right' ways of doing this: A) the whole thing is one large use case (primarily considering the 'ask for products' case to be the dominant one you're writing for), or B) the way you've got set up, where you have a short case for each atomic action (requiring budgeting, asking for products), and specifying a precondition where necessary (asking for products requires that budgeting already exists, which requires other stuff, etc.)

If I had to implement this using something like SpecFlow, keeping it the way you've posted is beneficial because I can do something like this:

Given the user has added budgeting
And the user views Review Products & Pricing
When the user enters their contact information
Then a request is sent to the sales department

...The first given step would likely be a call-forward macro for that first story, whcih would probably be written as such:

Given the user views Manage Budgeting
When the user requests Item [X] in Quantity [Y]
Then the requirement is saved

The ability to do it like this, in my opinion validates how you organized these two related test cases.


问:
Do you believe it's a good idea for Software Engineers to have to work as Quality Assurance Engineers for some period of time?
I believe it is.  Why?

I've encountered many Software Engineers who believe they are somehow superior to QA engineers.  I think it may help quench this belief if they do the job of a QA engineer for some time, and realize that it is a unique and valuable skill-set of its own.

The better a Software Engineer is at testing their own programs, the less cost in time their code incurs when making its way through the rest of the software development life-cycle.

The more time a Software Engineer spends thinking about how a program can break, the more often they are to consider these cases as they are developing them, thus reducing bugs in the end product.

A Software Engineer's definition of "complete" is always interesting...if they have spent time as a QA engineer maybe this definition will more closely match the designer of the software's.

Note I make above suggestion with a small time-frame in mind as I am aware having someone work in a position that is not the position they are hired for is definitely a recipe for losing that developer.

What do you all think?

答:
Getting programmers to work as QA engineers is a recipe to lose your best developers.  Programming and QA require different skill sets and thought processes.

However, It is important that your programmers are skilled in the art of testing and validating their own work before passing it to the QA team. Developers and QA have access to different tools, knowledge and skills. The developers need to be skilled at steping through their code looking for unexpected behavior, unit testing for boundry conditions, stressing threaded code looking for race conditions etc.  i.e. Testing from a developer perspective.

QA do their testing from the user perspective. Thinking like different types of users, inventing strange edge cases, and making obscure problems reproducable are QA skills.


问:
C# String.format extension method
With the addtion of Extension methods to C# we've seen a lot of them crop up in our group. One debate revolves around extension methods like this one:

```<code>public static class StringExt
{
    /// <summary>
    /// Shortcut for string.Format.
    /// </summary>
    /// <param name="str"></param>
    /// <param name="args"></param>
    /// <returns></returns>
    public static string Format(this string str, params object[] args)
    {
        if (str == null) return null;
        return string.Format(str, args);
    }
}
</code>```

Does this extension method break any programming best practices that you can name? Would you use it anyway, if not why? If I renamed the function to "F" but left the xml comments would that be epic fail or just a wonderful savings of keystrokes?

答:
I really dislike the fact that String.Format uses the current culture. This means that the output depends on the user's system. For example, if I code this quickly without thinking about cultures:

```<code>var now = DateTime.Now;
string json = String.Format("{{ 'Date': \"{0}\" }}", now);
</code>```

I can test this, and it works great on my system.

```
{ 'Date': "9-11-2013 13:37:00" }
```

And after a while I forget about this little snippet of code, and it ends up in my product. Then some user in Saudi Arabia uses program, and everything fails since it produced:

```
{ 'Date': "06/01/35 01:37:00 ?" }
```

To prevent such bugs I want String.Format to use the invariant culture by default, and if I want to use a specific culture I can specify the culture explicitly. This will prevent all such bugs.

In C# 6 you can use string interpolation to do string formatting. It's still current culture specific though.

```<code>string json = $"{{ 'Date': \"{now}\" }}";
</code>```

Luckily there is a way to make it culture invariant. Statically import the System.FormattableString namespace and use the Invariant method, like this:

```<code>using static System.FormattableString;

string json = Invariant($"{{ 'Date': \"{now}\" }}");
</code>```

For C# 5 and earlier, I wrote myself a set of extension methods to do that for me. In the process, it also provides a much nicer syntax.

```<code>public static string FormatInvariant(this string format, params object[] args)
{
    if (format == null) throw new NullReferenceException("format");
    if (args == null) throw new NullReferenceException("args");

    return FormatWith(format, CultureInfo.InvariantCulture, args);
}

public static string FormatCurrentCulture(this string format, params object[] args)
{
    if (format == null) throw new NullReferenceException("format");
    if (args == null) throw new NullReferenceException("args");

    return FormatWith(format, CultureInfo.CurrentCulture, args);
}

public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
    if (format == null) throw new NullReferenceException("format");
    if (provider == null) throw new NullReferenceException("provider");
    if (args == null) throw new NullReferenceException("args");

    return String.Format(provider, format, args);
}
</code>```

(Get the full source code with comments and Code Contracts.)

Example usage:

```<code>string json = "{{ 'Date': \"{0}\" }}".FormatInvariant(now);
</code>```

Title: C# String.format extension method

Body:
I really dislike the fact that String.Format uses the current culture. This means that the output depends on the user's system. For example, if I code this quickly without thinking about cultures:

var now = DateTime.Now;
string json = String.Format("{{ 'Date': \"{0}\" }}", now);

I can test this, and it works great on my system.

{ 'Date': "9-11-2013 13:37:00" }

And after a while I forget about this little snippet of code, and it ends up in my product. Then some user in Saudi Arabia uses program, and everything fails since it produced:

{ 'Date': "06/01/35 01:37:00 ?" }

To prevent such bugs I want String.Format to use the invariant culture by default, and if I want to use a specific culture I can specify the culture explicitly. This will prevent all such bugs.

In C# 6 you can use string interpolation to do string formatting. It's still current culture specific though.

string json = $"{{ 'Date': \"{now}\" }}";

Luckily there is a way to make it culture invariant. Statically import the System.FormattableString namespace and use the Invariant method, like this:

using static System.FormattableString;

string json = Invariant($"{{ 'Date': \"{now}\" }}");

For C# 5 and earlier, I wrote myself a set of extension methods to do that for me. In the process, it also provides a much nicer syntax.

public static string FormatInvariant(this string format, params object[] args)
{
    if (format == null) throw new NullReferenceException("format");
    if (args == null) throw new NullReferenceException("args");

    return FormatWith(format, CultureInfo.InvariantCulture, args);
}

public static string FormatCurrentCulture(this string format, params object[] args)
{
    if (format == null) throw new NullReferenceException("format");
    if (args == null) throw new NullReferenceException("args");

    return FormatWith(format, CultureInfo.CurrentCulture, args);
}

public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
    if (format == null) throw new NullReferenceException("format");
    if (provider == null) throw new NullReferenceException("provider");
    if (args == null) throw new NullReferenceException("args");

    return String.Format(provider, format, args);
}

(Get the full source code with comments and Code Contracts.)

Example usage:

string json = "{{ 'Date': \"{0}\" }}".FormatInvariant(now);


问:
Why do so many projects prefer "git rebase" over "git merge"?
One of the advantages of using a DVCS is the edit-commit-merge workflow (over edit-merge-commit often enforced by a CVCS). Allowing each unique change to be recorded in the repository independent of merges ensures the DAG accurately reflects the true pedigree of the project.

Why do so many websites talk about wanting to "avoid merge commits"? Doesn't merging pre-commit or rebasing post-merge make it more difficult to isolate regressions, revert past changes, etc.?

Point of clarification: The default behavior for a DVCS is to create merge commits. Why do so many places talk about a desire to see a linear development history that hides these merge commits?

答:
In short, because merging is often another place for something to go wrong, and it only needs to go wrong once to make people very afraid of dealing with it again (once bitten twice shy, if you will).

So, let's say we're working on an new Account Management Screen, and it turns out there is a bug discovered in the New Account workflow. OK, we take two separate paths - you finish the Account Management, and I fix the bug with New Accounts. Since we are both dealing with accounts, we've been working with very similar code - perhaps we even had to adjust the same pieces of code.

Now, at this moment we have two different but fully working versions of software. We've both run a commit on our changes, we've both dutifully tested our code, and independently we are very confident we've done an awesome job. Now what?

Well, it's time to merge, but...crap, what happens now? We could very well go from two working sets of software to one, unified, horribly broken piece of newly buggy software where your Account Management doesn't work and New Accounts are broken and I don't even know if the old bug is still there.

Maybe the software was smart and it said there was a conflict and insisted we give it guidance. Well, crap - I sit down to do it and see you've added some complex code I don't immediately understand. I think it conflicts with the changes I've made...I ask you, and when you get a minute you check and you see my code that you don't understand. One or both of us have to take the time to sit down, hash out a proper merge, and possibly retest the whole dang thing to make sure we didn't break it.

Meanwhile 8 other guys are all committing code like the sadists they are, I made a few small bug fixes and submitted them before I knew we had a merge conflict, and man it sure seems like a good time to take a break, and maybe you are off for the afternoon or stuck in a meeting or whatever. Maybe I should just take a vacation. Or change careers.

And so, to escape this nightmare, some people have become very afraid of commitment (what else is new, amiright?). We're naturally risk averse in scenarios like this - unless we think we suck and are going to screw it up anyway, in which case people start acting with reckless abandon. sigh

So there you go. Yes, modern systems are designed to ease this pain, and it's supposed to be able to easily back out and rebase and debase and freebase and hanglide and all that.

But it's all more work, and we just want to push the button on the microwave and have a 4-course meal done before we have time to find a fork, and it all feels so very unfulfilling - code is work, it's productive, its meaningful, but gracefully handling a merge just doesn't count.

Programmers, as a rule, have to develop a great working memory, and then have a tendency to immediately forget all that junk and variable names and scoping as soon as they've finished the problem, and handling a merge conflict (or worse, a wrongly handled merge) is an invitation to be reminded of your mortality.


问:
Storing object-graphs with class-evolution in Java with transformation (long time archiving)

Abstract

A common problem is to store objects (with graph), and to load them back. This is easy as long the stored object representation matches the executing code. But as time goes by, requirements change and stored objects do not match any longer the code. The stored objects should not loose their data, and the code in the clients should work with the latest object-models.

So a transformation has to occur somehow between loading the data and returning a object to the client.

I know that there exist some libraries such as XStream, gson, protobuf and avro. They could load older objects, but afaik just ignore data that does not match any longer the fields in the class (maybe I missed something).

(When I'm talking about storing and serialization I do not mean Java's built in serialization mechanism.)

Question

So what is the question? I'm now researching for some time, and there seems no library that adresses this issue (class evolution) without data-loss. I hope to find another working solution or idea how to implement it by myself here.

I have some requirements:

File-based - I want to be able to store the serialized object on disk

Appendable - I want to append multiple objects to one file without loading the whole file in memory again and again

Support for multiple versions in one file - A file could contain objects with different version (only of the same type)

Transformation - Data should be accessible by using the same type, even when changed in between.

Generic - The mechanism itself has to be generic, so I could use it for different objects (different objects do not get mixed in one file, only different versions of one type).

It would be nice if the storing format is human-readable.

Already stored objects are not updateable (at least not without huge effort). Think of an long-term archive.

Example

I could give an example for better illustration. Let's suppose we have two Pojos that we want to serialize.

```<code>public class MyPojo {
    String text;
    Long number;
    Integer[] values;
    SubPojo pojo;
}

public class SubPojo {
    List<String> items;
}
</code>```

In the next version we might have renamed a field (text->content), changed a type (Integer[]->List), and have transformed a field to List (SubPojo->List) where the previous field now is the first element of the new list (not loosing data, just transforming to new representation).

```<code>public class MyPojo {
    String content;
    Long number;
    List<Integer> values;
    List<SubPojo> pojo;
}

public class SubPojo {
    List<String> items;
}
</code>```

Some pseudocode how the client might take use of this:

```<code>// Write
Serializer ser = new Serializer();
MyPojo pojo = new MyPojo();
pojo.xxx = ...; // set fields
ser.store(pojo, file, append);

// Read (a version later)
Serializer ser = new Serializer();
ser.registerTransformer(new TransformerV1ToV2());
List<MyPojo> pojos = ser.load(file);
</code>```

This approach has some drawbacks:

The transformer have to work on some kind of intermediate format (could be the backed stored format such as json or xml)

You don't know how the class format was at some point in time, since you're only transforming relative to the previous version and mapping to the final class, making search for errors hard

Performance (depending on how the transformation happens)

答:
I use the Externalizable interface to solve this problem.  It doesn't really meet your Appendable requirement, but it might get you started.

Externalizable lets you write each object out yourself.  What I do is include a version number for each class.  Then, when I change the class, I adjust the readExternal method so it can can read the new format as well as the old ones and change the writeExternal method to write the new format with the new version number.  The code to read old formats may need to change to fill new fields (and not fill in removed fields).  Then I'm ready to go.

There's usually some sort of object hierarchy in the graph, so if a level 2 class is seriously modified, the new write/read for that class can output/input something completely different from the old one, with completely new lower-level classes.

Some care is needed because sometimes there isn't a hierarchy.  You have to remember that, after reading, you can't set a field by pulling data from objects in fields because they may not really be there yet.  (Sometimes I add a setUp method to all my classes that gets called after the top-level objectRead so the objects in the graph can get themselves organized after the whole graph has been read.

And it sometimes helps to write out objects manually using a method that just writes out plain bytes.  (But on the read you have to know precisely what you are reading, where readExternal will read a complete object of any class.)

Code looks something like:

```<code>// version 3 -- November 16, 2013
// version 2 -- March 22, 2013
// version 1 -- April 1, 2012
public void writeExternal( ObjectOutput out )  throws IOException  {
    out.writeShort( 3 )
    out.writeLong( longData );
    out.writeObject( something );
    ....
}

public void readExternal( ObjectInput in )  throws IOException,
             ClassNotFoundException  {
    short version = in.readShort();
    if (version > 3)  {
        // Admit program is too old to read file.
    }
    else if (version == 3)  {
        longData = in.readLong();
        something = readobject();
    }
    else if (version == 2)  {
        longData = 5;
        something = readobject();
    }
    else
       ...
}
</code>```

Body:
I use the Externalizable interface to solve this problem.  It doesn't really meet your Appendable requirement, but it might get you started.

Externalizable lets you write each object out yourself.  What I do is include a version number for each class.  Then, when I change the class, I adjust the readExternal method so it can can read the new format as well as the old ones and change the writeExternal method to write the new format with the new version number.  The code to read old formats may need to change to fill new fields (and not fill in removed fields).  Then I'm ready to go.

There's usually some sort of object hierarchy in the graph, so if a level 2 class is seriously modified, the new write/read for that class can output/input something completely different from the old one, with completely new lower-level classes.

Some care is needed because sometimes there isn't a hierarchy.  You have to remember that, after reading, you can't set a field by pulling data from objects in fields because they may not really be there yet.  (Sometimes I add a setUp method to all my classes that gets called after the top-level objectRead so the objects in the graph can get themselves organized after the whole graph has been read.

And it sometimes helps to write out objects manually using a method that just writes out plain bytes.  (But on the read you have to know precisely what you are reading, where readExternal will read a complete object of any class.)

Code looks something like:

// version 3 -- November 16, 2013
// version 2 -- March 22, 2013
// version 1 -- April 1, 2012
public void writeExternal( ObjectOutput out )  throws IOException  {
    out.writeShort( 3 )
    out.writeLong( longData );
    out.writeObject( something );
    ....
}

public void readExternal( ObjectInput in )  throws IOException,
             ClassNotFoundException  {
    short version = in.readShort();
    if (version > 3)  {
        // Admit program is too old to read file.
    }
    else if (version == 3)  {
        longData = in.readLong();
        something = readobject();
    }
    else if (version == 2)  {
        longData = 5;
        something = readobject();
    }
    else
       ...
}


答: People want to avoid merge commits because it makes the log prettier.  Seriously.  It looks like the centralized logs they grew up with, and locally they can do all their development in a single branch.  There are no benefits aside from those aesthetics, and several drawbacks in addition to those you mentioned, like making it conflict-prone to pull directly from a colleague without going through the "central" server.</p>

Title: Why do so many projects prefer "git rebase" over "git merge"?

Body:
One of the advantages of using a DVCS is the edit-commit-merge workflow (over edit-merge-commit often enforced by a CVCS). Allowing each unique change to be recorded in the repository independent of merges ensures the DAG accurately reflects the true pedigree of the project.

Why do so many websites talk about wanting to "avoid merge commits"? Doesn't merging pre-commit or rebasing post-merge make it more difficult to isolate regressions, revert past changes, etc.?

Point of clarification: The default behavior for a DVCS is to create merge commits. Why do so many places talk about a desire to see a linear development history that hides these merge commits?


答:
Have you tried any of the bang (!) keywords? You might be able to do it like so:

```<code>let specs =
    describe "Some feature" {
        do! describe "in some context" {
            do! it "has some behavior" (fun () ->
                // Test code goes here
            )
        }
        do! describe "in some other context" {
            do! it "has some behavior" (fun () ->
                // Test code goes here
            )
        }
    }
</code>```

assuming your it returns something in the describe workflow.

(The above might be improper F# as I've been away from it for a while, but you should be able to do something like it.)

Title: Is there a way to created nested computation expressions?

Body:
In F#, I want to build a hierarchical data structure in a way with a minimum
amount of language noise. The actual problem is trying to build an RSpec
inspired framework using F#. RSpec allows the construction of tests in a nested way. For example.

describe Order do
  context "with no items" do
    it "behaves one way" do
      # ...
    end
  end

  context "with one item" do
    it "behaves another way" do
      # ...
    end
  end
end
```

<p>I have something working here, but there are some
potential problems with the current solution. In particular general
setup/teardown code can become somewhat ugly.</p>

<p>My primary concern is to write an API that allows the user to write
tests/specifications in a way, where the language gets as little in the way as
possible.</p>

<p>I think that using computation expressions could allow my to create a better
API, but I am struggling with implementing nested contexts.</p>

<p>Currently I do have a builder that allows me to write:</p>

<pre class="lang-fs prettyprint-override"><code>let specs =
    describe "Some feature" {
        it "has some behavior" (fun () ->
            // Test code goes here
        )
    }
</code>```

But in order to have nested contexts I need to be able to write something like
this:

let specs =
    describe "Some feature" {
        describe "in some context" {
            it "has some behavior" (fun () ->
                // Test code goes here
            )
        }
        describe "in some other context" {
            it "has some behavior" (fun () ->
                // Test code goes here
            )
        }
    }
```

<p>I have no idea how to implement the nested context. Or even if it is possible to
bend F# in a way to allow me to create such a builder.</p>

<p>I did make an experiment, that allowed me to write this:</p>

<pre class="lang-fs prettyprint-override"><code>let specs =
    desribe "Some feature" {
        child (describe "in some other" {
            it "has some behavior" (fun () ->
                // Test code goes here
            )
        })
        child (describe "in some context" {
            it "has some behavior" (fun () ->
                // Test code goes here
            )
        })
    }
</code>```

But the added parenthesis and explicit builder construction is exactly what I
want to avoid in the first place.

type DescribeBuilder(name : string) =
    [<CustomOperation("it")>]
    member __.It (x, name, test : unit -> unit) =
        let t = TestContext.createTest name test
        x |> TestContext.addTest t
    [<CustomOperation("child")>]
    member __.Child(x, child :TestContext.T) =
        x |> TestContext.addChildContext child
    member __.Yield y =
        TestContext.create name
    member __.Delay (x) =
        x()
let describe name = new DescribeBuilder(name)
```

Body:
Have you tried any of the bang (!) keywords? You might be able to do it like so:

let specs =
    describe "Some feature" {
        do! describe "in some context" {
            do! it "has some behavior" (fun () ->
                // Test code goes here
            )
        }
        do! describe "in some other context" {
            do! it "has some behavior" (fun () ->
                // Test code goes here
            )
        }
    }

assuming your it returns something in the describe workflow.

(The above might be improper F# as I've been away from it for a while, but you should be able to do something like it.)


问:
What is the limit on REST API resource levels
When designing a REST API, how deep should the resources levels go?

For example; If I have the following database tables:

Companies: ID, Name

Employees: ID, Name, CompanyID

Tasks: ID, Name, EmployeeID

When exposing these through a REST API, it might look something like this (id is optional):

Companies: GET /api/companies/{id}

Employees: GET /api/employees/{id}

Tasks: GET /api/tasks/{id}

Lets say I want to retrieve all the employees working at company 1. I could do something like this: GET /api/companies/1/employees, right?

Performing a GET on /api/employees would be useless, because you don't want to return all the employees stored in the database. Should the /api/employees resource only be used in this case for retrieving individual data about a specific employee?

What if I want to get the tasks associated with an employee? Should the URL be:

GET /api/companies/1/employees/123/tasks

or

GET /api/employees/123/tasks.

If you don't want clients to have access to certain resources, without knowing its parent, how do you design your resources?

If I'm not being clear enough, or have to many questions, please let me know.

答:
Yes,

GET /api/companies/1/employees

would be the way to get the employees of a company.

What exactly your employee resource offers would depend on some details of your application. For example you could have logins for admins that are directly related to a specific company. It this case it would be a possible shortcut the employees resource and directly go to an employee or list of employees. But in normal cases /api/employees would only work in combination with companies.

Very interesting question would be the nesting levels. This is one of the questions some people can discuss for hours. Ruby on Rails for example has now an option for "shallow" routes.

While there is no hard technical limit to the number of levels (max length of an URL maybe) I think two levels should be enough for most cases and deeper nesting should be avoided if possible since doing so will make your code better structured and maintainable.

Your example is quite typical and it is easy to show why you would not really need a third level for the tasks in most scenarios. Your tasks are directly related to an employee. So the entity resource somehow already carries the information about the company. (Selecting an employee automatically selects the company). So providing the company in the URL again somehow repeats information.

```<code>GET /api/employees/123/tasks
</code>```

has all the information necessary to get to your data. So why make it more complex?

I'm not sure if I fully understand your last question.

Restricting access in this context is rather easy. Say you have a client who has only access to resources of the company with id 123. Then all you have to do is to start your controller code by assigning some "hard limits". If the logged in user is not allowed to access anything but one company, then create an obkect for that company and from there on use only this object for any firther access.

Assume we have a Rails projects. For this we have a model for each resource you mention. In addition we have an authentication system in place that gives us the currently logged in user. In this case it would be as easy as this to return something like the list of employees:

```<code>current_user.company.employees
</code>```

Notice that it does not even try to use any company id used in the URL (which in case of Rails would be stored in params[:company_id]).

Try to get the tasks of a specific employee with

```<code>GET /api/companies/123/employees/456/tasks

current_user.company.employees.find(params[employee_id]).tasks
</code>```

Notice again that this is going the "full path" instead of simply using

```<code>Employee.find(params[employee_id]).tasks
</code>```

The first form will create a SQL query with a lot of LEFT JOINS that starts from user, goes through company, employees and tasks. And important in this case: It will fail if a single relation is missing.

Even if not in context of a login and permissions you can still use this to enforce that the user has a certain knowledge about the data. Though in this case you would maybe have to use deeper nested routes. Same example without login but the user making the request must know the correct company id. In this case:

```<code>GET /api/companies/123/employees/456/tasks

Company.find(params[:company_id]).employees.find(params[employee_id]).tasks
</code>```

Again go the full way. If your framework does not have this kind of object relations simply nake sure that your SQL requests use JOINS in a similar fashion.

Body:
Yes,

GET /api/companies/1/employees

would be the way to get the employees of a company.

What exactly your employee resource offers would depend on some details of your application. For example you could have logins for admins that are directly related to a specific company. It this case it would be a possible shortcut the employees resource and directly go to an employee or list of employees. But in normal cases /api/employees would only work in combination with companies.

Very interesting question would be the nesting levels. This is one of the questions some people can discuss for hours. Ruby on Rails for example has now an option for "shallow" routes.

While there is no hard technical limit to the number of levels (max length of an URL maybe) I think two levels should be enough for most cases and deeper nesting should be avoided if possible since doing so will make your code better structured and maintainable.

Your example is quite typical and it is easy to show why you would not really need a third level for the tasks in most scenarios. Your tasks are directly related to an employee. So the entity resource somehow already carries the information about the company. (Selecting an employee automatically selects the company). So providing the company in the URL again somehow repeats information.

GET /api/employees/123/tasks

has all the information necessary to get to your data. So why make it more complex?

I'm not sure if I fully understand your last question.

Restricting access in this context is rather easy. Say you have a client who has only access to resources of the company with id 123. Then all you have to do is to start your controller code by assigning some "hard limits". If the logged in user is not allowed to access anything but one company, then create an obkect for that company and from there on use only this object for any firther access.

Assume we have a Rails projects. For this we have a model for each resource you mention. In addition we have an authentication system in place that gives us the currently logged in user. In this case it would be as easy as this to return something like the list of employees:

current_user.company.employees

Notice that it does not even try to use any company id used in the URL (which in case of Rails would be stored in params[:company_id]).

Try to get the tasks of a specific employee with

GET /api/companies/123/employees/456/tasks

current_user.company.employees.find(params[employee_id]).tasks

Notice again that this is going the "full path" instead of simply using

Employee.find(params[employee_id]).tasks

The first form will create a SQL query with a lot of LEFT JOINS that starts from user, goes through company, employees and tasks. And important in this case: It will fail if a single relation is missing.

Even if not in context of a login and permissions you can still use this to enforce that the user has a certain knowledge about the data. Though in this case you would maybe have to use deeper nested routes. Same example without login but the user making the request must know the correct company id. In this case:

GET /api/companies/123/employees/456/tasks

Company.find(params[:company_id]).employees.find(params[employee_id]).tasks

Again go the full way. If your framework does not have this kind of object relations simply nake sure that your SQL requests use JOINS in a similar fashion.


问:
What are the set of skills that every programmer graduating from college should have?
We had a guest lecturer at our school he went on a tangent regarding those graduating and not being upto the skill level he expects ie. knowledge of one big-time compiled languague like Java, C++ or C#, one scripting language like Python or Ruby, one web framework. What are some other skills that you guys think should be absolutely critical to graduating student?</p>

答:
I had once a team I "inherited" with mostly newly graduated staff and I had my experience that those who did real programming "next" to there study (to earn some extra money) were the most capable team members. Hence experience is the key and it does only little matter what language.

However if you look what recruiters are looking for (at all the common recruiter sites like jobserver.com etc.) it is interesting to observe that there is a lot being asked for the C++, C#, Java but also there are others looked for and also "exotic" things like COBOL is still around.

OwnerDisplayName: Wallz


答:
The automated tools are getting better at making sure that the merging code will compile and run, thus avoiding syntactic conflicts, but they cannot guarantee the absence of logical conflicts that may be introduced by merges. So a 'successful' merge gives you a sense of false confidence, when in reality it guarantees nothing, and you have to redo all of your testing.

The real problem with branching and merging, as I see it, is that it kicks the proverbial can down the road. It lets you say "I'll just work in my own little world" for a week, and deal whatever problems come up later. But fixing bugs is always faster/cheaper when they are fresh. By the time all of the code branches start getting merged you may already forget some of the nuances of the things that were done.

Take the two aforementioned problems together, and you might find yourself in a situation where it's simpler and easier to have everyone work out of the same trunk and continuously resolve conflicts as they come up, even if they make active development a little slower.


问:
How does rapid prototyping fit into an agile methodology?
I work for a large company, which dictates the use of agile processes. For example, for our projects, we use cloud-based services that are specifically targeted at managing agile development.

The specific engineering group I work for has not traditionally developed software (instead we help drive projects from a much more birds-eye point of view), but that is changing. We have a wide range of upcoming/planned software projects that are mostly data-centric - e.g., we will be doing data monitoring, collection, aggregation, and some reporting. Other tasks involve automation with specialized hardware and various types of client/server (multitiered) architectures. I am to assist in the process of hiring several people, and formulating many of our plans in moving forward.

My question is whether or not doing rapid prototyping (throwaway code) fits into an agile philosophy. For example, I love Python and its wide range of packages. I see the possibility of implementing many of our ideas very quickly with a Python based workflow. However, I think that there will be a lot of perceptions that Python is not "enterprise-quality", and much of this work would need to be rewritten in Java or maybe C++.

However, creating the Python prototypes would give us a lot of bang for our buck in enabling us to quickly deliver real results.

Have you been able to incorporate rapid prototyping - hopefully in Python - into a solid agile workflow in an enterprise environment?

答:
The true spirit of Agile is about interaction and communication.  I would say if the prototype works well as a tool to help communication, there is nothing wrong to use it in Agile world.
In our team (we have been practicing Agile for more than 5 years) we used it from time to time. And there are some benefits I can see from that

1) Assist communication

2) Get users into solution interviews and get early feedback

Caveat:

Direct communication between UX and engineers should NEVER be replaced by any prototyping artifacts. If possible, pairing with engineer works way more better than communicating through a mediator (prototype).


答: I'd add that prototypes are crucial for learning, and also in the Agile spirit. If the prototype allows you to learn, especially within faster feedback cycles, then go for it. It's all about maximizing learning and sharing learnings with the team.</p>

Title: How does rapid prototyping fit into an agile methodology?

Body:
I work for a large company, which dictates the use of agile processes. For example, for our projects, we use cloud-based services that are specifically targeted at managing agile development.

The specific engineering group I work for has not traditionally developed software (instead we help drive projects from a much more birds-eye point of view), but that is changing. We have a wide range of upcoming/planned software projects that are mostly data-centric - e.g., we will be doing data monitoring, collection, aggregation, and some reporting. Other tasks involve automation with specialized hardware and various types of client/server (multitiered) architectures. I am to assist in the process of hiring several people, and formulating many of our plans in moving forward.

My question is whether or not doing rapid prototyping (throwaway code) fits into an agile philosophy. For example, I love Python and its wide range of packages. I see the possibility of implementing many of our ideas very quickly with a Python based workflow. However, I think that there will be a lot of perceptions that Python is not "enterprise-quality", and much of this work would need to be rewritten in Java or maybe C++.

However, creating the Python prototypes would give us a lot of bang for our buck in enabling us to quickly deliver real results.

Have you been able to incorporate rapid prototyping - hopefully in Python - into a solid agile workflow in an enterprise environment?


答: In terms of learning, I'd add that prototyping gets you to learning, faster. That way, you can validate whether people even care about the problem you're trying to solve - and if the solution you have in mind is at all what they're looking for - without wasting a lot of time building a full solution that may, in the end, not solve a painful enough problem or not solve it the right way.</p>


问:
What's the best Git workflow for working with an open source project with employer-specific changes?
At my current employer, we are using an open-source project hosted on Github as a component of our application. I have been working on this project to both add some features that we need and to integrate it with our build systems. My manager and I are in agreement that we would like to submit as much of our work on this component as is reasonable back to the open-source project. My question is about what the best workflow/technique is to maintain my Git commits in such a way that I can easily seperate out things that make sense to add back to the open-source project - bug fixes and new features that are sufficiently general - from things that are specific to our project, like build locations and application constants.

What I have been doing so far is to maintain a private Git branch where I commit all of my changes, with appropriate granularity. I then use cherry-pick to add the open-sourceable commits to the master branch, and submit those back to Github.

It seems like I ought to be using merge to do this, so that I don't keep creating separate commits with identical contents, but I'm not sure how to do this while excluding the company-specific commits and keeping a reasonable workflow.

For example, I suppose I could commit open-sourceable things on master and company-specific things on the private branch, and then merge master into that branch as needed, leaving the master branch pointing at the commit before the merge, such that I could commit open-sourceable things to it again and then merge again. What seems awkward about this workflow is that I would need to decide in advance for everything I do which branch it belonged on, work on that to what seemed like completion, then commit it and merge before testing. One of the things that I really like about Git is how easy it is to just do whatever you need to make your application work, and then decide later how and where to commit your changes. As far as I can tell, if you're currently on a branch and have some work done, there's no easy way to just submit some of that work to another branch, since changing to that branch would require a clean working directory.

Is what I'm doing a reasonable workflow for long-term contributions? Can anybody recommend a different workflow that might be better, and why it's better?

答:
Here's a strategy that might work for you:

Create 2 private git repos, with one repo being for company work and the other being the general (I'd like to commit back) repo.

In order to make this system work, you need to do this (which I consider the most important strategy): Define what is "general" and can be used by everyone else in the community

By having this definition, you can separate out what you will commit back and what you don't need to commit.

It makes sense that what you code for the community be in a general form, as too specific a piece of code will benefit nobody (and might not even make it to the master branch).

Now that you know what you're going to commit to the community, you can do most "give-back" work in the repo dedicated to it. Then you simply fork that repo over to your work-based repo and do any work-specific work on top of that.

I suspect that you will spend a lot more time in the "give-back" repo, so just remember to provide valuable comments, etc (maybe even documentation) for people who would use that project in the future.

I also believe that git can do a lot more than you think. I watched this video on Vimeo: http://vimeo.com/46010208 and she did a brilliant job of explaining a lot of wacky things git can do.

My strategy isn't the only one out there, but it can definitely be a starting point for you to think of 1 that suits you specifically.


答:
"Being agile" simply means adhering to the values and principles of the agile manifesto. Nothing in that document mentions TDD, or even unit testing for that matter.

So yes, you can be agile without doing TDD or unit testing.

I wouldn't recommend it though...

Title: Can you be Agile without doing TDD (test driven development)?

Body: Is is possible to correctly call yourself (or your team) "Agile" if you don't do TDD (Test-Driven Development)?</p>


问:
Dota 2 running on Linux, Mac and Windows - How do they do it?
How do Valve create games that run on Linux, Mac and Windows? I imagine they dont really write one version for each platform bec that would just be a nightmare.. or do they? I imagine it is written in a portable C++ code (or C#?) but I wanted to know more details about this.
I've developed an app on Adobe AIR and considering on porting it to a diff language as Adobe abandoned linux support.</p>

答:
Every Valve product is developed using their own in-house game engine called Source. The Source Engine is written in C++. The source engine contains both an OpenGL and a DirectX renderer which helps it in being cross platform, but the key is SDL. The open source Simple Direct Media Library is used by a team inside Valve which is tasked almost exclusively with taking Valve's popular products cross-platform. SDL allows Valve to focus less on writing redundant code that will work here, there, and everywhere and instead focus on fixing what needs to be changed to allow for the build to work on platform X, Y, and Z and let SDL take care of the rest.

SDL allows for this by creating a simple interface that works for every platform (well not every platform, but the ones that matter) when it comes to things like window management, context management, event handling, etc. Without SDL you would have to write code that makes a window for Windows, OSX and Linux just to get the basic window management stuff to work cross platform. In SDL, you call three functions and you have a window. See the reason why people use it now? SDL is at the heart of most of Valve's games today because they are beginning to think about cross-platform from the beginning.

Here is a good article about Linux support and the team that makes it possible at Valve.


答:
I'm not specifically talking about Dota2 but about most of cross-platform games in general.

Usually developers create/use a middle were called GameEngine. It's usually in a form of a large scale library containing tools for all sorts of things such as handling game physics, loading and rendering graphical objects, loading and running scripts, managing network related stuff, and so on...

That GameEngine thing can also provide support for those kind of things across multiple platforms. It provides developers with a unified interface, while having different implementations across different platforms. The same thing happens almost every time you see a cross platform application. Even C# itself that you mentioned is doing the same thing under the hood; it's providing a unified developing experience across all platforms, while handling platform-specific differences under the hood.

In case of valve (Dota2 and their other games) that GameEngine is called "Source Engine". while anything built on top of Source Engine is platform independent, the engine itself have different implementations for different operating systems. Here is an example: the engine might have a function to draw an sphere. In windows this routine is written using DirectX while in linux and mac it's using OpenGL.

It means higher level developers including those who are implementing game logic and pretty much everything in a game, won't even notice platform changes, but in it's base level code Dota2 (and pretty much any other game) is written once per platform.

Title: Dota 2 running on Linux, Mac and Windows - How do they do it?

Body:
How do Valve create games that run on Linux, Mac and Windows? I imagine they dont really write one version for each platform bec that would just be a nightmare.. or do they? I imagine it is written in a portable C++ code (or C#?) but I wanted to know more details about this.
I've developed an app on Adobe AIR and considering on porting it to a diff language as Adobe abandoned linux support.</p>


问:
What does "testing surface" mean in the context of programming?
I encountered the following text in an article on the ModelViewPresenter pattern and my brain blue-screened:

Passive View usually provides a larger testing surface than Supervising Controller because all the view update logic is placed in the presenter.

I haven't come across this particular jargon before and I'm rather puzzled about what exactly constitutes the "testing surface" of a design pattern.  Would someone please enlighten me regarding what the term means and also what it means for one design pattern to have a larger (or smaller) "testing surface" than another?

答:
The testing surface of an object is the collective area that is encompassed by the public properties, methods and constructors of that object (its Application Programming Interface, or API). The term "testing surface" is essentially a proxy term for how much programming effort will be required to unit test an object.

Things that can increase the testing surface of an object:

Objects that have a greater number of public members have a greater testing surface, because there are more end-points to test.

Members that have more complex logic in them have a greater testing surface, because a test is required for each "bifurcation" (e.g. the two sides of an if statement).

Members that have a greater number of parameters in them increase the testing surface, because it increases the number of different combinations of parameter values that the member uses.

Boundary conditions (such as nulls, transition between positive and negative numbers, and off-by-one conditions) increase the testing surface, because a greater number of tests are required to indentify and test those boundary conditions).

Exceptions to normal control flow (such as thrown exceptions) increase the testing surface, because you need tests to insure that those exceptions are accounted for, and that they are working properly under the right conditions.

Things that can decrease the testing surface of an object:

Good design practices.

A simpler API design

The practice of TDD (Test-Driven Design), which makes your code more testable in the first place, and decreases the need for exotic tests.

Design by Contract, if the programming language supports it directly, reduces the testing surface, because it already accounts for incorrect input or contract violations (assuming that the contract conditions are correctly specified).


答:
Rebasing provides a moving branch point which simplifies the process of pushing changes back to the baseline.  This allows you to treat an long running branch as if it were a local change.  Without rebasing, branches accumulate changes from the baseline which will be included in the changes being merged back to baseline.

Merging leaves your baseline at the original branch point.  If you merge a few weeks worth of changes from the line you branched off of, you now have a lot of changes from your branch point, many of which will be in your baseline.  This makes makes it difficult to identify your changes in your branch.  Pushing changes back to the baseline may generate conflicts unrelated to your changes.  In the case of conflicts, it is possible to push inconsistent changes.  Ongoing merges take effort to manage, and it is relatively easy to loose changes.

Rebase moves your branch point to the latest revision on your baseline.  Any conflicts you encounter will be for your change(s) alone.  Pushing changes is much simpler.  Conflicts are dealt with in the local branch by doing an additional rebase.  In the case of conflicting pushes, the last one to push their change will need to resolve the issue with their change.


答:
In two words:  git bisect

A linear history allows you to pinpoint the actual source of a bug.

An example.  This is our initial code:

```<code>def bar(arg=None):
    pass

def foo():
    bar()
</code>```

Branch 1 does some refactoring such that arg is no longer valid:

```<code>def bar():
    pass

def foo():
    bar()
</code>```

Branch 2 has a new feature that needs to use arg:

```<code>def bar(arg=None):
    pass

def foo():
    bar(arg=1)
</code>```

There will be no merge conflicts, however a bug has been introduced.  Luckily, this particular one will get caught on the compilation step, but we're not always so lucky.  If the bug manifests as unexpected behaviour, rather than a compile error, we may not find it for a week or two.  At that point, git bisect to the rescue!

Oh crap.  This is what it sees:

```<code>(master: green)
|             \_________________________
|                \                      \
(master: green)  (branch 1: green)     (branch 2: green)
|                 |                     |
|                 |                     |
(master/merge commit: green)            |
|                         ______________/
|                        /
(master/merge commit: red)
|
...days pass...
|
(master: red)
</code>```

So when we send off git bisect to find the commit that broke the build, it's going to pinpoint a merge commit.  Well, that helps a little, but it's essentially pointing at a package of commits, not a single one.  All ancestors are green.  On the other hand, with rebasing, you get a linear history:

```<code>(master: green)
|
(master: green)
|
(all branch 1 commits: green)
|
(some branch 2 commits: green)
|
(branch 2 commit: red)
|
(remaining branch 2 commits: red)
|
...days pass...
|
(master: still red)
</code>```

Now, git bisect is going to point at the exact feature commit that broke the build.  Ideally, the commit message will explain what was intended well enough to do another refactor and fix the bug right away.

The effect is only compounded in large projects when the maintainers didn't write all the code, so they don't necessarily remember why any given commit was done/what each branch was for.  So pinpointing the exact commit (and then being able to examine the commits around it) is a great help.

That said, I (currently) still prefer merging.  Rebasing onto a release branch will give you your linear history for use with git bisect, while retaining the true history for day-to-day work.

Body:
In two words:  git bisect

A linear history allows you to pinpoint the actual source of a bug.

An example.  This is our initial code:

def bar(arg=None):
    pass

def foo():
    bar()

Branch 1 does some refactoring such that arg is no longer valid:

def bar():
    pass

def foo():
    bar()

Branch 2 has a new feature that needs to use arg:

def bar(arg=None):
    pass

def foo():
    bar(arg=1)

There will be no merge conflicts, however a bug has been introduced.  Luckily, this particular one will get caught on the compilation step, but we're not always so lucky.  If the bug manifests as unexpected behaviour, rather than a compile error, we may not find it for a week or two.  At that point, git bisect to the rescue!

Oh crap.  This is what it sees:

(master: green)
|             \_________________________
|                \                      \
(master: green)  (branch 1: green)     (branch 2: green)
|                 |                     |
|                 |                     |
(master/merge commit: green)            |
|                         ______________/
|                        /
(master/merge commit: red)
|
...days pass...
|
(master: red)

So when we send off git bisect to find the commit that broke the build, it's going to pinpoint a merge commit.  Well, that helps a little, but it's essentially pointing at a package of commits, not a single one.  All ancestors are green.  On the other hand, with rebasing, you get a linear history:

(master: green)
|
(master: green)
|
(all branch 1 commits: green)
|
(some branch 2 commits: green)
|
(branch 2 commit: red)
|
(remaining branch 2 commits: red)
|
...days pass...
|
(master: still red)

Now, git bisect is going to point at the exact feature commit that broke the build.  Ideally, the commit message will explain what was intended well enough to do another refactor and fix the bug right away.

The effect is only compounded in large projects when the maintainers didn't write all the code, so they don't necessarily remember why any given commit was done/what each branch was for.  So pinpointing the exact commit (and then being able to examine the commits around it) is a great help.

That said, I (currently) still prefer merging.  Rebasing onto a release branch will give you your linear history for use with git bisect, while retaining the true history for day-to-day work.


问:
Do you actively think about security when coding?
When you're coding, do you actively think about your code might be exploited in ways it wasn't originally meant to do and thus gain access to protected information, run commands or something else you wouldn't want your users to do?</p>

答: No, because I do not work in a problem domain where security is relevant (massive data visualization SW). I do have a bunch of asserts in my code (index checking, consistency checking, etc.), not because of security concerns, but because I like wrong code to crash early and crash visibly.