答:
The Boost libraries for C++ include an article on dimensional analysis that presents a sample implementation of handling units of measure.

To summarize:  Units of measurement are represented as vectors, with each element of the vector representing a fundamental dimension:

```<code>typedef int dimension[7]; // m  l  t  ...
dimension const mass      = {1, 0, 0, 0, 0, 0, 0};
dimension const length    = {0, 1, 0, 0, 0, 0, 0};
dimension const time      = {0, 0, 1, 0, 0, 0, 0};
</code>```

Derived units are combinations of these.  For example, force (mass * distance / time^2) would be represented as

```<code>dimension const force  = {1, 1, -2, 0, 0, 0, 0};
</code>```

Imperial versus SI units could be handled by adding a conversion factor.

This implementation relies on C++-specific techniques (using template metaprogramming to easily turn different units of measurement into different compile-time types), but the concepts should transfer to other programming languages.

Title: Data structure for accessing units of measure

Body:
TL;DR - I'm trying to design an optimal data structure to define units within a unit of measure.

A Unit of measure is essentially a value (or quantity) associated with a unit.  SI Units have seven bases or dimensions.  Namely: length, mass, time, electric current, temperature, amount of substance (moles), and luminous intensity.

This would be straightforward enough, but there are a number of derived units as well as rates that we frequently use.  An example combined unit would be the Newton: kg * m / s^2 and an example rate would be tons / hr.

We have an application that relies heavily upon implied units.  We'll embed the units within the variable or column name.  But this creates problems when we need to specify a unit of measure with different units.  Yes, we can convert the values at input and display but this generates a lot of overhead code that we'd like to encapsulate within its own class.

There are a number of solutions out on codeplex and other collaborative environments.  The licensing for the projects is agreeable but the project itself usually ends up being too lightweight or too heavy.  We're chasing our own unicorn of "just right."

Ideally, I could define a new unit of measure using something like this:

UOM myUom1 = new UOM(10, volts);

  UOM myUom2 = new UOM(43.2, Newtons);

Of course, we use a mix of Imperial and SI units based upon our clients' needs.

We also need to keep this structure of units synchronized with a future database table so we can provide the same degree of consistency within our data too.

What's the best way of defining the units, derived units, and rates that we need to use to create our unit of measure class?  I could see using one or more enums, but that could be frustrating for other developers.  A single enum would be huge with 200+ entries whereas multiple enums could be confusing based upon SI vs Imperial units and additional breakdown based upon categorization of the unit itself.

Enum examples showing some of my concerns:

myUnits.Volt

  myUnits.Newton

  myUnits.meter

SIUnit.meter

  ImpUnit.foot
  DrvdUnit.Newton

  DrvdUnitSI.Newton

  DrvdUnitImp.FtLbs

Our set of units in use is pretty well defined and it's a finite space.  We do need the ability to expand and add new derived units or rates when we have client demand for them.  The project is in C# although I think the broader design aspects are applicable to multiple languages.

One of the libraries I looked at allows for free-form input of units via string.  Their UOM class then parsed the string and slotted things accordingly.  The challenge with this approach is that it forces the developer to think and remember what the correct string formats are.  And I run the risk of a runtime error / exception if we don't add additional checks within the code to validate the strings being passed in the constructor.

Another library essentially created too many classes that the developer would have to work with.  Along with an equivalent UOM it provided a DerivedUnit and RateUnit and so on.  Essentially, the code was overly complex for the problems we're solving.  That library would essentially allow any:any combinations (which is legitimate in the units world) but we're happy to scope our issue (simplify our code) by not allowing every possible combination.

Other libraries were ridiculously simple and hadn't even considered operator overloading for example.

In addition, I'm not as worried about attempts at incorrect conversions (for example: volts to meters).  Devs are the only ones who will access at this level at this point and we don't necessarily need to protect against those types of mistakes.

Body:
The Boost libraries for C++ include an article on dimensional analysis that presents a sample implementation of handling units of measure.

To summarize:  Units of measurement are represented as vectors, with each element of the vector representing a fundamental dimension:

typedef int dimension[7]; // m  l  t  ...
dimension const mass      = {1, 0, 0, 0, 0, 0, 0};
dimension const length    = {0, 1, 0, 0, 0, 0, 0};
dimension const time      = {0, 0, 1, 0, 0, 0, 0};

Derived units are combinations of these.  For example, force (mass * distance / time^2) would be represented as

dimension const force  = {1, 1, -2, 0, 0, 0, 0};

Imperial versus SI units could be handled by adding a conversion factor.

This implementation relies on C++-specific techniques (using template metaprogramming to easily turn different units of measurement into different compile-time types), but the concepts should transfer to other programming languages.


问:
Time consuming Unit test for support for 100,000 records: Am I doing it right?
I am working on adding test coverage for an application that previously didn't have any. One additional requirement that emerged is that one of the background processes should be able to process 100,000 rows at a time.

I've written a unit test that ensures that the background process is able to work with the 100,000 entities without crashing the interpretter (PHP) on a 4.0MB memory limit. But each test run takes close to 4 minutes to finish. All other tests take just 10 seconds to run.

Can this be approached differently than a unit test?

答:
This is more along the lines of a load test.  Unit tests should be about whether the code produces correct results.  Load tests are geared toward testing whether the system meets certain volume and timing requirements, and are typically run at a higher level of evaluation than unit tests.

If the system could only handle 99,000 records, what level of failure is that and what does it mean.  What if it was desired to process 100,000 records in three minutes but your test indicates it took 4 minutes.  Load tests are not so much about absolute failure or success.  They are more aligned to testing minimum levels of performance and provide guidance toward needed scalability enhancements.

Edit:
Sorry, I guess I didn't really answer your title question.  I would say that this is a valuable test, but I think you are doing it wrong to consider this as part of your unit tests.

ContentLicense: CC BY-SA 3.0


问:
Data structure for accessing units of measure
TL;DR - I'm trying to design an optimal data structure to define units within a unit of measure.

A Unit of measure is essentially a value (or quantity) associated with a unit.  SI Units have seven bases or dimensions.  Namely: length, mass, time, electric current, temperature, amount of substance (moles), and luminous intensity.

This would be straightforward enough, but there are a number of derived units as well as rates that we frequently use.  An example combined unit would be the Newton: kg * m / s^2 and an example rate would be tons / hr.

We have an application that relies heavily upon implied units.  We'll embed the units within the variable or column name.  But this creates problems when we need to specify a unit of measure with different units.  Yes, we can convert the values at input and display but this generates a lot of overhead code that we'd like to encapsulate within its own class.

There are a number of solutions out on codeplex and other collaborative environments.  The licensing for the projects is agreeable but the project itself usually ends up being too lightweight or too heavy.  We're chasing our own unicorn of "just right."

Ideally, I could define a new unit of measure using something like this:

UOM myUom1 = new UOM(10, volts);

  UOM myUom2 = new UOM(43.2, Newtons);

Of course, we use a mix of Imperial and SI units based upon our clients' needs.

We also need to keep this structure of units synchronized with a future database table so we can provide the same degree of consistency within our data too.

What's the best way of defining the units, derived units, and rates that we need to use to create our unit of measure class?  I could see using one or more enums, but that could be frustrating for other developers.  A single enum would be huge with 200+ entries whereas multiple enums could be confusing based upon SI vs Imperial units and additional breakdown based upon categorization of the unit itself.

Enum examples showing some of my concerns:

myUnits.Volt

  myUnits.Newton

  myUnits.meter

SIUnit.meter

  ImpUnit.foot
  DrvdUnit.Newton

  DrvdUnitSI.Newton

  DrvdUnitImp.FtLbs

Our set of units in use is pretty well defined and it's a finite space.  We do need the ability to expand and add new derived units or rates when we have client demand for them.  The project is in C# although I think the broader design aspects are applicable to multiple languages.

One of the libraries I looked at allows for free-form input of units via string.  Their UOM class then parsed the string and slotted things accordingly.  The challenge with this approach is that it forces the developer to think and remember what the correct string formats are.  And I run the risk of a runtime error / exception if we don't add additional checks within the code to validate the strings being passed in the constructor.

Another library essentially created too many classes that the developer would have to work with.  Along with an equivalent UOM it provided a DerivedUnit and RateUnit and so on.  Essentially, the code was overly complex for the problems we're solving.  That library would essentially allow any:any combinations (which is legitimate in the units world) but we're happy to scope our issue (simplify our code) by not allowing every possible combination.

Other libraries were ridiculously simple and hadn't even considered operator overloading for example.

In addition, I'm not as worried about attempts at incorrect conversions (for example: volts to meters).  Devs are the only ones who will access at this level at this point and we don't necessarily need to protect against those types of mistakes.

答:
If you can pull switching to F# instead using C#, F# has a units of measure system (implemented using metadata on values) that looks like it'll fit what you're trying to do:

http://en.wikibooks.org/wiki/F_Sharp_Programming/Units_of_Measure

Notably:

```<code>// Additionally, we can define types measures which are derived from existing measures as well:

[<Measure>] type m                  (* meter *)
[<Measure>] type s                  (* second *)
[<Measure>] type kg                 (* kilogram *)
[<Measure>] type N = (kg * m)/(s^2) (* Newtons *)
[<Measure>] type Pa = N/(m^2)       (* Pascals *)
</code>```

Body:
If you can pull switching to F# instead using C#, F# has a units of measure system (implemented using metadata on values) that looks like it'll fit what you're trying to do:

http://en.wikibooks.org/wiki/F_Sharp_Programming/Units_of_Measure

Notably:

// Additionally, we can define types measures which are derived from existing measures as well:

[<Measure>] type m                  (* meter *)
[<Measure>] type s                  (* second *)
[<Measure>] type kg                 (* kilogram *)
[<Measure>] type N = (kg * m)/(s^2) (* Newtons *)
[<Measure>] type Pa = N/(m^2)       (* Pascals *)


问:
serving up future-proof kinfolk - extensible contract interfaces
Ok, I have this human here, but what can it do, how would you discover its special abilities? And when you find out what kind of expert you've got then how would you actually make use of its unique responsibilities?

An example for this architectural pattern question:

Base Interface with Characteristics Common to All

```<code>interface IHuman {
    DateTime GetDoB();
}
</code>```

Extended Interface 1

```<code>interface ICivilian : IHuman {
    string GetEmail();
    void SendEmail();
}
</code>```

Extended Interface 2

```<code>interface IAccountant : IHuman {
    double CalculateProfits();
}
</code>```

Extended Interface n+

```<code>interface IAnotherSpecializedHuman : IHuman {
    void DoSomethingExpert();
}
</code>```

Specialized API Discovery and Usage

How would you design

a highly pluggable and loosely-coupled system

with which you can carry out all the common human operations (e.g. get age),

but also carry out any specialized operations that are available,

depending on which modules are incorporated

e.g. you can send email, because ICivilian module is provided

but you cannot calculate profits, because IAccountant plug-in is not provided

and the question is not so much about providing different implementations but about providing different specialized APIs (and APIs that have a common parent with shared functionality)

答:
First things first, I would not have different APIs share a common parent. As soon as you run into alien accountants or want to get the age of a dog, you're out of luck.

I would (and have) dealt with this via Component Based Entity designs. Instead of making a solid object that implements a ton of interfaces, you have a very thin object that contains a ton of interfaces. The user can then query "do you have some capability that satisfies this contract?". The consumer still needs to know about all of the contracts it wants to use, but the entity is free to construct, aggregate, or otherwise supply these (or not!) at its discretion. Need a new capability? Just add the new one to the collection and give the contract to end users to ask for.

The traditionally hard part with these designs is how to split up the contracts. Invariably the different components of the entity need to talk to each other, or share some common data. How you solve that tends to be specific to your particular problem.


问:
Heap overflow vs stack overflow
So as a general rule to avoid a stack overflow, big objects should be allocated to the heap (correct me if I am wrong). But, since the heap and the stack expand towards each other, wouldn't this cause heap overflow or alternatively limit the space for the stack and higher the chances of stack overflow?  </p>

答:
Given the assumptions below, yes -- does not really matter whether you pile it on the floor or hang it from the ceiling.

You question indicates that you choose between heap or stack, only. (And we are not talking about very big objects that might be better mmap'd and other less common scenarios).

Assumption

Stack and heap live in the same, fixed process memory region, and there exists no other limitation.

Your new big object will be added to the end of the heap respective stack.

Objects on the stack are deallocated when the function returns. To make this choice really symmetric we assume that this holds true when using the heap as well.

Now what happens if we remove these assumptions?

Stack can be limited, for example on old OS or in multi-threaded applications each thread might get its own size-limited stack, then allocating big objects on stack might overflow it. Heap on the other hand is typically backed up by virtual memory management which allows it to grow during process life time.

Normally your heap will contain holes: space leftover from objects being deallocated, if you are lucky your new object fits just inside of such hole. Such a hole could for example open when two or more smaller objects, allocated at adjacent addresses have been deallocated. Often allocations using heap can be satisfied without growing the heap. On the other hand using the heap for small objects could invite memory fragmentation (see also Mozilla), this depends a lot on the allocator.

In contrast, creating a variable on stack grows the stack by the same amount.

Assume that you want return your object to the calling function instead. Then big objects on the stack must be copied as whole! It is more efficient in both time and space to return a pointer to memory address of the heap instead, which conviently fits inside a register easily. Small objects (such as integers, float, doubles) often fit into a register (typically 4 or 8 bytes) or two. Fortunately modern compiler optimize this case so we do not have to worry about this so much.

Resume: the exact behavior depends a lot on your OS and your compiler, on Linux only the sky it the limit.

Addendum
related SO question

OwnerDisplayName: Rayhunter

Title: Heap overflow vs stack overflow


答:
Based on the fact that all required conversions are scaling conversions (except if you have to support temperature conversions. Calculations where the conversion involves an offset are significantly more complex), I would design my 'unit of measure' system like this:

A class unit containing a scaling factor, a string for the unit's textual representation and a reference that the unit scales to. The textual representation is there for display purposes and the reference to the base unit to know which unit the result is in when doing math on values with different units.

For each supported unit, a static instance of the unit class is provided.

A class UOM containing a value and a reference to the value's unit. The UOM class provides overloaded operators for adding/subtracting another UOM and for multiplying/dividing with a dimensionless value.

If addition/subtraction is performed on two UOM with the same unit, it is performed directly. Otherwise both values are converted to their respective base units and the added/subtracted. The result is reported as being in the base unit.

Usage would be like

```<code>unit volts = new unit(1, "V"); // base-unit is self
unit Newtons = new unit(1, "N"); // base-unit is self
unit kiloNewtons = new unit(1000, "kN", Newtons);
//...
UOM myUom1 = new UOM(10, volts);
UOM myUom2 = new UOM(43.2, kiloNewtons);
</code>```

As operations on incompatible units are not considered an issue, I have not tried to make the design type-safe in that respect. It is possible to add a runtime check by verifying that two units refer to the same base unit.

Body:
Based on the fact that all required conversions are scaling conversions (except if you have to support temperature conversions. Calculations where the conversion involves an offset are significantly more complex), I would design my 'unit of measure' system like this:

A class unit containing a scaling factor, a string for the unit's textual representation and a reference that the unit scales to. The textual representation is there for display purposes and the reference to the base unit to know which unit the result is in when doing math on values with different units.

For each supported unit, a static instance of the unit class is provided.

A class UOM containing a value and a reference to the value's unit. The UOM class provides overloaded operators for adding/subtracting another UOM and for multiplying/dividing with a dimensionless value.

If addition/subtraction is performed on two UOM with the same unit, it is performed directly. Otherwise both values are converted to their respective base units and the added/subtracted. The result is reported as being in the base unit.

Usage would be like

unit volts = new unit(1, "V"); // base-unit is self
unit Newtons = new unit(1, "N"); // base-unit is self
unit kiloNewtons = new unit(1000, "kN", Newtons);
//...
UOM myUom1 = new UOM(10, volts);
UOM myUom2 = new UOM(43.2, kiloNewtons);

As operations on incompatible units are not considered an issue, I have not tried to make the design type-safe in that respect. It is possible to add a runtime check by verifying that two units refer to the same base unit.


问:
Find the peak of each islands in sparse matrix
I have a sparse matrix that contains several islands of unknown size. I would like to find the highest peak of each islands. Consider this matrix as an example:

```<code>0 0 1 0 0 0 0
0 0 1 2 1 0 0
0 0 0 3 2 1 0
0 1 0 0 0 0 0
0 2 3 4 0 1 0
0 0 1 1 0 1 0
0 0 0 0 0 1 0
</code>```

In this case I would like to get the position of 3 at (3, 2), the position of 4 at  (3, 4) and the position of 1 at (5, 4), (5, 5) or (5, 6). Note: I consider 4-connected neighbours.

Until now I came up with the solution that scans each pixel and if it is not zero it starts a flood fill from that pixel. The flood fill paints the pixels to zero keeping track the maximum value visited. This algorithm works well but I was wondering if there are any faster solution?

In my target platform (iOS) I have access to different vector processing frameworks like BLAS, LAPACK, vDSP that provide some functions for fast finding the maximum value in a vector (or matrix). Maybe one could implement a faster solution with the help of these functions?

答:
Sounds like a variation of blob coloring.  (Google is your FRIEND!)

You're going to make a list of blobs, initially empty.  Scan for a nonzero value.  When you find one, do 4-way-connectivity to find the blob pixels, and call the "color" the highest value.  When you run out of 4-way-connected pixels, restart your scan to find a new blob.


问:
For a socket based application : how must I handle dynamic ip adress?
I plan to write an network application whose use steps is the following :

Connect to the server and choose a name (and enter your email "id")

The list of others "free" (not playing a game) players is shown to you : so you have to select one.

The server use the two players ip adress in order to connect them

But I think I will be facing a great issue :

how to handle dynamic ip adress carefully : can a dynamic ip adress change while the established connection is not yet finished ?

if yes, how must I handle that, let's with Java 7 for example ?

Regards

答:
Once someone has been assigned an IP it will not change until they log off (basically).
So yes it can - in between getting a list of users and selecting one to play with, the person on the other end might disconnect, or be disconnected, or log off, or suffer a power cut or any other reason why they may no longer be available to play.

So you simply need to ensure that the person selected is still available when selected, so just attempt a connection and handle failures. The IP address will not change between the discovery and selection process so you don't need to worry about making connections to some random person, not unless the time between the 2 steps is very long.


问:
Scrum: Short VS long sprint
We were trying to figure out the optimal sprint length for our project. After working on a 3-weeks basis we thought that cutting the sprint to 2-weeks would provide better velocity.

The advantages were clear - shorter feedback loop, small stories (with user value) and so on.
On the other hand, there are a lot of disadvantages such as ceremonies (planning, retrospective) and so on in which we don't produce and now happen more often.

I was wondering how, for a new team, can we decide on optimal sprint length?

答:
I question your suggestion of a "shorter feedback loop".  Your team should be working with your customers on a daily basis--feedback should not wait for the Sprint Review and Retrospective.  Test, code, design, and get feedback immediately.

I personally like the three week sprint because the middle week allows the team some "flow" time.  That is, there is always so time revving up the first week (learning what the heck these new stories mean) and some wrapping up the last (prepping for the review).  A middle week to simply produce working software is a really nice thing to have.

Taking this logic further, four week sprints would make even more sense.  However, the sense of urgency can be lost if you start extending your sprints.  Moreover, there really is a relatively small chunk of information a person or team can grasp and hold in their conscious thought at one time--the longer the sprint, the more stuff you are trying to focus on, which can make things harder rather than easier.  Also, it's harder to judge what external factors will creep in if you extend things too far out.

Title: Scrum: Short VS long sprint


问:
I don't know C. And why should I learn it?
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.

答:
C (and possibly C++) is the sea you are swimming in. The OS that will run your code is probably coded in C (and C++). So your native API to access OS services will be in C.

If you can do without knowing what is there below, there is no need to know C. However most programmers need to dive into lower levels at sometime in their lives.

It is also based on your specialization of development areas. For example a web developer who writes HTML, Javascript and some server side scripting may never need to know anything about C, but a distributed system or game developer will.

It never hurts to spend a few weeks learning something so fundamental for your profession.


答:
Procoatively asked: Are you asking for confirmation that you do not have to learn C? If you learn pure C (not C++ necessarily) you will get a thorough understanding of the execution model of a computer. Especially about memory and allocation. This stuff also matters to people programming in higher level langauges.

For a PHP programmer its just less transparent how code is executed on the given machine. It might not matter for the PHP programmer since Network transfer is the bottle neck in the application, etc.

Plain PHP/Python/C# has a lot of abstraction layers between the language and the CPU. these layers are so thick that they do not allow you to look through them. When you learn C, there is a thin sheet between you and the CPU and the operating system. That does not make programming easier (and it might not even be better). But you are actually able to learn how the CPU works. Once you know the "intermediate" C, you can actually start to link that knowledge upwards to the  higher level language. This is the immediate benefit that you will gain.

In my opinion a programmer should always spent some time learning different programming concepts. It definitely pays of to have a look at C, but also to have a look at even higher level programming languages such as Clojure, Haskell, Prolog.

You don't have to become a master in these, they will just teach you the lesson that "levels" of programming languages are not binary but there are a lot of levels. Get to know them, from top to bottom (Assembler). It will make you a better programmer.

Title: I don't know C. And why should I learn it?

Body:
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.


答:
You need to know enough C to read code written in C, because of the vast amount of very important code written in the language. That's about all you will retain from going well through a thorough manual on the subject (I used Kochan's "programming in C") without actually having to code in the language, anyway. Should you ever wind up in a situation requiring you to use the language extensively, you will have a good base to build on. You probably want to study something like Duntemanns Assembly book if the machine is an abstacted black box to you. I also recommend Petzold's "Code".

Outside of that--basic literacy in C and basic familiarity with the underlying machine--you'd be best served spending your study time on the real stuff, like SICP, TCP/IP Illustrated or books on Concrete Mathematics, algorithms or data structure. The real stuff.

Spending a lot of time studying C while coding in PHP simply isn't worth the opportunity cost. There's more helpful things to learn. C really is just another language that you can learn well only though study and use, but can pick up when you need to.

Sweat the hard stuff.


问:
Large teams with layered application
I work in a fairly large team (~15 developers) which is currently discussing our working methodology. The software we work on is quite feature-rich and expanding rapidly in terms of scope so the number of developers has increased lately and will continue to increase. At the moment the different developers have different focus areas which they happen to be good at. Some focus on user interface, some on business logic and some on backend. But a UI developer may add something to the backend if he feels like doing it.

As the number of developers grow, we can no longer work in the same team (it's kind of hard to try to follow what 20 other people are doing). Multiple teams working in the same code base could get messy if people are changing "other peoples' code".

We are discussing some alternative ways to divide our tasks, and different people argues for different ways:

Some think that the current way of doing things is good enough. Sure, a guy who focuses on the UI could make changes to the backend business logic and potentially mess things up. But at the same time we trust him not to mess up too much. Reviews of changes could be enough to make sure that the quality stays good.

Some prefer that a team is assigned to a specific layer. For example, a team (2-3 developers) could be assigned to work only business logic implementation in backend, while another team could be assigned to work on frontend and a third could focus on the persistence stuff. This would encourage people to be experts in their layer. The down side is that if a UI developer needs something in the backend, there's an overhead with planning if the person doing the backend is in another team.

A third suggested way is to have teams with members knowing all layers. So one team would focus on a specific type of functionality, and then include members knowing about UI, business logic, backend, etc. This would give the benefit that a team won't need to wait for another team to finish to implement a new feature affecting all layers. The downside people see here is that this could lead to more split-focus between the developers, which could lead to lower quality.

I'm not sure what I'm asking here, but if someone has experience, or know any about any good reading material about this subject it would be appreciated.

答:
My preference would be that each small team specialize in one layer, with that layer being their primary area of responsibility, but that they be cross-trained in the other layers and be able to work in those other layers should the need arise.

Hopefully you have well-defined architectural layers and interfaces between those layers so that, however you assign your developers, they can work in a particular layer without negatively impacting the rest of the application.

Title: Large teams with layered application


答:
Regardless of the structure you choose, the quality of the communication within the team is possibly the most critical factor to  your success (assuming of course that the developers have good enough skills).

I am currently working in a project team of 20 developers, for a large layered application.  I manage 9 and my colleague manages 9, while we jointly manage the project.  We have developers who specialize in the same areas you discuss.  Some of them also have some experience in the other layers and feel confident in making changes there.  We have fluid sub-groups which we assemble for each feature based on the need.  We stress communication as a constant part of the process.  This includes meetings (minimal), WIKIs and just going to someone's desk.  The team members are willing to help each other out and share their knowledge.  When change happens to the code it can impact all the layers directly or indirectly and it is important to maintain that communication.

You mentioned "other peoples' code", and while some on this site have pointed out that the company owns the code,not the developer, it can still be unsettling to be the only developer touching a portion of the code for a while when suddenly someone else makes a change without informing you and you have to fix the outcome.  If those two developers talk before the updates happen, the developer experienced with the code can at least provide some background and issues can be avoided.  Good communication can again save the day.

Title: Large teams with layered application

Body:
I work in a fairly large team (~15 developers) which is currently discussing our working methodology. The software we work on is quite feature-rich and expanding rapidly in terms of scope so the number of developers has increased lately and will continue to increase. At the moment the different developers have different focus areas which they happen to be good at. Some focus on user interface, some on business logic and some on backend. But a UI developer may add something to the backend if he feels like doing it.

As the number of developers grow, we can no longer work in the same team (it's kind of hard to try to follow what 20 other people are doing). Multiple teams working in the same code base could get messy if people are changing "other peoples' code".

We are discussing some alternative ways to divide our tasks, and different people argues for different ways:

Some think that the current way of doing things is good enough. Sure, a guy who focuses on the UI could make changes to the backend business logic and potentially mess things up. But at the same time we trust him not to mess up too much. Reviews of changes could be enough to make sure that the quality stays good.

Some prefer that a team is assigned to a specific layer. For example, a team (2-3 developers) could be assigned to work only business logic implementation in backend, while another team could be assigned to work on frontend and a third could focus on the persistence stuff. This would encourage people to be experts in their layer. The down side is that if a UI developer needs something in the backend, there's an overhead with planning if the person doing the backend is in another team.

A third suggested way is to have teams with members knowing all layers. So one team would focus on a specific type of functionality, and then include members knowing about UI, business logic, backend, etc. This would give the benefit that a team won't need to wait for another team to finish to implement a new feature affecting all layers. The downside people see here is that this could lead to more split-focus between the developers, which could lead to lower quality.

I'm not sure what I'm asking here, but if someone has experience, or know any about any good reading material about this subject it would be appreciated.


问:
Visual Studio DBProjects and problem with it running post-build SQL (file too big)
What I am doing is creating a DBProject.. importing a DB.. then creating scripts in the PostBuild that are DATA scripts for each table (so that the post build can populate the tables after the schema is generated..

Then problem is some of these tables containg 50,000 rows and when you put a 50,000 row insert into ONE .sql file for the post build it fails because it is too big.. so.

Is there a better way to achieve this ? (getting a schema and data of a DB created as part of a DBprojects Build/Publish)

If this way is valid.. Is the only thing to do is create another post build process that manually breaks the one big .sql file into smaller .sql files ? (so it can build/publish)

答: We had a similar situation (actually we were using Entity Framework to create and populate the database) where we were populating a table of address data. Basically, we exported the address data into a csv file and used the SQL Bulk Insert command to process it (which took seconds instead of minutes to do). Possibly doing the same within the post build of your DBProj would fix your problem.</p>


问:
Are there any practical uses of allowing recursive inclusion of a file?
I am currently implementing NASM-like preprocessor for my assembler, and I am wondering what is the correct way of handling recursively included files. From what I see, there are two ways to deal with it without hanging the preprocessor or even the OS:

Set maximum include depth.

Disallow including a file recursively (not to be confused with disallowing including a file twice).

Also, as far as I can see, the second approach does essentially the same job, but produces nicer error messages. Compare output of Clang, when compiling file containing #include "main.cpp" only:

```<code>In file included from main.cpp:1:
[ repeated many times ]
In file included from main.cpp:1:
main.cpp:1:10: error: #include nested too deeply
#include "main.cpp"
</code>```

with this (current way of handling this in my preprocessor; input is similar to above, does %include "1.mov.asm" at line 6):

```<code>In file /home/griwes/projects/reaverasm/tests/1.mov.asm in line 6:
Error: file `/home/griwes/projects/reaverasm/tests/1.mov.asm` included recursively.
</code>```

The approach disallowing recursive inclusion produces - IMHO - more readable output.

The question is: is there any preprocessor technique that would be killed by disallowing recursive inclusion? This question is language-agnostic, so feel free to give examples from any languages.

答: The Boost.Preprocessor library extends and abuses the C/C++ preprocessor in strange and wonderful ways.  One of its features is file iteration, which lets you #include a file multiple times with different macros #define'd each time, and they note that it can be useful (and is supported) for a file to iterate over itself.  (Search the examples here for BOOST_PP_IS_ITERATING.)  This is an example of (limited) recursion.


答:
The stack's forte is ultra-fast allocation and deallocation of memory that follows a LIFO pattern (last allocated is first deallocated). If you need memory that will follow a different allocation/deallocation pattern then you are going to have to get it from the heap.

Note that for common multiprocessing operating systems every process gets its own stack and its own heap. Typically the stack for a process is only 1MB to 5MB. The small size is why you should avoid allocating large structures on the stack. In contrast the heap can grow to consume as much of the physical memory as the OS will allow. Yes, you can eventually use up all the heap that the OS will grant you, but that's going to typically be a factor of a 1000 times the size of the stack.

Title: Heap overflow vs stack overflow

Body: So as a general rule to avoid a stack overflow, big objects should be allocated to the heap (correct me if I am wrong). But, since the heap and the stack expand towards each other, wouldn't this cause heap overflow or alternatively limit the space for the stack and higher the chances of stack overflow?  </p>


问:
Real-time collaborative text editing (ie gdocs) - is it a viable software development tool?
"Google Docs" allows for real-time, collaborative document editing. Multiple document viewers are able to simultaneously read and change a document's content so that one user's updates are instantly applied and visible to all other viewers.

Are there any software/web-app IDEs
that facilitate this type of
collaboration for writing code?

Which processes (ie pair programming)
stand to benefit from a system like
this and which don't?

Does this model for collaborative
editing present a viable alternative
to the current source control systems
generally used by teams of software
developers working on a single code
base?

Related but less general

答:
Collaborative code writing tools

Visual Studio.Net has a plugin called wave-vs.net that allow real-time collaborative editing to support pair programming features.

Eclipse has two plugins called DocShare and Saros, that allow real-time collaborative editing of documents (DocShare) or projects (Saros).

(the above quoted from wikipedia)

Which processes benefit?

Obviously pair programming. Off the top of my head I can't think of any immediate show-stoppers when considering the improvement the GDocs experience brings, and extending that improvement to collaborative coding.

I think the collaborative approach would work best if multiple people are working on sections of code that can be considered 'close'. It can also improve round-trip time for changes, as you don't have to wait for a commit-update cycle to have the latest version.

Are they an alternative to VCS?

They are complementary. They both serve the same purpose of streamlining contributions from team members. But there is a fundamental difference in their approach: Current VCS'es mostly document snapshots of a project, while collaborative editing documents fine-grained changes, capturing the thought process of a developer.

Furthermore, commits in a VCS are neatly organised as a change set. In a collaborative environment, on the other hand, you can't even ensure the code will compile at any moment before completion of the whole project, because someone else might always be in the middle of writing a line of code. Change is continuous. Therefore it might not be possible to unravel the contributions into change sets.

ContentLicense: CC BY-SA 2.5


问:
Whatever happened to Pascal?
In reading this blog post about Photoshop 1.0 I was surprised to learn that it was written in Pascal (Object Pascal to be exact).  But you never hear about Pascal anymore.  Why is that?</p>

答: In a word: Fragmentation. Delphi and TurboPascal took a lot of the users and set them on their own paths. Then there's the official ISO standard (more like a couple) vs what the original author considers the standard. The mainframe crowd and the PC crowd didn't agree what was what. Nobody really wants to learn 5 different languages to get things done. One true unified language being standard helps a lot. Instead of making Pascal better, the offshoots became competitors to the original.

Title: Whatever happened to Pascal?


答:
This is something that you do not need to worry about.  The heap and the stack are managed seperately.  More specifically the heap is backed up by virtual memory so if you overallocate it the OS will page things out.  The stack is a seperate thing that does not normally expand beyond a certain size.  It does not freely allocate from the heap.

The reason that they say allocate the big stuff from the heap is that the heap can handle that and the stack, a fixed size, cannot.

If you look more closely at the stack you might think that it can keep growing forever, or until memory is exhausted, and you are right.  However most/all OSes monitor the size of the stack and will prevent it from continously growing.

Lastly when you allocate data off of the heap it is managed data.  What I mean by this is that the OS is allocating/deallocating the data when you need it and when its out its out.  If the heap were to run out malloc would return a NULL.  Note that on most OSes virtual memory backs this up so malloc will always return something.

Title: Heap overflow vs stack overflow


问:
Two-Dimensional vector in C++ – inefficient with dynamic-sized sub vectors?
I know that std::vector uses a contiguous block of memory, but I often see people use vectors of vectors, even when they modify the number of elements in these vectors contained within an outer vector. Won't this lead to efficiency problems when an inner vector need to be resized as all the following vectors will have to have their elements moved as well?

In other words, in the following code, won't growing lists[0] trigger the moving of the elements of the 99 sub vectors following it too, and not just lists[0]?

```<code>std::vector<std::vector<int>> lists;
lists.resize(100);

// use and grow sub vectors
// ...
lists[0].push_back(88); // ← !
</code>```

答:
std::vector stores its elements in a contiguous block of memory as you described, but that doesn't mean that the whole vector object resides in a contiguous piece of memory. While it's implementation dependent, it's most likely safe to assume that the vector object itself contains some data that is mostly "management overhead" like the size of the vector and a pointer to the payload data instead of the payload data itself. That way it's much easier to do efficient move assignments or reallocations.

For example if you look at the vector implementation in Visual C++, you'll find that its data members are actually just a few pointers.

So in your scenario of a vector of vectors, the data stored in the "inner" vector simply contains the management data but not the payload for the nested vector. Thus, extending or shrinking the nested vector will not cause elements in the outer vector to move around in memory.


答:
What you tried to do it for the functional testing.

Unit tests have to be FIRST (Fast Isolated Repeatable Self-verifying

The faster your tests run, the more often you’ll run them. Tests take half a minute to run? You’ll maybe run them every 5 minutes instead of every few seconds. Tests take over two minutes to run? You might run those tests once every half hour, and you can write a lot of questionable code in that time! Tests take ten, fifteen, or more minutes to run? Forget it. You’ll run those a few times per day at best.

Title: Time consuming Unit test for support for 100,000 records: Am I doing it right?

Body:
I am working on adding test coverage for an application that previously didn't have any. One additional requirement that emerged is that one of the background processes should be able to process 100,000 rows at a time.

I've written a unit test that ensures that the background process is able to work with the 100,000 entities without crashing the interpretter (PHP) on a 4.0MB memory limit. But each test run takes close to 4 minutes to finish. All other tests take just 10 seconds to run.

Can this be approached differently than a unit test?


问:
Threads or ThreadPool? Fixed or Dynamic ThreadPool?
I have a java program which listens on a port for input. Based on Input, it calls a webservice and then returns a success/failure back to the client program.

I fork a thread for each client connection. The response back to the client which connects to the program has to be quick.

These are the choices I am considering

use regular threads

use ExecutorService with newFixedThreadPool

use ExecutorService with newCachedThreadPool

The reason I am considering Pools is because my threads are shortlived - they just call a webservice, return result to the client and close the connection.

I don't think newFixedThreadPool would be the right thing because then connections would be waiting in queues to get a thread.

newCachedThreadPool would have been perfect except for one thing - threads die after a minute. In my case, I get bursts of connections - i.e. multiple connections and then there may be a lull for a few minutes and then again bursts. I think the threads in the CachedThreadPool would die and and would again have to be recreated - so in this case, it may work like #1 sometimes.

Ideally I would have loved to have newCachedThreadPool with a minimum - i.e. a setting which says number of threads would never go below say 20. So idle threads are killed but never allow to go below a minimum threshold.

Is there anything like this available? Or are there any better alternatives?

答:
The methods in the Executors class are just convenience methods for common use cases.  There are a lot more options available for creating thread pools.

To create the same thing that Executors.newCachedThreadPool() does but with a minimum of 20 threads (this is copied from the method in Executors, with the core thread size changed from 0 to 20).

```<code>        return new ThreadPoolExecutor(20, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
</code>```

Body:
The methods in the Executors class are just convenience methods for common use cases.  There are a lot more options available for creating thread pools.

To create the same thing that Executors.newCachedThreadPool() does but with a minimum of 20 threads (this is copied from the method in Executors, with the core thread size changed from 0 to 20).

        return new ThreadPoolExecutor(20, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());


答: On the Mac, at least, C, C++, and especially OOP happened to Pascal. The original Macintosh Toolbox API was specified using Pascal interfaces and calling conventions, and Pascal was the language of choice for early Mac programmers. C arrived on the platform fairly early, and Pascal and C coexisted for a number of years while programmers on each side argued about which language was better. Compiler vendors (Apple, Think/Symantec, and later metrowerks) provided compilers for Pascal, C, and C++, often in a single product. At the same time, the benefits of object oriented programming were becoming obvious. Apple's OOP framework was MacApp, written in Object Pascal, and this was surely the framework used to build the first versions of Photoshop (and many other important products). As C++ gained popularity and other OO frameworks appeared written in C++ (Think Class Library from Symantec, followed later by PowerPlant from metrowerks) Apple gave in and rewrote MacApp in C++. That was pretty much the end of Pascal in regular use on the Mac, save for maintaining older code.

Title: Whatever happened to Pascal?

Body: In reading this blog post about Photoshop 1.0 I was surprised to learn that it was written in Pascal (Object Pascal to be exact).  But you never hear about Pascal anymore.  Why is that?</p>


问:
Jenkins to automate deployment of ASP.NET applications
Is there any possibility to automate/semi-automate deployments of ASP.NET web applications using Jenkins. It can be under controlled or uncontrolled environments, for uncontrolled user needs to enter userid and password. I am looking out for ways to copy the files from target to destination and run sql scripts in web farm scenario.

Edit
Currently we are using bat files to xcopy/configure app pool/sql cmd, etc to deploy the application. But for this to work, production support team needs to download the source code, build the project and run the bat files to deploy the application.

Now, we want to automate the deployment without user downloading the source code and end user just needs to visit a url and fill userid and password parameters and select svn tag and it should get deployed. But Jenkins is running under anonymous login, so the existing bat file will not work since it doesn't have permissions to run the script.

So, I would like to know if there exists any alternatives for this kind of situation. It will be good if user context is impersonated by using entered userid and password allowing existing batch file to run without further changes. If it is not possible, we would like to explore other ideas too but we don't have flexibility to choose a automated tool like  puppet, etc, we should stick around with these batch files.

答:
I'll share what we've been using, and where we're planning on going, maybe it'll help give you a better idea.

We currently use Jenkins and Github together-- once something is merged into master, Github tells Jenkins and it kicks off a build.

We use a Nant script on Jenkins to build the project, run unit tests, and if everything looks good, it kicks off another Jenkins project. The Nant script also spits out a directory with fully compiled code/minimized CSS/JS, etc.

The secondary Jenkins project takes the output from the build, and sends it back up to Github, on a separate repository.

A .BAT file runs every 5 minutes on the staging web server, and it basically checks for updates to that repository. If an update is found, we download the latest build, backup our staging files, then deploy the newest build over to staging folder.

To go live, we have a .BAT file that handles backing up the live files, and copying the repository files over the live files. It's run manually. It doesn't handle SQL updates (we do those by hand).

Now, obviously this isn't totally ideal but it's working for us. We want to expand this in the future to:

Use Web Deploy to push the files from Jenkins straight to IIS, and do any other commands we need to run.

Use automatic migrations (a feature of Entity Framework) to handle all SQL updates, as part of the go live.


答:
Each std::vector stores its elements in a contiguous heap allocation.  This means the element data is separate from the object member data (remember,  locally declared std::vector's  are allocated on the stack, not the heap...).  That is what allows a std::vector to be dynamically resized -- note that C/C++ has no provision for resizing a struct!

So, in a std::vector< std::vector<int> >, the outer std::vector stores an array of fixed-size std::vector<int> datastructures in its heap allocation.  Each of those vectors manages its own heap-allocated array of int, separately from its "parent" or any of its "siblings".

Title: Two-Dimensional vector in C++ – inefficient with dynamic-sized sub vectors?

Body:
I know that std::vector uses a contiguous block of memory, but I often see people use vectors of vectors, even when they modify the number of elements in these vectors contained within an outer vector. Won't this lead to efficiency problems when an inner vector need to be resized as all the following vectors will have to have their elements moved as well?

In other words, in the following code, won't growing lists[0] trigger the moving of the elements of the 99 sub vectors following it too, and not just lists[0]?

```<code>std::vector<std::vector<int>> lists;
lists.resize(100);

// use and grow sub vectors
// ...
lists[0].push_back(88); // ← !
</code>```


答:
Agile generally prefers 3rd approach. I'm sure most resources about agile recommend this.
Major reason for not preferring layered approach is that it would be hard for each team to deliver working software each iteration, because work of one team is dependent on work of another. You could try approaching it so teams on "lower" level would work beforehand the ones on "higher" level, but then it would be hard to communicate changes. Especially if only thing customer sees is the UI. What you want to look for is named feature teams, versus layer teams.

To ensure that experience is properly shared across different teams and layers, it is also recommended to often rotate people between team. This will ensure consistency and quality across whole application.

Also, the note about "other's people code", I would recomend looking at CodeOwnership from Martin Fowler.

Title: Large teams with layered application


问:
Chain class behaviour
I have a Bird class.
A bird can learn and a bird can fly (methods).
A bird can only fly after it learns.

Considering both methods are public. How can you make this clear to another fellow developer. Usually they should take a look at the public method names and understand what they do. But how can he understand without reading comments or understand the encapsulated code that method2 can be called only after method1?

答:
The cleanest (but not always most practical) way is to have learn return an EducatedBird which can then fly.

I'm not sure if there's a formal pattern named for it, but this sort of pattern works very well for other sorts of state transitions such as opening connections.

Title: Chain class behaviour


答:
Telastyn's answer is the textbook suggestion, and not a bad one. This is called the state pattern, and can be implemented in most programming languages, but I find it very clunky, and when you start getting into the 10-20 state range, you'll want to have had implemented the pattern as a series of decorators and by the time you're done you'll have foresworn OOP completely.

The state pattern is useful only if you have a clear and distinct number of states and state transitions. If you want to have an arbitrary number of states, or have multidimensional states, you should probably use the decorator pattern. That, though, has its own caveats. Depending on your language, it, too, can be clunky (If you have a method that expects a FlyingBird but you pass a YellowBird that wraps a FlyingBird...). You tend to lose some of your language's benefits by implementing the decorator pattern in this way.

The best way, in my opinion, would be to either implement the state pattern implicitly using an internal state for the object and exception handling, or to composite the object (if your language supports that) at run time.

Title: Chain class behaviour

Body:
I have a Bird class.
A bird can learn and a bird can fly (methods).
A bird can only fly after it learns.

Considering both methods are public. How can you make this clear to another fellow developer. Usually they should take a look at the public method names and understand what they do. But how can he understand without reading comments or understand the encapsulated code that method2 can be called only after method1?


答:
Third option for me.

Communication is key, and minimising the reliance on another layer team to finish their bit or implement to the agreed interface correctly can greatly inhibit this.

I also prefer my team to be generalists who can easily move into different areas when needed. Got a new feature? A "person" can work on the whole thing instead of waiting for 3 different people layers to all become available.

By all means have 1 DB expert keeping an eye on things there, and 1 UI expert monitoring that side of things, but having flexible multi talented people, working on feature silos rather than horizontal layers, for me, always works better.

Title: Large teams with layered application


问:
Preventing Web Users From Using Their Location Bar Within An App
My boss asked me to alter our Java Webapp such that users cannot go to places in our Webapp by typing URLs into their browser location bar.

I told her that I can not disable their location bars.

I told her the way this is usually done is to launch a WebApp in a new customized browser window sans a location bar.

That was not acceptable to her.

I already have a Java Filter class set up to enforce various rules.  So, I was thinking of this approach

Implement a system wide "writeFlagCookie" javascript function to write a cookie anytime a user initiates a GET by clicking on a link or a button.

Everywhere the WebApp does a redirect or a forward, put a flag variable, say "wasRedirected" into the HTTP session.

In my Filter, intercept each request and check for the request type.

If it is a POST, I know a human didn't type the URL into their browser, so I automatically let it through.

If it is a GET, look for a javascript generated cookie, or the flag
stored in the session to indicate a redirect or a forward.  If I find neither send the user back to the page they just tried to leave from.

Though it will be a lot of work, it sounds too simple to be adequate.

Is there anyway this approach can bite me in the ass?

My boss wants two problems solved

Users going to screens out of sequence and getting error messages.  This includes multi-screen forms ( which we have to keep ) and users using a back button.

Preventing the user from leaving particular pages and going to other parts of the application until they fill out what we want them to fill out on those screens.

I have ideas how to solve #1 & #2, also laborious, but my boss likes the idea of disabling typing URLs for navigation for a catch-all solution.

Maybe once she sees how much work is involved in disabling typed navigation I can market her on just solving those problems.

Thanks

Steve

答:
I think you might be talking about single page design, where the HTML is loaded from the server for the home URL, but all navigation is performed via AJAX requests. This prevents the history of the browser from changing, and the user has no other URL they can navigate too.

One Page Design

MSDN One Page Design


问:
What's the best documentation you produce and why?
I think it's safe to assume that for most programmers, producing documentation is not as fun as actually coding. I think it's also safe to assume that most good programmers recognize the need for useful documentation, and the code that they write is not an exception by any stretch of the imagination.

So, I'd like to know: what's the best documentation you produce (and source code doesn't count). Answer can be anything from comments to unit tests.

The bigger question is why is that the best documentation you produce?

答:
Good Requirements Documents

Developers come from all backgrounds, but a well written requirements specification can fill in their knowledge gaps and clearly explain the business and the objective of the user. You may not think a developer should be writing requirements, but if you can find a developer that is also a good communicator and good writer, you essentially have a business analyst that understands the complexities of software development, which is better than having a business analyst that doesn't understand the real complexity in software development (and there are a lot of those running around).

Why?

Karl Weigers once wrote that if you miss the requirements then it doesn't matter how well you execute the rest of the project, you are at increased risk for failure (and that's putting it a lot more mildly than he did). A good requirements specification doesn't have to be monolithic (although if the cost of failure is loss of life, then perhaps it might have to be) and a good one will get everyone, not just programmers, but also analysts, managers, project managers, subject matter experts, and end users on the same page.

Experienced developers know that the synergy of good domain knowledge, programming skill, and communication is important to successful software projects. A requirements document (on paper, wiki, or any medium) is a good part of that, not only for the beginning of the project, but also for life after go-live.


答:
The mechanism described by Timo is accurate, but it may help to consider that changing vector.size() cannot change sizeof(vector), because the latter has to be a compile-time constant.

Conversely, if your 2D array was really a contiguous int[HEIGHT * WIDTH], changing the width would require reorganising everything.


答:
A teaching language

Pascal started its life as a programming language for teaching. It was carefully crafted to get people started and gently tugg them onto the right way: structured programming. And the language as such if compared to "Your-father's-C" is much gentler to the novice than C. I think its actually quite amazing that Pascal caught on as it did. I think it is worthwhile to have a look at Algol 68 http://en.wikipedia.org/wiki/ALGOL_68 to get an idea how other languages at the time looked like that were considered to be advanced.

The original Pascal had to be extended in order to "scale" for greater projects (i.e. no notion of modules/units, etc.). Implementations extended Pascal to acommodate the needs of application development. As mentioned: by Philip this lead to fragmentation.

While fragmentation happend to C as well, the real issue with Pascal is, that it was never unified in the same way as C has been. Niklaus Wirth, the creator of Pascal started to develop successor languages (Modula, Oberon) which was probably not the best marketing choice.

Still with Delphi, Pascal had retained a lot of popularity throughout the years, especially as a better alternative to Visual Basic 6. Over the time however support faded and now I think one can only speculate. I think that people considered it on a "professional" scale somewhere between C (and emerging C++) and Visual Basic. With Java and .NET emerging the whole programming language landscape shifted. Lots of projects were probably migrated to Java and the .NET platform eventually and the community lost its drive. That might be the real issue, once lots people "leave the ship" it gets hard for a platform to stay relevant.

Pascal was not so bad after all as some people remember it. Pascal compilers were really fast back then, because Wirth had done a really fine job at grammar definition, it is easily parseable.

Aging with grace

In the long run Pascal has aged with grace before disappearing from stage. It does look outdated from today's perspective but overall it has been a success story.

A lot of comparisons about its success highlight things that it lacks in comparison to C, however I feel like that with new high level languages emerging, it was actually too close to C, and the world was not big enough for both of them. Today, there is not viable alternative to C/C++ while scripting languages are created by the dozens.

Title: Whatever happened to Pascal?


问:
Should I open up to .net, c# and visual basic?
I am a huge linux fan and have been ignoring .net, C#, and visual basic due to their relationship with Microsoft. Am I foredooming them just for their relationship?

Is there any advantage to learning them, when you are mainly a linux user?

答:
vb.net is on the way out:

http://channel9.msdn.com/Series/Windows-Store-apps-for-Absolute-Beginners-with-C-/Part-1-Series-Introduction

Bob Tabor: "While I began with VB, I haven't seen a lot of docs / videos / articles / books using VB for Win8 or other recent technologies.  Increasingly, it feels to me personally like C# would be a good investment."

C# is the way to go. But you can always use mono for c# on Linux.


答:
It's evil, but you can use the negative reinforcement method:

```<code> class Bird
   fn learn :  _learned = true
   fn fly : assert(_learned) ...do flying...

   bool _learned = false
</code>```

The clear disadvantage is lack of compile-time or static type information to guide the developer, but it's been used before, particularly in C.

Title: Chain class behaviour

Body:
It's evil, but you can use the negative reinforcement method:

 class Bird
   fn learn :  _learned = true
   fn fly : assert(_learned) ...do flying...

   bool _learned = false

The clear disadvantage is lack of compile-time or static type information to guide the developer, but it's been used before, particularly in C.


答:
You can not close a file unless it's open. How should the close method react when executed in the wrong state? Should it return a failure, or throw an exception. That depends upon the language and programming style you are following.

Weather or not the Bird can fly or not is a representation of it's internal state. The same as a file resource, and as such you would follow the same design patterns. Treating the Bird as having an internal state the the developer needs to control.

```<code>class Bird {
    boolean canFly();
    void teach();
    void fly();
}

try
{
  if(!b.canFly()) { b.teach(); }
  b.fly();
} catch (e) { ... }
</code>```

Having the perspective, that a method is order dependant upon another method doesn't follow my understanding of OOP design. The object has an internal state. The object manages it's own internal state, and outside source code shouldn't be responsible for management of that state (if possible). If you have to tell the developers to execute the methods in a given order, then you've designed the object wrong.

Instead of teaching and flying. You should initialize the bird, and make handling of the Bird's internal state an internal matter of the object. This way, you will not break other people's source code when you have to revise the design of Bird.

```<code>class Bird {
   private boolean taught = false;
   private boolean flying = false;
   private void teach() {...}

   protected void init() {
      if(!this->taught) { this->teach(); }
   }

   public void startFlying() { this->init(); this->flying = true; }
   public void stopFlying() { this->init(); this->flying = false; }
}
</code>```

Title: Chain class behaviour

Body:
You can not close a file unless it's open. How should the close method react when executed in the wrong state? Should it return a failure, or throw an exception. That depends upon the language and programming style you are following.

Weather or not the Bird can fly or not is a representation of it's internal state. The same as a file resource, and as such you would follow the same design patterns. Treating the Bird as having an internal state the the developer needs to control.

class Bird {
    boolean canFly();
    void teach();
    void fly();
}

try
{
  if(!b.canFly()) { b.teach(); }
  b.fly();
} catch (e) { ... }

Having the perspective, that a method is order dependant upon another method doesn't follow my understanding of OOP design. The object has an internal state. The object manages it's own internal state, and outside source code shouldn't be responsible for management of that state (if possible). If you have to tell the developers to execute the methods in a given order, then you've designed the object wrong.

Instead of teaching and flying. You should initialize the bird, and make handling of the Bird's internal state an internal matter of the object. This way, you will not break other people's source code when you have to revise the design of Bird.

class Bird {
   private boolean taught = false;
   private boolean flying = false;
   private void teach() {...}

   protected void init() {
      if(!this->taught) { this->teach(); }
   }

   public void startFlying() { this->init(); this->flying = true; }
   public void stopFlying() { this->init(); this->flying = false; }
}


答:
Apart fro "one-page design", the other common way this is accomplished is via means of a session identifier (which generally prevents users from saving a bookmark and coming back to it; tabbed browsing may or may not be prevented depending on browser implementation), coupled with a "request token". All links in each page served to the browser that redirect within the application have a query string with a GUID (or the GUID's stored in ViewState to make it completely inaccessible), which was generated by the server when rendering the page.

The server remembers this GUID and the page last served in the session store, and if a request comes from that session that does not have a request token or doesn't have the right one (indicating the user's been using their back/forward buttons), the user is directed to a simple page telling them politely not to do that, with a link back to the last page the server actively served them. Therefore, in order to successfully jump around using the location bar, the user must be smarter than the average bear and include the token in their hand-typed request.

This is a little simpler to implement in an existing multi-page architecture than moving to one-page (IMO a pretty serious redesign), and follows the 80/20 rule of keeping the vast majority of your users honest with minimal effort; the other 20% will need more advanced anti-tampering, possibly by remembering the available links of the current page and performing the same redirect if they are going somewhere they couldn't have gotten to with a link, with or without the correct GUID.

Title: Preventing Web Users From Using Their Location Bar Within An App

Body:
My boss asked me to alter our Java Webapp such that users cannot go to places in our Webapp by typing URLs into their browser location bar.

I told her that I can not disable their location bars.

I told her the way this is usually done is to launch a WebApp in a new customized browser window sans a location bar.

That was not acceptable to her.

I already have a Java Filter class set up to enforce various rules.  So, I was thinking of this approach

Implement a system wide "writeFlagCookie" javascript function to write a cookie anytime a user initiates a GET by clicking on a link or a button.

Everywhere the WebApp does a redirect or a forward, put a flag variable, say "wasRedirected" into the HTTP session.

In my Filter, intercept each request and check for the request type.

If it is a POST, I know a human didn't type the URL into their browser, so I automatically let it through.

If it is a GET, look for a javascript generated cookie, or the flag
stored in the session to indicate a redirect or a forward.  If I find neither send the user back to the page they just tried to leave from.

Though it will be a lot of work, it sounds too simple to be adequate.

Is there anyway this approach can bite me in the ass?

My boss wants two problems solved

Users going to screens out of sequence and getting error messages.  This includes multi-screen forms ( which we have to keep ) and users using a back button.

Preventing the user from leaving particular pages and going to other parts of the application until they fill out what we want them to fill out on those screens.

I have ideas how to solve #1 & #2, also laborious, but my boss likes the idea of disabling typing URLs for navigation for a catch-all solution.

Maybe once she sees how much work is involved in disabling typed navigation I can market her on just solving those problems.

Thanks

Steve


问:
How is it possible to build the whole codebase from source at Google scale?
The first answer to an old, recently active question linked to a video which talks about how Google repository is done.

One interesting thing which was mentioned is the fact that everything is build from source, without relying on binaries. This helps avoiding issues with dependencies becoming obsolete but still being used in other projects, an issue I indeed encountered a lot.

How is it technically possible? If I try the same thing in my company, even considering the huge gap between the scale of my company codebase and the scale of Google's one, it wouldn't be possible for two reasons:

The IDE (Visual Studio) will quickly become unresponsive, given that is suffers a lot at even small solutions containing, say, 50 projects.

Any static analysis would be crunched by the size of the whole codebase. For example code metrics or static checking of code contracts would hardly be possible (code contracts would probably take days or weeks).

With continuous integration, compiling would take a huge amount of time too and would crunch the servers as soon as a project with lots of dependencies is modified, requiring a large tree of projects to be recompiled.

How can a small company circumvent those issues and be able to:

Use the IDE without being affected by poor performance,

Compile the code after each commit without crunching the server, even when the consequences of a change require a large amount of the codebase to be recompiled?

答:
You don't have to build all 2000 projects to use just the ones you need.

The Go language was specifically designed to alleviate this problem by making compile times very fast.  it was one of the reasons they invented the language.

That said, I'd be wary of "just-in-time building," unless the code that is being deployed company-wide has been verified as part of a (more or less) formal release cycle, and is not just a random nightly build.  H

Having 5000 developers accessing 2000 projects that are all in a continuous state of flux sounds like a recipe for disaster, and Google hires very smart people, so I'm quite certain that's not what is actually happening.


问:
When are chained assignments (i.e. a=b=c) bad form?
I'm working on a VB.Net WinForms project and found myself writing code like this:

```<code>this.Fizz.Enabled = this.Buzz.Enabled = someCondition;
</code>```

I couldn't decide whether that was bad code or not. Are there any .NET guidelines for when/when-not to do assignment chaining?

答:
I never do it.  I always put each assignment on its own line.  Clarity is king.

In practice, I seldom use enough state variables to make chaining assignments necessary.  If I get to that point, I start looking for ways to trim the amount of state I am using.


答:
Generally, if I have to enforce at compile-time that one method must happen first, and make it obvious to the coder, I generally either use a monad which is a similar idea to Telastyn's state pattern, or I enforce the use of a token.

Have Learn() return a FlightKnowledge object. This object should have a constructor visibility that precludes the average consumer from creating their own (private, protected, internal etc). Then, expose Fly(FlightKnowledge) as the only overload of the Fly method. This requires the coder to pass in a valid FlightKnowledge object (depending on your language you can either make FlightKnowledge a type that can't be null, or enforce by decoration that the parameter cannot be null), and if the only way he can get one is by calling Learn(), then you've enforced your order of operations.

Just don't turn this into a "King's Quest" anti-pattern (to Fly(), you must have FlightKnowledge, which you get by calling Learn(), which takes a Tuition object that is produced by the MamaBird by calling AskForTuition() which takes a SweetTalk object that's...). If your order of operations is that deep, tokens by themselves are the wrong pattern.

Title: Chain class behaviour


答:
It depends on the programming language. If you use a language where variable types are not enforced, then this could happen.

```<code>x = 1;
y = 494.0;
z = new Object();
x = y = z = "hello";
</code>```

Now x,y,z are all a string. This might be confusing if found later on in the code.

The other problem is operator overloads. Some languages allow you to change what happens for the left-hand assignment of a property. So the following could happen.

```<code>x = y.something = 0;
</code>```

Where y.something doesn't return 0. It returns null.

Otherwise, I don't have a problem with it. If it's a strongly typed language and there is no risk in the above happening. Then no problem.

The other problem is in how you read the source code.

```<code> a = b = c = new Object();
</code>```

Is not the same as.

```<code> a = new Object();
 b = new Object();
 c = new Object();
</code>```

It's really like this.

```<code> c = new Object();
 b = c;
 a = b;
</code>```

It might not be clear that all three variables have the same reference.

Title: When are chained assignments (i.e. a=b=c) bad form?

Body:
I'm working on a VB.Net WinForms project and found myself writing code like this:

```<code>this.Fizz.Enabled = this.Buzz.Enabled = someCondition;
</code>```

I couldn't decide whether that was bad code or not. Are there any .NET guidelines for when/when-not to do assignment chaining?

Body:
It depends on the programming language. If you use a language where variable types are not enforced, then this could happen.

x = 1;
y = 494.0;
z = new Object();
x = y = z = "hello";

Now x,y,z are all a string. This might be confusing if found later on in the code.

The other problem is operator overloads. Some languages allow you to change what happens for the left-hand assignment of a property. So the following could happen.

x = y.something = 0;

Where y.something doesn't return 0. It returns null.

Otherwise, I don't have a problem with it. If it's a strongly typed language and there is no risk in the above happening. Then no problem.

The other problem is in how you read the source code.

 a = b = c = new Object();

Is not the same as.

 a = new Object();
 b = new Object();
 c = new Object();

It's really like this.

 c = new Object();
 b = c;
 a = b;

It might not be clear that all three variables have the same reference.


答:
It's not necessarily bad code, but it does make your code significantly less readable. Typically, I would strongly recommend against it, although I suppose there are a few cases where it might be acceptable (or merely less bad). For example, when setting a few local variables to constant value:

```<code>// accumulators
int j = 0, k = 0;
for(int i = 0; ...)
{
    ...
    if(reset)
    {
        // oops we have to start from the beginning
        i = j = k = 0;
    }
}
</code>```

In this case the line, and more importantly the comment that accompanies it, make it clear what the authors intention was when writing it. This code also contains a compound declaration which I also generally discourage, but are more acceptable here for the same reasons.

Still, I would recommend against it in most cases. There is never any harm in writing more explicit code (as long as it's functionally identical).

Body:
It's not necessarily bad code, but it does make your code significantly less readable. Typically, I would strongly recommend against it, although I suppose there are a few cases where it might be acceptable (or merely less bad). For example, when setting a few local variables to constant value:

// accumulators
int j = 0, k = 0;
for(int i = 0; ...)
{
    ...
    if(reset)
    {
        // oops we have to start from the beginning
        i = j = k = 0;
    }
}

In this case the line, and more importantly the comment that accompanies it, make it clear what the authors intention was when writing it. This code also contains a compound declaration which I also generally discourage, but are more acceptable here for the same reasons.

Still, I would recommend against it in most cases. There is never any harm in writing more explicit code (as long as it's functionally identical).


问:
Data structure for accessing units of measure
TL;DR - I'm trying to design an optimal data structure to define units within a unit of measure.

A Unit of measure is essentially a value (or quantity) associated with a unit.  SI Units have seven bases or dimensions.  Namely: length, mass, time, electric current, temperature, amount of substance (moles), and luminous intensity.

This would be straightforward enough, but there are a number of derived units as well as rates that we frequently use.  An example combined unit would be the Newton: kg * m / s^2 and an example rate would be tons / hr.

We have an application that relies heavily upon implied units.  We'll embed the units within the variable or column name.  But this creates problems when we need to specify a unit of measure with different units.  Yes, we can convert the values at input and display but this generates a lot of overhead code that we'd like to encapsulate within its own class.

There are a number of solutions out on codeplex and other collaborative environments.  The licensing for the projects is agreeable but the project itself usually ends up being too lightweight or too heavy.  We're chasing our own unicorn of "just right."

Ideally, I could define a new unit of measure using something like this:

UOM myUom1 = new UOM(10, volts);

  UOM myUom2 = new UOM(43.2, Newtons);

Of course, we use a mix of Imperial and SI units based upon our clients' needs.

We also need to keep this structure of units synchronized with a future database table so we can provide the same degree of consistency within our data too.

What's the best way of defining the units, derived units, and rates that we need to use to create our unit of measure class?  I could see using one or more enums, but that could be frustrating for other developers.  A single enum would be huge with 200+ entries whereas multiple enums could be confusing based upon SI vs Imperial units and additional breakdown based upon categorization of the unit itself.

Enum examples showing some of my concerns:

myUnits.Volt

  myUnits.Newton

  myUnits.meter

SIUnit.meter

  ImpUnit.foot
  DrvdUnit.Newton

  DrvdUnitSI.Newton

  DrvdUnitImp.FtLbs

Our set of units in use is pretty well defined and it's a finite space.  We do need the ability to expand and add new derived units or rates when we have client demand for them.  The project is in C# although I think the broader design aspects are applicable to multiple languages.

One of the libraries I looked at allows for free-form input of units via string.  Their UOM class then parsed the string and slotted things accordingly.  The challenge with this approach is that it forces the developer to think and remember what the correct string formats are.  And I run the risk of a runtime error / exception if we don't add additional checks within the code to validate the strings being passed in the constructor.

Another library essentially created too many classes that the developer would have to work with.  Along with an equivalent UOM it provided a DerivedUnit and RateUnit and so on.  Essentially, the code was overly complex for the problems we're solving.  That library would essentially allow any:any combinations (which is legitimate in the units world) but we're happy to scope our issue (simplify our code) by not allowing every possible combination.

Other libraries were ridiculously simple and hadn't even considered operator overloading for example.

In addition, I'm not as worried about attempts at incorrect conversions (for example: volts to meters).  Devs are the only ones who will access at this level at this point and we don't necessarily need to protect against those types of mistakes.

答: This is the raison d'etre of the Unix units command, which does it all using a data-file-driven approach for specifying the relationships.


问:
"Generators are function derivatives"
I am reading this article on a new feature of ECMAscript 6, generators, that are landing in the V8 JavaScript interpreter. Not too far from the top, the author suggests an analogy:

generators are like functions, with their bodies taken to the
  first derivative. Calling next integrates between two yield points.

I really like this analogy. Has this analogy already been discussed in the literature? Are there similar ones? Does it fit within a bigger framework of analogies? (I made a quick Google search but that was not helpful.)

答:
I think this analogy is more like a metaphor, used playfully by the author to get you to think conceptually about what a generator is.

Let's review what iterators and generators actually are in Javascript:

An Iterator is an object that knows how to access items from a
  collection one at a time, while keeping track of its current position
  within that sequence. In JavaScript an iterator is an object that
  provides a next() method which returns the next item in the sequence.
  This method can optionally raise a StopIteration exception when the
  sequence is exhausted.

Generators provide a powerful alternative: they allow you to define an iterative algorithm by writing a single function which can maintain its own state, and then returning individual values based on that persistent state using the yield keyword.

In short, an iterator is a function that returns one of a succession of data points each time it is called, and a generator is just some syntactic sugar that allows you to create such a function with the syntax and ease of use of an ordinary method.

The data points returned individually from an iterator method can come from an array or collection, or they can be generated by code.  A pseudo-random generator can be thought of as an iterator, since giving it the same initialization seed will return the same sequence of values.

So what is a derivative?  Put succinctly, it is a function that, at any given point on a curve returns the slope of a line at a tangent to the curve at that point.  It looks something like this:

Well, that does look like an iterator, doesn't it?  The graphic is basically illustrating a function that accepts multiple, successive positions on a curve, and returns the slope of the line at each point on that curve, one value at a time.

The only problem with this analogy is that an iterator doesn't have to return derivative values; it can return anything.  The derivative values are just a convenient way of forcing you to think about the nature of iterators.

A better analogy might be a Pez dispenser.

Title: "Generators are function derivatives"


答:
You are assuming a traditional build process, and Google's process is anything but traditional. There's a series of articles in the Engineering Tools blog that explain their process in some detail, elaborating on the 2010 presentation: Tools for Continuous Integration at Google Scale:

Build in the Cloud: Accessing Source Code

Build in the Cloud: How the Build System works

Build in the Cloud: Distributing Build Steps

Build in the Cloud: Accessing Source Code

Testing at the speed and scale of Google

To summarise, they use a custom distributed build system that allows for a very high degree of parallelism and automation, taking full advantage of their existing infrastructure. It also relies heavily on caching, with a 90% overall cache hit rate.

But how can you apply all this in your company? The first step is distributing compiling, and for that you'd need:

A cloud

A distributed compiler

A compiler cache

On a gcc development environment, setting up a compile farm is relatively easy. distcc takes care of distribution and ccache takes care of caching, and they work beautifully together. I don't know of any similar tools for Microsoft's ecosystem (I'm assuming you are using a Microsoft language based on your choice of IDE), but I do know that MSBuild can run builds in parallel, taking advantage of multi-core CPUs. Not really a compile farm, but certainly a step in the right direction.

Title: How is it possible to build the whole codebase from source at Google scale?

Body:
The first answer to an old, recently active question linked to a video which talks about how Google repository is done.

One interesting thing which was mentioned is the fact that everything is build from source, without relying on binaries. This helps avoiding issues with dependencies becoming obsolete but still being used in other projects, an issue I indeed encountered a lot.

How is it technically possible? If I try the same thing in my company, even considering the huge gap between the scale of my company codebase and the scale of Google's one, it wouldn't be possible for two reasons:

The IDE (Visual Studio) will quickly become unresponsive, given that is suffers a lot at even small solutions containing, say, 50 projects.

Any static analysis would be crunched by the size of the whole codebase. For example code metrics or static checking of code contracts would hardly be possible (code contracts would probably take days or weeks).

With continuous integration, compiling would take a huge amount of time too and would crunch the servers as soon as a project with lots of dependencies is modified, requiring a large tree of projects to be recompiled.

How can a small company circumvent those issues and be able to:

Use the IDE without being affected by poor performance,

Compile the code after each commit without crunching the server, even when the consequences of a change require a large amount of the codebase to be recompiled?


答:
My solution sort of bends UML around its corners but I think it's worth a shot. if it's only to make a fellow programmer know how to call the methods, then this may suffice

When you model your design of the Bird class, add a dependence between methods. Currently, UML only allows dependence between objects but you may choose a define a standard which allows you specify dependencies between attributes. This way, the dependence…

```<code>fly --------------> learn
</code>```

…would mean fly depends on learn

In implementation, you may have a flag which indicates the bird has learnt how to fly. if the amount of things to learn becomes too many, you may want to abstract the learnedness of the bird into a different class altogether; thereby falling back to the better part of the pre-stated answers

Title: Chain class behaviour

Body:
My solution sort of bends UML around its corners but I think it's worth a shot. if it's only to make a fellow programmer know how to call the methods, then this may suffice

When you model your design of the Bird class, add a dependence between methods. Currently, UML only allows dependence between objects but you may choose a define a standard which allows you specify dependencies between attributes. This way, the dependence…

fly --------------> learn

…would mean fly depends on learn

In implementation, you may have a flag which indicates the bird has learnt how to fly. if the amount of things to learn becomes too many, you may want to abstract the learnedness of the bird into a different class altogether; thereby falling back to the better part of the pre-stated answers


问:
Forcing ExtJS application updates after deployment
I work on an ExtJS application with a Django backend, and we keep running into issues when we push new code. Our users seldom refresh their browsers, so after a code push we end up with users using the same (now outdated) version of our ExtJS application for days at a time instead of the new, updated version.

How do other people deal with this issue? (I haven't found anything online about this, so I probably haven't found the right keywords yet.)

答:
This is a social problem and not really a technological problem. You need to inform the user that your application has updated.

A good example is Google Chrome. It updates in the background, and waits. If you don't restart Google Chrome in about a week, it will give you a humorous message saying something along the lines that 'it's been a long time since you have restarted the browser. Restart the browser to get the updated version.'

You could do something similar. Have a service which responds with the version number of your Application. Send an Ajax request to this service every day or something. and if the version  number has incremented, show a message to the user..