答:
Acording to "Clean Code":

Variable names should:

Be intention revealing

Avoid disinformation

Make meaningful distinctions

Be pronounceable

Be searchable

Exceptions are the proverbial i,j,k,m,n used in for loops.

The variable names you, rightfully, complain about do nothing of the above. Those names are bad names.

Also, as every method must be short, using prefixes to indicate either scope or type is no longer in use.

This names are better:

```<code>radius
curvature
conicConstant
innerAperture
outerAperture
innerRadius
outerRadius
</code>```

A commenter says that this would be too complex with long variable names:

Short variable names don't make it simple either:

```<code>fnZR = (r^2/fnR(1+Math.sqrt((1+k) * (r^2/R^2)))) + a[1]*r^2 + a[1]*r^4 + a[1]*r^6 ...;
</code>```

The answer is long names and intermediate results until you get this at the end:

```<code>thisNiceThing =  ( thisOKThing / thisGreatThing ) + thisAwsomeThing;
</code>```

Body:
Acording to "Clean Code":

Variable names should:

Be intention revealing

Avoid disinformation

Make meaningful distinctions

Be pronounceable

Be searchable

Exceptions are the proverbial i,j,k,m,n used in for loops.

The variable names you, rightfully, complain about do nothing of the above. Those names are bad names.

Also, as every method must be short, using prefixes to indicate either scope or type is no longer in use.

This names are better:

radius
curvature
conicConstant
innerAperture
outerAperture
innerRadius
outerRadius

A commenter says that this would be too complex with long variable names:

Short variable names don't make it simple either:

fnZR = (r^2/fnR(1+Math.sqrt((1+k) * (r^2/R^2)))) + a[1]*r^2 + a[1]*r^4 + a[1]*r^6 ...;

The answer is long names and intermediate results until you get this at the end:

thisNiceThing =  ( thisOKThing / thisGreatThing ) + thisAwsomeThing;


问:
Is there an excuse for short variable names?
This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent.

For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows:

```<code>double dR, dCV, dK, dDin, dDout, dRin, dRout
dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1));
dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1));
... and so on
</code>```

Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant:

```<code>dR = radius
dCV = curvature
dK = conic constant
dDin = inner aperture
dDout = outer aperture
dRin = inner radius
dRout = outer radius
</code>```

I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?

答:
Is there a good reason to name variables this way, or am I justified
  in updating them to more descriptive names as I come across them?

The reason to use smaller names is if the original programmer finds them easier to work with.  Presumably they have the right to find that to be the case, and the right not to have the same personal preferences that you have.  Personally, I'd find...

```<code>dDin better than dDinnerAperture
dDout better than dDouterAperture
</code>```

...if I was using them in long, complex calculations.  The smaller the math expression, often the easier it is to see the whole thing at once.  Though if that was the case, they might be better as dIn and dOut, so there wasnt a repetitive D that could lead to an easy typo.

On the other hand, if you find it harder to work with, then knock yourself out and rename then to their longer form.  Especially if you are responsible for that code.

ContentLicense: CC BY-SA 3.0

Body:
Is there a good reason to name variables this way, or am I justified
  in updating them to more descriptive names as I come across them?

The reason to use smaller names is if the original programmer finds them easier to work with.  Presumably they have the right to find that to be the case, and the right not to have the same personal preferences that you have.  Personally, I'd find...

dDin better than dDinnerAperture
dDout better than dDouterAperture

...if I was using them in long, complex calculations.  The smaller the math expression, often the easier it is to see the whole thing at once.  Though if that was the case, they might be better as dIn and dOut, so there wasnt a repetitive D that could lead to an easy typo.

On the other hand, if you find it harder to work with, then knock yourself out and rename then to their longer form.  Especially if you are responsible for that code.


问:
Database development/admin - What exactly should I be trying to learn?
I've been a bit weary about approaching learning databases. I've dabbled into them before, and "DATA" in itself appeals to me a lot. Maintaining/searching/moving, everything about it in the abstract sense I love. (This isn't a career question, this is a learning question.)

But as RDBMS's begin to be easier to maintain, and with tools that "anyone" can use to manage data I feared for the database admin jobs. (Yet I see jobs for SQL everywhere!). I know "No-SQL" was a big deal but it kinda has its niche.

But that leaves me here... unsure of really "what" to study. What tools should I have in my tool belt?

I'm sure RDBMS's will be around in both use and maintaining legacy code. But what else? Obviously data will always be around, but is this a secure field or a dying one? And what should I be concentrating on?

答:
Honestly, I hear all the buzz about object-oriented databases, how well-known Web 2.0 and 3.0 sites are using NoSQL, Raven, Mongo, (insert non-SQL DMBS of the day here), etc for data persistence. All that goes in one ear, and in the other, the boss of my day job is asking for a new table, column, index, stored proc, view, SSRS report, etc etc. to go behind the brand-new never-existed-before C# web or Windows app we're developing.

SQL's not going anywhere. I just got a headhunter e-mail not half an hour ago asking for 2 full-time SSRS developers; the company wants two people whose only job will be to design queries and report forms against a SQL database, and apparently they'll pay pretty handsomely. I know my own company will not hire a developer without at least a basic knowledge of SQL DDL/DML, because if you don't know SQL, you don't know how to make your application save its users' work, and frankly the rest of us don't have time to implement your DAL in addition to our own.

As such, there remains great practical value in learning it, and you should not be hesitant to do so.


问:
Looking for a non-cryptographic hash function that returns a single character
Suppose I have a dictionary of ASCII words stored in uppercase.  I also want to save those words into separate files so that the total word count of each file is approximately the same.    By simply looking at the word I need to know which file it should be in (if it's there at all).  Duplicate words should go into the same file and overwrite the last one.

My first attempt at solving this problem is to use .NET's object.GetHashCode() function and .Trim() to get one of the "random" characters that pop up.  I asked a similar question here

If I only use one character of object.GetHashCode()  I would get a hash code character of A..Z or 0..9.  However saving the result of GetHashCode to disk is a no-no so I need a substitute.

Question:

What algorithm (or subset of an algorithm) is appropriate for pigeonholing strings into a single character or range of characters (Like hex 0..F offers 16 chars)?

Real world usage:

I'll use this answer to modify the Partition key used in Azure Table storage as described here

答:
The simplest 'hash' function would be to take the first character of the string and that is the hash code.  It works.  It doesn't have a good distribution, but it works for some degree of 'works'.

To get a better hash, sum up the value of the string (A = 1, B = 2, C = 3 ...) and then take the modulus of the resulting value.  If this is to be assigned to the 'A-Z' hash range, take this mod 26 and assign that back into the character array (in this case, A = 0).  If this is to be in the hex range hash, take the value mod 16.


问:
Advice on reconciling discordant data
Let me support my question with a quick scenario.

We're writing an app for family meal planning.  We'll produce daily plans with a target calorie goal and meals to achieve it for our nuclear family.  Our calorie goal will be calculated for each person from their attributes (gender, age, weight, activity level).

The weight attribute is the simplest example here.

When Dad (the fascist nerd who is inflicting this on his family) first uses the application he throws approximate values into it for Daughter.  He thinks she is 5'2" (157 cm) and 125 lbs (56kg).  The next day Mom sits down to generate the menu and looks back over what the bumbling Dad did, quietly fumes that he can never recall anything about the family, and says the value is really 118 lbs!

This is the first introduction of the discord.  It seems, in this scenario, Mom is probably more correct that Dad.  Though both are only an approximation of the actual value.

The next day the dear Daughter decides to use the program and sees her weight listed.  With the vanity only a teenager could muster she changes the weight to 110 lbs.
Later that day the Mom returns home from a doctor's visit the Daughter needed and decides that it would be a good idea to update her Daughter's weight in the program.  Hooray, another value, this time 117 lbs.

Now how do you reconcile these data points?  Measurement error, confidence in parties, bias, and more all confound the data.  In some idealized world we'd have a weight authority of some nature providing the one and only truth.  How about in our world though?

And the icing on the cake is that this single data point changes over time.

How have you guys solved or managed this conflict?

答:
There are two ways that this data can change, as I see it: Corrections (where the wrong value was entered) and natural variation over time (because people's weight changes). So you may not want to record weight as a single value, but maybe record it as weight_measure_at_point_in_time which has a value for weight, and another for the date it was recorded. That way you know the measurement changes, and you know when. When you do calculations with this value, you could choose to look at only the most recent measure, and compare similar calculations to earlier measurements.

If you want to start auditing the table, you can do that too by setting up audit fields that record who changed the measured value, when they did it, and why (and also store all records for the measurement so you have a history of all edits). If you want to calculate weights on the changed measurement based on who did it, you have to have some way of deciding whose changes are more authoritative and how much weight those changes carry (and I would not want to be around when you have that discussion with everyone, about how much or how little their opinion matters). That can be done too, you could use all weights for different versions of a measurement at a single point in time to calculate a "final" measurement, but that makes it all a bit more complicated.

Title: Advice on reconciling discordant data


答:
It feels like your question is very related to your previous stackoverflow question.

Generally speaking, Azure Table IO performance improves as more partitions are used (with some tradeoffs in continuation tokens and batch updates I won't go into).

Since the partition key is always a string I am considering using a "natural" load balancing technique based on a subset of the GetHashCode() of the partition key, and appending this subset to the partition key itself. This will allow all direct PK/RK queries to be computed with little overhead and with ease. Batch updates may just need an intermediate to group similar PKs together prior to submission

With that background information the problem is not simply taking a database of words and splitting into multiple smaller but equal sized databases of the same words. Instead it looks like you are trying to determine how to automatically partition your data based on a key so that it is separated into equal parts.

If our end goal is to partition the words evenly across the shards I would not do so based on the data itself. That is to say if my method for determining which partition a bit of data goes into is based on what is included in that data I would not expect my end distribution to be even.

Given the follow list of words as an example

Programmer,Programmer,StackExchange

The value Programmer is repeated twice. If that value is what I am using to determine which partition the data will end up in I would expect that both Programmers would end up in the same partition. If the end goal is to keep all closely related words on the same partition this may be the way you want to go, but I don't think it is.

If instead we do not care which words are where and want an even distribution I would first determine the number of shards that I want to run and then simply loop through my database of words assigning the partition key 1-N where N is the number of partitions I have.

i.e.

```<code>int totalPartitions = 5;
int currentPartition = 1;
Foreach(var item in MyData) {
  MyData.PartitionKey = currentPartition;
  if(currentPartition < totalPartitions)
    currentPartition++
  else
    currentPartition = 1;
}
</code>```

Title: Looking for a non-cryptographic hash function that returns a single character

Body:
Suppose I have a dictionary of ASCII words stored in uppercase.  I also want to save those words into separate files so that the total word count of each file is approximately the same.    By simply looking at the word I need to know which file it should be in (if it's there at all).  Duplicate words should go into the same file and overwrite the last one.

My first attempt at solving this problem is to use .NET's object.GetHashCode() function and .Trim() to get one of the "random" characters that pop up.  I asked a similar question here

If I only use one character of object.GetHashCode()  I would get a hash code character of A..Z or 0..9.  However saving the result of GetHashCode to disk is a no-no so I need a substitute.

Question:

What algorithm (or subset of an algorithm) is appropriate for pigeonholing strings into a single character or range of characters (Like hex 0..F offers 16 chars)?

Real world usage:

I'll use this answer to modify the Partition key used in Azure Table storage as described here

Body:
It feels like your question is very related to your previous stackoverflow question.

Generally speaking, Azure Table IO performance improves as more partitions are used (with some tradeoffs in continuation tokens and batch updates I won't go into).

Since the partition key is always a string I am considering using a "natural" load balancing technique based on a subset of the GetHashCode() of the partition key, and appending this subset to the partition key itself. This will allow all direct PK/RK queries to be computed with little overhead and with ease. Batch updates may just need an intermediate to group similar PKs together prior to submission

With that background information the problem is not simply taking a database of words and splitting into multiple smaller but equal sized databases of the same words. Instead it looks like you are trying to determine how to automatically partition your data based on a key so that it is separated into equal parts.

If our end goal is to partition the words evenly across the shards I would not do so based on the data itself. That is to say if my method for determining which partition a bit of data goes into is based on what is included in that data I would not expect my end distribution to be even.

Given the follow list of words as an example

Programmer,Programmer,StackExchange

The value Programmer is repeated twice. If that value is what I am using to determine which partition the data will end up in I would expect that both Programmers would end up in the same partition. If the end goal is to keep all closely related words on the same partition this may be the way you want to go, but I don't think it is.

If instead we do not care which words are where and want an even distribution I would first determine the number of shards that I want to run and then simply loop through my database of words assigning the partition key 1-N where N is the number of partitions I have.

i.e.

int totalPartitions = 5;
int currentPartition = 1;
Foreach(var item in MyData) {
  MyData.PartitionKey = currentPartition;
  if(currentPartition < totalPartitions)
    currentPartition++
  else
    currentPartition = 1;
}


问:
What should I study to 'learn' Comp Sci?
[This question was originally asked on Stack Overflow, but recommended to move the question here.]

I can't find anything quite like the question I'm about to ask, so please forgive me if there's something just like it already, please feel free to point me in the right direction. It'll take a bit of background explaining too, please forgive me for that.

[backstory]

Basically, I graduated from University about 18 months ago with a degree in Business Information Systems and Japanese. The Japanese took up half of the degree so the BIS was only joint. I only learned PHP in terms of languages and basically no computing theory - everything was vocational (Networking, programming basics, CMS development, Office and VBA and then loads of Business theory courses).

Since this, I decided to teach myself C# and ASP.Net and try to get a position as a programmer. I created an online shop style website and a small CRM application in Windows Forms to both teach myself and build a portfolio, and luckily I managed to snag a developer position.

Bad side? I'm the only developer at my company. Now don't get me wrong, in the last year I've learned loads and loads, I did some devpt. before Uni so knew the basics anyway, but it was very much a "learning from books" job - every night.

Now then... I am now at a point where I'm building software on a regular basis, making good judgements for time scales, and have even been told my code and methodology are good by other professionals that have been in the game longer than me, and they have offered me jobs.

[/backstory]

What this whole thing boils down to, is that I now want to study up on the topics I'll have missed by not doing CS. More importantly, could you recommend books / free online courses? I want to learn about Computer Science theory, not just better coding.

Thank you!

答:
The key here is to try to absorb the concepts, rather than the specifics. For example, rather than learning Java, learn about the Virtual Machine that it brings to the table and how that differs from, e.g. the C# CLR.

The kind of topics you want to cover are (in no particular order):

Algorithms. How does Bubble Sort compare with QuickSort (QS not always fastest), what is a binary search, etc.

Compilers. All modern programming languages have some concept of being compiled from source to bytecode or machine code. It helps to understand how to write efficient code if you know the pain the compiler goes through. Some processor architecture theory may help your understanding - see the Andrew Tanenbaum book.

Scale. There are some differences between programming for e.g. a supercomputer versus a phone, even though they may both run the same OS. Find out the differences and challenges, for example, why/behaviour when malloc() fails.

Concurrency. With multiple cores, desktop PCs can now actually be running different pieces of code simultaneously. This causes all sorts of issues - locking, race conditions, starvation, etc.

Debugging. Get good with tools or instrumenting code to work out how best to fix stuff when it goes wrong, particularly when it's live and you can't reboot/restart

Databases. It doesn't matter which database, but an understanding of database organisation and how they work helps. The introductory chapters to most Database books give a good overview - pages, rows, locking, optimism, indices, execution plans, etc.

SDLC. Learn the Requirements > Specifications > Design > Code > Build > Test > Commit > QA > Deploy > Maintain lifecycle, regardless of actual project methodology.

Methodologies. Look at traditional BUFD, Waterfall, Agile, Scrum, XP, etc.

Tools. Other than an editor and compiler, there are lots of tools used in SE practices, from code generators to static analysis.

Functional vs Procedural. More and more functional programming constructs are making their way into procedural languages lately - with good reason. Go find out why Lisp/Prolog/Haskell are still in use and how things like F# are taking the concepts forward.

There are a ton of resources out there - MSDN's Channel 9, Yahoo!/Google videos, YouTube, VideoJug, etc.

If you want to actually keep up with a Comp Sci person, then take a look at any university's course prospectus, to get an idea for what topics they cover in their CS course. Personally, I'd pay more attention to the Software Engineering courses than Computer Science as you have a history of programming but perhaps don't need to learn micro electronics to understand them (in the UK, CS = programming + hardware, SE = programming + theory).

ContentLicense: CC BY-SA 2.5


问:
When does "proper" programming no longer matter?
I've been building an android game in my spare time. It's using the libgdx library so quite a bit of the heavy lifting is done for me.

While developing, I carelessly selected datatypes for some procedures. I used a hashtable because I wanted something close to an associative array. Human readable key values. In other places to achieve similar things, I use a vector. I know libgdx has vector2 and vector3 classes, but I've never used them.

When I come across weird problems and search Stack Overflow for help, I see a lot of people just reaming the questions that use a certain datatype when another one is technically "proper." Like using an ArrayList because it does not require defined bounds versus re-defining an int[] with new known boundaries. Or even something trivial like this:

```<code>for(int i = 0; i < items.length; i ++)
{
    // do something
}
</code>```

I know it evaluates item.length on every iteration. However, I also know items will never be more than 15 to 20 items. So should I care if I evaluate items.length on every iteration?

I ran some tests to see how the app performs using the method I just described versus the proper, follow the tutorial and use the exact data types suggested by the community. The results: Same thing. Average 45 fps. I opened every app on the phone and galaxy tab. No difference.

So I guess my question to you is this: Is there a threshold when it no longer matters to be proper? Is it ok to say - "so long as it gets the job done, I don't care?"

答:
You write a program to solve a problem.  That problem is accompanied by a specific set of requirements for solving it.  If those requirements are met, the problem is solved and the objective is achieved.

That's it.

Now, the reason that best practices are observed is because some requirements have to do with maintainability, testability, performance guarantees and so forth.  Consequently, you have those pesky folks like me who require things like proper coding style.  It doesn't take that much more effort to cross your T's and dot your I's, and it is a gesture of respect to those who have to read your code later and figure out what it does.

For large systems, this kind of restraint and discipline is essential, because you have to play nice with others to get it all to work, and you have to minimize technical debt so that the project doesn't collapse under its own weight.

At the opposite end of the spectrum are those one-off utilities that you write to solve a specific problem right now, utilities that you'll never use again.  In those cases, style and best practices are completely irrelevant; you hack the thing together, run it, and get on with the next thing.

So, as with so many things in software development, it depends.


答:
There are two good reasons not to rename variables in legacy code.

(1) unless you're using an automated refactoring tool, the possibility of introducing bugs is high.  Hence, "if it's not broken, don't fix it"

(2) you will make comparing current versions with past versions, in order to see what changed, impossible.  This will make future maintenance of the code more difficult.

Title: Is there an excuse for short variable names?

Body:
This has become a large frustration with the codebase I'm currently working in; many of our variable names are short and undescriptive. I'm the only developer left on the project, and there isn't documentation as to what most of them do, so I have to spend extra time tracking down what they represent.

For example, I was reading over some code that updates the definition of an optical surface. The variables set at the start were as follows:

```<code>double dR, dCV, dK, dDin, dDout, dRin, dRout
dR = Convert.ToDouble(_tblAsphere.Rows[0].ItemArray.GetValue(1));
dCV = convert.ToDouble(_tblAsphere.Rows[1].ItemArray.GetValue(1));
... and so on
</code>```

Maybe it's just me, but it told me essentially nothing about what they represented, which made understanding the code further down difficult. All I knew was that it was a variable parsed out specific row from a specific table, somewhere. After some searching, I found out what they meant:

```<code>dR = radius
dCV = curvature
dK = conic constant
dDin = inner aperture
dDout = outer aperture
dRin = inner radius
dRout = outer radius
</code>```

I renamed them to essentially what I have up there. It lengthens some lines, but I feel like that's a fair trade off. This kind of naming scheme is used throughout a lot of the code however. I'm not sure if it's an artifact from developers who learned by working with older systems, or if there's a deeper reason behind it. Is there a good reason to name variables this way, or am I justified in updating them to more descriptive names as I come across them?


问:
Is Java much harder to "tweak" for performance compared with C/C++?
Does the "magic" of the JVM hinder the influence a programmer has over micro-optimisations in Java? I recently read in C++ sometimes the ordering of the data members can provide optimizations (granted, in the microsecond environment) and I presumed a programmer's hands are tied when it comes to squeezing performance from Java?

I appreciate a decent algorithm provides greater speed-gains, but once you have the correct algorithm is Java harder to tweak due to the JVM control?

If not, could people give examples of what tricks you can use in Java (besides simple compiler flags).

答:
Sure, at the micro-optimization level the JVM will do some things that you'll have little control over compared to C and C++ especially.

On the other hand, the variety of compiler behaviors with C and C++ especially will have a far greater negative impact on your ability to do micro-optimizations in any sort of vaguely portable way (even across compiler revisions).

It depends on what sort of project you're tweaking, what environments you're targeting and so on. And in the end, it doesn't really matter since you're getting a few orders of magnitude better results from algorithmic/data structure/program design optimizations anyways.


答:
View your data in the same way stock market prices are commonly viewed; as a linear combination of a smooth function (your actual data) and random fluctuations. Compute the rolling average of your data with an appropriate number of historic samples, and assume this to be the data you actually want.

Given both the actual data y and the average y', you can regard the fluctuations y-y' as a stochastic process. This process has properties such as a standard deviation and variance, giving you useful information about the data in terms of its accuracy. This information could be used to discard some data points (those for which the fluctuation is larger than the standard deviation, for example), allowing you to recalculate the moving average from more accurate data or even using the data directly, but this may not necessarily be a good idea.

In this process, determining a good number of samples to use in the rolling average is the most difficult problem. It depends very much on the frequency and regularity of your data, but also on wether you expect your actual data to fluctuate much. For human weight with samples every day the number of samples can likey be fairly large (14 perhaps). There are different weighted variants of the rolling average that could be used as well.

Title: Advice on reconciling discordant data

Body:
Let me support my question with a quick scenario.

We're writing an app for family meal planning.  We'll produce daily plans with a target calorie goal and meals to achieve it for our nuclear family.  Our calorie goal will be calculated for each person from their attributes (gender, age, weight, activity level).

The weight attribute is the simplest example here.

When Dad (the fascist nerd who is inflicting this on his family) first uses the application he throws approximate values into it for Daughter.  He thinks she is 5'2" (157 cm) and 125 lbs (56kg).  The next day Mom sits down to generate the menu and looks back over what the bumbling Dad did, quietly fumes that he can never recall anything about the family, and says the value is really 118 lbs!

This is the first introduction of the discord.  It seems, in this scenario, Mom is probably more correct that Dad.  Though both are only an approximation of the actual value.

The next day the dear Daughter decides to use the program and sees her weight listed.  With the vanity only a teenager could muster she changes the weight to 110 lbs.
Later that day the Mom returns home from a doctor's visit the Daughter needed and decides that it would be a good idea to update her Daughter's weight in the program.  Hooray, another value, this time 117 lbs.

Now how do you reconcile these data points?  Measurement error, confidence in parties, bias, and more all confound the data.  In some idealized world we'd have a weight authority of some nature providing the one and only truth.  How about in our world though?

And the icing on the cake is that this single data point changes over time.

How have you guys solved or managed this conflict?


答:
This question is very hard to answer, because it depends on language implementations.

In general there's very little room for such "micro optimizations" these days. The main reason is that compilers take advantage of such optimizations during compilation. For example there's no performance difference between pre-increment and post-increment operators in situations where their semantics are identical. Another example would be for example a loop like this for(int i=0; i<vec.size(); i++) where one could argue that instead of calling the size() member function during each iteration it would be better to get the size of the vector before the loop and then comparing against that single variable and thus avoiding function a call per iteration. However, there are cases in which a compiler will detect this silly case and cache the result. However, this is only possible when the function has no side-effects and the compiler can be sure that the vector size remains constant during the loop so it merely applies to fairly trivial cases.

Title: Is Java much harder to "tweak" for performance compared with C/C++?

Body:
Does the "magic" of the JVM hinder the influence a programmer has over micro-optimisations in Java? I recently read in C++ sometimes the ordering of the data members can provide optimizations (granted, in the microsecond environment) and I presumed a programmer's hands are tied when it comes to squeezing performance from Java?

I appreciate a decent algorithm provides greater speed-gains, but once you have the correct algorithm is Java harder to tweak due to the JVM control?

If not, could people give examples of what tricks you can use in Java (besides simple compiler flags).


答:
Java (as far as I'm aware) gives you no control over variable locations in memory so you have a harder time to avoid things like false-sharing and alignment of variables (you can pad out a class with several unused members). Another thing I don't think you can take advantage of are instructions such as mmpause, but these things are CPU specific and so if you figure you need it Java may not the be language to use.

There exists the Unsafe class that gives you flexibility of C/C++ but also with the danger of C/C++.

It might help you to look at the assembly code the JVM generates for your code

To read about a Java app that looks at this kind of detail see the Disruptor code released by LMAX


问:
What software do you use to track time spent on a project?
What software do you use to track time spent on a project?</p>

答:
ActiTIME (http://www.actitime.com/).

Cheap (free for up to 10 users, then increments up to $200 for unlimited users - prices to buy it and host it yourself), clear and powerful.

There are some management and accounting modules too (a few hundred dollars each) but I've not tried them.


问:
Why does Facebook convert PHP code to C++?
I read that Facebook started out in PHP, and then to gain speed, they now compile PHP as C++ code. If that's the case why don't they:

Just program in c++? Surely there must be SOME errors/bugs when hitting a magic compiler button that ports PHP to c++ code , right?

If this impressive converter works so nicely, why stick to PHP at all? Why not use something like Ruby or Python? Note -- I picked these two at random, but mostly because nearly everyone says coding in those languages is a "joy". So why not develop in a super great language and then hit the magic c++ compile button?

答:
“Indeed, why not work in assembly directly, since the C++ code is ultimately translated into machine code instructions?”

– That, in its essence, is what the argument reduces to. And hopefully this makes it obvious why it isn’t done:

A (vastly!) different skill set is required to program in assembly (C++) than in C++ (PHP).

It’s potentially much harder to program, for a variety of reasons

The code produced by a assembler/compiler may not be human-readable (speak: maintainable), even though you can, from scratch, write readable programs in assembly (C++).


答:
The problem with the code is not the short names, but rather the lack of a comment which would explain the abbreviations, or point to some helpful materials about the formulas from which the variables are derived.

The code simply assumes the problem-domain familiarity.

That is fine, since problem-domain familiarity is probably required to understand and maintain the code, especially in the role of someone who "owns" it, so it behooves you to acquire the familiarity rather than to go around lengthening names.

But it would be nice if the code provided some hints to serve as springboards. Even a domain expert could forget that dK is a conic constant. Adding a little "cheat sheet" in a comment block wouldn't hurt.


答:
The proper way to look at this is diminishing returns: comparing the added benefit of developing the program to the cost of the additional development.

Diminishing returns sets in when the marginal benefit is less than the marginal time/effort.

Can you make a business case for moving items.length out of the for loop? Economically, can that change even justify the time spent trying to justifying it? Since there is no difference in the user experience, you will never get anything for even the time spent measuring (other than a useful lesson to remember). The users will not like the program any more than they do, and more copies will not be sold, as a result of that change.

This is not always easy to evaluate, because business cases are filled with unknowns and risks, and are thus susceptible to fall prey to unconsidered factors that will only become obvious in hindsight. Proposed changes can be completely nontrivial, such that they do make a big difference.

Diminishing-returns type of thinking can amount to a hunt for excuses not to take some action, and avoid taking risks, which could in hindsight prove to be a string of missed opportunities.

But sometimes it is obvious when not to do something.  If some piece of development seems to require an economic miracle to occur just to pay for the cost of development (break even), it's probably a bad idea.

Title: When does "proper" programming no longer matter?

Body:
I've been building an android game in my spare time. It's using the libgdx library so quite a bit of the heavy lifting is done for me.

While developing, I carelessly selected datatypes for some procedures. I used a hashtable because I wanted something close to an associative array. Human readable key values. In other places to achieve similar things, I use a vector. I know libgdx has vector2 and vector3 classes, but I've never used them.

When I come across weird problems and search Stack Overflow for help, I see a lot of people just reaming the questions that use a certain datatype when another one is technically "proper." Like using an ArrayList because it does not require defined bounds versus re-defining an int[] with new known boundaries. Or even something trivial like this:

```<code>for(int i = 0; i < items.length; i ++)
{
    // do something
}
</code>```

I know it evaluates item.length on every iteration. However, I also know items will never be more than 15 to 20 items. So should I care if I evaluate items.length on every iteration?

I ran some tests to see how the app performs using the method I just described versus the proper, follow the tutorial and use the exact data types suggested by the community. The results: Same thing. Average 45 fps. I opened every app on the phone and galaxy tab. No difference.

So I guess my question to you is this: Is there a threshold when it no longer matters to be proper? Is it ok to say - "so long as it gets the job done, I don't care?"


问:
C++ job interview questions?
I am expecting a job interview for a C++, what kind of questions should I expect?

I have been programming with C for 5 years. I know what OOP is and I have been reading about it for some time. But it is most likely I can miss important details because I do not do anything real on C++.

Best Regards,

答:
Here are some things I would ask about if someone claimed to be capable of answering C++ questions and was applying for a senior level position.

Explain placement new and when you would use it

What are templates

What is template specialization

Why should you make the destructor of a base class virtual

What is RAII

This list could become exhausted but if I was interviewing I would skip over the basic questions like constructor vs. destructor or anything that was abstractly related to Object Oriented development.

If you do not know C++, especially modern C++ you have to be upfront about this. Don't try to fake your way as the interviewer would know immediately. What I find most frustrating when interviewing candidates are ones that try to claim they can develop C++ but really only know C.

This of course is not an exhaustive list of questions that could be asked during an interview. The most important ones are regarding critical thinking, designing under pressure and confidence in solutions that are presented.

Title: C++ job interview questions?


答: For certain variables which are well-known in the problem domain -- like the case you have here -- terse variable names are reasonable. If I'm working on a game, I want my game entities to have position variables x and y, not horizontalPosition and verticalPosition. Likewise loop counters that don't have any semantics beyond indexing, I expect to see i, j, k.


答:
There's a wise old quote: "Do not follow in the footsteps of the wise men of old.  Seek what they sought."  There are reasons for all of the rules of 'proper' coding.  Knowing why those rules exist is more important than knowing what those rules are.

There is a rule that you shouldn't put a test that could be repeatedly recalculated in a for loop like that.  In the cases that the rule was invented to remedy (where performance would really be different), it makes sense.  In that case, there is only one right answer.  In your example, it is known that there is no performance difference and that there can't be more than a couple dozen iterations.  In this case, there are two right answers, either to apply the rule anyway, since it's simple and won't hurt anything and could help form good habits, or to ignore the rule, since there is no performance difference to worry about.

I prefer the first right answer, and you appear to prefer the second.  You are not wrong about that.  I think you are wrong in your idea of what 'proper' programming is about.  It isn't about following a randomly selected set of rules that don't help you and have no purpose.  Your not fixing the for loop in the example is actually following a very good rule against premature optimization.

Real proper programming is about following good rules that make sense in an intelligent way.


问:
Are there programming languages that allow you to do set arithmetic on types?
Out of curiosity, are there languages that allow you to do set arithmetic on types to create new types? Something like:

```<code>interface A {
  void a();
  void b();
}

interface B {
  void b();
  void c();
}

interface C = A & B; // has b()
interface D = A | B; // has a(), b() and c()
interface E = (A & B) ^ B; // has c()
</code>```

I know that in some languages these ideas can be expressed (i.e., Java has List<Comparable & Serializable> for the union of the interfaces) but I've never heard of a language that supports type arithmetic. Thanks!

答:
Tangent(0.3 spec) uses something akin to this. (disclaimer: this is my own little research project)

Currently with acts as a union operator modelling inheritance, though pragmatism has made it not commutative. Once you introduce implementations to methods, a strict union of methods with the same name is often not what you want and impossible to do right anyways.

intersect is supported that models type inference for something like foo(T,T) where the parameters are different.

Complements were interesting, but led to partial types that seemed not so useful and/or troublesome to include correctly - so are not included.

I know there are a few other research languages I ran across that had something similar, but cannot remember them at the moment. The main issue is that the things aren't really useful without structural typing, which isn't terribly popular itself. The other is that you need some sort of kind (type of types) to store the constructed type, or else it's just shorthand for something that isn't particularly idiomatic without that capability. And that's far less common than even structural typing.

It's biased, and it's not much, but there it is.


答:
Scala supports it partially (intersections but not unions), and any language with structural subtyping (I think OCaml is an example) or a type system powerful enough to emulate that (Haskell is a classic one) will have full "types-as-sets" capabilities, at least within the fragment of its type system that accepts such things (relevant when it's emulated ala HList/OOHaskell).

Since I don't know OCaml very well, I'll give the portion of your example that works in Scala:

```<code>trait A {
  def a(): Unit
  def b(): Unit
}

abstract class B { // just to prove it works with both traits and classes
  def b(): Unit
  def c(): Unit
}

type C = A with B
type D = { def b(): Unit } // not an exact translation, because unions aren't directly available
// type `E` is unrepresentable
</code>```

A version for Haskell would depend on the record system you were using, and would likely be somewhat clunky, because it would be emulated rather than natively supported.

As far as I know, Ceylon has both intersection and union types built into the language in full power, so you could presumable encode a type-level "xor" in terms of those.

Title: Are there programming languages that allow you to do set arithmetic on types?

Body:
Out of curiosity, are there languages that allow you to do set arithmetic on types to create new types? Something like:

```<code>interface A {
  void a();
  void b();
}

interface B {
  void b();
  void c();
}

interface C = A & B; // has b()
interface D = A | B; // has a(), b() and c()
interface E = (A & B) ^ B; // has c()
</code>```

I know that in some languages these ideas can be expressed (i.e., Java has List<Comparable & Serializable> for the union of the interfaces) but I've never heard of a language that supports type arithmetic. Thanks!

Body:
Scala supports it partially (intersections but not unions), and any language with structural subtyping (I think OCaml is an example) or a type system powerful enough to emulate that (Haskell is a classic one) will have full "types-as-sets" capabilities, at least within the fragment of its type system that accepts such things (relevant when it's emulated ala HList/OOHaskell).

Since I don't know OCaml very well, I'll give the portion of your example that works in Scala:

trait A {
  def a(): Unit
  def b(): Unit
}

abstract class B { // just to prove it works with both traits and classes
  def b(): Unit
  def c(): Unit
}

type C = A with B
type D = { def b(): Unit } // not an exact translation, because unions aren't directly available
// type `E` is unrepresentable

A version for Haskell would depend on the record system you were using, and would likely be somewhat clunky, because it would be emulated rather than natively supported.

As far as I know, Ceylon has both intersection and union types built into the language in full power, so you could presumable encode a type-level "xor" in terms of those.


问:
As a programmer, are you required to do timesheets?
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?

答: I don't get the anti-timesheet thing at all. Timesheets are what cause you to get paid. No timesheet, no money. I like getting paid, therefore I like my timesheets. I've never had a timesheet that took more that five minutes a day to fill out. Honestly, there are plenty of much more annoying things in my day than a five-minute timesheet. </p>


问:
Why didn't "cloud computing" offer appear earlier?
Cloud computing is a model of renting resources - servers and data storage. Both servers and data storage have been around for much more than a decade so far. Yet cloud computing offers only appeared several years ago.

What's the deal here? What was the critical change that triggered massive adoption and massive marketing of cloud computing offers?

答:
Apparently most people have a shaky grasp on 'Cloud Computing'...

The short version:

A system whereby computing power has been abstracted away from physical infrastructure so that it can easily be bought, sold, and leveraged as a commodity.

The Long Version:

'Cloud Computing' is simply the next step in abstracting away the maintenance and infrastructure requirements involved in developing and supporting software platforms.

Cloud can be broken down by the types of services it represents...

SaaS (Software as a Service):

Geared more toward users. This can be anything from a website, CRM webapp, to a REST API. The point is, the data/interface is made accessible but the hardware details have been sufficiently abstracted away enough that they no longer matter.

Basically, you take software and make it publicly accessible. Requirements such as installation, resource usage (ie memory/cpu), updates, etc are no longer relevant. You connect and it works.

PaaS (Platform as a Service):

Geared for use by developers. These include anything that has 'hosting' after it. Including webservers, email servers, dns management, etc.

Basically, the platform options are limited to whatever the is provided by the hosting company but they can be leveraged by developers to build on.

IaaS (Infrastructure as a Service):**

The newest addition to the party and where the 'Cloud' name probably originated. It's geared toward providing a full system architecture (ie complete OS) that can be built on without any need to maintain physical devices.

Basically, developers are given access to a virtual machine to develop and deploy. Since the virtual machine is decoupled from the hardware, it's much easier to migrate and clone that machine to whatever physical locations are necessary.

Where 5 years ago, providing region-specific hosting would probably involve a lot of manual work to clone the platform to servers around the world, IaaS platforms automate the process.

It provides a LOT more flexibility compared to PaaS because the developer gets full access control over the VM. On top of that, the number of physical machines actually hosting the image can be easily increased/decreased to match demand (ex such as during peak access).

It's no longer necessary for businesses to worry about downtime or scalability. IaaS costs more than PaaS hosting because it requires more resources but it's still significantly cheaper than hiring dedicated systems administrators and providing the bare metal in-house.

There are probably hundreds of different types of _aaS platforms that exist in the wild but it all boils down to one concept. Computer hardware has been abstracted away to the point where systems have become a commodity that can be traded at whim.

Need a thousand clones up and running in 10 minutes for the Super Bowl, not a problem. Need them scaled back to 10 just as quickly, also not a problem. Need clones to do heavy number crunching? Yep, those exist. What about massive amounts of storage space to host media? Just as easy.

IT infrastructure in general is not revenue generating so the only gains to be made will come from minimizing cost. One way to do that is reduce/eliminate/automate the infrastructure as much as possible. At the end of the day, all the developers want and need is a platform to build their services on. Companies like Google/Amazon/Rackspace all specialize in massive scalability so doesn't it make sense to tap into their infrastructure?

The disruptive change that 'Cloud Computing' represents is that it's no longer necessary for anybody but designers, developers, and creative/media types to own computers that include a full OS. The web, games, documents, social applications, business applications, everything is being made accessible on the web.


问:
Automated Qt testing framework
Can someone recommend a good robust "Free" testing framework for Qt?

Our requirements:

Should be able to test basic mouse click / mouse move events

Should be able to handle non-widget view components

Should have "record" capability to generate test scripts.

Should be automatable for running it daily.

We looked at:

Squish - this solves all our problems. But it is just too da** expensive.

KD Executor - the download page now links to the squish page and says that's what they recommend for testing. Not sure what they mean by that.

TDriver - from nokia.qt. Super difficult to install. Very little documentation. Having a hard time to just install. I wonder how much harder it would be to write tests.

qtestlib - Could not handle non-widget components. Everything has to be a widget to be tested. No "record" feature.

Can someone help with any other alternative?

答:
We use the builtin QtTest - basically a cppunit clone like all the others, but understands signals/slots so can mockup gui interaction..

It's not as automated as googletest, you need to explictily include the tests into a main.cpp and run that rather than it pickign them up from a directory, and there is no pretty testrunner - just the stdout from main.cpp

We haven't used it to test a lot of gui interaction directly (yet) - mostly just as a unit test tool

Title: Automated Qt testing framework


问:
Programming language features that help to catch bugs early
Do you know any programming language features that help to detect bugs early in the software development process - ideally at compile-time or else as early as possible at run-time?

Examples of well-known and effective bug-reducing features are:

Static typing and generic types: type incompatibility errors are detected by the compiler

Design by Contract (TM), also called Contract Programming: invalid values are quickly detected at runtime (through preconditions, postconditions and class invariants)

Unit testing

I ask this question in the context of improving an object-oriented programming language (called Obix) which has been designed from the ground up to 'make it easy to quickly write reliable code'. Besides the features mentioned above this language also incorporates other Fail-fast features such as:

Objects are immutable by default

Void (null) values are not allowed by default

The aim is to add more Fail-fast concepts to the language. If you know other features which help to write less error-prone code then please let us know. Thank you.

答:
Go has a few:

Any unused imports are errors (not sure if this is bug catching, certainly good code style)

No implicit conversions, var i int = .5 is an error, not a warning or an automatic truncation.

Keying off of 2, being strongly statically typed serves to catch many errors.

Everything is 0 initialized (sensibly so) so there are no null pointers.

Some sort of unit test support built in. I haven't dug too deeply into this.

Another one that pops into my head is Haskell

Strongly statically typed. Ask any Haskeller about the type system, it catches 99% of my haskell errors before I even get to running it.

Design by contract to an extent Int->Int->Int though this would be encapsulated in most function declarations in languages

Purely Functional. If a function works once in a scenario, it'll always work.

However in general, good practices in a language with poor safety beat a careless programmer in a safe language. Take for example C (Not a jab at C, but it leans more on the user to double check that things are sane) clearly it is possible to write good robust code in C despite it's lack of features for this. In the end the programmer>programming language.


问:
What is the common definition of a Hacker?
I'm wondering if the term Hacker means different things to different people.  When most people hear the word hacker what are the first things that come to mind?</p>

答:
To programmers, it means "writes ninja code to get the thing to work", a positive connotation to someone whose code is awe-inspiring if a little scary. The project may be some open-source community project or just hobby code.

To the media, it means "subverts security mechanisms to infiltrate large organisations and steals money/data/Google source code", as can be seen from any web search, or even an article in today's online news: http://www.theregister.co.uk/2010/11/08/royal_navy_website_hack/

Here's what Wikipedia thinks.


答:
When you should not care about your code being "proper"

If you manage to answer the business goal, and keep it over time with low overhead. (users don't view source before they pay you)

MVP / POC - If writing proper code means wasting time on a concept before you know how to make money from it (if you spend years and 45 million dollars writing your app and end up closing shop because it had no market, no one cares how proper was the code)

When having a life threatening situation (e.g. iron man prototype 1 was a dirty hack, but it got him out of the cave right?)

or if you simply don't know how to write proper code (if somene manages to make a living writing non proper code, in today's unemployment, I say, better write bad code than be homeless)

if you simply know what your'e doing or think you can get away with it pretending you do

When to write proper code

If it will have a significant business impact, e.g. performance will impact the revenue, or prevent sales

If it's so not proper that maintaining the code becomes a business issue (high maintenance costs)

If you are a known programmer working on a big open source project

Same for a big company contributing an in-house library to the world

If you want to show your work as a portfolio in  future interviews


答:
Start by taking a long, hard look at the original Ada programming language, from 1983.  Ada was designed specifically for writing highly reliable systems that would have very long life cycles.

Strong static typing.  Strong semantics.  Easily readable.  Tasking built-in.

You can hack 'til you crack, but you have to WORK at it, and the resulting code LOOKS like it.  This is a feature: it warns the next poor maintenance schlub that Here Be Dragons.

There's a remark from the dawn of computing: Running with subscript checking enabled during checkout, and turning it off for production, is like wearing your lifejacket in the harbor and then taking it off when you go out onto the open ocean.  Note that Ada required that subscript checking be turned ON by default, and required programmers to turn it off explicitly if they were so bold.

Title: Programming language features that help to catch bugs early

Body:
Do you know any programming language features that help to detect bugs early in the software development process - ideally at compile-time or else as early as possible at run-time?

Examples of well-known and effective bug-reducing features are:

Static typing and generic types: type incompatibility errors are detected by the compiler

Design by Contract (TM), also called Contract Programming: invalid values are quickly detected at runtime (through preconditions, postconditions and class invariants)

Unit testing

I ask this question in the context of improving an object-oriented programming language (called Obix) which has been designed from the ground up to 'make it easy to quickly write reliable code'. Besides the features mentioned above this language also incorporates other Fail-fast features such as:

Objects are immutable by default

Void (null) values are not allowed by default

The aim is to add more Fail-fast concepts to the language. If you know other features which help to write less error-prone code then please let us know. Thank you.


问:
How old is "too old"?
I've been told that to be taken seriously as a job applicant, I should drop years of relevant experience off my résumé, remove the year I got my degree, or both. Or not even bother applying, because no one wants to hire programmers older than them.1

Or that I should found a company, not because I want to, or because I have a product I care about, but because that way I can get a job if/when my company is acquired.

Or that I should focus more on management jobs (which I've successfully done in the past) because… well, they couldn't really explain this one, except the implication was that over a certain age you're a loser if you're still writing code. But I like writing code.

Have you seen this? Is this only a local (Northern California) issue?

If you've ever hired programmers:2

Of the résumés you've received, how old was the eldest applicant?

What was the age of the oldest person you've interviewed?

How old (when hired) was the oldest person you hired?

How old is "too old" to employed as a programmer?

1 I'm assuming all applicants have equivalent applicable experience. This isn't about someone with three decades of COBOL applying for a Java guru job.

2 Yes, I know that (at least in the US) you aren't supposed to ask how old an applicant is. In my experience, though, you can get a general idea from a résumé.

答:
I tend not to hire anyone who no longer has control over their bodily functions.

If you strip away stereotypes about lacking energy and dynamism and so on (which are generally as worthless as any other stereotype), the only genuine factor I can think of is how close is the person to retirement and how long before they leave you.

Given that it's not uncommon for a programmer of any age to move on after 2 - 3 years, this is basically a non-issue so long as the person is smart, knowledgeable and hard working I wouldn't consider it.

Oh, and in the UK at least as an employer I should probably mention that considering someone's age as a reason for hiring or not is illegal - though obviously very hard to prove that that was the reason.

Title: How old is "too old"?


问:
What is the best strategy for licensing a desktop application using a web service, when all I need to know is when people use the product?
Our company's main application is a desktop program that is used at warehouses and written in C# and Windows Presentation Forms.

The next thing we want to be able to do is track when customers open up the application and when it is being used. The reason for this is so we can charge them per month, based on if they are/arn't using the application. My boss is having me research different ways to "license" the product under these requirements.

Not having any experience doing this, a few things come to mind. I could create a web application that runs on a server, and every time the desktop application is opened and the user logs in, the application connects to the server and marks a database with the DateTime. Or is there licensing software that I can use to accomplish this? Just looking for tips/advice from people who have experience with this type of stuff.

答:
The quickest and cheapest way is to do something similar to what you suggested: Every time the user performs a main function of your program, say it's "Pack Widgets onto Warehouse Floor," log that function, with an ID of the individual installation of the program, username and maybe the machine name too. Generate the unique ID on installation - maybe a GUID generated during the installation process.

The reason I say a main function (or several/all main functions) of the program is that they could just start the program once and you will only have one entry for billing. This way you can avoid that scenario, and also have the added side-benefit of seeing which functions of your program which users are actually using the most. This can help your sales team and also your development team target the correct areas.

Make sure that you tell the client that you're going to be billing them based on usage and that the program needs to connect to external servers in order to function. However, you need to make sure that the client's business can continue to function when their internet connection is down. Cache these usage logs locally in an encrypted cache (so that tech savvy clients can't jippo your system easily) and then have a maximum period that the program can function without having an internet connection, say a week or two. After that period, the program will refuse to work unless it connects to your server.

Let's say the client can't connect because a hurricane has taken down the comms for two weeks. In that really bad situation, the client types in a code that you give them over the phone that gets evaluated in your program (NOT something like "give me more time", but a proper code that gets checked by a relatively simple algorithm) and they get another week's grace period. However, I discourage this as it adds unnecessary complexity. If you're concerned about this type of scenario and you're on a monthly billing cycle, rather consider making the cache period three or four weeks.


问:
Requiring multithreading/concurrency for implementation of scripting language
Here's the deal: I'm looking at designing my own scripting/interpreted language for fun. I'm only in the planning stages right now; I want to make sure I have a very strong hold on exactly how I will implement everything before I start coding.

What I'm currently struggling with is concurrency. It seems to me like an easy way to avoid the unpredictable performance that comes with garbage collection would be to put the garbage collector in its own thread, and have it run concurrently with the interpreter itself. (To be clear, I don't plan to allow the scripts to be multithreaded themselves; I would simply put a garbage collector to work in a different thread than the interpreter.) This doesn't seem to be a common strategy for many popular scripting languages, probably for portability reasons; I would probably write the interpreter in the UNIX/POSIX threading framework initially and then port it to other platforms (Windows, etc.) if need be.

Does anyone have any thoughts in this issue? Would whatever gains I receive by exploiting concurrency be nullified by the portability issues that will inevitably arise? (On that note, am I really correct in my assumption that I would experience great performance gains with a concurrent garbage collector?) Should I move forward with this strategy or step away from it?

答:
writing anything multithreaded is hard

I can think of at least one race condition of the top of my head you'll need to be aware of:

there is an object A with field foo

the GC just started its mark phase and has examined field A.foo and is currently examining some other part of the object tree

meanwhile the interpreter has allocated a new object B and the script assigns it to A.foo and the local variable it was in goes out of scope (deleting any other references to B)

the GC finishes and won't notice the change to A.foo so B won't be marked alive

B gets cleaned up and you have a dangling pointer in A.foo

this doesn't need to be allocation (any method of getting to be the sole owner of a yet unmarked B and then assigning to an already examined field will cause trouble)

this can be solved by putting any object handled by the interpreter (not yet marked alive in the sweep) in a to-be-examined list so it gets marked alive during the sweep

so essentially in each object you have a bit field with an "alive" flag and a "handled by interpreter" flag

and on each object the script uses the interpreter will have to do

```<code>if(!obj.alive && !obj.alreadyHandled){
     obj.alreadyHandled=true;
     GC.addToQueue(obj);
}
</code>```

this will delay cleanup for some objects but that is acceptable

I'm sure there are many other things to be aware of (like plain memory visibility effects) that will make things harder and this is probably a large reason why concurrent GCs are rare

Body:
writing anything multithreaded is hard

I can think of at least one race condition of the top of my head you'll need to be aware of:

there is an object A with field foo

the GC just started its mark phase and has examined field A.foo and is currently examining some other part of the object tree

meanwhile the interpreter has allocated a new object B and the script assigns it to A.foo and the local variable it was in goes out of scope (deleting any other references to B)

the GC finishes and won't notice the change to A.foo so B won't be marked alive

B gets cleaned up and you have a dangling pointer in A.foo

this doesn't need to be allocation (any method of getting to be the sole owner of a yet unmarked B and then assigning to an already examined field will cause trouble)

this can be solved by putting any object handled by the interpreter (not yet marked alive in the sweep) in a to-be-examined list so it gets marked alive during the sweep

so essentially in each object you have a bit field with an "alive" flag and a "handled by interpreter" flag

and on each object the script uses the interpreter will have to do

if(!obj.alive && !obj.alreadyHandled){
     obj.alreadyHandled=true;
     GC.addToQueue(obj);
}

this will delay cleanup for some objects but that is acceptable

I'm sure there are many other things to be aware of (like plain memory visibility effects) that will make things harder and this is probably a large reason why concurrent GCs are rare


问:
Why put the business logic in the model? What happens when I have multiple types of storage?
I always thought that the business logic has to be in the controller and that the controller, since it is the 'middle' part, stays static and that the model/view have to be capsuled via interfaces. That way you could change the business logic without affecting anything else, program multiple Models (one for each database/type of storage) and a dozens of views (for different platforms for example).

Now I read in this question that you should always put the business logic into the model and that the controller is deeply connected with the view.

To me, that doesn't really make sense and implies that each time I want to have the means of supporting another database/type of storage I've to rewrite my whole model including the business logic.

And if I want another view, I've to rewrite both the view and the controller.

May someone explain why that is or if I went wrong somewhere?

答:
To truly isolate business logic and make it separate from the presentation layer infrastructure, it should be encapsulated by application services. The MVC architecture is a way to implement the presentation layer and it should remain at that scope, delegating all business logic to these application services. Think of view models as adapters between the view and the data that needs to be displayed on and or read. The controller mediates the interaction between view models, views and application services which host the business logic.

Application services implement business use cases and are decoupled from the presentation layer, whether it be MVC or something else. In turn, application services can host transaction scripts or a domain-driven design.

For storage, the application service can reference a repository or any abstraction of a persistence mechanism. Different implementations can be supported by abstracting the data access into an interface. Typically, these abstractions are leaky and are only partially portable across implementations and it is often a futile attempt to attain full portability.

UPDATE

My suggestion is based on the Hexagonal architecture. In a hexagonal architecture, your domain model (business logic) is at the core. This core is encapsulated by application services which act as a facade. Application services are simple classes which have methods corresponding to use cases in your domain. For an in-depth discussion on application services take a look at Services in Domain-Driven Design. The code sample contains a PurchaseOrderService which is an application service for a purchasing domain. (Note that an application service does not imply the use of domain-driven design.)

In a hexagonal architecture, an MVC presentation layer is an adapter between your domain model (business logic) and a GUI. The domain model isn't aware of the presentation layer, but the presentation layer is aware of the domain model.

This solution certainly has moving parts than a solution which places business logic in the controller and you should weigh the drawbacks and benefits. The reason I suggest it is because I prefer to keep business logic decoupled from the presentation layer in order to combat complexity. This becomes more important as the application grows.


答:
Some test I would like to have (probably not all of them all the time):

Boundary testing: Many errors occur on the bounds of the domain (like putting < in stead of <=). So if you could somehow support this, it would be grate. (Let the programmer define int[0-90] and so no value above 90 or below 0 will be allowed).

Robustness testing: Is almost the same as the above, but aims to test values that should not be supported, and see that the app doesn't crash.

The above may be combined to one test -> the software doesn't crash, and just testing random values from the whole domain (random integers, random strings)

Domain knowledge: A convenient way to insert tests by domain experts will be good. That means someone that has very good knowledge in banking but no clue in programming should be able to write some tests, according to his knowledge.

Program graph: Build a program graph, including branches and loops. And while running a set of tests, mark the lines of code tested, and those that where never touched. So the programmer\tester can know what part of the code was never tested. (May be time and space consuming)

Asserts: Give the programmer an option to make an assert while testing, that will be taken out by the compiler in production. This is a very old idea no one really implemented in a nice way (if at all).


答:
Timesheets aren't a dealbreaker for me. My last job had them at first for providing transparency for a client, then dropped them. My current job has them and they're kept in case of an audit, since we apply for government research grants.

The software used for timesheets utterly sucks, but it still takes about 5 minutes for me to fill in a timesheet because they're at a very high level: 8 hours a day, mark down vacation/sick days and put in some notes on what was worked on during the week. I take notes every day, so it doesn't take me long to come up with a few lines to type into the timesheet.

Title: As a programmer, are you required to do timesheets?

Body:
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?


答:
ElYusubov's answer mostly nails it, domain logic should go into the model and application logic into the controller.

Two clarifications:

The term business logic is rather useless here, because it is ambiguous. Business logic is an umbrella term for all logic that business-people care about, separating it from mere technicalities like how to store stuff in a database or how to render it on a screen. Both domain logic ("a valid email address looks like...") and workflows/business processes ("when a user signs up, ask for his/her email address") are considered business logic, with the former clearly belonging in the model and the latter being application logic that goes in the controller.

MVC is a pattern for putting stuff on a screen and allowing the user to interact with it, it does not specify storage at all. Most MVC-frameworks are full stack frameworks that go beyond mere MVC and do help you with storing your data, and because the data that should be stored are usually to be found in the model, these frameworks give you convenient ways of storing your model-data in a database, but that has nothing to do with MVC. Ideally, models should be persistence-agnostic and switching to a different type of storage should not affect model-code at all. Full fledged architectures have a persistence layer to handle this.

Title: Why put the business logic in the model? What happens when I have multiple types of storage?

Body:
I always thought that the business logic has to be in the controller and that the controller, since it is the 'middle' part, stays static and that the model/view have to be capsuled via interfaces. That way you could change the business logic without affecting anything else, program multiple Models (one for each database/type of storage) and a dozens of views (for different platforms for example).

Now I read in this question that you should always put the business logic into the model and that the controller is deeply connected with the view.

To me, that doesn't really make sense and implies that each time I want to have the means of supporting another database/type of storage I've to rewrite my whole model including the business logic.

And if I want another view, I've to rewrite both the view and the controller.

May someone explain why that is or if I went wrong somewhere?


答:
Depends on what you mean by business logic.  Any "logic" that gives meaning to contents of the model should be in the model.  In the linked question, the highest voted answer seems to define "business logic" as anything relating to data; this makes sense from the point of view that a business' data is its business!

I once saw an example by the creator of Rails (I think) who was going on about exactly this - not putting "business logic" in the model.  His example was a controller class and method for app registration and login - a supplied password in plaintext was encrypted before being inserted into or queried against the model (a database.)

I can't think of a better example of something that is not controller logic and that belongs directly in the model.

The model could be an interface to myriad data stores, alleviating portability concerns.  It's here one could find confusion over wether or not the model interface is actually the "controller."

Generally speaking, the controller links the model and view (which are the meat-and-potatoes of the app.)  In Cocoa development it can be simplistic to the point where the controller is handled via the XCode GUI (controller objects and bindings.)

The GoF's "Design Patterns" section on MVC, loosely quoted:

The MVC triad of classes is used to build user interfaces in Smalltalk-80. The Model
  is the application object, the View is its screen presentation, and the Controller defines
  the way the UI reacts to user input.  MVC decouples views and models by establishing a
  subscribe/notify protocol between them.  The following diagram shows a model and three
  views.  We've left out the controllers for simplicity.

MVC is all about UIs.  The focus is on the model and view - defining and displaying data.  Note the "subscribe/notify protocol" - this is where your controller comes in.  You can build all the views you want; so long as they adhere to the protocol you'll never have to touch the model or controller.

If you're talking web development specifically, IMHO many popular web frameworks are fast and loose with the term MVC and its component definitions.


答:
Yes, employees are required to do time sheets and this isn't an unusual thing for me to see.

Usually they are broken up into various categories,e.g. support or some big feature like search on a site, with a minimum of 15 minutes per entry, which is .25 of an hour.

No, timesheets are just an administrative feature I've come to accept as part of my job in a way.  It can be interesting to break down my work into various buckets like administrative, support and development work.

There are a couple of different justifications that I know for having developers do timesheets:

There are various accounting rules about how some expenses can be capitalized and amortized so that it looks better on the books, or at least that is what I remember from hearing it a couple of times.

Quantifying our time allocation allows management to see how much time is spent in various areas which can be used for strategic planning in a sense.  If there are a group of developers spending a large time on support then it may make sense to create a new support team to take that over possibly to give an example here.  Another thought is that even though we are internal employees, there is still the question of from which budget do our salaries come.  If we are doing mostly project work, then it is out of the project's budget which isn't the same as a support budget possibly.


答:
Micro-optimizations are almost never worth the time, and almost all the easy ones are done automatically by compilers and runtimes.

There is, however, one important area of optimization where C++ and Java are fundamentally different, and that is bulk memory access. C++ has manual memory management, which means you can optimize the application's data layout and access patterns to make full use of caches. This is quite hard, somewhat specific to the hardware you're running on (so performance gains may disappear on different hardware), but if done right, it can lead to absolutely breathtaking performance. Of course you pay for it with the potential for all kinds of horrible bugs.

With a garbage collected language like Java, this kind of optimizations cannot be done in the code. Some can be done by the runtime (automatically or through configuration, see below), and some are just not possible (the price you pay for being protected from memory management bugs).

If not, could people give examples of what tricks you can use in Java (besides simple compiler flags).

Compiler flags are irrelevant in Java because the Java compiler does almost no optimization; the runtime does.

And indeed Java runtimes have a multitude of parameters that can be tweaked, especially concerning the garbage collector. There's nothing "simple" about those options - the defaults are good for most applications, and getting better performance requires you to understand exactly what the options do and how your application behaves.


问:
Views : ViewControllers, many to one, or one to one?
I have developed an Android application where, typically, each view (layout.xml) displayed on the screen has it's own corresponding fragment (for the purpose of this question I may refer to this as a ViewController).

These views and Fragments/ViewControllers are appropriately named to reflect what they display. So this has the effect of allowing the programmer to easily pinpoint the files associated with what they see on any given screen.

The above refers to the one to one part of my question.

Please note that with the above there are a few exceptions where very similar is displayed on two views so the ViewController is used for two views. (Using a simple switch (type) to determine what layout.xml file to load)

On the flip side. I am currently working on the iOS version of the same app, which I didn't develop. It seems that they are adopting more of a one-to-many (ViewController:View) approach.

There appears to be one ViewController that handles the display logic for many different types of views. In the ViewController are an assortment of boolean flags and arrays of data (to be displayed) that are used to determine what view to load and how to display it.

This seems very cumbersome to me and coupled with no comments/ambiguous variable names I am finding it very difficult to implement changes into the project.

What do you guys think of the two approaches? Which one would you prefer? I'm really considering putting in some extra time at work to refactor the iOS into a more 1:1 oriented approach.

My reasoning for 1:1 over M:1 is that of modularity and legibility. After all, don't some people measure the quality of code based on how easy it is for another developer to pick up the reigns or how easy it is to pull a piece of code and use it somewhere else?

答:
First of all Android and iOS are different platforms, what is very efficient in one, may be not so good in the other. But honestly, I have no idea, because I haven't read into them. I use the 1:1 approach because its easy, and I never got performance issues that led me to that area.

As to the quality of code, you are right. Readability, and "how easy it is to pull a piece of code" is defiantly a measurement. Sometimes I leave some inefficient code with a comment just so I can later understand what the hell I did there.

To your problem, well its up to you to decide if you want to be a nice guy, and make it easy on the next programmer or just get the job done. (consider: will the next programmer be you?)


问:
Generics and Type-erasure
Generics in Java are implemented using type erasure. The JLS  says that the inspiration was backward compatibility. Where as on the other hand C# generics are reifiable.

Theoretically what are the advantages and disadvantages by having Generics as "erasure" or "reifiable"?

Is Java missing onto something?

答:
The downside of type erasure is that you do not know at runtime the type of the generic. This implies that you cannot apply reflection on them and you cannot instantiate them at runtime.

You cannot do something like this in Java:

```<code>public class MyClass<T> {
    private T t;

    //more methods
    public void myMethod() {
        //more code
        if (someCondition) {
            t = new T();//illegal
        } else {
            T[] array = new T[];//illegal
        }
    }
}
</code>```

There is a workaround for this but it requires more code. The advantage, as you have mentioned it, is backwards compatibility.

Title: Generics and Type-erasure

Body:
The downside of type erasure is that you do not know at runtime the type of the generic. This implies that you cannot apply reflection on them and you cannot instantiate them at runtime.

You cannot do something like this in Java:

public class MyClass<T> {
    private T t;

    //more methods
    public void myMethod() {
        //more code
        if (someCondition) {
            t = new T();//illegal
        } else {
            T[] array = new T[];//illegal
        }
    }
}

There is a workaround for this but it requires more code. The advantage, as you have mentioned it, is backwards compatibility.


答:
There appears to be one ViewController that handles the display logic
  for many different types of views. In the ViewController are an
  assortment of boolean flags and arrays of data (to be displayed) that
  are used to determine what view to load and how to display it.

It's typical in iOS apps to have one view controller instance for each "screenful" of content, i.e. a view and its subviews, similar to what you'd get from a layout in Android. If the app you're working on uses a single view controller object, or even separate instances of the very same view controller class, to manage a number of different screens then you're probably right that the code should be refactored. Before you jump into that project, though, read Apple's View Controller Programming Guide so that you have a solid understanding of how view controllers work together in iOS.

Title: Views : ViewControllers, many to one, or one to one?

Body:
I have developed an Android application where, typically, each view (layout.xml) displayed on the screen has it's own corresponding fragment (for the purpose of this question I may refer to this as a ViewController).

These views and Fragments/ViewControllers are appropriately named to reflect what they display. So this has the effect of allowing the programmer to easily pinpoint the files associated with what they see on any given screen.

The above refers to the one to one part of my question.

Please note that with the above there are a few exceptions where very similar is displayed on two views so the ViewController is used for two views. (Using a simple switch (type) to determine what layout.xml file to load)

On the flip side. I am currently working on the iOS version of the same app, which I didn't develop. It seems that they are adopting more of a one-to-many (ViewController:View) approach.

There appears to be one ViewController that handles the display logic for many different types of views. In the ViewController are an assortment of boolean flags and arrays of data (to be displayed) that are used to determine what view to load and how to display it.

This seems very cumbersome to me and coupled with no comments/ambiguous variable names I am finding it very difficult to implement changes into the project.

What do you guys think of the two approaches? Which one would you prefer? I'm really considering putting in some extra time at work to refactor the iOS into a more 1:1 oriented approach.

My reasoning for 1:1 over M:1 is that of modularity and legibility. After all, don't some people measure the quality of code based on how easy it is for another developer to pick up the reigns or how easy it is to pull a piece of code and use it somewhere else?


答:
You and large parts of the programming world seem to misunderstand what the roles of the MVC parts are. In short, they are:

Model = domain logic

View = output logic

Controller = input logic

This means that the model is responsible for the entire business logic: anything that is related to drawing widgets on a screen, driving a printer, outputting data as HTML, parsing HTTP requests, etc. etc. doesn't belong in the model.

However, many of the modern so-called "MVC" frameworks don't really do MVC at all, or they mis-label their parts. Quite often, what is called "model" is the persistence layer of the model, while the business logic sits in what they call the "controller"; the actual controller is usually just a central entry point with a routing table and a bit of code in the individual "controller"s to dispatch the input they receive to the correct business processes. What these frameworks call "view" is really a bit of everything: some presentation logic (View), a bit of input handling and validation (Controller), and some more business logic (Model). The lion's share of the actual view is usually called "templates".

You might also want to read about the Multi-Tier Architecture; where MVC is kind of one-way (the flow is Controller -> Model -> View), Multi-Tier is a two-way thing (Presentation -> Logic -> Data -> Logic -> Presentation), and quite a few frameworks that pretend to do MVC actually do Three-Tier, relabeling Presentation to View, Logic to Controller, and Data to Model.


问:
Why do generics in Scala have erased types, and are not reifiable?
Why do generics in Scala have erased types, and are not reifiable?

Is it due to lack of support from the JVM or for compatibility with Java libraries?
What are the advantages in general of having generics as reifiable?

答:
These two are only indirectly related.

Scala chose to run on the JVM to leverage the portability and the huge amount of libraries and frameworks that this buys you. This gave it a head start over many other fashionable new languages, and it may also have been a smart move culturally: although many new form of expression are possible in the language, many existing Java programmers liked the fact that the language was more powerful, but not quite entirely unlike Java, and started using the language early.

The price to pay for this is that you have to abide by the limitations of the underlying VM, and yes, among others that means no reified generic types. Time will tell whether the trade-off was worth it or whether breaking with tradition more radically would have been better in the long run. (Note that a goal of Java itself was "to drag about half of C++ programmers about halfway over to Common Lisp" (Guy Steele), which meant that reusing the old C-like syntax was necessary to catch their attention. Perhaps history is repeating itself.)


问:
PHP MVC error handling, view display and user permissions
I am building a moderation panel from scratch in a MVC approach and a lot of questions cropped up during development. I would like to hear from others how they handle these situations.

Error handling

Should you handle an error inside the class method or should the method return something anyway and you handle the error in controller? What about PDO exceptions, how to handle them? For example, let's say we have a method that returns true if the user exists in a table and false if he does not exist. What do you return in the catch statement? You can't just return false because then the controller assumes that everything is alright while the truth is that something must be seriously broken. Displaying the error from the method completely breaks the whole design. Maybe a page redirect inside the method?

The proper way to show a view

The controller right now looks something like this:

```<code>include('view/header.php');
if ($_GET['m']=='something') include('view/something.php');
elseif ($_GET['m']=='somethingelse') include('view/somethingelse.php');
include('view/foter.php');
</code>```

Each view also checks if it was included from the index page to prevent it being accessed directly.
There is a view file for each different document body. Is this way of including different views ok or is there a more proper way?

Managing user rights

Each user has his own rights, what he can see and what he can do. Which part of the system should verify that user has the permission to see the view, controller or view itself? Right now I do permission checks directly in the view because each view can contain several forms that require different permissions and I would need to make a seperate file for each of them if it was put in the controller.
I also have to re-check for the permissions everytime a form is submitted because form data can be easily forged.
The truth is, all this permission checking and validating the inputs just turns the controller into a huge if/then/else cluster.

I feel like 90% of the time I am doing error checks/permissions/validations and very little of the actual logic. Is this normal even for popular frameworks?

答:
There is no single proper approach to your problems even within MVC pattern so simple answer to your questions does not exist.

1 Error handling

If you are using the PDO you can change error handling by setting PDO::ATTR_ERRMODE so you don't have to use exceptions but regardless of the way errors are returned it is a programmers responsibility to handle them properly.
If your method is returning false if the user doesn't exists then the controller should check what value was returned. There is no such thing as "controller assumes" it only means that the programmer assumed and didn't check returned value.

There are different errors which should be handled in different way some of them may require only showing error message some of them may be critical (like no db connection). You can use messages, views or additional controller to handle errors.

2 The proper way to show a view

Code from your example would be usually handled by the layout (header, footer, different element placement) and by the controller (using different views depending on the request). It is not good idea to use 'include' directly rather wrap it in the method. You can also create view class which would be responsible for handling views. view != .phtml

3 Managing user rights

In MVC pattern used for web applications there is usually additional "front controller" and permission checking will be handled there. You have to check for permission with each request and each request will require access to specific controller/method if you implement proper ACL it should resolve all your problems with user rights.


答:
I would not prefer either, I would prefer the one that has least ifs, switches, auxiliary state variables and code duplication.

Usually it's 1:1 with auxiliary classes that take care of displaying information that appears in multiple places, but that's not the rule. The rule is whatever has fewer branches without causing code duplication in that particular situation.