问:
How to identify unstable floating point computations?
In numerics, it is very important to be able to identify unstable
schemes and to improve their stability.  How to identify unstable
floating point computations?

I am working on a very complex simulation where many numerical schemes work together and I am looking for a methodic to identify its weak parts.  I am working on a physical model involving differential equations.  A bird's eye view of the overall process is:

(Preliminary step) Gather physical observations P.

Determine initial parameters of the simulation. This uses an optimisation algorithm, where we walk in a parameter space and look for parameters C such that some error function E(F(C), P) is minimised, where F is some derived quantity of the parameters.

Plug C in the simulation engine. This is an Euler scheme of the EDP, so that at each time step, we compute the terms driving the dynamic (each of them is a complex function, potentially subject to instability) and feed the Euler scheme with these dynamic terms to compute the next state. This goes on for thousands time points.

At the end of the simulation, we compute some function Proof(S) of the final state S and compare to some quantities Require(P) deduced from the observed quantities. This is not a formal proof of the result, more a plausibility check.

Also, I see a tower of complex operations (computation of dynamic terms, within the Euler scheme, within the Proof). And would like to recognise “bad parts” and fix them.

I speculate that using a software implementation of floating point
numbers with reduced precision would magnify the unstability of
numerical schemes, thus easing the comparison between different
implementations.  Is this a common technique to investigate this
question?  Is it possible to use a virtual machine, as Bochs, to
achieve this without altering the program?

To deal appropriately with the stability question, it is sometimes
acceptable to target the typical input of the numerical procedure, so
that it can be tuned to do well on that input and maybe less well on
other valid, yet unlikely, input.  Given a sample of typical inputs,
it is possible to snoop some intermediate results and prepare a
statistical profile for them.  Again, is this a common technique to
study stability issues?  Is a virtual machine useful for this?

答:
How to identify unstable floating point computations?
  Is this a common technique to investigate this question?

I think unless you need to show some statistics on error, you don't really need to gather samples. What you need is Numerical Analysis, which also falls under the subjects of Numerical Methods, Numerical Linear Algebra, etc. And they're part of computer science, so you might get some answers too in cs.stackexchange.

Anyhow, in general programming, most problems are easy to spot given some basic understanding about how floating point works and basic numerical methods. But even more complex problem are "easier" to solve today with availability of 128-bit floats, even less reason to produce error samples. Here are some example problems to show my point:

using floating point for calculating monetary values.

using floating point for big numbers.

not doing divisions before other operations when it's possible to do so. (to make value closer to 0).

long calculation without special treatment for error propagation.

There's also example of a naive algorithm and error compensated algorithm here algorithm for calculating variance. In the example, looking at the naive version, you just kind of can smell that doing calculation in loops will carry some errors and is not being compensated.


问:
Use MAC address for license
One of my company product need to implement a license mechanism. I'm planing to generate a key  base on users PC MAC address. But I'm bit scared is this method confuse with some advance hardware. configurations such as.

Multiple network cards.

Virtualization.

Mac address change possibilities(?)

Working with VPNs.

Is it a good idea to generate license key with MAC address? Some ideas?

答:
I've use MAC-based licensing (as a user and a bit as a developer), and it was fine.

BUT

You must have a customer support person readily available, who can quickly handle all those cases where a user buys a new laptop, their IT department changes stuff, etc.  And said support person must be both technically qualified, and bureaucratically qualified, to promptly create and email out a new license.  If they have to consult much with a "real" programmer or the official sales rep you are doomed cause one of them will be on vacation.  And your customers will get pissed and look elsewhere.

Yes, you'll probably lose a tiny bit of money to cheaters.  Live with it.

ContentLicense: CC BY-SA 3.0

Title: Use MAC address for license


问:
How do I make multiple calls to a web service without taxing that service heavily? Scaling question
is there a good pattern for how to send multiple calls to a web service but without taxing it and ensuring the data is sent back? I don't know enough to correctly describe the problem to even start googling it properly - current google results compare streaming vs. non-streaming wcf answers?

Scenario: I am working on an app (I'm a jr. dev.) that needs to gather information from several sources about a 'customer' and the domains they own

Technical:
for one of the sources, I need to send a string array of domains to a web service and this web service returns an entry for each domain name, but this list of domain names will be thousands long - I would like to attempt to divide this list into bite-size chunks (1k domain names each) and then... queue them up to send to that web service, but ensure the web service doesn't skip one

PseudoRequirements:
Consumer of web page does not care how long it takes, but would like a list of results up front that does not require pagination to navigate.

Current Theory:
Should I take my massive 30k list, break it into 1k chunks, stuff each 1k-sized chunk into a 'request' object, assemble those 'request chunks' into a 'request chunk list' and iterate over that list (sequentially / blocking, so I don't strangle the WS) and for each 'request chunk' get back a 'response chunk' assemble those into a list, and then pass that list back into the front end for viewing? is this a viable method? is there a better way to queue items? Does anyone know off-hand any useful articles for this sort of queuing? are there any 'gotchas' or additional items to consider before I attempt my first pass?

Additional Edits:
-I do not have full control to the receiving service, I can not view it's code and the developers that manage it are... less than responsive to email. I do not currently know the stress testing limits of the web service. I emailed the owners of that component but have yet to receive a response - I was going to work up my design while I waited on them.

答:
Its admirable that you take this into consideration but if the API owners aren't being helpful then your doing your best.

Personally i'd break it down into "normal" traffic chunks, if they are expecting people to throw 1000 at a time to them then do that. Normally this stuff would be listed in the api terms and conditions

With modern internet/networks and webservers you could probably get through those 30,000 records before anyone even had time to complain, last night I did some fairly intensive scraping of 120,000 records from a website in a few hours and simply added a 2 second delay between each request.

The key here is that if they're not getting calls saying people can't access the API then there isn't a problem, since they put it up for you to access and you're not abusing it!


问:
How is major software protected?
I am a new software developer and I wish to sell my software. I recently realized that from C++ code we can not stop the user seeing parts of the code that are related to scripts or system commands.

Would you make some comments on how software written in C++/JAVA (distributed via CD-ROMs or available via download) is protected from reverse engineering, scanners for when the code is in memory and direct copy of parts (as system commands).

What a small software company which just starts producing software should do to protect its product from the technological point of view (it should not be able to pay legal fees …)?

答:
I've been writing software for many years and 2 decades ago I used to think along the lines that you're describing and try and work out ways to protect my software.

To answer your question: Software protection is done through encryption and obfuscation just like data protection. The shortfalls, as you described, is that much code is very difficult to protect and usually relatively easy to reverse engineer.

One way to protect your code (from decompiling) is to never release a compiled version of it and always run it from a server and your consumers use a client such as a browser. That does not however protect you from reverse engineering.

The defense, in my opinion, is to not waste cycles (time/money) trying to protect your code but rather be continually innovating and adding more value to your product over time. If a competitor got hold of your code and took (say) 1 month to decompile it and released a competing product then you should be a step ahead of them with your next feature or next product by that time.

Spending time and effort to block out your competition by keeping everything secret would be better spent by encouraging your team to be innovative and stay ahead of the competition.

Title: How is major software protected?


答:
In my opinion, before asking how, you should be asking whether it's needed and/or worth it.

I think in many cases, it isn't.

People are (understandably) quite paranoid about other people stealing their codez. But is this fear rational? I think it usually isn't.

Is your app really so awesome that somebody would go to the trouble of reverse-engineering it?  (Sorry, but probably not - as you said, you're a new developer. And even if you weren't... there are many very talented devs out there)

Would reverse engineering (to the point of getting usable and complete source code) be so much easier than just writing a competing product? (Very probably not)

How maintainable do you think such a program would be? (Probably not very)

There are many, many things to worry about before having to worry about protection from rip-off artists. Not the least is getting a viable and attractive product into the market in the first place.

For completeness' sake I should add that there are obviously good reasons for trying to protect certain kinds of software, or certain parts of many common pieces of software, but generally, I think trying to protect your code is mostly a waste of time better spent on making the product better.

Title: How is major software protected?

Body:
I am a new software developer and I wish to sell my software. I recently realized that from C++ code we can not stop the user seeing parts of the code that are related to scripts or system commands.

Would you make some comments on how software written in C++/JAVA (distributed via CD-ROMs or available via download) is protected from reverse engineering, scanners for when the code is in memory and direct copy of parts (as system commands).

What a small software company which just starts producing software should do to protect its product from the technological point of view (it should not be able to pay legal fees …)?


问:
Is functional programming actually used to create applications?

Possible Duplicate:

  What are some well known applications written in F#?

I see a lot of people talking about how cool functional programming is, how awesome Lisp and Haskell and F# are, etc, but what I don't see is them actually being used.  Just about every program on my computer is written in either something in the C family, Delphi, or Python.  I see tutorials talking about how easy it is to use functional languages to do complicated math problems, but no one talking about using them to do things most people actually care about using computers for, like business applications and games.

Does anyone have any examples of actual programs that people have heard of and are using, written in a functional language?  The only one I can think of off the top of my head is Abuse, from almost 15 years ago.  (Things like Emacs, where the core program is written in C with a functional language scripting layer on top, don't count.)

答:
Functional Programming is not just limited to a particular language, its also a style of coding in my mind.

When I say style of course I'm ignoring the "pure" functional requirement of not including any states..

In that sense, I suspect its used a lot in daily situations.

Just to give you an example, in a recent project I used "functional" style of programming to transform URL's into dynamic Site-maps (tree structure) on the fly. This was done by breaking down the problem into smaller functions which was then composed together to create the final solution : Data In -> Function (F1+F2+Fn) -> Tree

ContentLicense: CC BY-SA 2.5


问:
How can I write complex validation and business logic that can be reused in both direct data model changes and pending dialog changes?
I was hoping for some advice:

I need to design a software solution for a medium-sized java / Swing application.

The application will have about 200 use cases requiring complex data validation and business logic.

Typically, this is my usual design:

Create a simple POJO for each use case, with a custom constructor and custom validation and business logic within it's execute method. These Operations implment simple and complex data validation such as required fields, unique names and more complex constraints.

Create a single controller that has a method for every use case. Each method takes custom parameters, constructs and executes it's related operation.

For the sake of simplicity, I won't mention details about Data Model notification or Operation queuing mechanism.

This solution has worked will in the past because it encourages all developers to reuse existing controller methods and validation, however:

The new application will use dialogs extensively for data entry;

These dialogs are expected to implement the same complex data validation and business logic that the controller implements, however the dialogs are not expected to update the data model until the OK button is clicked.

I hate the idea of writing multiple versions of the same complex validation and business logic, due to the maintenance nightmare it invites.

How can I perform complex business logic and validation for both standard data model changes and "pending" dialog changes, given that the dialog doesn't commit it's changes until the OK button is clicked?

The data model may be quite large, so creating an in-memory clone of it and the controller doesn't seem viable.

Does anyone have any suggestions? If so, I'll be forever in your debt.

答:
I design my models so they don't easily get themselves into an invalid state to begin with.  Then when my Interface (UI, or service), attempts to put it into such a state, an error is thrown which I can then send back to the offending source.

Most of the time this means that my models have a method called isValid(), that checks itself for things that can't be checked via setter.  This method also handles more complex business logic that encompasses more of the model.

Validations that get repeated in multiple places I abstract out into utility functions xor validation classes so I don't have to copy-and-paste my validations.  Sometimes I end up having to write a more complex service type validation, but that's fairly rare.

This makes my models fairly thick, however, I know that wherever I use that model, the validation is brought along with it.  Keeping your validation separate, means always having to remember to do the validation, which can lead to programmer errors.  This also tends to makes my interface (UI, SOAP, JSON etc) thinner, since it focuses on converting from the input to the model, and responding to the model changes, including validation errors.

In UI Interfaces, I'll do some basic checking of types, ranges and the like, before sending data to the model residing on a server.  In some cases, where performance dictates I'll move some validation to the UI, but only as performance dictates.

This doesn't mean my models are monolithic either.  I break my validations down into composable separate pieces that I call inside my model.  It just means that the validations themselves are hidden from the model user.


问:
Unit test DAO code using SQL Lite when the application database is Oracle
We have an application with Oracle backend. The DAO layer is written in C# and uses nHibernet to perform the data operations.

To unit test our DAO code, we use SQL Lite which creates the database based on our existing mapping in the project.

Some of our nHibernate queries that go to oracle use (+) for outer joins. Now SQL Lite doesn't understand (+).

There can be some more syntax from Oracle that SQL Lite doesn't understand. How do we fix problems like these?

What are the other database systems that can be used for unit testing the application code.

答: I wouldn't consider needing a database as part of the test to be unit testing.  That's more like integration testing.  A unit test shouldn't need something external to the method being tested, especially a database.  Your unit test should test that the correct sql is being generated, not that the database is doing the right thing.</p>


问:
How do I recreate this Access Control/Group/ whatever methodology in OO/MVC
I am looking at trying to rewrite an application that is mostly procedural to an MVC/OO approach in order to teach myself a deeper understanding of both.

BUT, I am having some conceptual issues with the current group/access control that is used.

We have Groups (Businesses) that have role based users (Manager, salespersons, customers).
They can have customers either assigned to a salesperson, or not. The manager sees everything, the salesperson only those customers assigned to him.

```<code>Business
  |
  ---Manager
       |
       ---Salespersons
            |
            ---Customers
  |
  ---Customers
</code>```

The table structure for this currently is something like this:

```<code>users (userID [demographic info])
business (businessID, userID, et al [demographic info])
salespeople (salesID, businessID, userID [just foreign keys])
customers (customerID, businessID, userID, et al [demographic info])
salesAssignments (salesID, customerID [just foreign keys])
</code>```

The Manager can affect everyone within that businesses group (everyone has a businessID that links them to that business and no other). The customers can login and make minor changes to their profiles or interact via messaging to their salesperson or the businesses manager.

Added Spice to the mix: (comment on any of these if they apply to your insights to the above question) Is there a better way to have similar user access and control?
I want to rebuild the site with an API that can be used by both the web app and mobile apps.

EDIT
My main conceptual hangup at the moment relates to how to recreate this structure in a user object for the OO part of the application. Now everything is accessible via session variables, or queried from the DB via procedural functions.
Again my understanding of OO is limited, and this is an attempt to figure it out.

答:
Conceptually, the way you achieve this in your repository is to limit your database accesses by adding a WHERE clause to your SQL, to the effect of:</p>

```<code>WHERE <User is manager> OR UserID = <currently logged in employee id>
</code>```

Body:
Conceptually, the way you achieve this in your repository is to limit your database accesses by adding a WHERE clause to your SQL, to the effect of:

WHERE <User is manager> OR UserID = <currently logged in employee id>


答:
I don't know of a lot of games or end-user applications written in functional languages, though I'm sure there are some. Games and end-user applications, though an important and visible part of the software market, are only a part of it. Remember, there is huge amounts of software out there that you never see because it is orchestrating processes that don't have end-user application or game interfaces.

For example, F# is popular at Credit Suisse for quantitative analysis:

http://blogs.msdn.com/b/dsyme/archive/2010/07/15/f-jobs-at-credit-suisse-london.aspx

Unless you work there, you're probably not going to ever see the user interface to that software.

Or, Erlang is popular for writing the software that controls mobile phone switches:

http://en.wikipedia.org/wiki/Erlang_(programming_language)

You probably don't think of making a phone call as an application, but someone had to write the software that controls the switch.

Title: Is functional programming actually used to create applications?

Body:
Possible Duplicate:

  What are some well known applications written in F#?

I see a lot of people talking about how cool functional programming is, how awesome Lisp and Haskell and F# are, etc, but what I don't see is them actually being used.  Just about every program on my computer is written in either something in the C family, Delphi, or Python.  I see tutorials talking about how easy it is to use functional languages to do complicated math problems, but no one talking about using them to do things most people actually care about using computers for, like business applications and games.

Does anyone have any examples of actual programs that people have heard of and are using, written in a functional language?  The only one I can think of off the top of my head is Abuse, from almost 15 years ago.  (Things like Emacs, where the core program is written in C with a functional language scripting layer on top, don't count.)


问:
Creative Commons 3 vs Common Public Attribution License Version 1.0 for my PHP Script
I am currently working on an open source PHP script and trying to adopt an attribution license. The ones that I found are

CC 3.0: http://creativecommons.org/licenses/by/3.0/

and

CPAL 1.0: http://opensource.org/licenses/CPAL-1.0

They seems very similar to me. What's the difference, pros and cons?

What I want is:

Allow use for free and commercial work, modify it to suit their needs if required, but can not redistribute it as a new product or with a different name (no sublicensing?).
EDIT: I am bit confused about CPAL license on this, what does it allow and disallow?

Copyright info in the source codes can not be removed

Copyright attribution on the frontend and backend (admin panel) can not be removed. But I will adopt dual licensing model by adding commercial license to allow removing them with a fee (only the frontend and backend, not the copyright info in the source codes).

Any plugins or themes created for this script doesn't need to adopt my license as long as the main source codes are not modified, it can be any license(commercial, MIT, GPL, CC, CPAL) adopted by the authors.
I think that's basically it.

I am also open to suggestions for other kinds of license types and why

答:
From the Creative Commons FAQ:

Can I apply a Creative Commons license to software?

We recommend against using Creative Commons licenses for software. Instead, we strongly encourage you to use one of the very good software licenses which are already available. We recommend considering licenses made available by the Free Software Foundation or listed as “open source” by the Open Source Initiative. Unlike our licenses, which do not make mention of source or object code, these existing licenses were designed specifically for use with software. Furthermore, most of our licenses are currently not compatible with the GPL, the most frequently used free software license. (We are looking into compatibility of BY-SA with GPL in the future; for more detail, see the compatibility page.)

CC licenses may be used for software documentation, as well as separate artistic elements such as game art or music.

Note that the CC0 Public Domain Dedication is GPL-compatible and acceptable for software. For details, see the relevant CC0 FAQ entry.


问:
What is the difference between apache and tomcat in the xampp control panel?
I installed xampp in my machine. I wonder what is the difference between apache and tomcat in the xampp control panel.

p/s: I started apache only and test with "localhost/index.html", it works.
I started tomcat only, but it doesn't work.

答:
Apache is the Apache Web Server also known as httpd. See http://httpd.apache.org

Tomcat is Apache Tomcat. See http://tomcat.apache.org

httpd is a web server whereas Tomcat is a Servlet Container. While at the simplest level both can be viewed as web servers that serve static files they have very different focuses. httpd is typically used to host static content and dynamic content written in perl, php amongst others. Tomcat is primarily intended to be used to serve web applications developed in Java to the Java Servlet specification.


答:
This question depends a lot on who your clients are.

If you are selling business to business, it should be fairly easy to prevent competitors from even getting compiled code.  The easiest way to deal with this kind of situation is with strong contractual wording.  With IBM Cognos (major business intelligence product like SAP), a license key isn't even used.  They do somethings like code obfuscation but they, mostly protect their product with layers.

This is obviously harder with business to person type situations.  You probably can't control who has access to the software.  The other posters have some good solutions with regards to this.

Title: How is major software protected?


问:
How does customized executable generation work?
One of the things that Valve's Steam distribution platform is known for is its Custom Executable Generation system, which creates a unique copy of a program for each person that buys it.

I'm sure that Valve isn't the only company or person to have implemented or thought of implementing such a system, however. If I wanted to try and roll my own system that generated executable files on the server side that are unique to the downloader or their account, what would I need to know how to do? What are the basics of such a system in the first place?

答:
For purposes of discussion, I am assuming that your program is written in C, compiled on unix, and that there is a small amount of customization done (only changing compile time constants). We start with a template, lets call it customer.c.templ

```<code>#include "customer.h"
const char custname="$$custname$$";
const int custnum=$$custnum$$;
.
.
.
</code>```

and we write a simple script to do substitutions, say markup.pl

```<code>#!/usr/bin/perl -p
s/\$\$([^$])\$\$/$ENV[$1]/e;
</code>```

and have our sales guys give us some customer data

```<code>custname="Billy Bob's Clam Shack"
custnum=404
.
.
.
</code>```

and a simple little script:

```<code>#!/bin/sh
. customer_data
markup.pl <customer.c.tmpl >customer.c
make customer.o
make a.out
mv a.out $custnum.exe
</code>```

and there you go. custom binary.

Body:
For purposes of discussion, I am assuming that your program is written in C, compiled on unix, and that there is a small amount of customization done (only changing compile time constants). We start with a template, lets call it customer.c.templ

#include "customer.h"
const char custname="$$custname$$";
const int custnum=$$custnum$$;
.
.
.

and we write a simple script to do substitutions, say markup.pl

#!/usr/bin/perl -p
s/\$\$([^$])\$\$/$ENV[$1]/e;

and have our sales guys give us some customer data

custname="Billy Bob's Clam Shack"
custnum=404
.
.
.

and a simple little script:

#!/bin/sh
. customer_data
markup.pl <customer.c.tmpl >customer.c
make customer.o
make a.out
mv a.out $custnum.exe

and there you go. custom binary.


答:
Unless you software is pretty devious internally I am sure any competent programer could replicate the behavior of your programs in about the same time as you took to write it!

So spending a lot of effort on keeping your code secret is usually just wasting time and effort.

Some algorithms do need to be kept secret for instance google's page rank algorithm is only useful if scammers don't know how to promote a rubbish page to the top of the search, or, an automated trading system which could be manipulated by a competitor. But this situation is pretty rare.

Software giants like SAP and ORACLE sell many packages based on the fact that everybody knows exactly what they do; "GAAP compilance" or "Embodies Best Business Practice" in marketing speak.

But do not lose heart, testing is at least 50% of the effort of programming and probably adds 80% of the value; you cannot reverse engineer a decent set of tests.

Title: How is major software protected?


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: There must be an open source program for my business. Can't you just download it and tweak to my requirements.</p>


问:
C++ code navigation on OS X
Other than using Emacs / Vim with ctags or cscope or both, are there alternatives to C++ code navigation of an existing code base? I used to use Source Insight on Windows and it worked for me fairly well. The main functionality I am looking for is quickly find definition of macros, variables and functions and places a function is referenced.</p>

答:
In XCode, which comes with the OS, you have the "Jump to Definition" function, which I usually assign to Cmd-F1 (VC has some similar shortcut if I remember correctly). You will have to create an XCode project for your code base though. I don't know if there are any automatic converters, say, from Makefile to XCode project.

Most of the time Jump to Definition works fine, except when the name of your .cpp module differs from the .h header name; also doesn't work for overloaded operators. There are some intermittent failures that I can't explain, but overall, on simple and straightforward C++ code it can do the job OK.

P.S. there is no such thing like find references in XCode, but you have a project-wide Find function with an option to look for "Symbols", which I think is almost exact equivalent of finding references.

Title: C++ code navigation on OS X


答:
Testing against a different DB than the one you're going to use in production isn't going to give you any benefits. What's the point? Some of your tests might pass against SQL Lite but fail when connected to oracle. Worse than useless.

So you've got two choices:

Mock out your DAO layer, so that your code doesn't actually talk to a DB, and thus making them "real" unit tests. Now you are actually testing your c# code and not the DB nor nhibernate.

Connect to another Oracle DB (eg, a UnitTesting DB with dummy data in it) and test against that, which would be my preferred choice. The TDD nazi's will scream at you "it's not a REAL UNIT TEST" to which I'll answer "I don't care what it's called, it's testing my code which is what I need".

Title: Unit test DAO code using SQL Lite when the application database is Oracle

Body:
We have an application with Oracle backend. The DAO layer is written in C# and uses nHibernet to perform the data operations.

To unit test our DAO code, we use SQL Lite which creates the database based on our existing mapping in the project.

Some of our nHibernate queries that go to oracle use (+) for outer joins. Now SQL Lite doesn't understand (+).

There can be some more syntax from Oracle that SQL Lite doesn't understand. How do we fix problems like these?

What are the other database systems that can be used for unit testing the application code.


问:
How can I structure my code when I have orthogonal arrays of features?
Example:

You have a game with different schools of magic (fire, ice, etc). Each school has a set of properties that pertain to independent features of the game, such as:

strings to be displayed on the GUI (generic data stored in memory)

graphics, sounds, and other files to be loaded as necessary

different behaviours (code), e.g. each school of magic has a different interaction with various terrain types

I can think of two designs for implementing this, but I don't particularly like either of them.

I could make an abstract MagicSchool class that contains all the various properties of a given school. This makes the MagicSchool class dependent on many distinct features of the game (GUI, SFX, other areas of game logic etc), which seems like an unnecessary mixing of concerns (something of a god class).

I could put the GUI/SFX/etc data for each school in the GUI/SFX/etc systems as arrays. But then the code for the magic schools gets scattered all across the project (albeit in very logical places).

So in this case, there are two axes along which to structure code: the various magic schools, and the various features in which the schools feature.

In terms of clarity and maintainability, which of the above two solutions should I prefer? Or perhaps there's another way I haven't considered yet?

答:
I'm not sure I fully understand the problem, let's say what if we do it this way (in a Java-like language):

Define interface's for your three bullets, say GUI, FX and Behavior. For example:

```<code>interface GUI {
    String name();
    ....
}

interface FX {
    Image image();
    Sound sound();
    ....
}

interface Behavior {
    Interaction interact(Terrain t);
    ....
}
</code>```

Each abstract MagicSchool is a product of objects drawn from each of the above interface:

```<code>abstract class MagicSchool(GUI gui, FX fx, Behavior b) {
    GUI gui();
    FX fx();
    Behavior behavior();
}
</code>```

To display a school's GUI element, we can do something like:

```<code>System.display(school.gui().name());
</code>```

Now for example, you want to define Fire:

```<code>class FireGUI implements GUI { .... }
class FireFX implements FX { .... }
class FireBehavior implements Behavior { .... }
</code>```

Now you define FireSchool as the product of these, overloading the constructor:

```<code>class FireSchool = MagicSchool {
    FireSchool() {
        super(new FireGUI(), new FireFX(), new FireBehavior());
    }
}
</code>```

Or if you don't actually need a new class, just define ad-hoc schools and behavior:

```<code>iceSchool = new MagicSchool(new GUI() { /* Ice GUI */ },
                            new FX() { /* Ice FX */ },
                            new Behavior() { /* Ice behavior */ });
</code>```

Java doesn't have a convenient way of doing higher-order functions, so I promote GUI, FX, Behavior to the level of interface to reduce syntactic burden at a few places. If your language has first-class functions, just define all those as objects.

Body:
I'm not sure I fully understand the problem, let's say what if we do it this way (in a Java-like language):

Define interface's for your three bullets, say GUI, FX and Behavior. For example:

interface GUI {
    String name();
    ....
}

interface FX {
    Image image();
    Sound sound();
    ....
}

interface Behavior {
    Interaction interact(Terrain t);
    ....
}

Each abstract MagicSchool is a product of objects drawn from each of the above interface:

abstract class MagicSchool(GUI gui, FX fx, Behavior b) {
    GUI gui();
    FX fx();
    Behavior behavior();
}

To display a school's GUI element, we can do something like:

System.display(school.gui().name());

Now for example, you want to define Fire:

class FireGUI implements GUI { .... }
class FireFX implements FX { .... }
class FireBehavior implements Behavior { .... }

Now you define FireSchool as the product of these, overloading the constructor:

class FireSchool = MagicSchool {
    FireSchool() {
        super(new FireGUI(), new FireFX(), new FireBehavior());
    }
}

Or if you don't actually need a new class, just define ad-hoc schools and behavior:

iceSchool = new MagicSchool(new GUI() { /* Ice GUI */ },
                            new FX() { /* Ice FX */ },
                            new Behavior() { /* Ice behavior */ });

Java doesn't have a convenient way of doing higher-order functions, so I promote GUI, FX, Behavior to the level of interface to reduce syntactic burden at a few places. If your language has first-class functions, just define all those as objects.


问:
Obstacles to using Git Flow in Subversion
My team at work is starting a new project, using Subversion as our VCS (you may consider this set in stone for the purpose of this question).  We're still in the early stages of the project and are trying to agree on a branching model.  Our previous project was based on a non-standard version model that led to issues when managing hot-fixes and patches to existing releases.

I've found different branching models to be rather complicated, but one model that I do understand fairly clearly is git flow.  I'm curious how hard/undesirable it would be to implement a variation of this in Subversion.  Obviously there would some difference in terms of people collaborating on branches.   The feature branches would have to be centralized
rather than limited to local repositories, but the other concepts of the model should be reproducable in Subversion as I understand it.

What would be the drawbacks or challenges to this approach.  What I've heard is that in SVN "merging is expensive" relative to Git.  But I'm not completely clear on what this means in practice or how it would effect our ability to use a git flow like branching model.

What would be the biggest concerns with this approach.  Is there a similarly clear approach that is more natural in Subversion?

答:
Gitflow is based on the best practices of source code versioning and branching.  A very good article on this is Advanced SCM Branching Strategies

The point that Vance makes in the linked article is that different branches have different roles.  He identifies the roles of:

Mainline (all branches from here)

Development (where development work is done)

Maintenance (where maintenance work is done)

Accumulation (Bringing things together in preparation for release)

Packaging (packaging the build for the release)

In gitflow, these are:

Develop

feature branches

Hotfix branches

Release branches

Master

The article on branching was written with Perforce in mind.  Perforce is a centralized VCS, much like svn is.  The patterns of branching that he describes perfectly map to svn.

The key to realize is that its not how does gitflow get ported to svn, but rather how to apply the same fundamental concepts of branching and the roles of branches to different VCS structures.

I would strongly recommend reading the article, I can't do much credit to it.  The way things are described in there are based off of a trunk/mainline build philosophy that you will find it easy to map svn to.


问:
Textarea validation
I'm interested to hear what characters people permit in the various common fields of input forms (barring e-mail...)

For example:

Textarea/Messages:  do you allow completely free text, or restrict to alphanumeric and punctuation? I've tried to go the second route, but you always find someone out there that likes using tilde's...

Full name: do you allow anything, or do you use a regex?

Telephone numbers: numbers only

Addresses: alphanumeric, whitespace, hyphens

City/Town names: alphabet, hyphens, whitespace

[NB: edited as requested]

答:
I've worked at more than one place with these fields in portions of the software I needed to write.  None of them had exactly the same answers.

It really depends on the needs of the people using the software..

Title: Textarea validation


问:
Coding styles when using several disparate libraries
I am working on some C++ code that uses several libraries, including some C libraries, that all have different coding styles.  It will be open sourced once it reaches a usable stage.  Which would cause the least confusion for a short-term contributor who checks out the code to fix one bug or add one feature?

Have one consistent coding style throughout the entire application, even if it occasionally doesn't match the typical coding style of the libraries used.

When a library is heavily used in a certain module, conform to the typical coding style of that library (i.e. the coding style used in the library's own code and documentation) in that module.

My thought is that the latter will make it easier for experts in that particular library to make one-off contributions, and make it easier to incorporate tutorial/example code during development.  However, it also makes the coding style inconsistent throughout the application.  What are the pros and cons of each approach?

答:
I will agree with @MetaFight here in case you are developing a big size project with lot of third party modules.

Lets map your problem with a real word problem: "Suppose you have quiet lifestyle in your house. You like your place to be quiet, you never speak louder and never like any member of your family to do so. But you interact with lot of different people outside everyday to bring in something for your house. Not necessarily they will also speak with lower voice, in that case you mold yourself accordingly while dealing with such people. Thus interface or wrapper for these people is highly flexible just for the sake of your work to be done." Dumb example...lol

But my point is to create wrapper for such libraries as per their coding standard in such a way that you use these libraries through these wrappers maintaining your original coding style inside.

+1 for MetaFight.


答:
I am generally very liberal in what I allow, especially for phone numbers. And if you allow for international phone numbers there are literally hundreds or even thousands of types.

For states I have a drop down list to select from but make sure it is international friendly.

For towns/city I often have a searchable list but allow them to override and enter their own. For street addresses I generally allow almost anything especially when loading from external data which is often full of rubbish addresses in an inconsistent format.

Title: Textarea validation

Body:
I'm interested to hear what characters people permit in the various common fields of input forms (barring e-mail...)

For example:

Textarea/Messages:  do you allow completely free text, or restrict to alphanumeric and punctuation? I've tried to go the second route, but you always find someone out there that likes using tilde's...

Full name: do you allow anything, or do you use a regex?

Telephone numbers: numbers only

Addresses: alphanumeric, whitespace, hyphens

City/Town names: alphabet, hyphens, whitespace

[NB: edited as requested]


问:
Why doesn't Java String have static string manipulation methods?
Why didn't Java designers create static versions of string manipulation methods in the java.lang.String class? The following methods are what I refer to, but the question can be extended to other non-static methods in the class as well.

```<code>concat(String)                        substring(int, int)
replace(char, char)                   toLowerCase()
replace(CharSequence, CharSequence)   toLowerCase(Locale)
replaceAll(String, String)            toString()
replaceFirst(String, String)          toUpperCase()
split(String)                         toUpperCase(Locale)
split(String, int)                    trim()
substring(int)
</code>```

Having only non-static versions of these methods forces explicit null-checking anywhere such a method has to be called. For example, simply calling example = example.trim() would lead to NullPointerException if String example = null. So the programmer has to do the following boilerplate null check:

```<code>if (example != null)
    example = example.trim();
// OR:
example = (example==null) ? null : example.trim();
example = (example==null) ? null : example.substring(5);
</code>```

I would imagine it would have been a lot more convenient if String had static versions of these methods (perhaps even exclusively), which would take the input string as the first argument:

```<code>example = String.trim(example);
example = String.replace(example, 'a', 'b');
example = String.substring(example, 5);
</code>```

This would have led to cleaner code written by programmers which would have automatically taken care of null cases by simply returning null, rather than forcing programmers to explicitly handle null cases. The returning of null makes sense to me since manipulating a null string should result in a null string, not an error.

Why didn't Java designers think of this when they designed the String class in Java 1 or Java 2, or even add such a functionality in a later Java version?

答:
The returning of null makes sense to me since manipulating a null string should result in a null string, not an error

Well, that is your opinion. Others may argument that String operations on a null object, which does not contain a String, make no sense and hence should throw an Exception

Why "Java designers" did or did not something is difficult to anwer.

There are already libraries out there which can do null-safe String operations, e.g. StringUtils of Apache Commons. You can use that or similar libraries if you need them.

Addition based on your comments

Reading through the comments, it seems like the real problem you face is that you have to check for null all over your code. That can be an indicator of a bad program design without clearly defined contracts between interfaces. You might want to read Avoiding “!= null” statements in Java?


答:
Not saying this is the reason, but except for toString, all of these methods are easily encapsulated in a static helper class, while the reverse is not true.

I.e. if you want Stings.toUpper(string input) the code for that is easy to write,  but if you want instance.toUpper and all you have is String.toUpper, well, that is impossible...unless they introduce extension methods, which most likely wasn't even considered at the time.

Title: Why doesn't Java String have static string manipulation methods?

Body:
Why didn't Java designers create static versions of string manipulation methods in the java.lang.String class? The following methods are what I refer to, but the question can be extended to other non-static methods in the class as well.

```<code>concat(String)                        substring(int, int)
replace(char, char)                   toLowerCase()
replace(CharSequence, CharSequence)   toLowerCase(Locale)
replaceAll(String, String)            toString()
replaceFirst(String, String)          toUpperCase()
split(String)                         toUpperCase(Locale)
split(String, int)                    trim()
substring(int)
</code>```

Having only non-static versions of these methods forces explicit null-checking anywhere such a method has to be called. For example, simply calling example = example.trim() would lead to NullPointerException if String example = null. So the programmer has to do the following boilerplate null check:

```<code>if (example != null)
    example = example.trim();
// OR:
example = (example==null) ? null : example.trim();
example = (example==null) ? null : example.substring(5);
</code>```

I would imagine it would have been a lot more convenient if String had static versions of these methods (perhaps even exclusively), which would take the input string as the first argument:

```<code>example = String.trim(example);
example = String.replace(example, 'a', 'b');
example = String.substring(example, 5);
</code>```

This would have led to cleaner code written by programmers which would have automatically taken care of null cases by simply returning null, rather than forcing programmers to explicitly handle null cases. The returning of null makes sense to me since manipulating a null string should result in a null string, not an error.

Why didn't Java designers think of this when they designed the String class in Java 1 or Java 2, or even add such a functionality in a later Java version?


问:
Ways of developing for small system. What is expedient?
I'm developing a small system for internal automation. I use asp.net webforms and faced with a choice:

develop a system architecture in an object-oriented style (development becomes more difficult and time-consuming)

or

just put controls on forms and write sql queries in control handlers (high speed development, the complexity of testing)

Сurrently I'm using the first method, but starting to have doubts that my choice is correct.
What way is expedient?

答:
Ehy if you start coding putting things here and there then your project becomes a mess!
Follow method number 1, as you are doing now, it will pay later.

Consider that an automation system, for how small it can be, must guarantee a reliable and affordable service for a medium to long period of time.

If you don't use a good structure and then you have to do maintenance in 2-3 years you will be thankful to yourself if you structure the design/implementation in a much better, organized and consistent way.

Even updating the system will be easier, if you continue with approach 1 and you have also the big advantage that you can recycle some code for other projects if the components are well designed.


问:
Should the helper function in class be defined before the usage or after
I need to do the code review of fellow members.

One of the member always defined the helper functions at the bottom and use them at top e,g

```<code>class Sample {

public function SendFile(){
file = $this-convertFile($file);
}

public function convertFile(){
//bla bla
}

}
</code>```

I sometimes dont know if he has custom defined this function of it is inherited from base class or some builin php function . when i reach bottom then i find it was custom defined

答:
Generally, the most important things should come first, with less important things later. In a class this means that the members and the constructor should come first, followed by public methods that make up the API of the class. After that, (private) helpers are listed. Putting the less important bits at the top would be probably more confusing.

I don't think your problem is that files are structured in a sensible way, but that you are trying to understand code top-down in a linear fashion. Code does not execute in a linear fashion, so this a linear approach is bound to fail.

Use code folding in your editor to get an overview of all definitions.

Use automatically extracted documentation to get an overview of a class before reading the code.

Is a method defined in this class or a base class? This can be looked up through a quick search.


答:
Flexibility vs. formalism

There is a continuum between projects which require no quality (e.g. prototypes) and the ones which need the highest quality possible (e.g. life-critical systems).

On the left side, prototypes have one and one only goal: being developed quickly in order to show something, then thrown away. Here, writing quality code or following standards is not the point. The code is written once, and never read. High ratio of bugs is acceptable.

On the right side, life-critical systems require extreme caution when it comes to the reliability, which means that some particularly expensive techniques, such as formal proof, should be used. Here, a bug can cause a plane crash or a nuclear plant meltdown, which makes is extremely important to be as close to perfection as possible.

When moving from a prototype to a life-critical system, more and more techniques become required in order to either decrease the medium/long-term expenses or ensure some sort of compliance required by an authority. Those techniques come at a cost: they increase the immediate-term cost of the product. Those techniques include but are not limited to:

Software testing,

Informal and formal code reviews,

Coding conventions,

Compliance with the standards,

Formal documentation,

Static code analysis,

etc.

Locating a project

Where is your project on this continuum? If it's a short term throw-away project, just put controls on forms, ship early, and forget about it. If it's a project which have a potential of being maintained by several developers over years, then make it clean: your successors (or yourself a few months later) will thank you.

There are many factors which may help determining the position of the project:

Are there many developers working on a project, or one only?

Is compliance to precise norms required (think software related to accounting, for example)?

Is the project made to be maintained for years, or quickly replaced by another system? Note that there is a bias towards small duration: some projects were thought to live at most two-three years, and twenty or thirty years later, they are still active.

Is reliability required? A web app for your personal use may crash frequently; nobody will care. A business system which handles every transaction of every customer will cause much more trouble if it crashes from time to time.

How many persons will use the product?

etc.

If you don't know where to put your product on the continuum, ask your customer. Make sure it's written in a contract (I had customers who asked to deliver ASAP a prototype, then were truly surprised that it won't be maintained without rewrite, despite being informed by e-mail from the beginning). If nobody knows, apply YAGNI: do it as it were a prototype, but be ready to have to start from scratch if the project appears to be a good candidate to be maintained over years.

Paradigms and processes

If you constantly fail shipping a product early, you may want to think about changing:

Either the paradigms you use. For example move from static programming languages to dynamic ones, which often offer better flexibility and development velocity for web apps, without compromising code quality.

Or the processes. For example, Agile enables to ship working products early, then continuously improve them, meaning that you have both high speed development and quality code together.

To answer the question…

To finally answer the question:

You talk about a “small system for internal automation”. Seems like you don't need extreme quality. But still, be careful; you don't want to ship something bad, then maintain that for years. If it's really small, what about spending a few days creating a prototype, and then if it is successful, create the real app?

ASP.NET? Why not a dynamic language, such as Python? With Django, it is an excellent candidate for a web application which should be done quickly, and will probably be much cleaner compared to ASP.NET with SQL queries in forms.

Title: Ways of developing for small system. What is expedient?

Body:
I'm developing a small system for internal automation. I use asp.net webforms and faced with a choice:

develop a system architecture in an object-oriented style (development becomes more difficult and time-consuming)

or

just put controls on forms and write sql queries in control handlers (high speed development, the complexity of testing)

Сurrently I'm using the first method, but starting to have doubts that my choice is correct.
What way is expedient?


问:
What do programmers "micro-optimize" for today?
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.

答:
Reading a file line by line instead of just reading the whole line into a string and process the string in one take.

Sure, it makes a difference in execution speed but is rarely worth the extra lines of code. It makes the code far less maintainable and increases code size.

Yes, this probably doesn't make sense if the file is 3GB big but most of the files aren't that big (at least not the ones I'm working with ;-)).


答:
IMO the whole "if arg is null return null"  approach to writing methods needlessly increases the cyclomatic complexity of your program.

Early Java libs used the return null approach,  but the JDK guys always guarded against null with exceptions.

With time,  I think the latter approach has come out as the clear winner.

Why?  Since null fields break a lot of oo principles. You simply cannot treat them as members of a polymorphic class. This means that  you always have to code special cases for null,  and hence your cyclomatic complexity soars when you have to assume that things can be null.

In order to solve your problems,  consider using the null object pattern instead of relying on null fields.


问:
How is a committer expected to behave?
In open source projects there is typically a set of devs that have permissions to commit code - the committers -, and others that "pull request" or send patches, the "general public".

I find a annoying when

the committer signs the commit with its own name, and writes in the commit message a "Thanks to ...".

the committer changes the patch before commit without asking if the original author agrees.

Given this two annoyances, I'm compelled to think that I should put myself in the other side and ask how should a core committer behave. Are these two particular situations expected?

I mean, is this the correct behaviour for building and maintaining an active community of "general public"?

EDIT:

I'm not asking if they have the right to do it or are legally obliged to do so. IMO a committer should not content himself to follow the law, but should be interested in building/maintaining the community within the project objectives constraints. That is what I'm asking for: how he should behave to accomplish this.

答:
Ad 1.

That's the reason git has separate author and committer entries in the commit metadata.  So there it's obvious they should keep the contributor in "author" and themselves as "committer".

Git and Linux projects also have this 'Signed-Off-By:' tag. It is simply used as part of the commit itself – so we are back to "thanks to…", just somewhat formalized – that lists all copyright holders as even single commit may have more than one. It happens often when the maintainer does significant changes to the contribution, but sometimes a half-done contribution is picked by somebody else and reworked, even several times over, so it's not unusual to have 3 or more signatures on a commit.

Other version control systems (like Subversion) keep just the committer and track them automatically, so there is no other way than to mention the actual author in the message.

Ad 2.

The maintainer usually have some style they want to maintain and various interactions in the project may make them prefer some solution over another. So they often tweak submissions to match.

They have full right to do it. The original author did agree by putting the contribution under the project's license! To qualify as open-source a license has to allow modification.

On the other hand, good maintainer distinguishes between integrator work and developer work and does not privilege themselves as developer. So as part of the integrator work they will pick what to merge and where, but doing changes falls under developer work. So when they change anything significant (not just typos in comments, whitespace and formatting), they will create a new submission with the reworked changes and post it for comments. So the original author or anybody else can point out any problems with the rework.

Note though that it still does not allow the original author to prohibit it on legal grounds, because they've already made the original contribution under license that permits modifying it. It does allow them to point out any technical (or aesthetic, but the maintainer is likely to stick to their taste anyway) reasons against the modification though.

Title: How is a committer expected to behave?


答:
In java, that string is an object. That's a design choice.

Object references can be null and are null if there is no object assigned to it. If you call such an object, a NullPointerException is thrown.
That's standard oo-behaviour.

Java designers made the choice of having strings as object and having those methods throwing null-pointer exceptions is what you get if you want strings to be objects.

Why didn't Java designers think of this when they designed the String class in Java 1 or Java 2, or even add such a functionality in a later Java version?

They probably did think about it and chose to incorporate oo-behaviour.


问:
What are the safety benefits of a type system?
In JavaScript: The Good Parts by Douglas Crockford, he mentions in his inheritance chapter,

The other benefit of classical inheritance is that it includes the specification of a system of types. This mostly frees the programmer from having to write explicit casting operations, which is a very good thing because when casting, the safety benefits of a type system are lost.

So first of all, what actually is safety? protection against data corruption, or hackers, or system malfunctions, etc.?

What are the safety benefits of a type system? What makes a type system different that allows it to provide these safety benefits?

答:
the safety benefits of a type system are lost.

So first of all, what actually is safety? protection against data corruption, or hackers, or system malfunctions, etc.?

What are the safety benefits of a type system? What makes a type system different that allows it to provide these safety benefits?

I feel like type systems have such a negative view.  A type system is more about making a guarantee than about proving the absence of errors.  The latter is a consequence of the type system.  A type system for a programming language is a way to produce, at compile time, a proof that a program meets some kind of specification.

The kind of specification that one can encode as a type depends on the language, or more directly, on the strength of the language's type system.

The most basic kind of specification is a guarantee about the input/output behaviour of functions and of the validity of the inside of a function body.  Consider a function header

```<code>f : (Int,Int) -> String
</code>```

A good type system will make sure that f is only applied to objects that will produce a pair of Int when evaluate, and guarantees that f will always produce a string.

Some statements in a language, like if-then blocks, don't have an input/output behaviour; here the type system guarantees that each declaration or statement in the block is valid; that is applies operations to objects of the correct kind.  These guarantees are composable.

Also, this does give a sort of memory safety condition.  The quote you are dealing with is about casting.  In some cases, casting is fine, like casting a 32-bit Int to a 64-bit Int.  However, generally, it does crash the type system.

Consider

```<code>Foo x = new Foo(3,4,5,6);
f((Int)x,(Int)x);
</code>```

Because of casting, x is turned into an Int, so technically the above does type check; however, it really does defeat the purpose of typechecking.

One thing that could make a different and better type system is to dissallow casts (A)x where x before the case is type B, unless B is a subtype (or subobject) of A.  The ideas of subtyping theory have been used in security to remove the possibility of integer overflow/underflow attacks.

Summary

A type system is a way to prove a program meets some kind of specification.  The benefits a type system can provide depend on the strength of the type system used.

Body:
the safety benefits of a type system are lost.

So first of all, what actually is safety? protection against data corruption, or hackers, or system malfunctions, etc.?

What are the safety benefits of a type system? What makes a type system different that allows it to provide these safety benefits?

I feel like type systems have such a negative view.  A type system is more about making a guarantee than about proving the absence of errors.  The latter is a consequence of the type system.  A type system for a programming language is a way to produce, at compile time, a proof that a program meets some kind of specification.

The kind of specification that one can encode as a type depends on the language, or more directly, on the strength of the language's type system.

The most basic kind of specification is a guarantee about the input/output behaviour of functions and of the validity of the inside of a function body.  Consider a function header

f : (Int,Int) -> String

A good type system will make sure that f is only applied to objects that will produce a pair of Int when evaluate, and guarantees that f will always produce a string.

Some statements in a language, like if-then blocks, don't have an input/output behaviour; here the type system guarantees that each declaration or statement in the block is valid; that is applies operations to objects of the correct kind.  These guarantees are composable.

Also, this does give a sort of memory safety condition.  The quote you are dealing with is about casting.  In some cases, casting is fine, like casting a 32-bit Int to a 64-bit Int.  However, generally, it does crash the type system.

Consider

Foo x = new Foo(3,4,5,6);
f((Int)x,(Int)x);

Because of casting, x is turned into an Int, so technically the above does type check; however, it really does defeat the purpose of typechecking.

One thing that could make a different and better type system is to dissallow casts (A)x where x before the case is type B, unless B is a subtype (or subobject) of A.  The ideas of subtyping theory have been used in security to remove the possibility of integer overflow/underflow attacks.

Summary

A type system is a way to prove a program meets some kind of specification.  The benefits a type system can provide depend on the strength of the type system used.


问:
How to store collections of linked Text objects in database
I'm writing a Java program that works as a presentation of a written document, which needs to be stored in a database (I'm using MySQL, but am open to suggestions of other DB types).

The Essay class is a collection of objects of the Paragraph class (more specifically Essay extends LinkedList<Paragraph>, which consists primarily of an int ID and a String content. The Essay object is stored as its own table in the DB, which is fairly straightforward (with columns int paragraphId and Blob text), and I do a simple query that creates a new Paragraph object for each row in the table when the program gets initialized.

Within each paragraph, certain hyperlinked words link to other Essay objects, which also need to be stored in the database. My question is how best to save them - the options I'm considering are:

Creating a single additional DB table where each essay is stored on a row, with paragraphs being stored in a single text object separated by a delimiter, and the program separates them into separate Paragraph object as it pulls them from the DB. (this is fairly manageable because these linked essays are much shorter than the main essay).

Create a single additional table, with a large number of content columns, storing each paragraph in a separate column. Then, when the data is pulled from the database, it creates a new essay for each row and a new paragraph for each column in that row, until it comes upon one that is null.

Dynamically create a separate DB table for each linked essay, setting it up identically to the primary one. This doesn't seem ideal because it would end up being a very large number of tables, and many of them would only have two or three paragraphs, making a new table seem wasteful.

Do a different arrangement altogether: Have one Paragraphs table, where all paragraphs from all essays are stored, and another table called Essays, which uses a SET datatype to store the IDs (foreign keys) of the paragraphs included in each essay.

I've modified my actual use case here to make it more simple to explain. I'm new to database programming, and am doing this largely as an exercise, so I'm looking for general tips about the pros/cons of these approaches, as well as any additional suggestions.

答:
There are problems with each of the first three options.

Storing the entire text in one column can work, but may become inefficient depending on how large and how numerous your paragraphs are, whether you always want to retrieve all paragraphs of an essay or maybe only some of them, etc. A separate table for paragraphs linked to essays via foreign keys is often the better way to go.

Stuffing successive paragraphs into neighbouring columns of one table is a bad idea. You have to predict how many paragraphs there can be, then provision that much storage for every essay, much of which will be wasted, only to find that you misestimated and either have to tweak the schema in production, or introduce unwanted limits that look totally arbitrary to the users (because they are). Also, you'll have to generate at least part of your queries dynamically depending on just how many of those columns there are, which opens up several cans of worms better left closed.

Creating a new table for each linked essay is much worse still. Any solution that requires you to change not only your table definitions but the set of tables that exist in the schema just because a user entered new data is at best a profound misunderstanding of what relational data bases are for. It can work with a schema-free platform (usually called 'NoSQL', but the decisive difference is the lack of a relational schema, not the query syntax), but I'm not experienced enough here to advise you on how and when.

Option 4 is what I would do, but instead of maintaining a set of foreign keys, which introduces all of the problems of multiple columns in miniature, I would go with paragraphs pointing back to essays via a foreign key. If your database is too inefficient to perform the JOIN needed to reconstruct an entire essay, then something else is probably wrong besides the organisation of your data - databases have been optimized for exactly this task for decades, so it would be very surprising if this were really the limiting factor.


答:
What you describe doesn't sound like a good fit for a SQL database.

Basically, what you have is a graph of documents, I would store those in either a document database (e.g. Cassandra, CouchDB, MongoDB, Redis) or a graph database (e.g. Neo4J), depending on how you want to traverse / query the data. (Or maybe even both: store the documents in a document database and the graph structure in a graph database, that way you can traverse the graph in the graph database, which is what they are good at, and then retrieve the document from the document database, which is what those are good at.)

There are even databases such as ArangoDB which combine a graph-oriented, document-oriented and key-value-based storage model in a single database.

This idea of choosing a database model that fits the shape of your data instead of trying to awkwardly fit the shape of your data to match the (SQL) database model has been gathering a lot of attention over the past 10 years or so, and is known as NoSQL (Not Only SQL). Note that NoSQL doesn't mean you shouldn't use SQL. It means that you should use SQL when it is the right tool for the job, i.e. when your data is actually table-shaped and relational.

Title: How to store collections of linked Text objects in database

Body:
I'm writing a Java program that works as a presentation of a written document, which needs to be stored in a database (I'm using MySQL, but am open to suggestions of other DB types).

The Essay class is a collection of objects of the Paragraph class (more specifically Essay extends LinkedList<Paragraph>, which consists primarily of an int ID and a String content. The Essay object is stored as its own table in the DB, which is fairly straightforward (with columns int paragraphId and Blob text), and I do a simple query that creates a new Paragraph object for each row in the table when the program gets initialized.

Within each paragraph, certain hyperlinked words link to other Essay objects, which also need to be stored in the database. My question is how best to save them - the options I'm considering are:

Creating a single additional DB table where each essay is stored on a row, with paragraphs being stored in a single text object separated by a delimiter, and the program separates them into separate Paragraph object as it pulls them from the DB. (this is fairly manageable because these linked essays are much shorter than the main essay).

Create a single additional table, with a large number of content columns, storing each paragraph in a separate column. Then, when the data is pulled from the database, it creates a new essay for each row and a new paragraph for each column in that row, until it comes upon one that is null.

Dynamically create a separate DB table for each linked essay, setting it up identically to the primary one. This doesn't seem ideal because it would end up being a very large number of tables, and many of them would only have two or three paragraphs, making a new table seem wasteful.

Do a different arrangement altogether: Have one Paragraphs table, where all paragraphs from all essays are stored, and another table called Essays, which uses a SET datatype to store the IDs (foreign keys) of the paragraphs included in each essay.

I've modified my actual use case here to make it more simple to explain. I'm new to database programming, and am doing this largely as an exercise, so I'm looking for general tips about the pros/cons of these approaches, as well as any additional suggestions.


问:
Examples of Java APIs that demand an action sequence
As part of a research I'm working on, I'm looking for public APIs that only work correctly when you apply a certain sequence of actions on them.

For example, the java.nio.channels.SocketChannel class, from the Java standard library, only works correctly with sequences such as open() -> connect() -> read() -> read() -> close(). A more complete demonstration if how it may be used may be represented in the following graph:

Additional examples of Java standard library APIs that require certain sequences are java.io.PrintStream (very similar to the one above) and java.util.Iterator (which requires a next() call between every two remove() calls, thus enforcing a certain sequence).

So, does you favorite API for doing X also behave that way? I would very much like to know about additional APIs that require a certain method sequence for correct usage; especially classes that are not part of the Java standard library. The more complex the sequence(s) required, the better.

Some APIs require a sequence that spans across multiple classes, for example:

```<code>X x = new X();
x.setup();
Y y = x.createNewY();
Z z = new Z(y);
z.doSomething();
</code>```

These examples are also interesting, but I'm mostly looking for sequences that all appear in the same class.

EDIT added bounty for greater visibility. I'm sure many of you have encountered many APIs that will match this description - I would really appreciate some good examples.

答:
An upcoming "best practice" to handle this problem in the initialization phase of objects in Java, is to use a Builder pattern which has a so-called builder on which the steps are taken, and then an object is requested built.  If the steps are invalid, the builder fails.

From http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html:

```<code>Widget z = new Widget.Builder("3", 4.0).
                     manufacturer("333").
                     serialNumber("54321").build();
</code>```

The Builder is a nested class to Widget, which then has methods called (returning the same builder object again) until the build() method is called, which creates and returns the Widget needed.

Can reduce complexity quite a bit.

Body:
An upcoming "best practice" to handle this problem in the initialization phase of objects in Java, is to use a Builder pattern which has a so-called builder on which the steps are taken, and then an object is requested built.  If the steps are invalid, the builder fails.

From http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html:

Widget z = new Widget.Builder("3", 4.0).
                     manufacturer("333").
                     serialNumber("54321").build();

The Builder is a nested class to Widget, which then has methods called (returning the same builder object again) until the build() method is called, which creates and returns the Widget needed.

Can reduce complexity quite a bit.


问:
How to identify unstable floating point computations?
In numerics, it is very important to be able to identify unstable
schemes and to improve their stability.  How to identify unstable
floating point computations?

I am working on a very complex simulation where many numerical schemes work together and I am looking for a methodic to identify its weak parts.  I am working on a physical model involving differential equations.  A bird's eye view of the overall process is:

(Preliminary step) Gather physical observations P.

Determine initial parameters of the simulation. This uses an optimisation algorithm, where we walk in a parameter space and look for parameters C such that some error function E(F(C), P) is minimised, where F is some derived quantity of the parameters.

Plug C in the simulation engine. This is an Euler scheme of the EDP, so that at each time step, we compute the terms driving the dynamic (each of them is a complex function, potentially subject to instability) and feed the Euler scheme with these dynamic terms to compute the next state. This goes on for thousands time points.

At the end of the simulation, we compute some function Proof(S) of the final state S and compare to some quantities Require(P) deduced from the observed quantities. This is not a formal proof of the result, more a plausibility check.

Also, I see a tower of complex operations (computation of dynamic terms, within the Euler scheme, within the Proof). And would like to recognise “bad parts” and fix them.

I speculate that using a software implementation of floating point
numbers with reduced precision would magnify the unstability of
numerical schemes, thus easing the comparison between different
implementations.  Is this a common technique to investigate this
question?  Is it possible to use a virtual machine, as Bochs, to
achieve this without altering the program?

To deal appropriately with the stability question, it is sometimes
acceptable to target the typical input of the numerical procedure, so
that it can be tuned to do well on that input and maybe less well on
other valid, yet unlikely, input.  Given a sample of typical inputs,
it is possible to snoop some intermediate results and prepare a
statistical profile for them.  Again, is this a common technique to
study stability issues?  Is a virtual machine useful for this?

答: You can avoid numerical errors by using appropriate data types (like, for example, continued fractions). If you need or want to use floating point arithmetic, you need to apply numerical know-how to know the errors.</p>


问:
C++ is easy once you know PHP
I was at work last week and one of our "lead developers" (who said he has programmed C++ before, but I don't believe him) was talking about C++ and how our team of developers who only know PHP would not have a hard time at all learning C++.

My first reaction was pure shock and then I laughed at his comment. He gave me a bad look and i asked if he was serious. Me personally I program a lot of C and C++ for mostly school projects and coding competitions. I don't think it's at all like PHP. I asked him why they were the same and he could not give me an answer (he doesn't know C++ at all I was thinking). Then I said "OK, yeah they both use curly braces and have conditional statements. But C++ you have to worry about memory management and all the easy to use built in functions in PHP, for example the array functions, are non-existent in C++. You actually have to know the algorithms behind them.". There are some great C++ libraries (STL, Boost) that will make your life easier but C++ is like PHP, come on!

If you already know one language it will make it a little easier to learn another because you will already be good at boolean login (if this then that) or looping but there is just so much more to C++ than PHP. Like you have to compile the language and actually have to define what type of variable you are using and returning from functions.

What do you think?

EDIT: Actually what he said was "C++ is not much different than PHP"

答: Just as a first thought, he could be referring to the syntactical styles. Yes there are a few differences in how certain things like string concatenation and arrays work but they are easily enough learned. Then there are pointers and things of that nature but once again, if you have solid knowledge of basic CS concepts then it shouldn't be a problem. I don't think that the statement is that far out of the ballpark, but I am by no means saying that it would be easy. C++ is a tough language to tackle.</p>

Title: C++ is easy once you know PHP


答:
It would clearly cause the least amount of confusion to use a single coding style throughout your project. The very point of using a coding style in the first place is to make code easier to read and modify.

As for the code style used internally in a library, I don't think it's relevant. If the library is too imperative, then writing an OO wrapper around is fine, but that doesn't require that you use the same code style as in the library's examples or internals.

Title: Coding styles when using several disparate libraries

Body:
I am working on some C++ code that uses several libraries, including some C libraries, that all have different coding styles.  It will be open sourced once it reaches a usable stage.  Which would cause the least confusion for a short-term contributor who checks out the code to fix one bug or add one feature?

Have one consistent coding style throughout the entire application, even if it occasionally doesn't match the typical coding style of the libraries used.

When a library is heavily used in a certain module, conform to the typical coding style of that library (i.e. the coding style used in the library's own code and documentation) in that module.

My thought is that the latter will make it easier for experts in that particular library to make one-off contributions, and make it easier to incorporate tutorial/example code during development.  However, it also makes the coding style inconsistent throughout the application.  What are the pros and cons of each approach?


问:
Build times for small incremental changes to C# Web Applications
I have recently been moving away from ASP.NET Websites in favor of Web Applications. More specifically I have recently been picking up MVC as an alternative to developing ASP.NET Forms websites.

Something that I find highly frustrating is the constant build->change->re-build process when testing small changes to compiled code. I find myself 'bundling' several changes between builds just to avoid waiting 20-25 seconds for Visual Studio to crunch it's way through the compilation process. I created a clean MVC 4 project from the VS template and timed the build after making a single line code change, it took 19 seconds.

When making a change in the code-behind in an ASP.NET website I've always found that the page is seemingly re-compiled on the fly when you next hit the page. This would seem to me to be a better environment for web development rather than VS forcing an entire rebuild after every small code change.

In the past I have enjoyed the luxury of making a change, hitting refresh in the browser, and waiting 1-2 seconds for my result. Is this achievable with web applications built using Visual Studio?

答:
You can edit your MVC views while the site is running. The code for controllers and everything in between must be recompiled after a change. Did you write everything in the .aspx when using ASP.NET?

Anyway, 20 seconds is quite long for an incremental build after changing a single line of code (though it might depend on what you changed, it may cascade through a few assemblies). I'd try to address compilation speeds first. Why is it taking long? NuGet package restore? Copying lots of assemblies? Slow disk drive, CPU and low on memory?

On the other hand it sounds like your development practice is a bit suboptimal. You might want to employ test driven development, where you write a test to show what your intentions are, after which you start working on the implementation. This way you won't  also have to wait for the development web server and the browser to start; you run the tests from Visual Studio.


问:
Freelance charging based on tasks completed
I've just started freelancing and have two projects where I am splitting my week with both companies, one I'm charging hourly and everything is fine, the other one however they have said they will pay me based on a points basis using Pivotal Tracker.

For example, there's a fixed rate per point and they work on an estimate that I will complete two points per day, I was just wondering if this is something that is used regularly or if I should try and get them to switch to hourly?

My concern is that points are only used for features and if a feature has a bug this isn't taken into consideration so any time spent fixing that bug won't be charged. Correct?

答:
This is a question that has two aspects to it: How you deal with your clients, and how your clients deal with your work.
The first is a business aspect, the second is a matter of QA.

I'm going to be somewhat optimistic, and assume that there's some way that they approve your work when you submit it. If there isn't, make it happen. This provides the basis for a stable working relationship, as it will make clear to both parties what it takes to work together and when things are going satisfactory.
Being an independent professional includes bargaining on stuff like this. You need to be able to function, otherwise you're paying for their incompetence. (in terms of Quality Assurance and Control)

I'd have to say that with a pay per task system, you're initially taking the burden of risk when it comes to bugs. That means that you have to plan for them, as they're inevitably going to happen. It also means you have to do a bit of your own QC and QA before you submit your work for approval, to minimise the risk of failure. Keeping track of your failure rate will improve your accuracy when it comes to making a good estimate on how long it will take you to complete a task until it has been accepted by the hiring company's QC department/process. Also, you need to make sure that a task is specified in clear and completable goals. (SMART)

If the client has no QA process whatsoever, then you're in trouble. If there isn't some kind of QC during acceptance, then there's no transfer of responsibility. You're stuck with the bugs until they're gone. This then enables them to play the blame game, forever. Some basic QC should take place upon accepting your work, or on a complete body of work that you have delivered (not points, but complete products/parts) that you deliver. Each task is like a mini project, and needs to be treated like one.

Now, if their QC has passed your work, it's up to them. If they throw it back on your plate after having accepted it before then it's a new job if you ask me. But this really is something that you and your client should have agreed on before commencing work. Maybe you need to (re?)negotiate this bit with your client.

As for x the points per day, that sounds like typical SCRUM-type agile work provisioning. I wouldn't have a problem with it, as long as your own estimates don't differ too much with theirs. It would help if you had a say in the estimate, but sometimes that's just not your call.

Some side notes on QA and QC:

Quality Assurance is the process that ensures quality in the processes that are used to develop software. e.g. Planning that you will do quality control, process evaluations and and how to improve processes after finding faults.

Quality Control is what you do to check that the product is doing what it is supposed to do. Things like setting up a unit test for a specific project etc. (including all the planning that is required to make it happen)

A company without a QA process is likely to have failures, which will probably mean that their code is likely to be buggy. Your code that has to integrate with it, and could suffer because of it. Implied QA is usually the same as no QA, as it's lacking structure, and therefore process improvement is very hard. (if not impossible) Having QC without guidance is then just a way to make it look good superficially.

QC should be the result of QA. There are a couple of systems that can help improve QA, like CMMI and SPICE (ISO/IEC 15504)


答:
On the first point, most open source maintainers go out of their way to give credit where credit is due.  Not all version control systems make it easy or even possible to maintain separate author and committer fields, especially if multiple people worked on it.  Be happy with the acknowledgement.  Sometimes you might even get an extra surprise, like being listed as an author in the about dialog.

On the second point, maintainers deal with a lot of "fire and forget" contributors, who want to make one submission and move on.  While some contributors prefer to own their code from start to finish, most are perfectly fine with letting someone else make tweaks for style issues and to address potential bugs they didn't see due to lack of familiarity with the code.  It is open source, after all, so it will get changed eventually, and it's a lot easier to just make the change than to explain it and wait.  If you're the former type of contributor, you need to make that clear up front.

Title: How is a committer expected to behave?

Body:
In open source projects there is typically a set of devs that have permissions to commit code - the committers -, and others that "pull request" or send patches, the "general public".

I find a annoying when

the committer signs the commit with its own name, and writes in the commit message a "Thanks to ...".

the committer changes the patch before commit without asking if the original author agrees.

Given this two annoyances, I'm compelled to think that I should put myself in the other side and ask how should a core committer behave. Are these two particular situations expected?

I mean, is this the correct behaviour for building and maintaining an active community of "general public"?

EDIT:

I'm not asking if they have the right to do it or are legally obliged to do so. IMO a committer should not content himself to follow the law, but should be interested in building/maintaining the community within the project objectives constraints. That is what I'm asking for: how he should behave to accomplish this.


问:
History of vendor css prefix
When and how did this process of prefixing css with vendor specific prefix begin.

Which browser/org start this and why was this started. I searched the web but found no details on this.

答:
javascript coding may have had something to do with its spread.  Around the same time, people were writing such code as:

if (document.all) browser = isIE;
else if(document.layers) browser = isNN;

much like they do today.  So, when css started taking off, there was already a precedent for using vendor tags.

Title: History of vendor css prefix


问:
Should a DR & CR entry both be created or a single-entry accounting is fine
A new project has an amount. It is always related to a client.

One client can have many projects. And he may pay in steps for a particular project.

In order to keep track of client payments, I've created a table namely client_ledger which contains information about date, time, amount, mode of payment & related project.

But then in one of the software screens, I have to reports pertaining to a client's debit & credit.

So there are 2 things that can be done :

Either I can get the total amount of all projects of that client and his total payments & then can show how much balance is left to be paid.

Or if I'd created an entry in the client_ledger table for DR, then as soon as a project is created, an entry is made in the table for DR and subsequent payments received
will be CRed into the data-base. In this case, if a project's amount is modified/edited later, then either the original DR entry has to be modified, or a new CR entry followed by the new project amount's DR entry should be made.

Which of these processes should be followed ?

答:
The answer depends entirely based on the purpose of the screen in question.

If the screen is meant to show a client's current due balance, then displaying aggregate totals is appropriate.

If the screen is meant to show a client's payment history, then including both credits and debits on the ledger and displaying all is appropriate.

If you do implement a the second option, I would encourage as clear accounting principle to
enter the a debits for project estimation with a date the estimate is given, and then append additional positive or negate debits latter on as the estimate increases, decreases, or becomes final.  (I would not, under ANY circumstance, change an accounting entry from what was a correctly entered figure for the time in question.)


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
Why not mash a few answers into one?

```<code>while (expr) {

    // Executed every iteration, unless first{} is present.
    // May be explicitly called rest{} if you like first{} to come first.

    // Blocks may return results, and consequently be used in expressions.
    return expr;

} first {

    // Executed only on the first iteration.

} pre {

    // Executed before every iteration.

} post {

    // Executed after every iteration.

} catch (oops) {

    // All blocks are implicitly try{}ed if followed by a catch{}.

} finally {

    // Executes after the block completes, regardless of exceptions.

} else {

    // Executed if the loop body or rest{} never executes.

} never {

    // Executes only when a client is present.

} drop (bad, worse), // Explicitly ignore certain exceptions.
  until (expr);      // Here, have a post-body condition, too.
</code>```

An extensible, generalised flow-control construct syntax in an imperative language would be rather useful and entertaining. Until that shows up, guess I'll just use Lisp or something.

Body:
Why not mash a few answers into one?

while (expr) {

    // Executed every iteration, unless first{} is present.
    // May be explicitly called rest{} if you like first{} to come first.

    // Blocks may return results, and consequently be used in expressions.
    return expr;

} first {

    // Executed only on the first iteration.

} pre {

    // Executed before every iteration.

} post {

    // Executed after every iteration.

} catch (oops) {

    // All blocks are implicitly try{}ed if followed by a catch{}.

} finally {

    // Executes after the block completes, regardless of exceptions.

} else {

    // Executed if the loop body or rest{} never executes.

} never {

    // Executes only when a client is present.

} drop (bad, worse), // Explicitly ignore certain exceptions.
  until (expr);      // Here, have a post-body condition, too.

An extensible, generalised flow-control construct syntax in an imperative language would be rather useful and entertaining. Until that shows up, guess I'll just use Lisp or something.