答:
If you need this for choosing a unit test framework, then I would suggest the following:

Choose the one the rest of your team uses.

If your team does not use one, or you do not have a team, use the one your IDE supports out of the box in the default configuration.

If you still have not decided, then start with JUnit 4 which is the de-facto standard.

Title: What unit test frameworks exist for Java?

Body: I've used TestNG and JUnit.  What other frameworks are out there? What makes them special and/or different from the rest?</p>


问:
Smallest lexicographical rotation of a string using suffix arrays in O(n)
I will quote the problem from ACM 2003:

Consider a string of length n (1 <= n <= 100000). Determine its minimum lexicographic rotation. For example, the rotations of the string “alabala” are:

alabala

labalaa

abalaal

balaala

alaalab

laalaba

aalabal

and the smallest among them is “aalabal”.

As for the solution - I know I need to construct a suffix array - and let's say I can do that in O(n). My question still is, how can I find the smallest rotation in O(n)? (n=length of a string)

I'm very interested in this problem and still I somehow don't get the solution. I'm more interested in the concept and how to solve the problem and not in the concrete implementation.

Note: minimum rotation means in the same order as in an english dictionary - "dwor" is before "word" because d is before w.

EDIT: suffix array construction takes O(N)

LAST EDIT:
I think I found a solution!!! What if I just merged two strings? So if the string
is "alabala" the new string would me "alabalaalabala" and now I'd just construct a suffix array of this (in O(2n) = O(n)) and got the first suffix? I guess this may be right. What do you think?
Thank you!

答:
I'm pretty sure the information contained in a suffix array is not sufficient to help you get to O(n), but at most can help you to O(n log n). Consider this family of suffixes:

```<code>a
aba
abacaba
abacabadabacaba
abacabadabacabaeabacabadabacaba
...
</code>```

You construct the next suffix by taking the previous suffix (say aba), adding the next character not yet used and then adding the previous suffix again (so aba -> aba c aba).

Now consider these strings (the space is added for emphasis, but is not part of the string):

```<code>ad abacaba
bd abacaba
cd abacaba
</code>```

For these three strings, the start of the suffix array will look like this:

```<code>a
aba
abacaba
(other suffixes)
</code>```

Looks familiar? These strings of course is tailored to create this suffix array. Now, depending on the starting letter (a, b or c), the 'correct' index (the solution to your problem) is either the first, the second or the third suffix in the list above.

The choice of the first letter hardly affects the suffix array; in particular, it does not affect the order of the first three suffixes in the suffix array. This means that we have log n strings for which the suffix array is extremely similar but the 'correct' index is very different.

Although I have no hard proof, this strongly suggests to me that you have no choice but to compare the rotations corresponding to these first three indices in the array for their lexicographic ordering, which in turn means that you'll need at least O(n log n) time for this (as the number of alternative first characters - in our case 3 - is log n, and comparing two strings takes O(n) time).

This does not rule out the possibility of an O(n) algorithm. I merely have doubts that a suffix array helps you in achieving this running time.

ContentLicense: CC BY-SA 3.0

Body:
I'm pretty sure the information contained in a suffix array is not sufficient to help you get to O(n), but at most can help you to O(n log n). Consider this family of suffixes:

a
aba
abacaba
abacabadabacaba
abacabadabacabaeabacabadabacaba
...

You construct the next suffix by taking the previous suffix (say aba), adding the next character not yet used and then adding the previous suffix again (so aba -> aba c aba).

Now consider these strings (the space is added for emphasis, but is not part of the string):

ad abacaba
bd abacaba
cd abacaba

For these three strings, the start of the suffix array will look like this:

a
aba
abacaba
(other suffixes)

Looks familiar? These strings of course is tailored to create this suffix array. Now, depending on the starting letter (a, b or c), the 'correct' index (the solution to your problem) is either the first, the second or the third suffix in the list above.

The choice of the first letter hardly affects the suffix array; in particular, it does not affect the order of the first three suffixes in the suffix array. This means that we have log n strings for which the suffix array is extremely similar but the 'correct' index is very different.

Although I have no hard proof, this strongly suggests to me that you have no choice but to compare the rotations corresponding to these first three indices in the array for their lexicographic ordering, which in turn means that you'll need at least O(n log n) time for this (as the number of alternative first characters - in our case 3 - is log n, and comparing two strings takes O(n) time).

This does not rule out the possibility of an O(n) algorithm. I merely have doubts that a suffix array helps you in achieving this running time.


答:
I don't see anything better than O(N²).

If you have a list of N integers, you can pick the smallest in O(N) comparisons.

Here you have a list of N strings of size N (constructing them cost nothing, a string is fully determined by its starting index). You can pick the smallest in O(N) comparisons. But each comparison is O(N) basic operations.  So the complexity is O(N²).

Title: Smallest lexicographical rotation of a string using suffix arrays in O(n)

Body:
I will quote the problem from ACM 2003:

Consider a string of length n (1 <= n <= 100000). Determine its minimum lexicographic rotation. For example, the rotations of the string “alabala” are:

alabala

labalaa

abalaal

balaala

alaalab

laalaba

aalabal

and the smallest among them is “aalabal”.

As for the solution - I know I need to construct a suffix array - and let's say I can do that in O(n). My question still is, how can I find the smallest rotation in O(n)? (n=length of a string)

I'm very interested in this problem and still I somehow don't get the solution. I'm more interested in the concept and how to solve the problem and not in the concrete implementation.

Note: minimum rotation means in the same order as in an english dictionary - "dwor" is before "word" because d is before w.

EDIT: suffix array construction takes O(N)

LAST EDIT:
I think I found a solution!!! What if I just merged two strings? So if the string
is "alabala" the new string would me "alabalaalabala" and now I'd just construct a suffix array of this (in O(2n) = O(n)) and got the first suffix? I guess this may be right. What do you think?
Thank you!


答:
The smallest rotation is the one that start with some of the suffix from the suffix array. Suffixes are lexicographically ordered. This gives you a big jumpstart:

you know that once you get such k that rotation starting with suffix k is smaller than rotation starting with suffix k+1, you're done (starting from the first one);

you can do the comparision of "rotation starting with suffix k is smaller than rotation starting with suffix k+1" in O(1) by comparing lengths of suffixes and optionally, comparing one character with one another character.

EDIT: "one character with one another character" may not always be so, it may be more than one character, but overall, you do not examine more than n characters through the whole search process, so it is O(n).

Short proof: You only examine characters when suffix k+1 is longer than suffix k, and you stop and found your solution if suffix k+1 is shorter than suffix k (then you know suffix k is the one you sought for). So you only examine characters while you are in rising (length-wise) sequence of suffixes. Since you only examine excess characters, you cannot examine more than n characters.

EDIT2: This algorithm relies on the fact the "if there are two neighbour suffixes in suffix array and the previous is shorter than the subsequent, the previous is prefix of the subsequent". If this is not true, then sorry.

EDIT3: No, it does not hold. "abaaa" has suffix table "a", "aa", "aaa", "abaaa", "baaa". But maybe this line of thought can ultimately lead to the solution, just some more details must be sophisticated more. The primary question is whether it is possible to somehow make the aforementioned comparision done by examining less characters, so it is O(n) totally, which I somehow believe may be possible. I just can't tell how, now.


问:
What unit test frameworks exist for Java?
I've used TestNG and JUnit.  What other frameworks are out there? What makes them special and/or different from the rest?</p>

答:
With recent JUnit versions, Hamcrest was integrated into the library. Hamcrest adds additional matchers which improve readability but otherwise doesn't change the semantics of your tests. It therefore might be a good addition for your test setup.

```<code>import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

...

Person tom = new Person("Tom");
Person jerry = new Person("Jerry");

assertThat(tom, is(not(equalTo(jerry))));
</code>```

Body:
With recent JUnit versions, Hamcrest was integrated into the library. Hamcrest adds additional matchers which improve readability but otherwise doesn't change the semantics of your tests. It therefore might be a good addition for your test setup.

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

...

Person tom = new Person("Tom");
Person jerry = new Person("Jerry");

assertThat(tom, is(not(equalTo(jerry))));


问:
Why is BASIC bad?

Possible Duplicate:

  Do you think that exposure to BASIC can mutilate your mind?

BASIC, and related dialects, have long been branded "bad". I've seen it said by some of the best programmers I know, professors at Stanford, and even one of the most brilliant computer scientists:

It is practically impossible to teach good programming to students
  that have had a prior exposure to BASIC: as potential programmers they
  are mentally mutilated beyond hope of regeneration - Edsger W.
  Dijkstra

Now, I think that quote may have been taken slightly out of context, and was meant to be something of an exaggeration, but at the same time, anyone who says something along those lines clearly does not like BASIC.

When I started programming a while back, I started with BASIC and I don't consider myself a bad programmer, and I know of many good programmers who also started with BASIC.

Now, the obvious reason for dislike is that it teaches bad habits, skills, and methodologies. I'm just wondering why people say that, and if it's even correct to say that.

In my opinion, any programmer who is bounded by their language is a bad programmer, and that even if BASIC was somehow the boogeyman everyone made it out to be, it still shouldn't significantly hamper someone's "programming life".

tl;dr - Why do people consider BASIC a bad programming language (especially for beginners) and why do people say it teaches bad skills? What is the "mental mutilation" that Dijkstra speaks of?

答:
To be accurate, you need to qualify bad with an a specific application and also which version of BASIC. Today's MS VB.NET is not bad for learning OO or for creating business applications for the web and for the desktop. Microsoft still uses VBA for automation of its Office line of products and thousands of macros are running on it every day.

In the 80s, BASIC lacked pointers (which was a big thing for C developers), had line numbers (which to some was considered ugly) and had a GOTO (some implemenations did not allow IF/ELSE nesting so GOTO was very important) also Error handling was not cool (ON ERROR GOTO).

Also, at those days, BASIC was not OO. As far as I can remember, in the old days, BASIC did not have a way to access databases and only used Sequential and Random Files (Random Files,uses numeric keys only).

The above issues together with the fact that on the old days C and UNIX were the coolest couple in the block might have contributed to the image of BASIC. Nevertheless BASIC was popular to a great extent. Lots of games and business applications were written in BASIC and countless books were published about its different dialects. So it can't be too bad :)

Title: Why is BASIC bad?


问:
Optimal storage space calculation for name, address, phone, fax and email data
Given the following assumptions:

The amount of available data storage is highly limited

All data is international

As much storage as possible must be preserved since it will be used for something else

Is there any widely accepted standard or best practice which defines how much storage should be allocated for those items?

Note: I'm not looking for assumptions but for facts like "97.5% of all names fit into 70 bytes using UTF-8" and "An international address must at least contain field1, field2 and field3 of size1, size2 and size3".

Edit: I'm looking for the fields/lengths to use in the user interface. Not a technique to store it efficiently.

答:
Coming at it from a slightly different perspective, since your goal is to store things as compactly as possible, avoid using fixed width fields.

To pull from your own example:

97.5% of all names fit into 70 bytes using UTF-8

You shouldn't have a fixed 70 byte allocation for the name.

Instead, have a fixed allocation for the entire record - say, 200 bytes - then store all the data in that one record with a delimiter between fields.

```<code>For example:
Title/Given/Middle/Family/KnownAs/Born
Mr/William/Henry/Gates/1955-10-28
</code>```

This is a classic space/time tradeoff as searching such a structure will be slower.

One key advantage of this structure is that it allows for some fields to be unusually long without compromising storage. So, if someone's street address happened to require 70 characters, or if their full name took 90, you can accomodate this as long as the same person didn't have both.

Body:
Coming at it from a slightly different perspective, since your goal is to store things as compactly as possible, avoid using fixed width fields.

To pull from your own example:

97.5% of all names fit into 70 bytes using UTF-8

You shouldn't have a fixed 70 byte allocation for the name.

Instead, have a fixed allocation for the entire record - say, 200 bytes - then store all the data in that one record with a delimiter between fields.

For example:
Title/Given/Middle/Family/KnownAs/Born
Mr/William/Henry/Gates/1955-10-28

This is a classic space/time tradeoff as searching such a structure will be slower.

One key advantage of this structure is that it allows for some fields to be unusually long without compromising storage. So, if someone's street address happened to require 70 characters, or if their full name took 90, you can accomodate this as long as the same person didn't have both.


问:
Any standards for naming variables in for loops (instead of i,j,k)

Possible Duplicate:

  Why do most of us use 'i' as a loop counter variable?

I was just writing a nested loop and got to the point where I was using l and m as variables to control for loops, and I realized this could get very confusing; Ive already had a few bugs when I copied blocks of code to different levels.  So I was thinking instead of using i,j,k I would use iSomething,iSomethingelse.  So if I were going over a 3D model Id use

```<code>for(int iMesh=0;iMesh<numMesh;iMesh++)
    for(int iVertex=0;iVertex<meshes[iMesh].numVertex;iVertex++)
</code>```

or maybe use the name of the variable Im iterating over:

for(int iMeshes

for(int iVerts

So I was wondering if there are any other standard or commonly used practices for doing this?

EDIT: Im wondering if there ARE any standards, not if its OK to do this

答:
Choose a name that describes what the variable is for, such as

```<code>for (int loopCounter; loopCounter < 10; loopcounter++)
{
     if( loopCounter == doSomethingVal)
     {
          //do somthing
</code>```

This is the approach I use so that you can read out the logic of the code without having to translate the code to "english" which makes it easier for a new person to read the code and understand the intent of the code (as the code reads out the logic as would be spoken between people). A lot of people will not stylistaclly like this though (cue downvoting!) beacuse they do not like verbose code, or are just too comfortable with i,j,k, or are using a memory limited language/hardware. The problem with using somehing short like just i is that if you are debugging or reading a large section of code and you come to a like like:

```<code>   ......
   someVar = i;
</code>```

then you need to look up what i is, what someVar is and what this line means in terms of what the program is attempting to model. But if you have something like:

```<code>  ......
  currentItemId = loopItemCounter;
</code>```

then it is more obvious what the intent of the command is without comments or having to read through a large chunk of code. For short functions/methods it doenst make much difference (because you can probably see all the code on one page), but if you have ever tried to debug a large program with variable names that are just i or kk you will see why I prefer to be more vebose in nameing.

I think that I picked up this practice after reading the book code complete, or one of the other programming pricipals books.

Body:
Choose a name that describes what the variable is for, such as

for (int loopCounter; loopCounter < 10; loopcounter++)
{
     if( loopCounter == doSomethingVal)
     {
          //do somthing

This is the approach I use so that you can read out the logic of the code without having to translate the code to "english" which makes it easier for a new person to read the code and understand the intent of the code (as the code reads out the logic as would be spoken between people). A lot of people will not stylistaclly like this though (cue downvoting!) beacuse they do not like verbose code, or are just too comfortable with i,j,k, or are using a memory limited language/hardware. The problem with using somehing short like just i is that if you are debugging or reading a large section of code and you come to a like like:

   ......
   someVar = i;

then you need to look up what i is, what someVar is and what this line means in terms of what the program is attempting to model. But if you have something like:

  ......
  currentItemId = loopItemCounter;

then it is more obvious what the intent of the command is without comments or having to read through a large chunk of code. For short functions/methods it doenst make much difference (because you can probably see all the code on one page), but if you have ever tried to debug a large program with variable names that are just i or kk you will see why I prefer to be more vebose in nameing.

I think that I picked up this practice after reading the book code complete, or one of the other programming pricipals books.


问:
Does it hurt to learn bits of many programming languages?
I started my programming career with BASIC, during 9th grade. I learned a bit of BASIC by writing simple programs to add, subtract and to print. Then I went to the university and took Computer Information and Systems Engineering. In the first year I was taught C, and I have good command over it.

Next I learned C++ in the second year. It just taught me some knowledge of OOP. Now I am doing PHP (along with HTML). I have not mastered C++, BASIC or PHP. I am now planning to move to mobile development. But I feel that I have not covered everything in the languages I learned.

Does it really matter?

答: It's actually about as useful as learning a little bit of French, Spanish, English, Arabic, Hindi, and Chinese while never knowing any one of them well.</p>


问:
Copyright Laws for Apps
For my app that I'm about to release, I have used a bunch of 3rd party classes found for free online.  I checked all the liscenses before using the code and each one said I could use the code commercially  So now what I'm concerned about is do I have to give credit somewhere in my app to the creater of that class?

Also, I plan on having my app be free, but if in the future I charge for it, does that change things?

The most common license I see in an MIT License:

Permission is hereby granted, free of charge, to any person
  obtaining a copy   of this software and associated documentation files
  (the "Software"), to deal   in the Software without restriction,
  including without limitation the rights   to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell   copies of the Software,
  and to permit persons to whom the Software is   furnished to do so,
  subject to the following conditions:
       The above copyright notice and this permission notice shall be included in   all copies or substantial portions of the Software.
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY,   FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE   AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER   LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,   OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN   THE
  SOFTWARE.

The part I'm unsure about is:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Is it enough for this license to be at the top of the class file embedded in the binary, or do I have to make it literally accessible to the user?

Of course I'm not asking for expert legal advice, but any help would be appreciated.

答:
This link might help you.  If because it only says that the notice needs to be included in the software, putting in the source code should be fine.

Also, you do not really need to give credit to anyone else unless they ask you too (and if they wanted you to they'd make it evident when you download their code).

OwnerDisplayName: Andrew

Title: Copyright Laws for Apps


答:
The following is true to most of the opensource licenses:

When you embed an opensource component into your product or your product can not function without it your product is considered a derivative work.

Some of these licenses are sticky, meaning if you create a derivative work and you publish it, then you have to also publish it as an opensource program (under the same license as the component). GPL is an example for this kind.

There are more permissive licenses which are not sticky, meaning you do not have to redistribute your program (and full source code) under the same license. For example MPL is not sticky.

Edit

If you are using their code you have to comply with their rules (the license the chose).

The MPL defines what is considered a derivative work based on files. For example if you copy-paste MPL-ed code into your source file, then that file falls under MPL too. GPL uses more lofty ideas which are open to interpretation.

Title: Copyright Laws for Apps

Body:
For my app that I'm about to release, I have used a bunch of 3rd party classes found for free online.  I checked all the liscenses before using the code and each one said I could use the code commercially  So now what I'm concerned about is do I have to give credit somewhere in my app to the creater of that class?

Also, I plan on having my app be free, but if in the future I charge for it, does that change things?

The most common license I see in an MIT License:

Permission is hereby granted, free of charge, to any person
  obtaining a copy   of this software and associated documentation files
  (the "Software"), to deal   in the Software without restriction,
  including without limitation the rights   to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell   copies of the Software,
  and to permit persons to whom the Software is   furnished to do so,
  subject to the following conditions:
       The above copyright notice and this permission notice shall be included in   all copies or substantial portions of the Software.
       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY,   FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE   AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER   LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,   OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN   THE
  SOFTWARE.

The part I'm unsure about is:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Is it enough for this license to be at the top of the class file embedded in the binary, or do I have to make it literally accessible to the user?

Of course I'm not asking for expert legal advice, but any help would be appreciated.


答:
Use i, j, k... if your indexes have no "meaning".

I would use mesh, vertex, etc. without an i prefix instead, unnecessary Hungarian is evil.

You could also use stuff such as i0, i1, ... , in if you had a great number of nested loops, but I think more than 3-4 is unusual.

Title: Any standards for naming variables in for loops (instead of i,j,k)

Body:
Possible Duplicate:

  Why do most of us use 'i' as a loop counter variable?

I was just writing a nested loop and got to the point where I was using l and m as variables to control for loops, and I realized this could get very confusing; Ive already had a few bugs when I copied blocks of code to different levels.  So I was thinking instead of using i,j,k I would use iSomething,iSomethingelse.  So if I were going over a 3D model Id use

```<code>for(int iMesh=0;iMesh<numMesh;iMesh++)
    for(int iVertex=0;iVertex<meshes[iMesh].numVertex;iVertex++)
</code>```

or maybe use the name of the variable Im iterating over:

for(int iMeshes

for(int iVerts

So I was wondering if there are any other standard or commonly used practices for doing this?

EDIT: Im wondering if there ARE any standards, not if its OK to do this


问:
As a young developer, should I be worried about having to use "out-of-style" tech at work?
I'm a recent college graduate (last May!). While I was still in school, I wanted to make sure that I had a job before I graduated, and very early (probably too early) in my job search I settled on one in a region I'd been hoping to move to after undergrad.

However, I've been second guessing this decision for months now, for several reasons. One is that I'm not very challenged at work, and I feel like I haven't improved much at programming since starting here. I can always make time to work on open source (and have in the past) outside of my job, though, so I do have a venue to get around this disappointment. More importantly, I'm worried by the fact that my job is basically to work on a creaky old Perl web application (using Mason and a weird in-house ORM).

Am I shooting myself in the foot here by working with a technology that's no longer popular, and won't really help me out getting a job in the future? I rarely see Perl jobs, and when I do, it's usually doing something I'm not interested in (front-end web development stuff).

Systems programming, visualisation, network programming, or at least backend web development stuff are the sort of topics that I'd actually enjoy working in -- it doesn't seem like my current work experience is helping me towards positions doing any of these things.

答:
If you don't want to work in Perl anymore that's fine.

Just because Perl doesn't have a lot of flash currently, doesn't mean that it isn't popular.

I would like to point out that Perl's momentum has increased dramatically in just the past 5 years.

There have been more stable releases of Perl in each of the past 2 years, than there have been in any of the previous years.

Moose is considered by most, to be among the best Perl object systems to date, and it only dates back to early 2006. The next most popular object systems are basically simplified Moose object systems.

If you want proof of how popular Moose is, see how many CPAN modules depend on Moose.

Among those modules requiring Moose is Dist::Zilla, which has always required Moose. In case you didn't know, Dist::Zilla is arguably the single best way to build, and release CPAN modules.

Also there are still some cool new projects that are using Perl. The Lacuna Expanse for one.


答:
i,j and k are the standard counter variables. By using them you imply the variables are used to keep loop count and nothing else. If you use another more complex name then its less clear what the variable is used for.

If your counter variables are getting confusing then its a sign your code needs breaking up. i.e

```<code>for(int i=0;i<numMesh;i++)
   foo += CountVerticies(meshes[i]);
</code>```

Body:
i,j and k are the standard counter variables. By using them you imply the variables are used to keep loop count and nothing else. If you use another more complex name then its less clear what the variable is used for.

If your counter variables are getting confusing then its a sign your code needs breaking up. i.e

for(int i=0;i<numMesh;i++)
   foo += CountVerticies(meshes[i]);


答:
If the space is limited, then the overhead of skipping elements one-by-one wouldn't be so important.

Thus, you can construct a tree, made of lists of length-prefixed elements. You can encode the lengths as single bytes, and for records meant to be larger than what this allows, you can shift the value to the left (that wouldn't waste because it's compensated by the smaller field).

Also, if you want to simplify your code further, it might make sense to embed a flag in the size field indicating if the record is raw or a list. That would make trivial to parse the whole data set (either incrementally or on a single pass).

That would be much more efficient than the fixed-length statistical approach.

Plus, you might want to consider applying some form of compression to the whole thing to save some more space.

Title: Optimal storage space calculation for name, address, phone, fax and email data

Body:
Given the following assumptions:

The amount of available data storage is highly limited

All data is international

As much storage as possible must be preserved since it will be used for something else

Is there any widely accepted standard or best practice which defines how much storage should be allocated for those items?

Note: I'm not looking for assumptions but for facts like "97.5% of all names fit into 70 bytes using UTF-8" and "An international address must at least contain field1, field2 and field3 of size1, size2 and size3".

Edit: I'm looking for the fields/lengths to use in the user interface. Not a technique to store it efficiently.


答:
for standard looping people pick i,j,k because it is easy and in a lot of situations you don't have a meaning for it so i,j,k is meaningful also known by all developer so it is pretty close to a standard.

anyway if you need to change to something more meaningful, use the following guidelines that i picked from uncle bob book "Clean Code" note there is other things also to consider from the book, but this is what i thought fit to the looping name: -

Use Intention-Revealing Names

Avoid Disinformation

Make Meaningful Distinctions

Use Pronounceable Names

Use Searchable Names

Avoid Encodings (Hungarian Notation,Member Prefixes)

Don't be cute

Pick One Word per Concept

so the code will end up something like this more or less

```<code>        for(int cellPointer = 0; cellPointer < 10;cellPointer++)
        {
            for (int rowPointer = 0; rowPointer < 10; rowPointer++)
            {
               //do something
            }
        }
</code>```

so when you go back to it you can understand it, if somebody from outside got to work on it after you i'll be readable to him

Body:
for standard looping people pick i,j,k because it is easy and in a lot of situations you don't have a meaning for it so i,j,k is meaningful also known by all developer so it is pretty close to a standard.

anyway if you need to change to something more meaningful, use the following guidelines that i picked from uncle bob book "Clean Code" note there is other things also to consider from the book, but this is what i thought fit to the looping name: -

Use Intention-Revealing Names

Avoid Disinformation

Make Meaningful Distinctions

Use Pronounceable Names

Use Searchable Names

Avoid Encodings (Hungarian Notation,Member Prefixes)

Don't be cute

Pick One Word per Concept

so the code will end up something like this more or less

        for(int cellPointer = 0; cellPointer < 10;cellPointer++)
        {
            for (int rowPointer = 0; rowPointer < 10; rowPointer++)
            {
               //do something
            }
        }

so when you go back to it you can understand it, if somebody from outside got to work on it after you i'll be readable to him


答:
x,y, and z can be useful, especially when dealing with 2D or 3D coordinates.

Sure beats trying to remember that i = x and j = y, etc


答:
One of the problems with using counter variables is that outside of the control logic for iteration they don't have any meaning.

Your instinct is correct that using iVertex is better than using i, as that adds clarity.  However, the 'i' prefix tells you that the variable is an integer, which, while helpful in some circumstances isn't that useful with modern IDEs (this is one reason several answers argue against it).

What is best is just the general advice for naming a variable, which is based on what the variable contains.  In this case, you're thinking of the variable based on how it is modified, but not on how it is used, or what it represents.  A loop counter is incremented from some start to some end, but one can tell that by looking at the control structure.  A better option is to name it based on how it is consumed by the body of the loop.  In this case, iMesh is used as an index into the meshes array, so I would use something like 'meshId'.

One good reason for naming based on how something is intended to be used is that one can more easily detect code defects.  For example, if I see "a = MeshId+2"  I'm going to be very suspicious, because generally we don't want to be doing arithmetic operations on an Id, only index operations (meshes[MeshId]).

There are coding standards, but the problem is that there are too many of them.  For further reading, you can try here:

http://en.wikipedia.org/wiki/Naming_convention_(programming)


答:
i is standard parlance in mathematics to represent any integer in a series:

1, 2, 3 ... i, i+1, i+2 ... n.

The i stands for Integer (according to one of my former professors, I have no other cite.)  So, at any given time in the execution of your loop, it would be accurate from a mathematical perspective to call it i.


问:
Are there any languages that allow the static context of a method call to be available at runtime?
Is it possible for a method to know the type of the method it is called under? So for example in the following object orientated psuedo code:

```<code>Instance io = new InstanceSubclass();
io.doStuff();
</code>```

Is there a language that allows doStuff() to know that it was called as an Instance?

The question arose out of the fact the Java does not provide any kind of support for interface name clashes, for example if you create a class that implements interfaces A and B that both have a method signature such as void doWork() would it be possible for the body of doWork() to do something similar to the following :

```<code>public void doWork() {
    Class<?> context = getMethodCallContext();
    if(context == InterfaceA.class) {
        doAsInterfaceA();
    }
    else if(context == InterfaceB.class) {
        doAsInterfaceB();
    }
    else {
        // Shenanigans and error handling
    }
}
</code>```

I am not planning to write any code that takes advantage of this feature as to do so reeks of an anti-pattern waiting to happen, I only want to know if it CAN be done, if so which languages permit it?

答:
I don't see an interface method name clash here.  There would be a clash in the case of multiple inheritance, but that is a different class relationship.

In your example you have two interfaces both of which require that you implement a void doWork method with no parameters.  What the method needs to do should be independent of which Interface is used to call the method.  If there is a conflict, then it lies in the interface specification, or the design of the class to use the two interfaces with differing expectations of the doWork method.

More complicated method signatures could result in methods with the same name but differing signatures, in which case the signature would be used to differentiate between the two methods.


答:
In C# you just do:

```<code> void InterfaceA.doWork()
 {
 }

 void InterfaceB.doWork()
 {
 }
</code>```

So there are no real shenanigans involved.

The calling function needs to identify which doWork() is intended:

```<code>Instance io = new InstanceSubclass();
((InterfaceA)io).doStuff();
</code>```

See this page for more details.

Title: Are there any languages that allow the static context of a method call to be available at runtime?

Body:
Is it possible for a method to know the type of the method it is called under? So for example in the following object orientated psuedo code:

```<code>Instance io = new InstanceSubclass();
io.doStuff();
</code>```

Is there a language that allows doStuff() to know that it was called as an Instance?

The question arose out of the fact the Java does not provide any kind of support for interface name clashes, for example if you create a class that implements interfaces A and B that both have a method signature such as void doWork() would it be possible for the body of doWork() to do something similar to the following :

```<code>public void doWork() {
    Class<?> context = getMethodCallContext();
    if(context == InterfaceA.class) {
        doAsInterfaceA();
    }
    else if(context == InterfaceB.class) {
        doAsInterfaceB();
    }
    else {
        // Shenanigans and error handling
    }
}
</code>```

I am not planning to write any code that takes advantage of this feature as to do so reeks of an anti-pattern waiting to happen, I only want to know if it CAN be done, if so which languages permit it?

Body:
In C# you just do:

 void InterfaceA.doWork()
 {
 }

 void InterfaceB.doWork()
 {
 }

So there are no real shenanigans involved.

The calling function needs to identify which doWork() is intended:

Instance io = new InstanceSubclass();
((InterfaceA)io).doStuff();

See this page for more details.


答:
What you described is achievable via Aspect-Oriented Programming (AOP). It won't be as straightforward as in your example, but you can get the requested behaviour.

AOP has implementations in different languages; AspectJ being one of the most mature one. I will give you an example using AspectJ even though I don't want to go to in too much detail.

To implement the behaviour:

1) Create a pointcut that will intercept all the calls to the public void doWork() method.

[pointcut conflictingMethodIsExecuted(): execution(public void doWork()]

2) Create an advice around this pointcut. Within the advice, you can get the context; just as you have specified in your example. The JoinPoint will serve you that information.

[joinPoint.getThis() // returns the context]

3) With that information, the advice sets a certain parameter and lets the public void doWork() run. The method takes a look at that parameter and decides what to do.

I assume the question was a bit theoretical so this answer also goes along the same line. I can provide more details about the solution in AspectJ if you choose to take this path.


问:
Resources on Writing Efficient C Code for Micro-controllers?
Serious help needed here. I love programming. I've been reading bunch of books(such as K&R) and articles/forums online for C language lately. Even tried looking into Linux code(although, i was lost where to start but peeking into small libraries helped?).

I started as a Java programmer and in Java it's pretty cut and dry; If programs gets too big, slice it in classes then further into functions. Guidelines like, keep the code readable and add comments. Use information hiding and OOP techniques. Some of which still applies for C.

I've been coding in C now and so far i get programs to work one way or the other. A lot of people talk about performance/efficiency, algorithm/design, optimization, and maintainability. Some people stress one more then the other but for non-professional software engineers you often hear something like e.g: Linux kernel dev won't just take any code.

My question is this: I plan on writing a code for 8-bit microcontroller without wasting any resources. Know that i'm coming from java background so things are not the same anymore... resources/books/links/tips will be much appreciated. Performance and size now matters. Resources/Tricks on efficient(within best practices) C code for 8-bit micro-controllers?

Also, inline assembly plays a vital role as well sticking close to micro-controllers standard. But are there general rule of thumb to efficiency that applies to all?

For example:
register unsigned int variable_name; is preferred over char anytime. Or using  uint8_t  if you don't need big numbers.

EDIT: Thank you so much for all the answers and suggestions. I appreciate everyone's effort for sharing knowledge.

答:
I agree with mattnz's answer - for the most part. I started programming on the 8085 over 30 years ago, then the Z80, then quickly migrated to the 8031. After that I went to the 68300 series microcontrollers, then 80x86, XScale, MXL and (as of late) 8 bit PICS, which I guess means I've come full circle. For the record, I can state that FAE's at several major microprocessor manufacturers still use assembler, albeit in an object oriented fashion for purposeful code reuse.

What I don't see in the approved answer is a discussion of the target processor type and/or proposed architecture. Is it a 0.50$ 8 bitter with limited memory? Is it an ARM9 core with pipelining and 8Meg of flash? Memory management coprocessor? Will it have an OS? A while (1) loop? A consumer device with a intial production run of 100000 units? A start up company with big ideas and dreams?

While I do agree that modern compilers do a great job of optimization, I've never worked on a project in 30 years where I didn't stop the debugger and view the generated assembly code to see just what was going on under the hood (admittedly a nightmare when pipelining and optimization come into play), so knowledge of assembly is important.

And I've never had CEO, VP of Engineering, customer who didn't push me to try and stuff a gallon into a quart container, or save .05$ by using a software solution to fix a hardware problem (hey it's just software right? Whats so hard?). Memory (code or data) optimization will always count.

My point is if you view the project from a pure programming point of view you're going to get a narrower scope solution wise. Mattnz has it right - get it working, then get it working faster, smaller, better, but you still need to spend A LOT of time on the requirements and deliverables before you even think about coding.


问:
Is the GoF book still the one to read?

Possible Duplicate:

  Is there a canonical book on design patterns?

I'd like to read a design patterns book. GoF for sure is the one to read. But after 15 years is it still valid, I mean isn't there an updated one?

Something like "Charles Darwin On the origin of species" is a very important book, and some main concepts are still valid, anyway today (2010) one would read another book to study the subject.

In this question the main suggestions are the Head First and GoF books. But Head first is not a replacement for GoF.

So any suggestion or should I stick with GoF?

答:
Stick with the GoF. In addition, I'd suggest you read the following:

Steven John Metsker's "Design Patterns Java(TM) Workbook" (ISBN 0201743973)

I think this book is a nice complement to the GoF or it could be safely used instead of the GoF if you are learning or working with Java. Similar books exist for other languages like C# and Ruby, but I cannot attest of their quality since I have not read them.

William C. Wake's "Refactoring Workbook" (ISBN 0321109295)

Refactoring goes hand in hand with patterns. This one is a nice workbook to read.

Brown et al "AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis" (ISBN 0471197130)

The other side of the coin are anti-patterns, code smells that scream for refactoring. This book is good (at least the first half that deals with software-related anti-patterns.)

Craig Larmans' "Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition)" (ISBN 0131489062)

Larman's book is pretty much becoming a de-facto preferred textbook for undergrad courses in software engineering and systems analysis. It does a good work in walking through the utilization of UML and patterns in an iterative process.

Chris Okasaki's "Purely Functional Data Structures" (ISBN 0521663504)

I would consider this book once you have developed a good working knowledge of patterns, anti-patterns and re-factoring. It is a theoretical treatise of patterns and data structures from a purely functional point of view.

One of the things with the GoF (and books that carry that baton) is that those patterns are the product of an era where generic programming was finally being realized in C++. The patterns presented therein existed to accommodate a OO and procedural/algorithmic paradigm.

Several of these patterns (visitor for example) don't have much of a reason to exist in languages that treat functions as first-class objects. I would not touch this book without a good grasp of patterns and functional languages, though

ContentLicense: CC BY-SA 2.5

Title: Is the GoF book still the one to read?


问:
How to turn truth table into smallest possible if / else block
How can I take a truth table and turn it into a compacted if block?

For instance, let's say I have this truth table where A and B are conditions and x, y and z are possible actions:

```<code>A B | x y z
-------------
0 0 | 0 0 1
0 1 | 0 0 1
1 0 | 0 1 0
1 1 | 1 0 0
</code>```

This could transform into below if block:

if(A)
{
    if(B)
    {
        do(x)
    }
    else
    {
        do(y)
    }
}
else
{
    do(z)
}
```

This is an easy sample, but I frequently have several conditions that combined in different ways should produce different outputs and it gets hard to figure out the most compacted and elegant way to represent their logic in an if block.

答: Look at the "Gorgeous Karnaugh" software - it can accept truth tables quite exact as your sample, accept analytic boolean formulas definition, accept Lua scripting to build truth tables. Next, "Gorgeous Karnaugh" software draws the K-Maps for taken input, which you can minimize manually or using "Espresso" logic minimizer, and produces output for C/C++ and some hardware languages. Look to the summary features page for "Gorgeous Karnaugh" - http://purefractalsolutions.com/show.php?a=xgk/gkm</p>


问:
How should data be passed between client-side Javascript and C# code behind an ASP.NET app?
I'm looking for the most efficient / standard way of passing data between client-side JavaScript code and C# code behind an ASP.NET application. I've been using the following methods to achieve this but they all feel a bit of a fudge.

To pass data from JavaScript to the C# code is by setting hidden ASP variables and triggering a postback:

```<code><asp:HiddenField ID="RandomList" runat="server" />

function SetDataField(data) {
      document.getElementById('<%=RandomList.ClientID%>').value = data;
}
</code>```

Then in the C# code I collect the list:

```<code>protected void GetData(object sender, EventArgs e)
{
      var _list = RandomList.value;
}
</code>```

Going back the other way I often use either ScriptManager to register a function and pass it data during Page_Load:

```<code>ScriptManager.RegisterStartupScript(this.GetType(), "Set","get("Test();",true);
</code>```

or I add attributes to controls before a post back or during the initialization or pre-rendering stages:

```<code>Btn.Attributes.Add("onclick", "DisplayMessage("Hello");");
</code>```

These methods have served me well and do the job, but they just don't feel complete. Is there a more standard way of passing data between client side JavaScript and C# back-end code?

I've seen some posts like this one that describe HtmlElement class; is this something I should look into?

答:
You can simply and easily call a static page method from JavaScript like in this example. If you need to call the method from multiple pages, you can setup a web service and call it from Javascript the same way. Example also included below.

.aspx Code

```<code><asp:ScriptManager ID="ScriptManager1"
EnablePageMethods="true"
EnablePartialRendering="true" runat="server" />
</code>```

Code-behind Code

```<code>using System.Web.Services;

[WebMethod]
public static string MyMethod(string name)
{
    return "Hello " + name;
}
</code>```

Javascript Code

```<code>function test() {
    alert(PageMethods.MyMethod("Paul Hayman"));
}
</code>```

NOTE: The page methods have to be static. This could be problematic for you, depending on what the application is trying to do. However, if the information is based on session at all, and you're using some sort of built-in authentication, you can put an EnableSession attribute on the WebMethod decorator, and that will allow you to get at HttpContext.Current.User, Session, etc.

Body:
You can simply and easily call a static page method from JavaScript like in this example. If you need to call the method from multiple pages, you can setup a web service and call it from Javascript the same way. Example also included below.

.aspx Code

<asp:ScriptManager ID="ScriptManager1"
EnablePageMethods="true"
EnablePartialRendering="true" runat="server" />

Code-behind Code

using System.Web.Services;

[WebMethod]
public static string MyMethod(string name)
{
    return "Hello " + name;
}

Javascript Code

function test() {
    alert(PageMethods.MyMethod("Paul Hayman"));
}

NOTE: The page methods have to be static. This could be problematic for you, depending on what the application is trying to do. However, if the information is based on session at all, and you're using some sort of built-in authentication, you can put an EnableSession attribute on the WebMethod decorator, and that will allow you to get at HttpContext.Current.User, Session, etc.


答:
A lookup table containing functions pointers can work well in some situations. In C, for example, you can do something like this:

typedef void(*VoidFunc)(void);

void do(int a, int b)
{
    static VoidFunc myFunctions[4] = {z, z, y, x}; // the lookup table

    VoidFunc theFunction = myFunctions[ a * 2 + b ];
    theFunction();
}
```

This is a good solution when the number of inputs is relatively small, since the number of entries in the table has to be 2^^n where n is the number of inputs. 7 or 8 inputs might be manageable, 10 or 12 starts to get ugly. If you have that many inputs, try to simplify by other means (such as Karnaugh maps) first.

Title: How to turn truth table into smallest possible if / else block

Body:
How can I take a truth table and turn it into a compacted if block?

For instance, let's say I have this truth table where A and B are conditions and x, y and z are possible actions:

```<code>A B | x y z
-------------
0 0 | 0 0 1
0 1 | 0 0 1
1 0 | 0 1 0
1 1 | 1 0 0
</code>```

This could transform into below if block:

if(A)
{
    if(B)
    {
        do(x)
    }
    else
    {
        do(y)
    }
}
else
{
    do(z)
}
```

This is an easy sample, but I frequently have several conditions that combined in different ways should produce different outputs and it gets hard to figure out the most compacted and elegant way to represent their logic in an if block.

Body:
A lookup table containing functions pointers can work well in some situations. In C, for example, you can do something like this:

typedef void(*VoidFunc)(void);

void do(int a, int b)
{
    static VoidFunc myFunctions[4] = {z, z, y, x}; // the lookup table

    VoidFunc theFunction = myFunctions[ a * 2 + b ];
    theFunction();
}

This is a good solution when the number of inputs is relatively small, since the number of entries in the table has to be 2^^n where n is the number of inputs. 7 or 8 inputs might be manageable, 10 or 12 starts to get ugly. If you have that many inputs, try to simplify by other means (such as Karnaugh maps) first.


问:
Recommend a text that explains the physical implementation of C (stack, heap, etc)
One of the most popular questions on stackoverflow.com is this one:

https://stackoverflow.com/questions/4025768/what-do-people-find-difficult-about-c-pointers

Many of the answers seem to gravitate toward the fact that students often don't get a good understanding of what is physically going on when code executes... the very most basic part of this seems to be stack/heap.

I've read through K&R twice and finally have a good understanding of the language, but I don't think that is enough.  Nearly every tough question here has the work "stack" or "heap" in the answer, and while I have a limited understanding of what those mean just from context and wikipedia searches, I prefer the comprehensive approach of a textbook.  So, please recommend a textbook which explains things like stack, heap, memory allocation, etc from a physical standpoint, as it relates to C programming.

I tried asking this question on stackoverflow and apparently it was not the right place to ask it.  So I hope this site is a better location.  If not, please consider migrating it to the proper stackexchange site.  Thanks.

答:
Many of the answers seem to gravitate toward the fact that students
  often don't get a good understanding of what is physically going on
  when code executes... the very most basic part of this seems to be
  stack/heap.

This is indeed true. And one of the most essential need for understanding the machine is even more important when you are in C.

Ref: 1

There is a book to deal with exactly this subject - Write Great Code

There are two volumes of the book - the first one essentially is only about the way in which a typical machine architecture book. Unlike many microprocessor books which focus on particular architecture - here is a book that captures what high level abstractions matter at the time of programming.

The second volume actually tells you about "Thinking Low-Level, Writing High-Level"

Ref: 2

If you want to go even more deep, here is another book - "The art of Assembly language programming"

Unlike most other books - this book introduces Highlevel Assembly language. This is best reference on low level understanding.

Ref: 3

Many issues with C programming revolves around effective usage of memory. These abstractions become key to be able to write scalable systems in C.

Here is a very good resource that focuses on this. http://www.memorymanagement.org/articles/begin.html

Hope this helps.


问:
Unit testing methods with indeterminate output
I have a class that is meant to generate a random password of a length that's also random, but limited to be between a defined min and max length.

I'm constructing unit tests, and ran into an interesting little snag with this class.  The whole idea behind a unit test is that it should be repeatable.  If you run the test a hundred times, it should give the same results a hundred times.  If you're depending on some resource that may or may not be there or may or may not be in the initial state you expect then you're meant to mock the resource in question to ensure that your test really is always repeatable.

But what about in cases where the SUT is supposed to generate indeterminate output?

If I fix the min and max length to the same value then I can easily check that the generated password is of the expected length.  But if I specify a range of acceptable lengths (say 15 - 20 chars), then you now have the problem that you could run the test a hundred times and get 100 passes but on the 101st run you might get a 9 character string back.

In the case of the password class, which is fairly simple at its core, it shouldn't prove a huge problem.  But it got me thinking about the general case.  What is the strategy that's usually accepted as the best one to take when dealing with SUTs that are generating indeterminate output by design?

答:
Test against "the contract". When the methods is defined as "generates passwords of 15 to 20 characters length with a-z", test it this way

```<code>$this->assertTrue ((bool) preg_match('^[a-z]{15,20}$', $password));
</code>```

Additional you can extract the generation, so everything, that relies on it, can get tested using another "static" generator class

```<code>class RandomGenerator implements PasswordGenerator {
  public function create() {
    // Create $rndPwd
    return $rndPwd;
  }
}

class StaticGenerator implements PasswordGenerator {
  private $pwd;
  public function __construct ($pwd) { $this->pwd = $pwd; }
  public function create      ()     { return $this->pwd; }
}
</code>```

OwnerDisplayName: GordonM

Body:
Test against "the contract". When the methods is defined as "generates passwords of 15 to 20 characters length with a-z", test it this way

$this->assertTrue ((bool) preg_match('^[a-z]{15,20}$', $password));

Additional you can extract the generation, so everything, that relies on it, can get tested using another "static" generator class

class RandomGenerator implements PasswordGenerator {
  public function create() {
    // Create $rndPwd
    return $rndPwd;
  }
}

class StaticGenerator implements PasswordGenerator {
  private $pwd;
  public function __construct ($pwd) { $this->pwd = $pwd; }
  public function create      ()     { return $this->pwd; }
}

OwnerDisplayName: KingCrunch


答:
The actual output password might not be determinate each time the method is executed, but it will still have determinate features that can be tested, such as minimum length, characters falling within a determinate character set, etc.

You can also test that the routine returns a determinate result each time by seeding your password generator with the same value each time.

Title: Unit testing methods with indeterminate output

Body:
I have a class that is meant to generate a random password of a length that's also random, but limited to be between a defined min and max length.

I'm constructing unit tests, and ran into an interesting little snag with this class.  The whole idea behind a unit test is that it should be repeatable.  If you run the test a hundred times, it should give the same results a hundred times.  If you're depending on some resource that may or may not be there or may or may not be in the initial state you expect then you're meant to mock the resource in question to ensure that your test really is always repeatable.

But what about in cases where the SUT is supposed to generate indeterminate output?

If I fix the min and max length to the same value then I can easily check that the generated password is of the expected length.  But if I specify a range of acceptable lengths (say 15 - 20 chars), then you now have the problem that you could run the test a hundred times and get 100 passes but on the 101st run you might get a 9 character string back.

In the case of the password class, which is fairly simple at its core, it shouldn't prove a huge problem.  But it got me thinking about the general case.  What is the strategy that's usually accepted as the best one to take when dealing with SUTs that are generating indeterminate output by design?

OwnerDisplayName: Mark Baker


答:
"Non-deterministic" output should have a way of becoming deterministic for the purposes of unit testing. One way to handle randomness is to allow replacement of the random engine.  Here is an example (PHP 5.3+):

```<code>function DoSomethingRandom($getRandomIntLessThan)
{
    if ($getRandomIntLessThan(2) == 0)
    {
        // Do action 1
    }
    else
    {
        // Do action 2
    }
}

// For testing purposes, always return 1
$alwaysReturnsOne = function($n) { return 1; };
DoSomethingRandom($alwaysReturnsOne);
</code>```

You could make a specialized test version of the function which returns any sequence of numbers you want to make sure the test is fully repeatable.  In the real program, you can have a default implementation which could be the fallback if not overridden.

Body:
"Non-deterministic" output should have a way of becoming deterministic for the purposes of unit testing. One way to handle randomness is to allow replacement of the random engine.  Here is an example (PHP 5.3+):

function DoSomethingRandom($getRandomIntLessThan)
{
    if ($getRandomIntLessThan(2) == 0)
    {
        // Do action 1
    }
    else
    {
        // Do action 2
    }
}

// For testing purposes, always return 1
$alwaysReturnsOne = function($n) { return 1; };
DoSomethingRandom($alwaysReturnsOne);

You could make a specialized test version of the function which returns any sequence of numbers you want to make sure the test is fully repeatable.  In the real program, you can have a default implementation which could be the fallback if not overridden.

OwnerDisplayName: bobbymcr


答:
You have a Password generator and you need a random source.

As you stated in the question a random makes non-deterministic output as it is global state. Meaning it accesses something outside of the system to generate values.

You can never get rid of something like that for all your classes but you can separate the password generation for the creation of random values.

```<code><?php
class PasswordGenerator {

    public function __construct(RandomSource $randomSource) {
        $this->randomSource = $randomSource
    }

    public function generatePassword() {
        $password = '';
        for($length = rand(10, 16); $length; $length--) {
            $password .= $this-toChar($this->randomSource->rand(1,26));
        }
    }

}
</code>```

If you structure the code like this you can mock out the RandomSource for your tests.

You will not be able to 100% test the RandomSource but the suggestions you got for testing the values in this question can be applied to it (Like testing that rand->(1,26); always returns a number from 1 to 26.

Body:
You have a Password generator and you need a random source.

As you stated in the question a random makes non-deterministic output as it is global state. Meaning it accesses something outside of the system to generate values.

You can never get rid of something like that for all your classes but you can separate the password generation for the creation of random values.

<?php
class PasswordGenerator {

    public function __construct(RandomSource $randomSource) {
        $this->randomSource = $randomSource
    }

    public function generatePassword() {
        $password = '';
        for($length = rand(10, 16); $length; $length--) {
            $password .= $this-toChar($this->randomSource->rand(1,26));
        }
    }

}

If you structure the code like this you can mock out the RandomSource for your tests.

You will not be able to 100% test the RandomSource but the suggestions you got for testing the values in this question can be applied to it (Like testing that rand->(1,26); always returns a number from 1 to 26.

OwnerDisplayName: edorian


问:
Which algorithms and data structures should a developer absolutely know?
I want to be a successful enterprise Java developer. With what algorithms and data structures should I be well versed? What books would you recommend to me?

To be a successful Java developer, do I need to know all the advanced algorithms such as those given in CLRS?

Can you suggest a list of the topics that I should learn in the descending order of their priority?

Must I know:

Searching?

Sorting?

Graphs/Trees?

etc?

答:
I am learning Java now a days.

I want to be a successful enterprise
  developer. Then what algorithms and
  data structures I should be well
  versed with? What books would you
  recommend me?

To be a successful Java developer, do
  I need to know all the advanced
  algorithms such as those given in
  CLRS?

Can you suggest me a list of the
  topics that I should learn in the
  descending order of their priority?

Tell me the name of some topics that I
  must know. Like Searching, Sorting,
  Graphs, Trees etc?

It is good that you are eager to extend and improve your programming skills. It is important however, not to treat algorithms as a catalog of things to memorize. What you need to know to become a good developer (in Java or anything else for that matter) is to understand algorithmic analysis.

You learn this by learning a select few data structures and algorithms, and learning to analyze their performance in terms of time and space (memory). Searching, sorting, graphs, trees, heaps, stacks and all of that good stuff. This should also follow some basics of theory of computation and discrete mathematics (even if in the realm of Java we never get to actually use those two topics directly - their benefits are indirect.)

Separate the learning of a programming  language (in your case Java) with the learning of
algorithmic analysis (which is different from the "memorization" of algorithms and data structures.)

George T. Heineman, Gary Pollice and Stanley Selkow's "Algorithms in a Nutshell" is a good start. "Algorithms" by Sanjoy Dasgupta, Christos Papadimitriou, and Umesh Vazirani is another good undergrad textbook.

The best think is to take 9-12 credit courses in programming before taking an undergrad, 3000-level course in algorithms. Barring that, self-study with the two books I mentioned might be a good alternative (self-study might not be for everyone, though.)

Good luck!


答:
In the case of a particle physics Monte Carlo, I have written "unit tests"{*} that invoke the non-deterministic routine with a preset random seed, and then run a statistical number of times and check for violations of constraints (energy levels above the input energy must be inaccessible, all passes must select some level, etc) and regressions against the previously recorded results..

{*} Such test violate the "make the test fast" principle for unit testing, so you might feel better characterizing them in some other way: acceptance tests or regression tests, for instance. Still, I used my unit testing framework.

OwnerDisplayName: dmckee


答:
You actually have multiple responsibilities here. Unit testing and in particular TDD is great for highlighting this sort of thing.

Responsibilities are:

1) Random number generator.
2) Password formatter.

The password formatter uses the random number generator. Inject the generator into your formatter via its constructor as an interface. Now you can fully test your random number generator (statistical test) and you can test the formatter by injecting a mocked random number generator.

Not only do u get better code you get better tests.

OwnerDisplayName: Rob Smyth


问:
Is the author of an open-source application obliged to make the "open-sourceness" visible?
What are the legal obligations to put into evidence that my application (I am the author) is open-source (especially when it is derivate), if I want to sell copies of it?

I mean, could my open-source application be sold, with all the licensing stuff and source code inside and not hidden, but without saying so in the advertising for the app in the app-store?

答:
It is a requirement of the open source definition that "The program must include source code, and must allow distribution in source code as well as compiled form." There is no requirement to prominently advertise the fact that your application is open source, but you must make the code available.

As an example, my TV runs Linux. If I go deep into the settings menu I can find an "licence" page that displays the licence and a URL to get the source. However, nowhere in the advertising or the handbook does it say anything about open source.

NOTE: Many app-store terms and conditions prevent some types of open source license being deployed on their service. See App Stores and Openess for more information.

OwnerDisplayName: rgardler


问:
What is a good time/task tracking software to use when consulting?
I am looking for time tracking software to use as an individual consulting on multiple projects at once.  The projects I work on are billable to different clients.  Some clients are billed on an hourly basis while others are billed on a project basis.  I also track personal projects that may never produce income.  I need to be able to track the time down to the individual task level.  I am looking for software that is easy to use, cost effective, easy to invoice out of and has data mining reports.</p>

答:
I prefer FogBugz.

It's UI is very easy to work with, specifically because it supports using only the keyboard well.  It is primarily task based, and tracks time against tasks.  It has evidence-based scheduling, which I think can be particularly helpful for an individual working in a consulting type environment.  Over time, FogBugz helps me more accurately translate my work estimates into calendar time until completion.

FogBugz also integrates beautifully with Kiln, a hosted Mercurial system.  This lets me kill two birds with one stone, so to speak.  Mercurial is my preferred DVCS, and the UI - like FogBugz - is as polished as any.

When you consider the quality of FogCreek's software, and their obvious commitment to building the best of breed developer tools in their market - it is easy to rely on them for such cornerstone's of development as task management and source code control.

And, both FogBugz and Kiln have free accounts for up to two users.  This sounds like an advertisement, but honestly I think they are great tools.


问:
Undefined behaviours in C
Recently I came across a number of undefined features in C, one of them being the following:

https://stackoverflow.com/questions/8698048/behaviour-of-non-const-int-pointer-on-a-const-int

Could someone tell me what should I answer when such a question is asked during online exams ( and None of These / Undefined option is not available ) ?

Also, could you point me to a document specifying the most commonly encountered undefined behaviours in C ?

Thanks.

答:
You can do either of the following:

Check the "right" answer (the one that your experience with the professor tells you that he wants to see). Sometimes the professors think they know better when they don't. You can argue (and get a hit with the grade) or just let them hear what they want to hear.

Approach the professor and raise the issue. Ask a question during the office hours or even in the class. That's what I would do. You don't want to know my GPA.

Write (if possible) an additional answer "This is undefined behavior per standard, but I believe most compilers would do ..." and proceed with #1.

Generally if professors put you in this position it means a lot about their own knowledge and qualifications. But, I don't think you want to put yourself into a position of that annoying student that puts the professor to shame. I did it twice, in one class I ended up with A+, in another with barely a B (after scoring 100% in the final exam). You never know how they'll take it. Some are ready to admit a mistake, some will be very vicious.

Title: Undefined behaviours in C


问:
What is an effective way to convert a shared memory-mapped system to another data access model?
I have a code base that is designed around shared memory.  Each process that needs to access the memory maps it into its own address space.  The data structures in the shared memory are directly accessed, that is, there is no API.  For example:

Assume the following:

```<code>typedef struct {
  int x;
  int y;
  struct {
    int a;
    int b;
  } z;
} myStruct;

myStruct s;
</code>```

Then a process might access this structure as:

```<code>myStruct *s = mapGlobalMem();
</code>```

And use it as:

```<code>int tmpX = s->x;
</code>```

The majority of the information in the global structure is configuration information that is set once and read many times.  I would like to store this information in a database and develop an API to access the database.  The problem is, these references are sprinkled throughout the code.  I need a way to parse the code and identify global structure references that will need to be refactored.

I've looked into using ANTLR to create a parser that will identify references to a small set of structures and enter them into a custom symbol table.  I could then use this symbol table to identify which source files need to be refactored.  It looks like a promising approach.

What other approaches are there?  Of course, I'm looking for a programmatic approach.  There are far too many source files to examine each one visually.

This is all ordinary ANSI C.  Nothing else.

答:
Based on your description, here is how i would set out as the objective.

The mechanism of use for end application should remain same; i.e.

myStruct *s = mapGlobalMem();
int tmpX = s->x;   should not change. This implies that application which uses this GlobalMap shouldn't be aware that such a map is actually from the database.

Both mechanism should continue to function - i.e the existing app should work as it is where it is currently getting the Map or additionally now it can get it from the DB as well.

The system should be thread-safe, and multi-instance capable. Think of it like Malloc(). It manages internal data structures of various things. However, if multiple threads approaches simultaneously it doesn't spoil the structure and different thread/objects can ask for memory and are assigned different blocks.

The overall code base is much larger - hence the unit of changes should be isolated on specific central segments only. i.e. i would change the Map creation part (central) rather than Map access part (distributed all over the code). In this case

Since, i am anyway extending this system in one aspect - say connectivity with DB - i may also extend it in such a way that tomorrow other mechanisms can be used to provide such information.

I am assuming that DATA which is represented in *s is now fetched from DB rather than current source.
(If i am wrong here - most of the answer below might need to be rewritten.)

Here is what i would do.

There is extension of primary functionality with a new API : something like
setGlobalMem(info);

The info is where i decide which source to use - whether current methodology or db, and if in DB - which query will essentially redistribute it.
Alternatively one can also imagine that config can come through a .conf file or through some other form of input.

Re-factor the primary API to support both options. Basically i would have a guarded pointer something like *currentValidMap. Whenever there is an update to/from any data source the final s is updated as one of this; probably something like this might just exists.

I might have an additional function like updateMap(section,source) used restrictively to override some config options locally for example. Here i would use part of the info through some other source. More importantly i might also have lockMap to close any further modifications to the Map. All these APIs are used centrally to establish the Map as required.

I am assuming things - so might be inaccurate in some cases because of this.

Basically I would never modify any other part of the application which is only reading the config data - they have no business to understand where the config data is coming from.


问:
Naming conventions for instance, local and parameter variables
I was discussing with a senior developper coding conventions to apply to our projects (mainly Java/JEE projects). I disagreed with one convention he proposed:

Instance variable names should start with "_", local variables with
  "loc", and method parameters with "par", so it would be easy to identify
  a variable origin and scope.

While he put forward arguments for short-term memory and readability, I disagreed on the fact that it rather decreases readability, IDEs like Eclipse format variables differently depending on their type, and this problem would be avoided with a good class and method design.

Do you have any opinion, arguments or studies that supports my point (or opposes it)?

答:
As Wikipedia says on the subject - Rules for naming of java,

Local variables, instance variables, and class variables are also
  written in lowerCamelCase. Variable names should not start with
  underscore (_) or dollar sign ($) characters, even though both are
  allowed. Certain coding conventions state that underscores should be
  used to prefix all instance variables, for improved reading and
  program understanding.

According to my experience with coding standards, Instance variable names start with "_" is not much good as wikipedia standards say.

local variables with "loc", and method parameters with "par", as you said it would be easy to identify a variable origin and scope, but it should be for you, not the other programmers who may go through your code for maintenance someday.

As per the Clean Code specification about the methods these should be short as much they can you do for readability and variables names should should not be mind mapped, they should be relevant to your operation that your method perform.

Member/Scope Prefixes,
You also don’t need to prefix member variables with m_ anymore. Your classes and functions
should be small enough that you don’t need them. And you should be using an editing
environment that highlights or colorizes members to make them distinct.

```<code>public class Part {
private String m_dsc; // The textual description
void setName(String name) {
m_dsc = name;
}
}
</code>```

```<code>public class Part {
String description;
void setDescription(String description) {
this.description = description;
}
}
</code>```

Besides, people quickly learn to ignore the prefix (or suffix) to see the meaningful
part of the name. The more we read the code, the less we see the prefixes. Eventually the
prefixes become unseen clutter and a marker of older code.

Body:
As Wikipedia says on the subject - Rules for naming of java,

Local variables, instance variables, and class variables are also
  written in lowerCamelCase. Variable names should not start with
  underscore (_) or dollar sign ($) characters, even though both are
  allowed. Certain coding conventions state that underscores should be
  used to prefix all instance variables, for improved reading and
  program understanding.

According to my experience with coding standards, Instance variable names start with "_" is not much good as wikipedia standards say.

local variables with "loc", and method parameters with "par", as you said it would be easy to identify a variable origin and scope, but it should be for you, not the other programmers who may go through your code for maintenance someday.

As per the Clean Code specification about the methods these should be short as much they can you do for readability and variables names should should not be mind mapped, they should be relevant to your operation that your method perform.

Member/Scope Prefixes,
You also don’t need to prefix member variables with m_ anymore. Your classes and functions
should be small enough that you don’t need them. And you should be using an editing
environment that highlights or colorizes members to make them distinct.

public class Part {
private String m_dsc; // The textual description
void setName(String name) {
m_dsc = name;
}
}

public class Part {
String description;
void setDescription(String description) {
this.description = description;
}
}

Besides, people quickly learn to ignore the prefix (or suffix) to see the meaningful
part of the name. The more we read the code, the less we see the prefixes. Eventually the
prefixes become unseen clutter and a marker of older code.


答:
Most of the above answers indicate that mocking the random number generator is the way to go, however I was simply using the built in mt_rand function.  Allowing mocking would have meant rewriting the class to require a random number generator be injected at construction time.

Or so I thought!

One of the consequences of the addition of namespaces is that mocking built in PHP functions has gone from incredibly hard to trivially simple.  If the SUT is in a given namespace then all you need to do is define your own mt_rand function in the unit test under that namespace, and it will be used instead of the built in PHP function for the duration of the test.

Here is the finalized test suite:

```<code>namespace gordian\reefknot\util;

/**
 * The following function will take the place of mt_rand for the duration of
 * the test.  It always returns the number exactly half way between the min
 * and the max.
 */
function mt_rand ($min = 42, $max = NULL)
{
    $min    = intval ($min);
    $max    = intval ($max);

    $max    = $max < $min? $min: $max;
    $ret    = round (($max - $min) / 2) + $min;

    //fwrite (STDOUT, PHP_EOL . PHP_EOL . $ret . PHP_EOL . PHP_EOL);
    return ($ret);
}

/**
 * Override the password character pool for the test
 */
class PasswordSubclass extends Password
{
    const CHARLIST  = 'AAAAAAAAAA';
}

/**
 * Test class for Password.
 * Generated by PHPUnit on 2011-12-17 at 18:10:33.
 */
class PasswordTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var gordian\reefknot\util\Password
     */
    protected $object;

    const PWMIN = 15;
    const PWMAX = 20;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp ()
    {
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown ()
    {

    }

    public function testGetPassword ()
    {
        $this -> object = new PasswordSubclass (self::PWMIN, self::PWMAX);
        $pw = $this -> object -> getPassword ();
        $this -> assertTrue ((bool) preg_match ('/^A{' . self::PWMIN . ',' . self::PWMAX . '}$/', $pw));
        $this -> assertTrue (strlen ($pw) >= self::PWMIN);
        $this -> assertTrue (strlen ($pw) <= self::PWMAX);
        $this -> assertTrue ($pw === $this -> object -> getPassword ());
    }

    public function testGetPasswordFixedLen ()
    {
        $this -> object = new PasswordSubclass (self::PWMIN, self::PWMIN);
        $pw = $this -> object -> getPassword ();
        $this -> assertTrue ($pw === 'AAAAAAAAAAAAAAA');
        $this -> assertTrue ($pw === $this -> object -> getPassword ());
    }

    public function testGetPasswordFixedLen2 ()
    {
        $this -> object = new PasswordSubclass (self::PWMAX, self::PWMAX);
        $pw = $this -> object -> getPassword ();
        $this -> assertTrue ($pw === 'AAAAAAAAAAAAAAAAAAAA');
        $this -> assertTrue ($pw === $this -> object -> getPassword ());
    }

    public function testInvalidLenThrowsException ()
    {
        $exception  = NULL;
        try
        {
            $this -> object = new PasswordSubclass (self::PWMAX, self::PWMIN);
        }
        catch (\Exception $e)
        {
            $exception  = $e;
        }
        $this -> assertTrue ($exception instanceof \InvalidArgumentException);
    }
}
</code>```

I thought I'd mention this, because overriding PHP internal functions is another use for namespaces that simply hadn't occurred to me.  Thanks to everyone for the help with this.

Body:
Most of the above answers indicate that mocking the random number generator is the way to go, however I was simply using the built in mt_rand function.  Allowing mocking would have meant rewriting the class to require a random number generator be injected at construction time.

Or so I thought!

One of the consequences of the addition of namespaces is that mocking built in PHP functions has gone from incredibly hard to trivially simple.  If the SUT is in a given namespace then all you need to do is define your own mt_rand function in the unit test under that namespace, and it will be used instead of the built in PHP function for the duration of the test.

Here is the finalized test suite:

namespace gordian\reefknot\util;

/**
 * The following function will take the place of mt_rand for the duration of
 * the test.  It always returns the number exactly half way between the min
 * and the max.
 */
function mt_rand ($min = 42, $max = NULL)
{
    $min    = intval ($min);
    $max    = intval ($max);

    $max    = $max < $min? $min: $max;
    $ret    = round (($max - $min) / 2) + $min;

    //fwrite (STDOUT, PHP_EOL . PHP_EOL . $ret . PHP_EOL . PHP_EOL);
    return ($ret);
}

/**
 * Override the password character pool for the test
 */
class PasswordSubclass extends Password
{
    const CHARLIST  = 'AAAAAAAAAA';
}

/**
 * Test class for Password.
 * Generated by PHPUnit on 2011-12-17 at 18:10:33.
 */
class PasswordTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var gordian\reefknot\util\Password
     */
    protected $object;

    const PWMIN = 15;
    const PWMAX = 20;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp ()
    {
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown ()
    {

    }

    public function testGetPassword ()
    {
        $this -> object = new PasswordSubclass (self::PWMIN, self::PWMAX);
        $pw = $this -> object -> getPassword ();
        $this -> assertTrue ((bool) preg_match ('/^A{' . self::PWMIN . ',' . self::PWMAX . '}$/', $pw));
        $this -> assertTrue (strlen ($pw) >= self::PWMIN);
        $this -> assertTrue (strlen ($pw) <= self::PWMAX);
        $this -> assertTrue ($pw === $this -> object -> getPassword ());
    }

    public function testGetPasswordFixedLen ()
    {
        $this -> object = new PasswordSubclass (self::PWMIN, self::PWMIN);
        $pw = $this -> object -> getPassword ();
        $this -> assertTrue ($pw === 'AAAAAAAAAAAAAAA');
        $this -> assertTrue ($pw === $this -> object -> getPassword ());
    }

    public function testGetPasswordFixedLen2 ()
    {
        $this -> object = new PasswordSubclass (self::PWMAX, self::PWMAX);
        $pw = $this -> object -> getPassword ();
        $this -> assertTrue ($pw === 'AAAAAAAAAAAAAAAAAAAA');
        $this -> assertTrue ($pw === $this -> object -> getPassword ());
    }

    public function testInvalidLenThrowsException ()
    {
        $exception  = NULL;
        try
        {
            $this -> object = new PasswordSubclass (self::PWMAX, self::PWMIN);
        }
        catch (\Exception $e)
        {
            $exception  = $e;
        }
        $this -> assertTrue ($exception instanceof \InvalidArgumentException);
    }
}

I thought I'd mention this, because overriding PHP internal functions is another use for namespaces that simply hadn't occurred to me.  Thanks to everyone for the help with this.


答:
I presume you are referring to an online exam in which there is no professor to speak to, and no margin to handwrite an objection.

So, what I would do in your shoes is that I would pick the answer that most closely matches "undefined" (something like "prohibited" or "crash") and if none of these are available then I would just pick a guess.  Then, I would wait until my exam gets graded, and if my answer to this question is flagged as wrong, I would take it to the dean.

Start looking for the dean's email from now.

EDIT

The most famous instance of undefined behavior in C is this:

```<code>int somefunction( int x, int y );
...
int a = 5;
int result = somefunction( a, a++ );
</code>```

The question is "what is wrong with the above call?"

I came across this one in an interview once, but it was just for bonus points, they did not really expect the candidate to know. The answer is undefined behavior because C does not guarantee to you that 'a++' will be evaluated after 'a'. So, somefunction may be called with x=5, y=6 or it may be called with x=5, y=5 or x=6, y=6. (or a whale and a bowl of petunias might fall from the sky <-- EDIT: no, this is not a possibility.)

Title: Undefined behaviours in C

Body:
Recently I came across a number of undefined features in C, one of them being the following:

https://stackoverflow.com/questions/8698048/behaviour-of-non-const-int-pointer-on-a-const-int

Could someone tell me what should I answer when such a question is asked during online exams ( and None of These / Undefined option is not available ) ?

Also, could you point me to a document specifying the most commonly encountered undefined behaviours in C ?

Thanks.

Body:
I presume you are referring to an online exam in which there is no professor to speak to, and no margin to handwrite an objection.

So, what I would do in your shoes is that I would pick the answer that most closely matches "undefined" (something like "prohibited" or "crash") and if none of these are available then I would just pick a guess.  Then, I would wait until my exam gets graded, and if my answer to this question is flagged as wrong, I would take it to the dean.

Start looking for the dean's email from now.

EDIT

The most famous instance of undefined behavior in C is this:

int somefunction( int x, int y );
...
int a = 5;
int result = somefunction( a, a++ );

The question is "what is wrong with the above call?"

I came across this one in an interview once, but it was just for bonus points, they did not really expect the candidate to know. The answer is undefined behavior because C does not guarantee to you that 'a++' will be evaluated after 'a'. So, somefunction may be called with x=5, y=6 or it may be called with x=5, y=5 or x=6, y=6. (or a whale and a bowl of petunias might fall from the sky <-- EDIT: no, this is not a possibility.)


答:
There is an additional test you should include in this situation, and that is one to ensure that repeated calls to the password generator actually produces different passwords. If you need a thread-safe password generator you should also test simultaneous calls using multiple threads.

This basically ensures that you are using your random function properly, and not re-seeding on every call.


问:
How do existential types differ from interfaces?
Given the existential type

```<code>T = ∃X.{op₁:X, op₂:X→boolean}
</code>```

and this generic Java interface:

```<code>interface T<X> {
    X op₁();
    boolean op₂(X something);
}
</code>```

What are the fundamental differences between the existential type and the Java interface?

Obviously there are syntactical differences, and Java's object-orientation (which also includes details such as hidden this parameters etc.). I'm not so much interested in these as in conceptual and semantic differences — though if someone would like to shed light on some finer points (such as the notational difference between T vs. T<X>), that would be appreciated too.

答:
Hmm... That definition looks very similar to some haskell sample I've seen long time ago.

{-# LANGUAGE ExistentialQuantification #-}
data X = forall a . X { value :: a, viewValue :: a -> String }
instance Show X where show (X { value = x, viewValue = f}) = f x
sample :: [X]
sample = [X 3 show, X "abc" show, X 3.14 show]
```

<p>When constructor <code>X</code> is applied ∀ actually becomes ∃. Note that when you take out <code>value</code> you don't know the type and have empty set of operation over it. But since <code>viewValue</code> is kinda coherent with <code>value</code> it can be applied to it.</p>

<p>I guess the main difference of Java <code>interface</code> you proposed is the fact that you have to know intermediate type for passing result of <code>op₁</code> to <code>op₂</code>. I.e. proper system for existential type should select the right type which is guaranteed to exist by condition. I.e. you should be able to write function with type: <code>∀X. X→(X→boolean)→T</code>. In prev sample such function is <code>X</code> constructor used in <code>X 3 show</code> (<code>show</code> is function which takes argument of any type that implements <code>Show</code> and returns <code>String</code>)</p>

<p><strong>Updated:</strong> I just re-read your question and I think I've got proper construction for Java:</p>

<pre class="lang-java prettyprint-override"><code>interface T {
    boolean op₂();
}
...
T x = new T() {
    private final int op₁ = ...;
    public boolean op₂() { return ((op₁ % 2) == 0); }
};
T y = new T() {
    private final char op₁ = ...;
    public boolean op₂() { return ('0' <= op₁ && op₁ <= '9'); }
};
if (x.op₂() && y.op₂()) ...
</code>```

You are right about mentioning this - it's actually your op₁.

So I guess I understood now that classical OOP languages (Java, C#, C++ etc) always implement existential type with single value this and a functions over it called "methods" which implicitly called with that value :)

P.S. Sorry, I'm not very familiar with Java, but I hope you've got the idea.

Body:
Hmm... That definition looks very similar to some haskell sample I've seen long time ago.

{-# LANGUAGE ExistentialQuantification #-}
data X = forall a . X { value :: a, viewValue :: a -> String }
instance Show X where show (X { value = x, viewValue = f}) = f x
sample :: [X]
sample = [X 3 show, X "abc" show, X 3.14 show]

When constructor X is applied ∀ actually becomes ∃. Note that when you take out value you don't know the type and have empty set of operation over it. But since viewValue is kinda coherent with value it can be applied to it.

I guess the main difference of Java interface you proposed is the fact that you have to know intermediate type for passing result of op₁ to op₂. I.e. proper system for existential type should select the right type which is guaranteed to exist by condition. I.e. you should be able to write function with type: ∀X. X→(X→boolean)→T. In prev sample such function is X constructor used in X 3 show (show is function which takes argument of any type that implements Show and returns String)

Updated: I just re-read your question and I think I've got proper construction for Java:

interface T {
    boolean op₂();
}
...
T x = new T() {
    private final int op₁ = ...;
    public boolean op₂() { return ((op₁ % 2) == 0); }
};
T y = new T() {
    private final char op₁ = ...;
    public boolean op₂() { return ('0' <= op₁ && op₁ <= '9'); }
};
if (x.op₂() && y.op₂()) ...

You are right about mentioning this - it's actually your op₁.

So I guess I understood now that classical OOP languages (Java, C#, C++ etc) always implement existential type with single value this and a functions over it called "methods" which implicitly called with that value :)

P.S. Sorry, I'm not very familiar with Java, but I hope you've got the idea.


答:
As the others have already mentioned, you unit test this code by removing the randomness.

You might also want to have a higher-level test that leaves the random number generator in place, tests only the contract (password length, allowed characters, ...) and, on failure, dumps enough information to allow you to reproduce the system state in the one instance where the random test failed.

It does not matter that the test itself is not repeatable -- as long as you can find the reason why it failed this one time.


答:
This is largely a matter of preference, and as such there is no 'correct' answer. So, this question might actually be closed. But before it does, let me tell you that I totally agree with you. Prefixes decrease visibility as far as I am concerned. Let alone the fact that if there are to be any prefixes, they should be used for more useful stuff, like the original intention of the Hungarian Notation, and not for things that your IDE can provide highlighting for anyway.

I use SentenceCase for instance data (whether variables or constants) and lower_case for parameters and local variables, since there really is very little, if any, difference between the two. I never, ever use headlessCamelCase because it is lame: a single-component identifier looks like lowercase, even if it was intended to be headlessCamelCase.

Title: Naming conventions for instance, local and parameter variables

Body:
I was discussing with a senior developper coding conventions to apply to our projects (mainly Java/JEE projects). I disagreed with one convention he proposed:

Instance variable names should start with "_", local variables with
  "loc", and method parameters with "par", so it would be easy to identify
  a variable origin and scope.

While he put forward arguments for short-term memory and readability, I disagreed on the fact that it rather decreases readability, IDEs like Eclipse format variables differently depending on their type, and this problem would be avoided with a good class and method design.

Do you have any opinion, arguments or studies that supports my point (or opposes it)?


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
The real question is not whether
  machines think but whether men do.

— B. F. Skinner

Related more to AI than to simple programming, but I still like it.

LastEditorDisplayName: Roger Pate