问:
Building a string translation database for multiple (in-house) projects
At our company we have an existing translation ms-sql table wich stores strings like this:

```<code>Id |     Key     | Language | Value
 1 | hello-world |  nl-BE   | Hallo Wereld
 2 | hello-world |  en-GB   | Hello World
</code>```

There are 3 languages in the system and I expect this to grow to a maximum of about 10 in the future

This table is read by multiple very different projects (about 60 projects, mostly websites/web applications and some web services), that each  open a database connection to the translation database, cache the translations

Feedback from the front-end devs is that our UIto input or modify translations 's biggest downside  is that they cannot know what project uses what strings.

They sometimes modify strings not knowing they are breaking 7 projects with it.

Now they just have to type something like this.Translate("Hello World") and the system takes care of the rest.

I could ofcourse force them to  something like this.Translate("Hello World","AwesomeApplication1") but that seems like it's going to require quite a lot of refactoring across the many many projects.

How would you go about providing this solution? How would you, as a dev, provide the "project name" to the translation? How would you store this in the database?

Important note: the translation re-use is the whole point of the centralised database, so scoping translations to one project by going

```<code>1|hello-world|nl-BE|Hallo Wereld|MyAwesomeApplicatoin1
5|hello-world|nl-BE|Hallo Wereld!|MyAwesomeApplicatoin2
</code>```

is not really a wanted option.

I'd prefer something like :

```<code>1|hello-world|nl-BE|Hallo Wereld|MyAwesomeApplicatoin1,MyAwesomeApplicatoin2
</code>```

or a foreign key equivalent of just putting the names in the table.

UPDATE

Based on the advise to normalize the database I have come up with something like this so far:

```<code>//this allows me to distinquish if translations where added by developer or by translator
</code>```

UPDATE2: added edmx instead of text.
If people are interested I could github the WCF project i'm wrapping this concept in so other people can test and use it.

答:
Since they are referencing a 'this' ... you can assign the project name once to 'this' (via the constructor, for example) and the interface to the translation functions wouldnt change for the coders.  Under the hood, it just adds the project name to the database query.  Alternatively, you can provide 'this' a means of knowing the project name on its own.  Its really going to depend on how you have your classes structured.

For storage, you can do something like:

```<code>1 ! hello-world ! nl-EN ! Hello World  ! *
2 ! hello-world ! nl-EN ! Howdy, World ! CowboyApp
3 ! hello-world ! nl-EN ! Arrgh        ! PirateApp
</code>```

Use a wild card to apply a general translation to all apps, but the specific app name when you want to override a translation for a particular app.  This will keep the duplications down to a minimum.

To see what program is using which translations, you now know this - if you dont want to go through and manually gathter that information, you can log the translation requests.

Body:
Since they are referencing a 'this' ... you can assign the project name once to 'this' (via the constructor, for example) and the interface to the translation functions wouldnt change for the coders.  Under the hood, it just adds the project name to the database query.  Alternatively, you can provide 'this' a means of knowing the project name on its own.  Its really going to depend on how you have your classes structured.

For storage, you can do something like:

1 ! hello-world ! nl-EN ! Hello World  ! *
2 ! hello-world ! nl-EN ! Howdy, World ! CowboyApp
3 ! hello-world ! nl-EN ! Arrgh        ! PirateApp

Use a wild card to apply a general translation to all apps, but the specific app name when you want to override a translation for a particular app.  This will keep the duplications down to a minimum.

To see what program is using which translations, you now know this - if you dont want to go through and manually gathter that information, you can log the translation requests.


问:
Why are references rarely used in PHP?
I have some C++ knowledge and know that pointers are commonly used there, but I've started to look at PHP open source code and I never see code using references in methods.

Instead, the code always uses a return value instead of passing the reference to the variable to the method, which then changes that variable's value and just returns it.

I have read that using references uses less memory, so why aren't they used in PHP?

答:
PHP already does a copy-on-write thing where it doesn't create a new value til you change something, so there's not much memory saved by using references.  Doing so can even mess with some stuff PHP does internally to reduce memory usage, making things even worse.

Add to that the fact that references make things a bit too magical in general.  The default, and thus what most people expect, is pass-by-value; when i pass $i to a function, it complicates things tremendously to have to care whether that function mysteriously changes $i to something else entirely, and thus make defensive copies just in case.  (It can already modify $i if the value is an object, but in my opinion it shouldn't.)

Basically, i'd only find pass-by-reference useful for "out" parameters, meaning variables i expect to get back from the function rather than pass in, a la preg_match's &$matches.  Even for functions that clearly modify the object being passed in, like sort or array_pop, that feels a bit icky...but that's what we're stuck with.

OwnerDisplayName: Alexander Cogneau

ContentLicense: CC BY-SA 3.0

Title: Why are references rarely used in PHP?


问:
Randomness of wrapped RNG
There are plenty of questions around regarding random number generation, but I couldn't find anything that exactly matched my question. Apologies if I missed one.

Most random number generators in software tend to have flat distribution - in the given range, any number is as likely to come next as any other (more or less). This is obviously the intention, because anything other than a flat distribution isn't entirely random because some numbers are more likely than others. However, there are times when a flat distribution is not desirable. For example, when building a game, it is often necessary to model real-world scenarios, many of which have a normal (bell-curve) distribution.

If a "good" PRNG (such as an existing RNG from a popular programming language's main library) is fed into a simple equation, such as the equation for a bell curve, or a sine wave, or some other distribution, how far can we assume that the resulting PRNG is also "good"? Most of the tests for PRNGs test whether the system is purely random, so they won't work on this system. Is it just a matter of counting outputs over a long time and seeing how well they fit the desired distribution, or is there a simpler (eg. analytical or algebraic) way to check this?

Any help would be appreciated.

答:
You need to grab a bunch of numbers and see if they fit the desired curve. You did the algebra when you created the flat->curve transform equation. Doing more algebra isn't going to help you prove that you already know how to do algebra. You need some other way to prove that you created the equation correctly, and that you implemented it correctly.

The most straightforward way to check it is just to grab a bunch of numbers and plot them.

Title: Randomness of wrapped RNG


问:
Great Lunch and Learn Topics
We recently revived the lunch in learns for the programming department in the company I work for. We were all asked if we had any ideas for a session, and if we would be interested in doing a presentation. I've had a few ideas ranging from various topics such as:

How to think like a user when designing UI

or Differences in HTML5

A few coworkers I tossed these ideas around to seem to like them. However, I'd like some more ideas before I dig too far into creating a presentation.

What are some great lunch and learn topics?

答:
Depending on the audience, you could cover some basics and best practices, such as:

OO

Work through McConnell's "Code Complete"

Writing secure code

TDD

Design Patterns

ContentLicense: CC BY-SA 2.5

Title: Great Lunch and Learn Topics


答:
If the bell curve is implemented properly (e.g. doesn't distort the nature of the PRNG), then the generated bell curve PRNG will be as good as the PRNG it was generated from.

Also, due to the nature of the bell curve function, the translation should be bidirectional (you should be able to turn a bell curve PRNG into a flat PRNG, assuming real values). If it is not bidirectional, you did something wrong.

You might want to cross-post this to theoretical cs. You might get a cooler answer.

Title: Randomness of wrapped RNG

Body:
There are plenty of questions around regarding random number generation, but I couldn't find anything that exactly matched my question. Apologies if I missed one.

Most random number generators in software tend to have flat distribution - in the given range, any number is as likely to come next as any other (more or less). This is obviously the intention, because anything other than a flat distribution isn't entirely random because some numbers are more likely than others. However, there are times when a flat distribution is not desirable. For example, when building a game, it is often necessary to model real-world scenarios, many of which have a normal (bell-curve) distribution.

If a "good" PRNG (such as an existing RNG from a popular programming language's main library) is fed into a simple equation, such as the equation for a bell curve, or a sine wave, or some other distribution, how far can we assume that the resulting PRNG is also "good"? Most of the tests for PRNGs test whether the system is purely random, so they won't work on this system. Is it just a matter of counting outputs over a long time and seeing how well they fit the desired distribution, or is there a simpler (eg. analytical or algebraic) way to check this?

Any help would be appreciated.


答:
Preliminary note #1: You are not telling us how the translations are maintained at the moment

Preliminary note #2: Your database is not normalized. Whatever the solution you're going to take, first normalize your database. You run into terrible maintenance problems later if you don't do that now

This is what I would do.

Rewrite your translate call so that it carries a program ID back to the server

The back end translator will put the string in the database table if it does not yet exist, and will tag it with the program id

If the string already exists, it will only be updated if the program id matches the original program id with which the string was created. If not, return a conflict notification.

Variations:

You could use a 'developer ID/ translator ID' instead of a program ID. I consider that better because there are people that know a foreign language and those that think they know. Only the first group has modification rights.

You might want to store the IDs of all programs that use the string in the DB, so that you know which programs conflict.

You could extend this 'ownership' think to each individual language: one person can do English, the other Dutch.

Once your database is normalized you add build complexity like "Program A is in Languages 1,2,3; B is in 3 and 5"

I also suggest you write a separate 'translation maintenance' program that will show you missing translations etc. I once did that with 2-level authorization: each translation has to be vetted by a second person (usually a native speaker).

Title: Building a string translation database for multiple (in-house) projects

Body:
At our company we have an existing translation ms-sql table wich stores strings like this:

```<code>Id |     Key     | Language | Value
 1 | hello-world |  nl-BE   | Hallo Wereld
 2 | hello-world |  en-GB   | Hello World
</code>```

There are 3 languages in the system and I expect this to grow to a maximum of about 10 in the future

This table is read by multiple very different projects (about 60 projects, mostly websites/web applications and some web services), that each  open a database connection to the translation database, cache the translations

Feedback from the front-end devs is that our UIto input or modify translations 's biggest downside  is that they cannot know what project uses what strings.

They sometimes modify strings not knowing they are breaking 7 projects with it.

Now they just have to type something like this.Translate("Hello World") and the system takes care of the rest.

I could ofcourse force them to  something like this.Translate("Hello World","AwesomeApplication1") but that seems like it's going to require quite a lot of refactoring across the many many projects.

How would you go about providing this solution? How would you, as a dev, provide the "project name" to the translation? How would you store this in the database?

Important note: the translation re-use is the whole point of the centralised database, so scoping translations to one project by going

```<code>1|hello-world|nl-BE|Hallo Wereld|MyAwesomeApplicatoin1
5|hello-world|nl-BE|Hallo Wereld!|MyAwesomeApplicatoin2
</code>```

is not really a wanted option.

I'd prefer something like :

```<code>1|hello-world|nl-BE|Hallo Wereld|MyAwesomeApplicatoin1,MyAwesomeApplicatoin2
</code>```

or a foreign key equivalent of just putting the names in the table.

UPDATE

Based on the advise to normalize the database I have come up with something like this so far:

```<code>//this allows me to distinquish if translations where added by developer or by translator
</code>```

UPDATE2: added edmx instead of text.
If people are interested I could github the WCF project i'm wrapping this concept in so other people can test and use it.


答:
Your assertion that references are rarely used is incorrect. As others have already mentioned there's a ton of native functions that use references, notable examples include the array sorting functions and preg_match() / preg_match_all(). If you are using any of these functions in your code, you are also using references.

Moving on, references in PHP are not pointers. Since you're coming from a C++ background I can understand the confusion, but PHP references are an entirely different beast, they are aliases to a symbol table. Any performance gains you might have expected from C++ references simply don't apply to PHP references.

In fact, in most scenarios passing by value is faster and less memory intensive than passing by reference. The Zend Engine, PHP's core, uses a copy-on-write optimization mechanism that does not create a copy of a variable until it is modified. Passing by reference usually breaks the copy-on-write pattern and requires a copy whether you modify the value or not.

Don't be afraid to use references in PHP when you need to, but don't just do it as an attempt to micro-optimize. Remember, premature optimization is the root of all evil.

Further reading:

PHP references explained

Objects and references

In PHP (>= 5.0), is passing by reference faster?

Title: Why are references rarely used in PHP?

Body:
I have some C++ knowledge and know that pointers are commonly used there, but I've started to look at PHP open source code and I never see code using references in methods.

Instead, the code always uses a return value instead of passing the reference to the variable to the method, which then changes that variable's value and just returns it.

I have read that using references uses less memory, so why aren't they used in PHP?


答: The fundamental problem with your question is that you assume that this is common in C++, too. It isn't. We don't like output parameters and use them as little as possible- they're only really common in C-style APIs.</p>

Title: Why are references rarely used in PHP?


问:
Programming vs Engineering
I am in high school at the moment and soon reaching stages where I would have to make choices. To introduce, I love programming. I had started learning programming a year ago and have some experience with ActionScript3 and Java + (the web languages like html CSS JavaScript. But php I have found a bit hard to understand).

Other subjects which I absolutely love are mathematics, physics and chemistry. The professions related with these subjects that really interest me are engineering (piping engineer, mechanical engineer, electrical engineer etc.).

People say to me that I should choose the profession based on my interests. But I have absolutely no preference of one over another. My choice really depends on the demand of these professions in future. So my questions are -

Is the demand of programming going to degrade in future due to a excessive number of programmers in future? Or is it going to remain a profession in high demand.

Is engineering going to lose its demand? Almost everybody seems to be going for the profession of an engineer these days and it is scary to think what will happen of the world with the number of engineers there are.

Which profession is likely to remain well paid in future too?

答:
No, the demand for programmers is not going to decrease any time soon.  If anything, it will continue to increase.

No, the demand for engineers is not going to decrease any time soon.  If anything, it will continue to increase as well.

The salaries are comparable, and both will remain reasonably well paid.

Probably not the answers you were looking for since they don't help you make a decision.

Both are excellent fields if you enjoy that type of work.

I will attempt to draw some comparisons between the two fields, but I'm explicitly trying to sidestep a flame-war.

Traditional Engineering fields (electrical, mechanical, civil, chemical, etc...) tend to be more structured in the work that is performed.  Their body of knowledge is not growing at the rapid rate that programming is seeing.

Programming (Computer Science) and Software Engineering, are fields that are still in their formative state.  Their collective body of knowledge is growing at quite literally an explosive rate.  Drawing a comparison between those two related fields can be done, but doesn't serve much purpose in this case.

Work in any of those fields can be very fulfilling.  Traditional Engineering tends to be more concrete - you generally can see the results of your work with your own eyes.  Programming (CompSci and SE) tends to be more abstract or virtual.  It's harder to "see" the results of your work.  Don't read too far into that generalization though.

If you're down to picking between Computer Science and Software Engineering, then consider which Universities you are planning on attending and evaluate their programs from there.  Long term, I don't believe your career aspects will be impacted that much by picking one degree program versus the other.

Title: Programming vs Engineering


答:
I would say combine two of your passions. Go for electronics engineering. Also, make sure you broaden your horizons by taking some art and design courses. That will take you from being able to make functional devices and software to making beautiful devices and software that people will fall in love with.

Remember, the iPod wasn't the first MP3 player on the market but it might as well be the only game in town. Likewise with the iPhone and iPad. And despite the trend in the PC market for low margin products, the MacBook Pro and iMacs sell like hotcakes even though they cost more than the average PC.

All of this is because of an attention to details and making devices that aren't just functional but are also beautiful.

Now here's a big surprise for you. I don't own a SINGLE Apple product. But I can still respect the beauty in their work. If you're going to enter this field, mimic the best and strive to exceed what they've done.

Title: Programming vs Engineering

Body:
I am in high school at the moment and soon reaching stages where I would have to make choices. To introduce, I love programming. I had started learning programming a year ago and have some experience with ActionScript3 and Java + (the web languages like html CSS JavaScript. But php I have found a bit hard to understand).

Other subjects which I absolutely love are mathematics, physics and chemistry. The professions related with these subjects that really interest me are engineering (piping engineer, mechanical engineer, electrical engineer etc.).

People say to me that I should choose the profession based on my interests. But I have absolutely no preference of one over another. My choice really depends on the demand of these professions in future. So my questions are -

Is the demand of programming going to degrade in future due to a excessive number of programmers in future? Or is it going to remain a profession in high demand.

Is engineering going to lose its demand? Almost everybody seems to be going for the profession of an engineer these days and it is scary to think what will happen of the world with the number of engineers there are.

Which profession is likely to remain well paid in future too?


答:
If all your projects are written in C#, and all translator calls look like this

```<code>this.Translate("hello-world")
</code>```

where "hello-world" is the key in your translation table, it should not be too hard to write a small source code scanner using a regular expressions to find all translator calls and assign the keywords the corresponding project names. This way, you don't have to change any of your existing code or translator interfaces.

Depending on the real structure of your program, alternatively it may be easier to extract that information from the IL code of your assemblies. I did something very similar some time ago, also for translation purposes, using this example code to parse assemblies.

Body:
If all your projects are written in C#, and all translator calls look like this

this.Translate("hello-world")

where "hello-world" is the key in your translation table, it should not be too hard to write a small source code scanner using a regular expressions to find all translator calls and assign the keywords the corresponding project names. This way, you don't have to change any of your existing code or translator interfaces.

Depending on the real structure of your program, alternatively it may be easier to extract that information from the IL code of your assemblies. I did something very similar some time ago, also for translation purposes, using this example code to parse assemblies.


问:
How do I create a .NET WebService for File Upload
I need to create a web service using the .NET platform for accepting file uploads. What are the options available for doing this in C#?
What is the best approach to use? Can please you provide me with blogs/code samples/references for further reading?</p>

答:
The simplest approach would be to use WebDav there's even a C# library that you can embed in an application or for a server (can't find the link right now).

If you specifically have to use a WebService, it's as simple as creating a WCF Contract that accepts a Stream. Here's a great example on CodeProject. Enjoy.


问:
when to, and benefits, of replacing existing message passing with JMS in project?
I have moved to a new project and as the only 'software guy' I'm welcome, and expected, to suggest design improvements to the existing code (code just got out of prototype phase and needs extended to final releasable version; plus adding functionality)

The code has multiple stand alone components which are suppose to run in concert, but each one can be rebooted on it's own.  They are passing messages between these daemons via a few hand written classes which implement their own server with message queue's.  It works well enough, the project made it passed prototype phase and while stability is one of their biggest long term focuses it's not notoriously unstable; just not quite up to par for a final release.  Still, ever time I see the code all I can think is "I would have done this using JMS."  If I went back in time to their implementation days I would have told them to do this in JMS from the start; and I am very tempted to insist on that now.

Only problem is that, even if reinventing the wheel was suboptimal at the time, what they have mostly works now and I would hate to throw out large chunks of code.  I have no doubt if we kept their message passing logic I would have to spend some time working on it; I'm not certain it is 100% reliable; there are some minor data-races that they get away with because they system should be able to recover even if it happens, some 'code smells' I want to investigate further etc etc.  Still, replacing the whole system with JMS would be a pretty big overhaul.  Require writing allot of new code, some debugging to fix issues they already ran into and corrected with their home brewed system, and ultimately add a dependency on JMS when we release this project which may be undesirable.

To give a slightly better idea of the system as it is; it's mostly a direct pipeline with two way asynchronous calls.  Each separate part of the system (called daemons) at most speak with two other daemon, the one in front of it in the pipeline, and the one behind it.  Each daemon will pass requests further 'down' the pipeline to the low level architecture and want some response back (but doesn't block waiting for it), in addition asynchronous messages must be able to propagate back up the system.  Multiple people can be making requests at once; but we don't expect an absurdly high number of total messages.  Each customer will generate messages in a small burst, but the bursts aren't huge and I don't think this has to scale up to an absurdly high number of customers. Lost of a message would likely result in inconsistent state; lost messages are quasi-detected currently, but nothing really done to 'clean up' when it happens; but the system is basic enough that inconsistent state isn't likely to break things as horrible as some systems could (plus we have our own tiny closed system, probably aren't going to lose messages).  The current communication code is generic, any daemon can send any message to any other; and we just trust each daemon only sends messages to the correct daemons and that no daemon sends a message of a type another daemon doesn't know how to happen (all messages are enumerated, but some only are viable when sent to specific daemons)

So the question is, can I justify a switch to JMS?  I will feel more comfortable with stability if I know were using an enterprise system, and I think it would allow some of my other "crazy, probably never get around to implementing, but would be so cool" ideas a bit easier to implement later.  However, we have a small team and can't possible do everything I would love to do anyways.  Will JMS provide enough benefit to warrant the cost of rewriting mostly-working code (mostly working because we don't have an obvious "this doesn't work!" example, I know from code review that there are minor issues a few 'smells' that I need to look into further, and basically that it's a decent but no-where close to enterprise level, but the stuff I am certain I have to address wouldn't take as long as writing the JMS logic, much less testing and debugging).  How 'bad' is it to create a dependency on an external system like JMS when we currently can run without it?  Are there other useful advantages to JMS I'm not seeing (guaranteed message delivery seems a big one to me, but not sure just how much of a benefit that will be yet for this project)

Incidentally, one of our eventual "long term, cool to have, were see if we get around to it" goals would be to replace the current use of SQL calls to fetch data by storing everything in memory.  If we do store in-memory we will need very reliable message passing to keep state consistent between multiple daemons, and my inclination right now is that something like that should never be tried without the something like JMS.  The state wouldn't change very often, but when it does change were have to stay consistent, worry about data race etc.  We may not do that at all, would JMS make it substantially easier to keep consistent state and handle data-races, or will I still be doing the same logic in either case?

Are there certain things particularly prone to failing with quickly written message passing systems I should be looking for explicitly?

答:
Okay, finally read it all through. I agree, what you describe is a perfect scenario to using JMS. The benefits of leveraging the API is that you can remove the code that deals with the message passing and wiring up your service bus and leave it all to your JMS provider. The providers on the market have their own configuration tools and built in recovery mechanisms that will simplify your code.

Here's the hitch, making that change to as you mentioned "mostly working" code is hard to justify. But in my opinion, the less code you have to write/maintain the better, and it sounds like a great deal of effort was invested just to handle the infrastructure of passing the messages (and correlation, and session handling). Look at it this way. You can sell the change as "we can eliminate all of this code and let a vendor whose primary focus is on messaging infrastructure handle it." That's a big sell for some people. For others thinking of just throwing away all that effort (and money spent) is blasphemy.


问:
Why these attempts to water down Scala with Xtend and Kotlin?
So now Eclipse has offered Xtend and JetBrains is offering Kotlin - both of which seem to be watered down versions of Scala. My question is why?  I've played with Scala a bit and it's not that hard.  Is this just a reaction to the inherent difficulty of the leap from imperative to functional or is there something else at work here?

EDIT: Apologies.  Rereading the question as I originally posted it I can see where it sounds a bit like trolling.  The way I phrased the question just seemed to be the best way to ask the question.  I have seen blog postings to the effect "Scala is too hard/Scala is too complex" and also "Kotlin is an attempt to do Scala but simpler".  I'll leave the phrasing as it was originally but I honestly wasn't trying to troll.

答:
I've been using Scala as my primary language for the last year (with Java as a close second, both within a large legacy Java code base.)  I still have to look up fairly basic features if I haven't used them in a while.  Sure, you can write some Scala quickly, but it's an extremely feature-rich language, and it takes a long time to master.

What's more, its complexity is not just a problem for humans, but also for IDEs and compilers.  Both Celyon and Kotlin compile directly to fairly clean JavaScript.  Scala can produce JavaScript, via GWT, though getting there is complicated and GWT output is neither legible nor designed to play nicely with external JavaScript or HTML.

I am definitely more productive in Scala than Java, and the code is more compact and legible (once you know a little Scala.)  But its complexity makes me hesitate to recommend it to others.  A language with 20% of the complexity but 80% of the capability would be a welcome alternative.

[Edited to remove mention of legacy code, see comment below.]

[2017 addendum: Scala now supports JavaScript as a build target, while Kotlin has continued to add features which make sense for a Scala-like Java/Groovy/JavaScript replacement. They are now more distinctive languages than when I first wrote this.]


问:
Sorting rows off an autoincrementing primary key
Is it a bad practice to rely on an auto-incrementing primary key to sort rows in a table? A coworker and I were having an argument about this subject. We need to be able to find the last-inserted row in a table, and we have no create/update time columns (which might be considered a bad practice in itself, but that's a different argument). We obviously can't rely on the natural order of the rows, since that can be inconsistent. Is there anything inherently wrong with using the primary key in this way, given that it's an immutable value?

I should have noted: our implementation is using Hibernate (an ORM) to fetch our objects. We're not using any native queries -- only JPQL or Hibernate's functionality.

答:
If you care about time, time should be in your database.  Period.  Want to see a case where using a sequence could fail (I'm not sure if the same might happen with MySQL autoincrements)?

When you request a value from a sequence inside of a transaction, you don't just pull the next value, the DB reserves a whole block of values for you.  This is done to reduce the overhead of properly locking the sequence and handling multiple simultaneous connections.  Let's look at this sequence of events:

Client #1 connects to server

Client #1 requests a value from a sequence

DB reserves 1-10 for Client #1, gives Client #1 the value 1

Client #1 inserts the 1 into a table

Client #1 decides to do something that will take some time

Client #2 connects to server

Client #2 requests a value from a sequence

DB reserves 11-20 for Client #2, gives Client #2 the value 11

Client #2 inserts the 11 into a table

Client #2 commits & disconnects

Client #1 requests the next value from the sequence

DB gives Client #1 the value 2

Client #1 inserts 2 into a table

Client #1 commits and disconnects

What's the state of the database now?  You have 1, 2 & 11 in your table but the row with the 2 is the most recent.  Sorting by this value gives you the wrong result.


问:
When do you use float and when do you use double
Frequently, in my programming experience, I need to make a decision whether I should use float or double for my real numbers. Sometimes I go for float, sometimes I go for double, but really this feels more subjective. If I would be confronted to defend my decision, I would probably not give sound reasons.

When do you use float and when do you use double? Do you always use double, only when memory constraints are present you go for float? Or you always use float unless the precision requirement requires you to use double? Are there some substantial differences regarding the computational complexity of basic arithmetics between float and double? What are the pros and cons of using float or double? And have you even used long double?

答:
Use double for all your calculations and temp variables.  Use float when you need to maintain an array of numbers - float[] (if precision is sufficient), and you are dealing with over tens of thousands of float numbers.

Many/most math functions or operators convert/return double, and you don't want to cast the numbers back to float for any intermediate steps.

E.g.
If you have an input of 100,000 numbers from a file or a stream and need to sort them, put the numbers in a float[].

ContentLicense: CC BY-SA 4.0


问:
Why build data models in a dynamic language?
Background

This question stems out of an architectural discussion we had at work.

For the current project we are using Python and an object oriented database. There are input services that we consume, and certain interfaces that we are expected to provide output through.

Someone on our team started designing a data model, and my question was: why?

A data-only object in Python can just as well be be represented by a dict (there is a fair amount of questions about that on this site). We don't have a relational database that has columns that we need to map objects to either. At the same time, there is a cost to a data model in that it will always need to be maintained. When interfaces change it (IMHO) simply becomes another dependency that needs to be satisfied, but unlike in static-typed languages it does not actually enforce anything.

Question:

The way it seems to me is that when you are in an environment where everything is dynamic, it makes sense for the interfaces to define your data model implicitly rather than maintain some sort of classes that define a model. Are there ever any good reasons to the contrary?

EDIT

In the comments and answers people seem to be focusing on two areas, they are: database mapping and representation as well as validation of the data model.

I apologize for not being more explicit about the DB, but in this environment that we face we have an object-oriented DB that stores blobs in a file system-like representation. There is no mapping to SQL and no ORM of any sort to speak of. I do understand the argument though. For example, Django's models require subclassing for ORM to work. In thise case, making model classes makes perfect sense because the DB is effectively a static-typed data store and not 'dynamic'. But this is not the scenario of the question, because it's not a pure dynamically typed environment.

Regarding validators: yes. One will need to create validators that check fields being present, and them being of the right type. In static-typed languages the model implicitly does this (when you're coding C++/Java you can't stick user 'std::string' to where a User class should be). But in Python, a model class does not enforce anything. If I am building validators that check presence of attributes anyway, does this not make classes, dicts, generators etc functionally interchangable? And if so, should the solution not be one with least code? Validators in general seem to me to be an argument in favour of not building data model classes rather than the contrary. Am I wrong in this?

答:
When I worked against Mongo we got dictionaries back. In some parts of the code we converted it to an actual object. In other places we kept it a dictionary. In most cases, the objects were just for convenience so we could say customer.name instead of customer["name"]. In these cases we used a dotted dictionary (a class overriding __getattr__).

There were cases when the domain model "viewed" the data differently. In these cases we created objects with the structure we wanted and mapped our data objects to them. It can make a huge difference in readability to do this mapping once up-front rather than scattered all throughout your code.

Another place where an actual object was useful was when validating schema. There are some Mongo wrappers out there that will allow you to define checks when grabbing and storing documents. This is useful for keeping your "schema" consistent in the face of user error. They can provide default values for missing attributes, convert dates into strings and things of that nature. There are similar libraries for working with JSON returned from a web application.


问:
A Web application as a REST API client: how to handle resource identifiers
Several concepts related to REST conflict in my head when I try implementing it.

I have a REST-ful back-end API system that holds the business logic, and a web application that provides the UI. From various resources about REST (particularly, REST in Practice: Hypermedia and Systems Architecture) I know that I should not expose raw identifiers of my entities, but rather return hyperlinks with rel="self".

Consider the example. The REST api has a resource that returns a person:

```<code><Person>
  <Links>
    <Link rel="self" href="http://my.rest.api/api/person/1234"/>
  </Links>
  <Pets>
    <Link rel="pet" href="http://my.rest.api/api/pet/678"/>
  </Pets>
</Person>
</code>```

The problem arises with the web application. Let's assume it returns a page that contains a hyperlink to browsers:

```<code><body class="person">
  <p>
    href="http://my.web.app/pet/???????" />
  </p>
</body>
</code>```

What should I put into the href attribute? How do I keep the API entity URL in the web application to be able to get the entity when a user opens the target page?

The requirements seem conflicting:

The hyperlink href should lead to the web application because it is the system hosting the UI

The href should have some id of the entity because the web app must be able to address the entity when the target page opens

The web app should not parse/construct REST URLs beacuse it's not REST-ful, The mentioned book says

URIs should be opaque to consumers. Only the issuer of the URI knows how to interpret it and map it to a resource.

So, I cannot just take 1234 from the API response URL because as a RESTful client I should treat it as if it was something like http://my.rest.api/api/AGRIDd~ryPQZ^$RjEL0j. On the other hand, I must give some URL that leads to my web app and is enough for the app to somehow restore the API's original URL and use that URL to access the API resources.

The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

It all seems quite easy for a desktop app or a single-page javascript app. Since they live continuously, they can just keep the URLs in memory together with the service objects for the application lifetime and use them when necessary.

With a web app I can imagine several approaches, but all seem weird:

Replace the host in the API URLs and keep the result only. The huge downside is that it requires the web application to handle whatever URL the API generates, meaning monstrous coupling. Moreover, it's not RESTful again, because my web app starts interpreting the URLs.

Expose the raw ids in the REST API together with the links, use them to build Web App's URLs, and then use the ids on the web app server to find the required resources in the API. This is better, but will affect the web app server performance because the web app will have to go through the REST service navigation issuing a chain of get-by-id requests of some form to handle any request from a browser. For a somewhat nested resource this might be costly.

Store all self URLs returned by the api in a persistent (DB?) mapping on the web app server. Generate some ids for them, use the ids to build the web app page URLs and to get the URLs of the REST service resources. I.e. I keep the http://my.rest.api/pet/678 URL somewhere with a new key, say 3, and generate the web page URL as http://my.web.app/pet/3. This looks like a HTTP Cache implementation of some sort. I don't know why, but it seems weird to me.

Or Does it all mean that RESTful APIs cannot serve as backends for web applications?

答:
Does it all mean that RESTful APIs cannot serve as backends for web
  applications?

I challenge whether it is worthwhile to differentiate between a REST API and a web application. Your "web application" should just be alternate (HTML) representations of the same resources - which is to say, I don't understand how or why you expect to access http://my.rest.api/... and http://my.web.app/... and that they be simultaneously the same and different.

Your "client" is the browser in this case and it understands HTML and JavaScript. That is the web application in my opinion. Now you may disagree and think that you access said web application using foo.com and expose everything else via api.foo.com - but you have to then ask, how did foo.com provide me the representation of the resource? The "back-end" of foo.com is perfectly capable of understanding how to discover resources from api.foo.com. Your web application has merely become a proxy - no different than if you were talking to another API (from someone else) all together.

So your question can be generalized to, "How can I describe resources using my own URIs that exist in other systems?" which is trivial when you consider that it's not the client (the HTML/JavaScript) that must understand how to do this, but the server. If you agree with my first challenge, then you can simply think of your web application as a separate REST API that proxies or delegates to another REST API.

So when your client accesses my.web.app/pets/1 it knows to present the pet interface because either that's what was returned by the server-side template, or if it's an asynchronous request for some other representation (e.g. JSON or XML), the content-type header tells it so.

The server providing this is the one responsible for understanding what a pet is and how to discover a pet on the remote system. How you do this is up to you - you can simply take the ID and generate another URI, which is what you feel is inappropriate, or you can have your own database that stores the remote URI and proxies the request. Storing this URI is fine - it's equivalent to bookmarking. You'd be doing all this just to have a separate domain name. I don't honestly know why you want this - your REST API URIs have to be bookmark-able, too.

You've already brought up most of this in your question, but I feel you've framed it in a way that really didn't acknowledge that it's the practical way to do what you want to do (based on what I feel is an arbitrary constraint - that the API and the application be separate). By asking if REST APIs can't be back-ends for web applications, and suggesting that performance would be a problem, I think you're focusing all on the wrong things. It's like saying you can't create a Mashup. It's like saying the web doesn't work.

Body:
Several concepts related to REST conflict in my head when I try implementing it.

I have a REST-ful back-end API system that holds the business logic, and a web application that provides the UI. From various resources about REST (particularly, REST in Practice: Hypermedia and Systems Architecture) I know that I should not expose raw identifiers of my entities, but rather return hyperlinks with rel="self".

Consider the example. The REST api has a resource that returns a person:

```<code><Person>
  <Links>
    <Link rel="self" href="http://my.rest.api/api/person/1234"/>
  </Links>
  <Pets>
    <Link rel="pet" href="http://my.rest.api/api/pet/678"/>
  </Pets>
</Person>
</code>```

The problem arises with the web application. Let's assume it returns a page that contains a hyperlink to browsers:

```<code><body class="person">
  <p>
    <a href="http://my.web.app/pet/???????" />
  </p>
</body>
</code>```

What should I put into the href attribute? How do I keep the API entity URL in the web application to be able to get the entity when a user opens the target page?

The requirements seem conflicting:

The hyperlink href should lead to the web application because it is the system hosting the UI

The href should have some id of the entity because the web app must be able to address the entity when the target page opens

The web app should not parse/construct REST URLs beacuse it's not REST-ful, The mentioned book says

URIs should be opaque to consumers. Only the issuer of the URI knows how to interpret it and map it to a resource.

So, I cannot just take 1234 from the API response URL because as a RESTful client I should treat it as if it was something like http://my.rest.api/api/AGRIDd~ryPQZ^$RjEL0j. On the other hand, I must give some URL that leads to my web app and is enough for the app to somehow restore the API's original URL and use that URL to access the API resources.

The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

It all seems quite easy for a desktop app or a single-page javascript app. Since they live continuously, they can just keep the URLs in memory together with the service objects for the application lifetime and use them when necessary.

With a web app I can imagine several approaches, but all seem weird:

Replace the host in the API URLs and keep the result only. The huge downside is that it requires the web application to handle whatever URL the API generates, meaning monstrous coupling. Moreover, it's not RESTful again, because my web app starts interpreting the URLs.

Expose the raw ids in the REST API together with the links, use them to build Web App's URLs, and then use the ids on the web app server to find the required resources in the API. This is better, but will affect the web app server performance because the web app will have to go through the REST service navigation issuing a chain of get-by-id requests of some form to handle any request from a browser. For a somewhat nested resource this might be costly.

Store all self URLs returned by the api in a persistent (DB?) mapping on the web app server. Generate some ids for them, use the ids to build the web app page URLs and to get the URLs of the REST service resources. I.e. I keep the http://my.rest.api/pet/678 URL somewhere with a new key, say 3, and generate the web page URL as http://my.web.app/pet/3. This looks like a HTTP Cache implementation of some sort. I don't know why, but it seems weird to me.

Or Does it all mean that RESTful APIs cannot serve as backends for web applications?


答:
Even in a dynamic language the principles of Domain Driven Design can still apply. If all you're doing is passing around dictionaries, you have an Anemic model where your objects are pure data and other objects operate on them.

Taking the time to create a rich object model and embedding logic into the model provides an opportunity for your model to be more expressive and representative of the domain you're modeling.

Title: Why build data models in a dynamic language?

Body:
Background

This question stems out of an architectural discussion we had at work.

For the current project we are using Python and an object oriented database. There are input services that we consume, and certain interfaces that we are expected to provide output through.

Someone on our team started designing a data model, and my question was: why?

A data-only object in Python can just as well be be represented by a dict (there is a fair amount of questions about that on this site). We don't have a relational database that has columns that we need to map objects to either. At the same time, there is a cost to a data model in that it will always need to be maintained. When interfaces change it (IMHO) simply becomes another dependency that needs to be satisfied, but unlike in static-typed languages it does not actually enforce anything.

Question:

The way it seems to me is that when you are in an environment where everything is dynamic, it makes sense for the interfaces to define your data model implicitly rather than maintain some sort of classes that define a model. Are there ever any good reasons to the contrary?

EDIT

In the comments and answers people seem to be focusing on two areas, they are: database mapping and representation as well as validation of the data model.

I apologize for not being more explicit about the DB, but in this environment that we face we have an object-oriented DB that stores blobs in a file system-like representation. There is no mapping to SQL and no ORM of any sort to speak of. I do understand the argument though. For example, Django's models require subclassing for ORM to work. In thise case, making model classes makes perfect sense because the DB is effectively a static-typed data store and not 'dynamic'. But this is not the scenario of the question, because it's not a pure dynamically typed environment.

Regarding validators: yes. One will need to create validators that check fields being present, and them being of the right type. In static-typed languages the model implicitly does this (when you're coding C++/Java you can't stick user 'std::string' to where a User class should be). But in Python, a model class does not enforce anything. If I am building validators that check presence of attributes anyway, does this not make classes, dicts, generators etc functionally interchangable? And if so, should the solution not be one with least code? Validators in general seem to me to be an argument in favour of not building data model classes rather than the contrary. Am I wrong in this?


问:
Use of `is` and `as` in multiple conditions
Quite recently, I thought about the use of as, is and direct cast in C#.

Logically, is it a better idea to use :

```<code> var castedValue = value as type;
 if (null != castedValue)
 {
     // Use castedValue.
 }
</code>```

than :

```<code>if (value is type)
{
    var castedValue = (type)value;
    // Use castedValue.
}
</code>```

But I still have issues when dealing with this kind of pattern:

```<code>if (value is Implementation1)
{
    var castedValue = (Implementation1)value;
    // Use castedValue in a first way.
}
else if (value is Implementation2)
{
    var castedValue = (Implementation2)value;
    // Use castedValue in a second way.
}
else if (value is Implementation3)
{
    var castedValue = (Implementation3)value;
    // Use castedValue in a thrid way.
}
// And so on...
</code>```

How can I improve this code to prevent casting two times when OK, and is it really necessary to cast twice?

I don't want to make the code unreadable, but the idea is not to test a cast if a previous one succeeded.

I had several ideas to fix this, but none of them seems to really satisfy the conditions...

Edit:

Here is a case I've got... There is this object that is created by a lower part of teh code I do not have control on. This object can be of several inherited types. In my layer, I do want to create a specific object depending on this type. I do have this constructor class:

```<code>public static IHighLevelObject MakeHighLevelObject(LowLevelObject lowLevelObject)
{
    IHighLevelObject highLevelObject;

    if (lowLevelObject is LowLevelObject1)
    {
        highLevelObject = new HighLevelObject1((LowLevelObject1)lowLevelObject);
    }
    else if (lowLevelObject is LowLevelObject2)
    {
        highLevelObject = new HighLevelObject2((LowLevelObject2)lowLevelObject);
    }
    else if (lowLevelObject is LowLevelObject3)
    {
        highLevelObject = new HighLevelObject3((LowLevelObject3)lowLevelObject);
    }
    // And so on...

    return highLevelObject;
}
</code>```

How do I solve this case ?

答:
Assuming polymorphism is nowhere on the radar, you can use multiple returns and use as.

```<code>public static IHighLevelObject MakeHighLevelObject(LowLevelObject lowLevelObject)
{
    LowLevelObject1 object1 = lowLevelObject as LowLevelObject1;
    if (object1 != null)
    {
        return new HighLevelObject1(object1);
    }
    LowLevelObject2 object2 = lowLevelObject as LowLevelObject2;
    if (object2 != null)
    {
        return new HighLevelObject2(object2);
    }
    // And so on...
}
</code>```

Your LowLevelObject class could just have a virtual ToHighLevelObject method that each subclass overwrites and avoid this nastiness to begin with.

OwnerDisplayName: clemchen

Body:
Assuming polymorphism is nowhere on the radar, you can use multiple returns and use as.

public static IHighLevelObject MakeHighLevelObject(LowLevelObject lowLevelObject)
{
    LowLevelObject1 object1 = lowLevelObject as LowLevelObject1;
    if (object1 != null)
    {
        return new HighLevelObject1(object1);
    }
    LowLevelObject2 object2 = lowLevelObject as LowLevelObject2;
    if (object2 != null)
    {
        return new HighLevelObject2(object2);
    }
    // And so on...
}

Your LowLevelObject class could just have a virtual ToHighLevelObject method that each subclass overwrites and avoid this nastiness to begin with.


问:
Is it a good practice to have a remote branch for each developer?
Is it considered a good practice to have a remote branch for each individual developer in the project?

We're using Git with the following branches:

master

release

develop

If each developer had their own branch, they could push code into their branches and others could merge these changes into their own branches.

答:
If you're working with Git, you should try out Pull Requests.

In summary, you first merge the master branch into your current working branch. Any merge conflicts will be in your local branch. This is nice because your master branch is never broken. If you really screw up, you have you local commit that you can revert to.

Once you finish the merge, you ask someone else on the team to review and merge your branch into the master branch. Never merge your own! So long as no one sneaked in and did another Pull Request, you're guaranteed to merge successfully. Since everyone is aware of the Pull Request, you shouldn't have multiple people merging into master at the same time anyway.

Once you get used to this process, you should try to merge as often as possible - sort of a poor man's continuous integration. The less time between conflicts the better. You'll identify when two people are duplicating effort and they can team up. Some places will merge every time they complete a requirement, which could be every couple hours. I recommend merging at least once a week; otherwise you need to break your tasks out better.

I typically create one branch per task. Git is nice because it distinguishes between local commits and pushes. This provides some of the benefit of each person having their own branch without all of the complexity.

OwnerDisplayName: balanv


问:
How do programs like subversion detect when a file has been edited as opposed to created/deleted?
This is my first question here so I hope it is not off topic. Although I am using the Linux inotify library to listen for changes to files, and I compare use of that against the Subversion program, I am specifically looking for the algorithm used.

To a human it is very easy to tell if a file has been created or modified. Clicking the New button constitutes the former, and clicking the Save button constitutes the latter. To Linux, both those actions have serious overlap. In text editors, for example, generally a swap file is created and then copied/moved. This makes it difficult to distinguish via inotify between a minor edit to a file and a deliberate overwrite of a file. What I am trying to understand is how a program such as Subversion recognizes the difference between a user having modified a file with a text editor, and a user having actually deleted the file and opened a new file with the same name.

Edit:
It has been pointed out that subversion does not do what I want it to do, so it was a blunder on my part to use it as an example. Instead allow me to rephrase the question: "Is there any known program or programming approach to match high level actions such as creating new files and saving them to low level actions such as modifying, moving, copying, etc. such that I can log all the files in the system and changes to them"?

答:
You could read the file in yourself before setting up your inotify, then whenever you get an event, diff the file with your stored copy and see how much has changed. In a simple bash example with inotify-tools installed it would be something like this (with the file you're watching as first parameter):

```<code>#!/bin/bash
TEMPFILE=/tmp/${0}_${RANDOM}_$$.tmp
cp $1 $TEMPFILE
while true; do
   inotifywait $1
   changesize=`diff $1 $TEMPFILE | wc -l`
   if test $changesize -gt 10 ; then
       echo "Big change"
   else
        echo "Minor edit"
fi
</code>```

NOTE: This is a sample, treat it as pseudocode, I haven't test it for syntax errors and such so adapt before using.

Body:
You could read the file in yourself before setting up your inotify, then whenever you get an event, diff the file with your stored copy and see how much has changed. In a simple bash example with inotify-tools installed it would be something like this (with the file you're watching as first parameter):

#!/bin/bash
TEMPFILE=/tmp/${0}_${RANDOM}_$$.tmp
cp $1 $TEMPFILE
while true; do
   inotifywait $1
   changesize=`diff $1 $TEMPFILE | wc -l`
   if test $changesize -gt 10 ; then
       echo "Big change"
   else
        echo "Minor edit"
fi

NOTE: This is a sample, treat it as pseudocode, I haven't test it for syntax errors and such so adapt before using.


答:
There is rarely cause to use float instead of double in code targeting modern computers.  The extra precision reduces (but does not eliminate) the chance of rounding errors or other imprecision causing problems.

The main reasons I can think of to use float are:

You are storing large arrays of numbers and need to reduce your
program's memory consumption.

You are targeting a system that doesn't natively support double-precision floating point.  Until    recently, many graphics cards only supported single precision
floating points.  I'm sure there are plenty of low-power and
embedded processors that have limited floating point support too.

You are targeting hardware where single-precision is faster
than double-precision, and your application makes heavy use of
floating point arithmetic.  On modern Intel CPUs I believe all
floating point calculations are done in double precision, so you
don't gain anything here.

You are doing low-level optimization,
for example using special CPU instructions that operate on multiple
numbers at a time.

So, basically, double is the way to go unless you have hardware limitations or unless analysis has shown that storing double precision numbers is contributing significantly to memory usage.

Body:
Frequently, in my programming experience, I need to make a decision whether I should use float or double for my real numbers. Sometimes I go for float, sometimes I go for double, but really this feels more subjective. If I would be confronted to defend my decision, I would probably not give sound reasons.

When do you use float and when do you use double? Do you always use double, only when memory constraints are present you go for float? Or you always use float unless the precision requirement requires you to use double? Are there some substantial differences regarding the computational complexity of basic arithmetics between float and double? What are the pros and cons of using float or double? And have you even used long double?


问:
I code rarely. Is this a bad sign?
I am a computer science student and learning Java now a days.

I want to be a good developer/programmer.

I like reading books. I search on the internet for the related topics and study them. I refer to StackOverflow and other good programming websites daily but I code rarely. Is this a bad sign? If yes then what should I do to overcome this problem?

答:
Almost all of the other answers contain the basic premise that coding is the best thing to learn coding. If your goal is to pass the FizzBuzz test, this is true, and at some point you do have to start writing a lot of code to get good at writing code.

However, your question is not "should I ever code" but rather, "I am learning and not focusing on coding: is that bad." But then you say in other comments that you do write some code doing exercises in books.

In my opinion, there's way too much emphasis on writing-code-to-learn-programming. I think it's just silly. Coding is the last thing you should be worried about. Studying software development is much more important than actually writing thousands of lines of code. You'll always end up writing a lot of code. While you're studying, you should not be focusing on what will best prepare you to code, but rather whatever part of your studies you actually like. If you like studying techniques and methodologies, study that.

Jobs usually come out of your specific strengths. If you have none -- and you're just another person who wrote a lot of code, and can write good code -- then you won't have any competitive advantage. Play to your likes. You'll code enough in due time.

Title: I code rarely. Is this a bad sign?


问:
Study a project to be able to maintain it in future
I've joined as a fresher (trainee) a software company developing for Windows Store. I don't know much about C#. My company has started Windows Store development recently. They didn't do .Net development before, that's why my company got an Senior .Net employee to complete the project.

Whenever he completes the project he will leave the company. I will have to maintain the project after him. So I need to study the project flow and analyze the project to be able to maintain errors in future.

Can you suggest how to start to analyze the project and what to pay attention on?

答:
Sometimes, it takes a more skilled engineer to be able to maintain a less skilled engineer's code.

If the project is simple, it could be worth the struggle to write it yourself, because it will also be a struggle to understand somebody's code within such a short time and you are a fresher.

If the project is complex, your company should really wait to hire a long term and more experienced engineer.

To have a developer leave right after the first roll out is such a bad idea for all involved.  Most programs have some critical bugs at first, and if success(relatively speaking) for the first roll out is important, you are likely heading for failure. If first roll success is not important and can wait, then again why not wait for a more experience employee to come along or let you take your time to build something new?


答:
The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

I think you're right, that is the simplest way. You can relativise the URLs against http://my.rest.api/api to make them less ugly:

```<code>http://my.web.app/person/person%2F1234
</code>```

If the URL provided by the API doesn't happen to be relative to that base, it degrades to the ugly form:

```<code>http://my.web.app/person/http%3A%2F%2Fother.api.host%2Fapi%2Fperson%2F1234
</code>```

To take it a step further, inspect the response from the API server to determine what kind of view you want to present and stop encoding the path segment delimiter and colons:

```<code>http://my.web.app/person/1234 (best case)
http://my.web.app/http://other.api.host/api/person/1234 (ugly case)
</code>```

Title: A Web application as a REST API client: how to handle resource identifiers

Body:
The simplest way is probably just using the API URLs of resources as their string identifiers. But web page urls like http://my.web.app/person/http%3A%2F%2Fmy.rest.api%2Fapi%2Fperson%2F1234 are ugly.

I think you're right, that is the simplest way. You can relativise the URLs against http://my.rest.api/api to make them less ugly:

http://my.web.app/person/person%2F1234

If the URL provided by the API doesn't happen to be relative to that base, it degrades to the ugly form:

http://my.web.app/person/http%3A%2F%2Fother.api.host%2Fapi%2Fperson%2F1234

To take it a step further, inspect the response from the API server to determine what kind of view you want to present and stop encoding the path segment delimiter and colons:

http://my.web.app/person/1234 (best case)
http://my.web.app/http://other.api.host/api/person/1234 (ugly case)


问:
Is git-flow in the spirit of git?
The question is pretty self-explanatory.  I've had some experience with git-flow, and not much more true experience with plain git before that.  (I was using it more as a backup-provider.)  I'm confused as to what consensus is, given that I can safely assume that there are a large number of git users who miss 'the good old days' of formal, centralized version control, and just want a piece of it back (cf. rant article below)

Related articles:

The seminal

an anti-git-flow rant

"spirit of git" in the question title is, whatever it means to you. For me, I remember that it's a DVCS, not a CVS. git flow seems like it's imposing an organized branching model where one might not need to be there at all, where it would be essential in a centralized system such as SVN.

答:
There is no consensus, and that is the spirit of git.  Git very intentionally does not impose any sort of structure.  In that way, it is really more of a version control framework than a complete system.  People use git as a base to build whichever kind of structure works best for them.  For some teams that's a format-patch workflow, for some it's github style, for some it's git flow, and for others it's something completely unique.

In other words, use git flow if it works for your organization, otherwise don't feel like you're the only one not at the party or something.

Title: Is git-flow in the spirit of git?


问:
How to develop a Delete command through Behavior Driven Development?
I am trying to develop a Delete command through BDD that will simply delete an user from the database, given user_id as a parameter. What can be some possible behavioral tests that will drive me to write a proper implementation for the command? </p>

答:
Here are some possible tests:

(Delete works) When user_id is in the database, if delete(user_id) is called, user_id will no longer be in the database

(Delete affects only one record) When user_id is in the database, and there are other users as well, if delete(user_id) is called, the other users will still be in the database

(Delete no-op) When user_id is not in the database, if delete(user_id) is called, user_id should still not be in the database (or maybe an exception gets thrown; depends on your spec)


问:
Applications with duplicate data - keep separate or combine into one set?
We currently have 3 similar, but slightly different applications that use the same data.  We load the (same) data into each application that uses it.  The applications are similar and use the same technology (Ruby on Rails) but were developed by different programmers.

In consolidating this data, our management seem the benefit to using the same tools (gems, modules, etc) but does not seem aware of many other reasons why we should consolidate things centrally.

I've worked in several different organizations including one position in Data Warehousing so the centralization of data seems like a no-brainer to me.

The life-cycle of the data is the following year for the current paying customer, but then also longer term as we get the data from the various organizations that have it, over the years, and we'll want to compare one org and one year to others.

However I want to put together a list of all the reasons to centralize (or not) this set of data.  So far I have:

reduce duplication of effort.  When we implement a function we currently may have to do it in two places, increasing both the effort to implement the function in two places and also the cost of writing it twice.

Quality of data.  Creating two data set that have similar but different contents will lead to discrepencies between the two that will grow over time, reducing the value of the data.

I am looking for a list of other reasons, particularly those that relate to the overall cost.

答:
Ok, you said you are looking for pros and cons for centralizing the data, and gave yourself some pros. Here are some things when not to centralize may be the better option:

the data in place does change so seldom that the it simply does not pay to change your existing applications. Say, changing your applications needs 1 month development effort altogether for those three applications. But the data just changes once a year, is provided from outside, and the effort to provide it or enter it in all those 3 applications is one day. So your "return-of-invest" point is ~30 years in the future.

you can create an easy way to maintain the data just in one place and transform it automatically from that place to the place where the 3 applications access that data

the three applications must be kept strictly decoupled, so each of them can run without the other, without using data which belongs to one of the other (or belongs to a fourth one). This may have technical reasons (for example, fail safety) or legal reasons (for example, licensing issues).

the three applications need the data in different versions / in a different state of up-to-dateness

If none of those things applies, centralizing the data is probably the better option, especially when the data is changed often, can be changed directly through your 3 applications, and the 3 applications need the data in the same state.


问:
Is it safe to assume that one controller will only ever use one primary model?
So, I'm designing an MVC framework. In the name of keeping everything statically typed and non-magical, I've come to quite a problem with "automatically" passing models to a controller.

So, traditionally, I usually see no more than one model used at a time in a controller as far as automatic-population.

For instance, take this tutorial. There is a method like this in the controller:

```<code>[HttpPost]
public ActionResult Create(Movie newMovie)
{

    if (ModelState.IsValid)
    {
        db.AddToMovies(newMovie);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    else
    {
        return View(newMovie);
    }
}
</code>```

My concern is passing a Movie model to the Create method which is populated by FORM values "magically". In my API, this should be easily possible and would look something like this at routing:

```<code>var movie=router.Controller((context) => new MovieController(context))
                 .WithModel(() => new Movie());
movie.Handles("/movie/create").With((controller, model) => controller.Create(model));
</code>```

My concern with this is that it is much harder to have multiple models because of limitations with C#'s type system. Of course, the controller can always manually create the models from FORM values and such, but it's not nearly as pretty.

So, my question: Is it common to have something like Foo(Movie model) and Bar(SomeClass model) in the same controller class? Is it a good idea for me to attempt to support such a scenario, or is it just a symptom of putting too much unrelated logic in a single controller?

Note: if you're concerned about how this fluent API is even possible, the answer is generic delegates.. lots and lots of generic delegates :) (but so far very little reflection)

答:
In short No. I dont think you can ever assume that a controller will only ever use one primary model.

Most MVC applications will end up with a lot of different models that are used all over the place.

Using your Movie example if you only needed to use a couple of the items out of your Movie model then you would probably create a smaller view model that was mapped from the main view model as it will be quicker and use less resources.

If you are using Entity Framework then this can easily be achieved by overriding the AutoMapper setup.

Hope this helps a bit.


问:
Was classical BASIC ever used for commercial software development, and if so, how were limitations overcome?
Many of us, including me, started their programming life with programs written on home computers, something like

```<code>10 PRINT "ENTER RADIUS"
20 INPUT R
30 PRINT "CIRCUMFERENCE="; 2 * R * PI
40 PRINT "AGAIN?"
50 INPUT A$
60 IF A$="Y" THEN GOTO 10
70 END
</code>```

Of course, the line-number based BASIC was prone for creating spagetti code, also because most BASIC dialects missed structural statements like WHILE, doing everything but the FOR-loop with IF, GOTO and GOSUB. I'm talking about BASIC dialects before 1991, when QBASIC and Visual Basic appeared.

While BASIC dialects may have promoted bad style amongst aspiring programmers, were there larger commercial projects created in such a BASIC dialect? If so, how did they manage to live with and workaround the obvious shortcomings?

By "serious", I mean:

Not a game (I know some commercial games were written in BASIC, for example, Pimania)

Not freeware

Not trivial, that is, reasonably large (say: at least 1500 LOC)

Sold to several customers (not an in-house development)

"Mission critical" is a plus

答:
The only fear that I've had, as a QuickBasic programmer, 20 years ago, was "Out of memory" message. But this only made me a better programmer! I've learned how to write compact, and serious code.

I used to use QuickBasic for industrial programming. In the real world (factories) you cannot tell your boss "it's going to take half year to be written in C"; you can only say: "yes boss, it'll be ready next week". Yes, BASIC was the practical-and-quick solution in the real world. Not C or Pascal.

One of the programs I've written in QuickBasic 4.5, a unique database, was sold to few companies, and actually replaced the commercial database that they already had (which was probably written in C or Pascal). This database is in use until today.

One subject that I want to mention:

we all think that new programming methods are so much useful. But in the real life (industry), most machines, these days, are operated by modern PLC.
The programs are usually written in ladder programming, which is million times more primitive then GW-BASIC.
As a programmer for PLCs I can say clearly: I would love to replace this primitive ladder programming with high level language as GW-BASIC or even QuickBasic. (MEGA-BASIC is a dialect that was used for this purpose in the past).

After all, what most machines are doing? interpreting inputs and setting outputs. You don't need C/Assembly for that, and you don't need Java. You surly need QuickBASIC to create a maintainable code.


答:
This doesn't directly answer the question in the title, but it might give you some food for thought.

The snippet you have there looks like its from MVC3. In MVC3 there's an important distinction between domain/database/application models and view models. While the controller can use many domain models to process requests (build views, send stuff to the db and whatnot), it can only bind one view model to a view, and that view can only send back one view model on post-back. So sending multiple domain models to the action would actually involve an intermediary view model which would bind to the view and have references to the domain models.

In my opinion, the thing that most of the simpler tutorials do wrong is that they use the domain model as a view model, which is fine on it's own, but I believe that there's a conceptual distinction here that needs to be noted.

When working with complex forms/views in MVC3, you'll more often that not, need separate view models which will be composed of multiple domain models, and/or flatten some of the domain object graph to make for easier representations in the view and handling of post values.
Even then, some more complex forms make you fetch individual post values, either from the request itself or by setting another action parameter with the expected form field name.

Title: Is it safe to assume that one controller will only ever use one primary model?

Body:
So, I'm designing an MVC framework. In the name of keeping everything statically typed and non-magical, I've come to quite a problem with "automatically" passing models to a controller.

So, traditionally, I usually see no more than one model used at a time in a controller as far as automatic-population.

For instance, take this tutorial. There is a method like this in the controller:

```<code>[HttpPost]
public ActionResult Create(Movie newMovie)
{

    if (ModelState.IsValid)
    {
        db.AddToMovies(newMovie);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    else
    {
        return View(newMovie);
    }
}
</code>```

My concern is passing a Movie model to the Create method which is populated by FORM values "magically". In my API, this should be easily possible and would look something like this at routing:

```<code>var movie=router.Controller((context) => new MovieController(context))
                 .WithModel(() => new Movie());
movie.Handles("/movie/create").With((controller, model) => controller.Create(model));
</code>```

My concern with this is that it is much harder to have multiple models because of limitations with C#'s type system. Of course, the controller can always manually create the models from FORM values and such, but it's not nearly as pretty.

So, my question: Is it common to have something like Foo(Movie model) and Bar(SomeClass model) in the same controller class? Is it a good idea for me to attempt to support such a scenario, or is it just a symptom of putting too much unrelated logic in a single controller?

Note: if you're concerned about how this fluent API is even possible, the answer is generic delegates.. lots and lots of generic delegates :) (but so far very little reflection)


问:
Is there any technology similar to LINQPad for compiling C# that runs in a browser?
Think JSFiddle.  LINQPad is pretty sweet for fast C# with similar options.  Is there anything like LINQPad that runs in a browser?</p>

答:
Run Code is a very lightweight alternative that should work in any browser.

It does not require an account like compilr and the interface is even more slimmed down than ideone.


问:
Do you see an use for "Spreadsheet programming"?
A while ago I stumbled upon the concept of using spreadsheets (I mean cells and formulas not Macro code) as a way to specify programming logic.
The idea is:

create a spreadsheet with a cleanly defined flow of calculations (which sometimes are better suited to the "dataflow" paradigm of spreadsheets instead of procedural or object oriented programming styles)

define input cells

define output cells

compile the whole thing into a stand-alone executable class (or function, procedure, ...)

use it in normal code within a broader software project

use the spreadsheet as source code to be maintained over time

The idea is to use this technique for problems the really fit into the model and that this would lead to naturally well-documented and easy maintainable code.
I am interested in knowing whether you have experienced using the technique and what for.
An example application that came to my mind are insurance tariff calculators, that are typically drafted, created and validated by actuaries on Excel sheets and only later coded (it's a painful process) in some hard-to-maintain programming logic.

答:
Spreadsheet "programming" is a type of dataflow programming.

We have a linguistic problem with it, we should not call it "programming", because it's far less than we call programming, but it's definitelly more than entering data to a program.

Dataflow programming is an architecture and discipline, where the application is a network of independent modules, they sends messages (data) each other. This model is not applicable to every problem, only for ones, where there is a source data or stream (or there're more), which goes trhu the processing network, and produces output data/streams. See list below.

Dataflow programming has several types, let's see some:

Spreadsheet: input numbers are processed by formulas, then results numbers and graphs. Special characteristics: exectuion time is "one-shot", when input value (component) changes, the appropiate part of the processing graph re-runs and produces output.

Unix pipe: the shell launches up several programs, and links stdout->stdin. Special characteristics: only pipe-style linking is allowed, the graph is a single queue.

Synchronized execution: there is a clock, which triggers the processing of a frame or sample in a specified frequency. Every component runs once a clock cycle. Video and audio processing systems the examples, they works at a specified frame/sample rate.

Asynchronous execution: the graph is in idle, until an external event occurs. Then it processes the event, generates some output (or not), and goes to idle state.

Back to your question: I think yes, it's good idea to publish a dataflow application as a standalone app. I have already made it. Twice.

Me and a friend of mine has created a prototype DF system for home automation. We have no graph editor, so the app is not editable by the user, some parameters are stored in a config file, but nothing else. We have a DF script language, which is "compiled" to C++ code (a list of component creation and message definitions), which gets compiled to a native executable. The modules are C++ classes (other classes, just to get some info about our system: Message, Dispathcer, Component (abstract), Port (abstract), ConsumerPort, ProducerPort).

Also, we were amazed of the advantages of a DF system provide: we've made serial sniffer app within 2 minute, or we've made a test program on-site, which blinks lamps one-by-one (there were no documentation on hardware IDs). We've created MIDI and joypad components just for fun, I've also made a light organ with it (see http://homeaut.com/under_construction/ ).

I can see only one difficulty in case of spreadsheets: as every number and formula (potentially: every cell) is a component, your graph is not final. When you add a line to your simple sum() app, it means that the dataflow graph is changed. So, you have to "reprogramming" the graph in run-time, or we should call it "metaprogramming". In Excel, a macro would do the job, but then we loose the purity of dataflow.

I have a not-too-bad-but-not-perfect solution. I've made a spreadsheet, an AJAX app with PHP backend. The vertical axis is time (days), the lines are components. There are components, like input (the line can be edited by user), vertical average, horizontal average/sum, and some domain-specific statistical calculations. There is only one problem with it: this is "one-dimensional". As long as I want just sum and avg and whatsoever, I can add new lines, and create the component, which calculates the stuff. But there is a strong constraint: the columns are always days (I've made week and month "views", which displays daily data as sum/avg, but it's still one-dimensional). I can't show it, it's collaborative and requires PHP backend task to run 7/24, it's not supported by my host provider.

So, my model (which can be best described as: "days horizontally") is not able to handle other kind of problems.

I have an idea, how to solve this problem: tabs.

When you get stuck in Excel, and have to create another table, you can use a distinct area on the same tab, or open another tab. Also, referencing between tabs is uncomfortable, I prefer first method. I think, tabs should be displayed on the same screen, like non-overlapping windows.

Every table should have its growing axis: vertical, horizontal or fixed. Vertical growing tables has line components (as my day-based spreadsheet), where all the columns have the "same" formula, horizontal components have column components, fixed-size tables are just like any spreadsheet.

So, when the user adds a new line/column, the new line/column will have the same formula.

Also, in spreadsheets, I hate the thing, that I need to copy very same formulas 1000 times, if I have 1000 lines. It's a source of bugs (keeping old version of formula in some lines), waste of memory (storing same formula 1000x).

Maybe I'm wrong, and there're concept bugs in this model, but I hope it was a good thought-provoking.


问:
Why would each widget need a reference to its parent in a simple widget system?
I'm working on a simple widget system (single window, fixed size). Each widget gets its parent (i.e. the widget containing it) passed into its constructor - except for the root widget, which I called Screen.

I have some doubts if that approach makes sense. I did it because most of the widget systems I used before do it (Qt, GTK, ...), but I realised that these are quite a bit more complex than mine:

I have no window resizing

I don't plan to size containers based on their children's sizes

I don't think I need it for memory management (I'm using C++), I can use shared pointers instead (basically how it would work in Java)

Is there any reason why a widget would need a reference to its parent?

It's a major refactoring to change this. So before I go ahead and implement containers and layouts, I want to have a good idea of whether or not I'm going to need that parent.

Edit: Please note that the parent does know all its children anyway, I'm just wondering if the children need to know the parent as well.

答:
In most of these cases there is quite some communication going on between parent and children in case of events, signals or state change (or simply to destroy children when necessary). For example a grouping box may handle it's contained radio buttons to ensure only one of them is "on" at a given time.

You may or may not plan to have functionality of this kind. Personally I would doubt if a widget system without it is worth the time since it wouldn't offer much. But then I would simply use one of the existing solution anyway.


问:
How much usage of "likely" and "unlikely" macros is too much?
The often known as likely and unlikely macros help the compiler know whether an if is usually going to be entered or skipped. Using it results in some (rather minor) performance improvements.

I started using them recently, and I'm not sure how often should such hints be used. I currently use it with error checking ifs, which are usually marked as unlikely. For example:

```<code>mem = malloc(size);
if (unlikely(mem == NULL))
  goto exit_no_mem;
</code>```

It seems ok, but error-checking ifs happen quite often and consequently the use of the said macros.

My question is, is it too much to have likely and unlikely macros on every error-checking if?

While we're at it, what other places are they often used?

In my current usage it's in a library that makes an abstraction from the real-time subsystem, so programs would become portable between RTAI, QNX and others. That said, most of the functions are rather small and directly call one or two other functions. Many are even static inline functions.

So, first of all, it's not an application I could profile. It doesn't make sense to "identify bottle-necks" since it's a library, not a standalone application.

Second, it's kind of like "I know this is unlikely, I might as well tell it to the compiler". I don't actively try to optimize the if.

答:
Do you need performance that badly that you're willing to pollute your code with that? It's a minor optimization.

Does the code run in a tight loop?

Does your application have performance problems?

Have you profiled your application and determined that this particular loop costs a lot of CPU time?

Unless you can answer yes to all the above, don't bother with stuff like this.

Edit: in response to the edit. Even when you can't profile, you can usually estimate hotspots. A memory allocation function that is called by everyone is a good candidate, especially since it requires only a single use of the macro to work for the whole library.


问:
Why shouldn't a GET request change data on the server?
All over the internet, I see the following advice:

A GET should never change data on the server- use a POST request for that

What is the basis for this idea?

If I make a php service which inserts data in the database, and pass it parameters in the GET query string, why is that wrong? (I am using prepared statements, to take care of SQL Injection). Is a POST request in some way more secure?

Or is there some historic reason for this? If so how valid is this advice today?

答:
This is not advice.

A GET is defined in this way in the HTTP protocol. It is supposed to be idempotent and safe.

As for why - a GET can be cached and in a browser, refreshed. Over and over and over.

This means that if you make the same GET again, you will insert into your database again.

Consider what this may mean if the GET becomes a link and it gets crawled by a search engine. You will have your database full of duplicate data.

I also suggest reading URIs, Addressability, and the use of HTTP GET and POST.

There is also a problem with link prefetching in some browsers - they will make a call to pre-fetch links, even if not indicated so by the page author.

If, say, your log out is behind a "GET", linked from every page on your site, people can get logged out just due to this behaviour.


答:
As you pointed out, the child itself seldomly if at all needs to access the parent, as long as the parent does all the work and keeps track of its children. However, the classic getParent is most useful when you use the framework from outside.

Scenario

A simple operation that may cause problems is the following: given two concrete widgets that are somewhere in your overall widget tree and a use-case that requires you to swap these two, how does the swapping work?

Option 1: Tell the children

Tell your child widget to swap(withOtherChild). But swapping involves updating the parent's children datastructure in some way. As your child does not know its parent, how do you achieve this?

Option 2: Tell the parents

Tell the parent of a child to remove it and add the other one. Oh wait, same problem. You only have the children objects and there's no getParent on those.

Option 3: Grunt work

As a final option, you can traverse your whole widget tree in order to find a parent with hasChild(x) and one with hasChild(y) and then fall back to option 2.

Solution

You should keep the parent if you ever want to build large widget trees and perform operations that require moving a widget's position in the tree. If your widget trees are very small, or only have a very small depth, but fast hasChild accessors, then Option 3 may be acceptable for you and you could omit the parent reference.

References in Datastructures in general

What you are planning to do here is to build up a datastructure for a tree. Let's consider a simplification and for the sake of argument assume that every widget can only have one child. The result, of course, is a list and your question now becomes "should I have a single-linked or double-linked list?".

And just like lists, there is no definite answer, but only pros and cons. Obvious pros for the single-linked (i.e., no parent reference) are a) easier to implement and b) less memory. But the cons include a) some operations become slow as they have to traverse the structure and b) not having easy access to those operations may mean that the datastructure is cumbersome to use, and c) it uses more memory.

On the other hand, the double-linked variant, i.e. with parent reference, pretty much reverses these pros and cons.

In terms of a GUI library/framework though, the memory limits are usually not a problem that prohibits parent pointers. If you rule that out, and realize that it's a library/framework, and hence, it is preferrable for it to be hard to implement, but easy to use, then you essentially rule out the above pros of a single-linked approach.

I am not aware of the peculiarities of your project, so I want to refrain from telling you to keep the parent reference, as some of my above reasoning may well not apply in your case. In general, however, I consider parent references in a widget datastructure to be worthwhile for the above reasons.

Title: Why would each widget need a reference to its parent in a simple widget system?

Body:
I'm working on a simple widget system (single window, fixed size). Each widget gets its parent (i.e. the widget containing it) passed into its constructor - except for the root widget, which I called Screen.

I have some doubts if that approach makes sense. I did it because most of the widget systems I used before do it (Qt, GTK, ...), but I realised that these are quite a bit more complex than mine:

I have no window resizing

I don't plan to size containers based on their children's sizes

I don't think I need it for memory management (I'm using C++), I can use shared pointers instead (basically how it would work in Java)

Is there any reason why a widget would need a reference to its parent?

It's a major refactoring to change this. So before I go ahead and implement containers and layouts, I want to have a good idea of whether or not I'm going to need that parent.

Edit: Please note that the parent does know all its children anyway, I'm just wondering if the children need to know the parent as well.


问:
Pseudocode for Brodal queue
I'm trying to find more resources regarding Brodal heap. All I found is a haskell implementation of Brodal-Okasaki heap, but I think that they are skew heaps, is this correct? Furthermore, I'm illiterate in Haskell so that does not help much. Does anyone have (or know of) an Brodal queue implementation in pseudocode, C, C++, Python?

Also please correct if my assumptions above are wrong.

答:
The Haskell implementation is based on the functional Brodal-Okasaki heap and you are right, it is a variation of skew heaps. The paper is written very clearly, so it would be a good resource.

Regarding implementation, there's also an implementation in Scala as part of the scalaz library.

Title: Pseudocode for Brodal queue