问:
How long and what type of complexity would have been involved in Chris Sawyer writing most of rollercoaster tycoon in assembler?
From this question, I have another question about...

How long and what type of complexity would have been involved in Chris Sawyer writing most of rollercoaster tycoon in assembler?

In order to specify and break this question down, I am interested in;

Approximately how many man hours (have a guess) do you estimate it would have taken Chris to write the game by himself? Or alternatively give an approximate percentage of the ratio of assembler coding hours to say, writing the whole thing in C/C++.

Do the programmers that know assembler well think of this as an overly complex task for such a low level language abstraction? Apart from performance benefits is this just a freakish natural ability that Chris has, or a skillset worthy of learning to that extent? I'm interested if people think the complexity/performance thing is worth learning assembler that well (in order to write), or is it only "worth it" if you have a lot of naturally developed skills in assembler (presumably from working with hardware/hardware drivers/electronics/etc).

答:
From reading his rough bio, it looks like two years (early 1997 to late 1998).  Given that he seems to be a 'one project at a time' person and the tool set and timeframe isn't great for 'team development', I would assume a straight 24 programmer-months.

At that point he had been a professional games programmer working in assembly since 1983, so I wouldn't equate "two Chris years" to "two me years" of work.

Given that most professional games take around 25-person years for a team to develop, two-person years for an industry leading game is an amazing accomplishment, lending creedence to the sayings:

A great programmer is 10x more productive than a good programmer

The programmer is more important than the language for productivity

So in this case how much faster would Rollercoaster Tycoon be written had Chris used C or Java or Javascript or ...?  Probably it wouldn't have mattered other than the fact that he may have been a bit slower using a higher level language that he didn't have 14 years experience with...


问:
Making a class pseudo-immutable by setting a flag
I have a java project that involves building some pretty complex objects. There are quite a lot (dozens) of different ones and some of them have a HUGE number of parameters. They also need to be immutable.

So I was thinking the builder pattern would work, but it ends up require a lot of boilerplate. Another potential solution I thought of was to make a mutable class, but give it a "frozen" flag, a-la ruby.

Here is a simple example:

```<code>public class EqualRule extends Rule {
    private boolean frozen;
    private int target;

    public EqualRule() {
        frozen = false;
    }

    public void setTarget(int i) {
        if (frozen)
            throw new IllegalStateException(
                "Can't change frozen rule.");

        target = i;
    }

    public int getTarget() {
        return target;
    }

    public void freeze() {
        frozen = true;
    }

    @Override
    public boolean checkRule(int i) {
        return (target == i);
    }
}
</code>```

and "Rule" is just an abstract class that has an abstract "checkRule" method.

This cuts way down on the number of objects I need to write, while also giving me an object that becomes immutable for all intents and purposes. This kind of act like the object was its own Builder... But not quite.

I'm not too excited, however, about having an immutable being disguised as a bean however.

So I had two questions:
1. Before I go too far down this path, are there any huge problems that anyone sees right off the bat? For what it's worth, it is planned that this behavior will be well documented...
2. If so, is there a better solution?

Thanks

答:
Here is @9000 suggestion with a fluent setter that returns a new object:

```<code>public abstract class Rule {

    public Rule shallowClone() {
        // see http://stackoverflow.com/questions/5395501/shallow-vs-deep-copies-in-immutable-objects
    }
}

public class EqualRule extends Rule {

    private int target;

    public int getTarget() {
        return target;
    }

    public EqualRule setTarget(int target) {
         EqualRule clone = super.shallowClone();
         clone.target = target;
         return clone;
    }

    @Override
    public boolean checkRule(int i) {
        return (target == i);
    }
}

boolean result = new EqualRule().setTarget(1).checkRule(1);
</code>```

Pros: Allows creation of immutable objects in a strongly typed manner (less human errors when using the POJO).

Cons: More human errors when implementing the POJO.

ContentLicense: CC BY-SA 3.0

Body:
Here is @9000 suggestion with a fluent setter that returns a new object:

public abstract class Rule {

    public Rule shallowClone() {
        // see http://stackoverflow.com/questions/5395501/shallow-vs-deep-copies-in-immutable-objects
    }
}

public class EqualRule extends Rule {

    private int target;

    public int getTarget() {
        return target;
    }

    public EqualRule setTarget(int target) {
         EqualRule clone = super.shallowClone();
         clone.target = target;
         return clone;
    }

    @Override
    public boolean checkRule(int i) {
        return (target == i);
    }
}

boolean result = new EqualRule().setTarget(1).checkRule(1);

Pros: Allows creation of immutable objects in a strongly typed manner (less human errors when using the POJO).

Cons: More human errors when implementing the POJO.


问:
Is there an equivalent to Build-Operate-Transfer for software development?
Is there an equivalent to Build-Operate-Transfer or Build-Lease-Transfer in software development? Does it even make any sense to operate such a project in software? Do you know of any projects in your experience that have been launched as such?

Another way to put it is: for a large software system project, why wouldn't a company bid it out to third parties for them to build and operate for a period of time (i.e. the third party will be responsible for ongoing maintenance and operation of the system), until the concession is up? The third party recuperates expenses from software development through the running of the system; the original company might earn from residuals during this period, and then absorb income from the system once the concession is up.

Does this even make any sense?

答:
For that kind of arrangement to work, it would require that the system perform as a profit center.  That already limits the kinds of software that would have any chance of fitting.  Certainly some software fits that bill, but quite a bit doesn't.  B2B, or B2C, or perhaps a GOV system collecting usage fees might be more obvious candidates.

The second element that limits this kind of arrangement is [projected] life-cycle.  By the time the software has paid for itself, it may often be time to revamp or replace it. Keep in mind this is intended to be a profit center which is often pushed by and with certain marketing aims that follow or endure trends and freshness.

Now that being said, it could be a decent avenue to pursue, if trying to build a portfolio and partnerships where both parties are aware of the risk and opportunity.

EDIT:

Those arrangements do exist.  In particular, certain gov/gov related services that operate on a fee per use basis often have 3rd party payment processors under contract to provide the infrastructure.  I am sure the government ends up with a small cut of that fee while the contracted provider keeps a majority of the fee for providing us with that convenience.


问:
How to salvage a business model from a mismatched database?
There is an application that involves billing enterprise customers for the services their customers utilize. The database schema does not properly reflect the business model. For instance, on a given account, services may become activated and deactivated. There is only a column to represent when the service was deactivated and the code in place just updates that same row if the service is reactivated rather than adding a new row. Ideally, a row would be added when a service activates and updated when deactivated, and there would be a column to represent the activation date.

As it stands, there is no solid billing history for these enterprise customers, but there needs to be from here on out. Do we set a "cutoff" for the legacy model that was corrupted and wipe the table clean? Do we add the appropriate column and start working with the table properly and just check for rows that have a 'activated date' of null to detect legacy? There must be several ways of handling this, but I have no experience with this kind of situation and would like to hear out some various approaches.

答:
Your issue is not the database schema. It is the question where the code influences the data. If it is structured well you can just change code and schema. Implement a piece of code which handles missing history for old records and you are done.

The fact that you would want to put tricks into your schema or database to prevent any unknown issues means that the code view there is currently is not complete. So would focus strongly on having a good overview of where the code acts with the schema.

If you find it scattered all over the place then you might consider first improving the code structure instead of directly changing to the functionality you need. That will create a better end-result.

Why: Think about all changes you might have to make in future. If you need to apply tricks now you have to take care of them all the way along. If you fix it straight from the beginning in a right way it saves you time in the end without having to over-engineer.


问:
Why don't computers come with specialized hardware such as sorting networks?
Instead of programming the way we do, why don't we make specifications of common tasks such as "sorting", and then let the environment compile it to make best use of it's hardware? This way, we could ship computer with new specialized hardware such as sorting networks, and it would automatically work with existing code.</p>

答:
But they do! They're called instruction set extensions. (Stuff like SSE and the like)

Certain tasks have very nice implementations in software. Usually those implementations are good enough to do the job, so no specialized hardware is necessary.
If you'd make some kind of specialized hardware, you'd need to have a very wide range of applications to make it worthwhile.

If you look at hardware that could make this work, my guess would be that you'd be looking at something like FPGAs. As you can see with FPGAs, the chip would become much more expensive while it wouldn't be applicable for many applications.


问:
Is repeating links to the same class in a single javadoc comment a bad practice?
I'm currently writing an API and its documentation. For example I have something like this:

```<code>public interface Event {
}

public interface Process {
}

public interface EventProcessor {
    /**
     * Starts to process the sepcified event asynchronously. The returned
     * {@link Process} can be used to track progress on the processing. If the
     * specified event causes more {@link Event events} to be processed in this
     * system, then they are also tracked via the returned {@link Process}.
     *
     * @param event
     *            to be started to process
     * @return
     */
    Process startProcessing(Event event);
}
</code>```

In the example above, the javadoc link to the interface Process is repeated. In the API I'm writing there are cases where I have several more references to the same class in a single javadoc comment.

Should I always mark references to the class/method/etc. as javadoc links?

Generally, I think having many links in a javadoc comment is a sign for high cohesion. But when it's often the same target, which is linked, I'm not sure if this is good.

答:
Here is what the oracle javadoc guidelines say:

Use in-line links economically

  You are encouraged to add links for
  API names (listed immediately above) using the {@link}  tag. It is not
  necessary to add links for all API names in a doc comment. Because
  links call attention to themselves (by their color and underline in
  HTML, and by their length in source code doc comments), it can make
  the comments more difficult to read if used profusely. We therefore
  recommend adding a link to an API name if:

The user might actually want to click on it for more information (in your judgment), and

Only for the first occurrence of each API name in the doc comment (don't bother repeating a link)

Our audience is advanced (not novice) programmers, so it is generally
  not necessary to link to API in the java.lang package (such as
  String), or other API you feel would be well-known.

So summarized, repeating links to the same link target is a bad practice.

Thanks to @AaronKurtzhals for pointing me there.


答:
The main issue is that sorting algorithms (1) need a lot of flexibility, and (2) would be very difficult to accelerate using hardware anyway.

One thing is that sorting algorithms are already easily fast enough to outrun the memory bandwidth of the processor - the processor will already spend a large proportion of its time waiting for data to move backwards and forwards to main memory. A hardware-accelerated sorting co-processor or a special sorting instruction would have the same problem.

The way this memory bandwidth is being addressed is by using better algorithms and data structures that have better "locality", and there's still significant work being done in this field, particularly "cache oblivious algorithms" (they are oblivious in the sense that they work well irrespective of the details of caching, whereas "cache aware" algorithms are tuned for a particular cache page size etc).

In contrast, media applications (audio and graphics, particularly 3D graphics) make use of some very repetitive structures - of course there's flexibility, but it's built on top of a large and very well-structured foundation. That allowed graphics acceleration to start simple with things like Blitting (a configurable but still very structured block copy operation) and line/polygon drawing. It meant that as graphics and sound processing got more sophisticated, vector operations became an obvious target for optimisation - first MMX (vectors of integers) then SSE (vectors of floats). It meant there was a pretty well defined structure for how a 3D graphics engine worked when the old fixed-function 3D graphics pipeline was moved onto 3D graphics hardware.

Yet with 3D graphics, what was once done in hardware is now done in software for flexibility - shaders are software, for example, which is how we get a massive range of different shaders giving the appearance of different materials. However, that software still works in a much more structured way than general software, and therefore can still use a much more specialised hardware platform. That's why your graphics card can now accelerate everything from physics to cracking passwords - applications that also fit that same model and can be implemented efficiently using the instruction sets that modern graphics processors provide.

Graphics processors now are the spiritual or actual descendants of digital signal processors, which were (and probably still are) a kind of specialised processor for dealing with digital signals (e.g. audio).

Which leads to a final point - sorting algorithms can be accelerated by hardware. Depending on your data, sorting can be handled using MMX or SSE (single-instruction-multiple-data) instructions on your processor, but there's probably not much point because of the memory bandwidth issue - maybe you can be a bit more power-efficient that way, though. However, you could also use your graphics hardware. That way, you can benefit from the often much better memory bandwidth for graphics cards. You won't be able to replace all sorts this way, but it's certainly possible and probably being done where appropriate.

IOW because of the various economic and practical issues, designing hardware specifically to accelerate a relatively narrow task like sorting doesn't really make sense. A feature that accelerates a wider range of tasks, or which makes existing acceleration hardware applicable to a wider range of tasks often makes much more sense.

Title: Why don't computers come with specialized hardware such as sorting networks?

Body: Instead of programming the way we do, why don't we make specifications of common tasks such as "sorting", and then let the environment compile it to make best use of it's hardware? This way, we could ship computer with new specialized hardware such as sorting networks, and it would automatically work with existing code.</p>


答:
First of all, computers come with specialized hardware.  Every laptop and desktop computer sold for quite a few years now has a specialized co-processor, a Graphics Processing Unit, that handles visual-processing algorithms, such as video and gaming applications require.  Very large computers (e.g., "supercomputers", IBM's System Z family) have a variety of specialized processors to handle numerical processing ("vector processing"), etc.

Secondly, sorting is one of the best-researched aspects of computing, and turns out to be far too complex to build into hardware for more than the simplest cases.  Sorting is all about speed and correctness.  Speed depends on the choice of algorithm, the type and variation in the data, and the volume of data.  Correctness depends on the type and context of the data.  It is positively trivial to sort a medium-sized array of integers that fit inside the CPUs native word size (e.g., 31 or 63 bits plus sign).  Sorting character strings that contain more than merely ASCII values is extremely complex - IBM published a 500+ page book 20 years ago just discussing the issues of character sets in the context of national boundaries and common usage.  And then there's the question of non-contiguous data - sorting a linked list involves chasing pointers all over memory.


问:
Best practices for sharing tiny snippets of code across projects
I always try to follow the DRY principle strictly at work; every time I've repeated code out of laziness it bites back later when I need to maintain that code in two places.

But often I write small methods (maybe 10 - 15 lines of code) that need to be reused across two projects that can't reference each other. The method might be something to do with networking / strings / MVVM etc. and is a generally useful method not specific to the project it originally sits in.

The standard way to reuse this code would be to create an independent project for the reusable code and reference that project when you need it. The problem with this is we end up in one of two less-than-ideal scenarios:

We end up with tens/hundreds of tiny projects - each to house the little classes/methods which we needed to reuse. Is it worth creating a whole new .DLL just for a tiny bit of code?

We end up with a single project holding a growing collection of unrelated methods and classes. This approach is what a company I used to work for did; they had a project named base.common which had folders for things like I mentioned above: networking, string manipulation, MVVM etc. It was incredibly handy, but referencing it needlessly dragged with it all the irrelevant code you didn't need.

So my question is:

How does a software team best go about reusing small bits of code between projects?

I'm interested particularly if anyone has worked at a company that has policies in this area, or that has come across this dilemma personally as I have.

note: My use of the words "Project", "Solution" and "Reference" come from a background in .NET development in Visual Studio. But I'm sure this issue is language and platform independent.

答:
GitHub has a pretty useful tool for saving code snippets https://gist.github.com/

It stores your snippets as git repositories that you can keep private, or use to share snippets with other people.


问:
Differences between a Unified Process and an Agile project plan?
There've been many discussions on SO about the differences between (Rational) Unified Process and the Agile methodology. Can someone please give me an example on how different a project plan would be if there are 2 teams doing the same project, but following these 2 different methods? </p>

答: Agile methodology is based on the principle that any change in the iteration must cost the least to the developers. Thus changes from the customers are welcomed. Where as the Rational Unified Process is based on the principle that development of software must be such that changes are least. Thus RUP requires more experienced developers than Agile.</p>

OwnerDisplayName: Martin

ContentLicense: CC BY-SA 2.5


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: Unit Testing. This is a great way to codify your assumptions on how the code is to be used.</p>


问:
Describe the best deployment environment you've worked with
The Joel Test includes the question:

Can you make a build in one step?

Which is important, but I'm wondering, how streamlined have some of the deployment processes been?

All software from shrink-wrap to web applies: what's the best deployment environment you've worked with, and what steps were involved?

答:
Granted this is now rather dated, but I used to have the following be the steps to deploy my code many moons ago that I found to be the best I've had:

Check-in my code changes into Visual SourceSafe.

Get Latest Version on my boss' machine.

Compile the solution that produced a few DLLs.

Show that the new code worked like it should.

Disconnect the production server from the Internet to update it without interference.

Copy the binaries onto the production server.

Start IIS.

Redial back into the internet on the ISDN line used.

This was back in the late 1990s when I was programming in Visual C++ on NT 4.0 for a dot-com.  Most of the deployment processes since this have gotten more complicated in having nAnt tasks and other extra stuff like dealing with load balanced production servers whereas back in the day we just had the one production box.

Course handing the process over to a release engineer is better but isn't quite the same as if I put the code into the wild.


问:
The Proper UML Model of a System for Non-Technical Boss
I've taken on some side work for this non-profit and last week was my first week on the job. They have two SQL Server Databases each with many tables in them that represent over 20 different applications such as

Course signup - Trainers can signup to teach different available classes

Course Approval form - trainers complete this form to get new courses approved to be added to the list of available classes.

Schedule - schedule of important dates for a term (holidays, start date for classes, etc.)

Trainer - list of all trainers and other information about a trainer (contact info, education, etc.)

Training Calendar - List that students can look at to see what's available for the current term

Training plan - a report that is printed for student with all of the classes they've signed up for

Certificate - Print a certificate for a student once the training course has been completed

There are about 15 other applications but it's all related to trainers, training, courses, students, etc.

This data is all over the place as there are no relationships between tables and very tedious processes have to be done to complete simple task. For example, for every new term you have to copy the data in the "old" table, create a new table, paste the old data into the new table and append the new data for the current term to the new table. So there's a table for every term (3 terms per year) for the past 10 years and that's only the beginning.

There's a lot of copying and pasting from Excel to SQL Server to get the data into the database and their front-end to manipulate the data isMS Access which I'd like to replace with ASP.NET (they have IIS 7).

To properly architect this and have good documentation, I've installed Visio 2013 and I'm learning about UML. So that boss can know exactly how this system will be re-architected, and how all the pieces will fit together what UML diagram should I create for him? Would that be a component diagram? I need to give him the 10,000 foot view so something like use-case, sequence, or database diagrams is way to low-level for him.

答:
I would opt for using a Package Dependency/Domain Model diagram to relate all the various applications([super] classes) you have found. Obviously you will do this on a very very high level of abstraction first, then gradually dive deeper. This should effectively help you develop your ASP.NET application when it comes down to how to access, edit and store the data for retrieval into the front end system.

When and while you have a growing understanding of the business-data flow, you could also develop an Activity Diagram or a Business Process Diagram. The Activity Diagram should be easiest in Visio however if you are familiar with the BPM Notation, grab a stencil if you don't already have one; search "Visio 2003 BPMN" in your favourite search engine and you should get something like this.

These two diagrams are very useful for your eventual redesign work (requirements gathering), so doing them now, and showing them to those who know and understand the business will help you get refinements and an accurate representation of what the system is doing versus what it is expected to do. Review, review, review your work with those who are working there as much as you can so they all gradually 'learn' the benefits of what you are doing and the approach you are taking.

Here is a tip: whenever I draw diagrams which may look complex, I put them in PowerPoint and disguise them with small bullet points which help the business to understand where I am going with this.

Continue building the Glossary (in Excel) of every terminology or definition they have of their processes - just as you have done above. It works very well in a presentation when you have the terms spilled out clearly to back your designs.

Remember your UML Model is a collection of diagrams and descriptions so you are definitely on the right path. I am sure these can inspire the data model for communication and review when you move to the next phase.


问:
How to design a good receipt number
I am developing a web application, this application will need to generate receipt number for every confirmed transaction.

What is a good receipt number? I think a receipt number should not be just a running number generated by database, but it should have some meaning beyond just a unique running number.

Here is what I have come up with so far,

```<code>Format: EYY-ddd-XXXXXXX
Example output: E13-146-0000001
</code>```

Where:

E : It is just a to signify this receipt number was generated by my system. This value is always E.

YY : Is the current year the receipt was generated, so in this case it is 13

ddd : Is the day of the year, 146 is May 26 (in 2013).

XXXXXXX : Is a 7 digit running number, up to 9,999,999

So my system can generate up to 10 million unique receipt numbers daily until 2099.

What do you think? Is this sensible? Any suggestion is appreciated.

Update

Judging from the comments so far, it looks like there is no specific 'pattern' or 'best practices' for receipt number. My intention in asking the question is to know whether there is specific best practises in generating the number that I should know about. Looks like I am free to use whatever pattern I feel sensible.

Other requirements

As short as possible (that is why I didnt go for YYYYMMdd-XXXXXXX)

Somewhat not to obvious (YYYMMdd is way to obvious).

Should be fixed length. (Easier to detect if customer entered invalid receipt number)

Can generate fairly large numbers (10 million a day seems sensible, though I doubt my system will be that popular)

Can be made into QR code (so staff can scan and verify the number is valid)

Someone mentions about error detection code like ISBN, seems good but I havent read it yet.

答:
Unless encoding the extra information serves some useful purpose you didn't describe in your question, don't attempt to build any kind of intelligence into your numbers.  It will eventually backfire, often in a way that will make recovery difficult and expensive.

My advice?  Use an integer sequence number and be done with it.  They're easy to deal with, and if you're using them as identifiers in a database, they store compactly and index much more quickly than strings.

As short as possible

If you're actually doing only 10,000 transactions per day, you're going to have three unnecessary zeros in every receipt number pretty much forever.  That makes your numbers 30% larger than they need to be.  More digits increases the odds there will be a communication or keying error.  Someone unfamiliar with your scheme won't know that there should be seven digits in your sequence number and will have to count out a string of leading zeros for the low-numbered receipts -- you'll have a bunch of those daily -- and that will consume more time than having them will save.

An integer sequence number won't get any longer until it runs out of digits in its current size and can grow practically infinitely.  Days when you do low volume will delay the addition of digits.

Somewhat not to obvious (YYYMMdd is way to obvious).

Don't think for a minute that someone wanting to do something nefarious with your receipt numbers isn't going to look up at his calendar and notice that you're using the year and Julian day.  If the receipt number is your sole method of verifying that someone giving it to you is the customer who received it, you're going to get hacked hard.  Amateurs hack systems, professionals hack people.

Should be fixed length. (Easier to detect if customer entered invalid receipt number)

It's not really any easier; if the number isn't in your database, it's not valid.  There's plenty of potential for someone to enter an invalid number that's the right length.

Can generate fairly large numbers (10 million a day seems sensible, though I doubt my system will be that popular)

A 64-bit unsigned integer can hold a maximum value of 9,223,372,036,854,775,807.  That will give you a billion unique numbers daily for the next 2.5 million years, longer if you're not doing that kind of volume.

Can be made into QR code (so staff can scan and verify the number is valid)

Using digits only assures that you'll be able to use any barcode format out there.  Linear barcodes scan a lot faster than QR and are readable under much worse conditions.  That should be taken into account if there's a warehouse involved.

Title: How to design a good receipt number


问:
Is there a loophole in the GPL that allows proprietary software to be linked with GPL libraries?
Let’s examine a hypothetical scenario:

Company X writes a proprietary program (A) that dynamically links with a proprietary library (B). Company Y wants to use a replacement library (C) licensed under the GPL, and so writes a wrapper library (D) that dynamically links to both A and C and translates the API calls used by A to the API calls used by C.

As D is intended to be used with C, and uses C’s API calls, it is a derivative work of C and must therefore be distributed under the terms of the GPL*. As a result, the combined work of A and D must also be distributed under the terms of the GPL, which is impossible given that Company Y does not possess the source code for A. That said, so long as Company Y distributes D by itself, there is no problem. However, regardless of Company Y’s actions, Company X does not violate the GPL by distributing A, even without B. The mere existence of D does not mean that A is suddenly a derivative work of C (through D) that must be licensed under the GPL as well.

Now this is the loophole: there is nothing that stops Company X from writing its own version of D, distributing it separately from A, and telling end-users to use D instead of B when running A. It seems that a company is capable of designing a proprietary program to use a GPL library without violating the GPL, so long as a wrapper module is used to insulate the proprietary program from the GPL library and that module is distributed separately.

Am I correct in my reasoning? Is this a real loophole in the GPL?

*D is also a derivative work of A, but for the purposes of this scenario, Company X has explicitly authorized the creation of D and allowed it to be licensed under the GPL.

答:
IANAL, but here is my opinion of what is allowed within the limits of GPL:

distribute the combined work "A - B" in public: fine, can be done under any proprietary license

create a wrapper lib D for C by Y: fine, this does not imply that A has to be put under GPL

use the combined product "A - D - C" internally by Y: also fine, GPL does not require to open source A as long as the combination is not distributed to the public

distribute the combined work "A - D - C" in public: this will require A to be open-sourced and to be put under GPL (and it does not matter if X or Y distributed this combination; additionally , if Y wants to do this that, they would require a distribution license for A from X, of course)

The interesting question now is: can D & C be distributed separately as open source under GPL, A&B (or just A without B) be distributed under a proprietary license, and the end-user replaces B by D&C by himself ?

Here the final modification to "A-B" which makes A dependent on libs D & C is done by the end user - after distribution. So one could argue that the final modification is only done internally by the end user. And it seems that this indeed is possible without violating the GPL - and what you get is a working combination of "A-C&D" where A is under proprietary license and C&D under GPL.

Of course, a lawyer or a judge may have a different opinion on that. To get a final answer, I think you must wait until someone tries it out and a second one sues him.

I guess for most systems, it will be hard to create such a constellation without designing "A" from the beginning in a way so it will work seamlessly with either B or C. And in this case, one could come to the suspicion that A was somehow derived from C.

EDIT: thinking a while about this, a similar situation came into my mind: writing and distributing GPL licensed plugins for closed-source applications. Lets take for example, Photoshop. I don't think someone would seriously try to enforce Adobe to open-source Photoshop just because there exist some GPL plugins from third-party vendors. Here, not even a "wrapper lib" is needed since there exists a well-defined interface. However,  would it change the situation if Photoshop would incorporate some of its central functions from a GPLed third party plug-in? I think for such a case it may become really hard to decide where to draw the line, at which point the closed-source product is a work "based on" the GPL lib.

EDIT2: There are dual-license libs available, with a GPL license for non-commercial use and a proprietary license for commercial use like this one, for example. So your "loophole" would mean to develop a product based on such a lib (using the commercial version, so GPL does not apply to your product), deliver your product as closed-source without the lib to the public and let the end-user get and install the GPLed version by himself. For such a case, I guess the vendor of the lib will have a good chance of sucessfully sue you for license violation (if you don't pay for his lib, of course). Is it worth the hassle? Probably not. Especially in the example I linked to, you would have to buy the lib either, since the pricing is not dependend on how often you sell your product, but only how many devs are using the lib during development.

Finally, because of those legal risks, if I intend to use open-source libs within a closed-source product, I would avoid GPL libs if possible, and not try to make use of this "loophole". LGPL or GPL with linking exception is much safer, or any kind of non-viral OS license.


问:
MVC pattern with JSF-Spring-MyBatis webapp
I've a Java webapp with these frameworks and I want to know if my implementation meets with MVC pattern:

Controller Layer (V)

I'm using JSF

```<code>@ManagedBean
public class Controller{
    @ManagedProperty("#{business}")
    private Business business;

    public void insert(){
        business.insert();
    }
}
</code>```

Business Layer (C)

I'm using Spring

```<code>public interface Business{
    public void insert();
}

@Service("business")
public class BusinessImpl implements Business{
    @Autowired
    private DaoMapper mapper;

    @Override
    @Transactional
    public void insert(){
        mapper.insert();
    }
}
</code>```

Data Layer (M)

I'm using MyBatis (This java interface is associated to XML file of MyBatis)

```<code>public interface DaoMapper{
    public void insert();
}
</code>```

My layers implemented MVC pattern? I'm confused :S...

答:
No, your layers, as described, do not implement the MVC pattern.

Within the MVC pattern, the Model contains most of the application-specific logic, in particular the business logic and all the layers below it. So, in your three-layer structure, that would be both the Business and the Data layers.

The View contains the code for driving the the user interface. The View classes produce the HTML, JSON or XML that gets displayed by the browser.

The Controller classes tie it all together. They receive the requests from the browser, and instruct the Model and View to take the relevant actions based on that request.


问:
Summarize changes (insertions and deletions) in Git
I want to look at how my code base has grown over time. GitHub has a nice +/- display along the list of checkins which gives a sense of this. Is there something similar I can use with my Google Code hosted repo or offline?

答:
There are a few options natively in Git to get data about the changes.

git log --stat will show the amount each file was changed.

git whatchanged gives some detail into the files that were modified.

git diff --stat <sha1> <sha2> gives the files and the amount of changes between two commits.

There are many other blogs that give various formatted logs.  A google search can point you at these.  Also doing git log --help will give the various options for formatting the history of your repo.  Git has the ability to give you quite a bit of data through the various command line log options (filtering by author, file, etc).


答:
If you know the commits you would like to compare, you could try using the git diff command with the --stat argument. It gives output like this:

```<code>$ git diff --stat HEAD^ HEAD
_layouts/default.html |    1 -
_sass/_variables.scss |    2 +-
_sass/main.scss       |   42 +++++++++++++++---------------------------
3 files changed, 16 insertions(+), 29 deletions(-)
</code>```

Title: Summarize changes (insertions and deletions) in Git

Body: I want to look at how my code base has grown over time. GitHub has a nice +/- display along the list of checkins which gives a sense of this. Is there something similar I can use with my Google Code hosted repo or offline?

Body:
If you know the commits you would like to compare, you could try using the git diff command with the --stat argument. It gives output like this:

$ git diff --stat HEAD^ HEAD
_layouts/default.html |    1 -
_sass/_variables.scss |    2 +-
_sass/main.scss       |   42 +++++++++++++++---------------------------
3 files changed, 16 insertions(+), 29 deletions(-)


答:
Will many systems be generating these numbers at once? If so, then neither your system nor sequential numbers will be sufficient; there will be days when the internet isn't working, or a bug somewhere results in collisions, and so on.  If these things are true, I'd use a GUID (which is "unique enough"). If GUIDs aren't an option, I'd switch to hex and use a semantic numeric string like this:

```<code>EDDDDLLLLNNNNNNNNC
</code>```

Where E is your generic "I did this" flag, D is a hex string representing the year and date in hex, L is a hex string representing the source location (allowing 65,000 separate POS systems or other sources to use your system without collision), N is a simple sequence number for that source, and C is a check digit.

An example:

```<code>E3FDF00A2000000D2C
</code>```

3FDF represents 16351, or June 12, 2051. 00A2 represents your POS system. The 000000D2 represents that day's sequence number, and C is a check digit (calculated simply as (3FDF + A2 + D2) % F, which may not be algorithmically perfect).

If you are willing to relax the requirement that it be the same length every time, you can easily make it elastic, so that the above is rendered as:

```<code>E3FDF00A2D2C
</code>```

The first 9 digits are always the same, and the last digit is the check digit, so the remainder is the sequence number. If you are open to having a divider character, you could make it even shorter:

```<code>E3FDFA2-D2C
</code>```

Title: How to design a good receipt number

Body:
I am developing a web application, this application will need to generate receipt number for every confirmed transaction.

What is a good receipt number? I think a receipt number should not be just a running number generated by database, but it should have some meaning beyond just a unique running number.

Here is what I have come up with so far,

```<code>Format: EYY-ddd-XXXXXXX
Example output: E13-146-0000001
</code>```

Where:

E : It is just a to signify this receipt number was generated by my system. This value is always E.

YY : Is the current year the receipt was generated, so in this case it is 13

ddd : Is the day of the year, 146 is May 26 (in 2013).

XXXXXXX : Is a 7 digit running number, up to 9,999,999

So my system can generate up to 10 million unique receipt numbers daily until 2099.

What do you think? Is this sensible? Any suggestion is appreciated.

Update

Judging from the comments so far, it looks like there is no specific 'pattern' or 'best practices' for receipt number. My intention in asking the question is to know whether there is specific best practises in generating the number that I should know about. Looks like I am free to use whatever pattern I feel sensible.

Other requirements

As short as possible (that is why I didnt go for YYYYMMdd-XXXXXXX)

Somewhat not to obvious (YYYMMdd is way to obvious).

Should be fixed length. (Easier to detect if customer entered invalid receipt number)

Can generate fairly large numbers (10 million a day seems sensible, though I doubt my system will be that popular)

Can be made into QR code (so staff can scan and verify the number is valid)

Someone mentions about error detection code like ISBN, seems good but I havent read it yet.

Body:
Will many systems be generating these numbers at once? If so, then neither your system nor sequential numbers will be sufficient; there will be days when the internet isn't working, or a bug somewhere results in collisions, and so on.  If these things are true, I'd use a GUID (which is "unique enough"). If GUIDs aren't an option, I'd switch to hex and use a semantic numeric string like this:

EDDDDLLLLNNNNNNNNC

Where E is your generic "I did this" flag, D is a hex string representing the year and date in hex, L is a hex string representing the source location (allowing 65,000 separate POS systems or other sources to use your system without collision), N is a simple sequence number for that source, and C is a check digit.

An example:

E3FDF00A2000000D2C

3FDF represents 16351, or June 12, 2051. 00A2 represents your POS system. The 000000D2 represents that day's sequence number, and C is a check digit (calculated simply as (3FDF + A2 + D2) % F, which may not be algorithmically perfect).

If you are willing to relax the requirement that it be the same length every time, you can easily make it elastic, so that the above is rendered as:

E3FDF00A2D2C

The first 9 digits are always the same, and the last digit is the check digit, so the remainder is the sequence number. If you are open to having a divider character, you could make it even shorter:

E3FDFA2-D2C


答:
If you think of C as little more than a "high-level" assembler, and we make the assumption that Chris was not make mad optimizations to his assembly code in every routine, then I would imagine in terms of % time longer, then it might not be that much more for a skilled assembly programmer.

Assembly gets complicated when you're doing all those mad optimizations (vectorising operations, making use of special instruction sets (SSE, etc) bit twiddling, etc) that you simply can't do from C. If you're doing that stuff, then the time is actually in the "fiddle this bit, assemble, measure... fiddle this bit, assemble, measure..." loop and not in the actual coding. With a good macro assembler and a skilled programmer, then writing assembly is not a huge step down from writing C code.

Still, I wouldn't have been able to do it! I shudder to think about trying to initialize DirectX directly in assembly! (Edit: Wikipedia tells me that he wrote some parts in C to "interface with the Windows operating system" so I guess he wasn't initializing DirectX in assembly then... phew!)

Body:
From this question, I have another question about...

How long and what type of complexity would have been involved in Chris Sawyer writing most of rollercoaster tycoon in assembler?

In order to specify and break this question down, I am interested in;

Approximately how many man hours (have a guess) do you estimate it would have taken Chris to write the game by himself? Or alternatively give an approximate percentage of the ratio of assembler coding hours to say, writing the whole thing in C/C++.

Do the programmers that know assembler well think of this as an overly complex task for such a low level language abstraction? Apart from performance benefits is this just a freakish natural ability that Chris has, or a skillset worthy of learning to that extent? I'm interested if people think the complexity/performance thing is worth learning assembler that well (in order to write), or is it only "worth it" if you have a lot of naturally developed skills in assembler (presumably from working with hardware/hardware drivers/electronics/etc).


问:
Languages & Their Licensing?
Firstly, apologizes for any bad terminology, lack of research, or poor delivery of my question.

I should note that originally I had one big question, but I figured the first half is sort of independent, so I've posted it individually, link. My understanding of "commercial purposes" is so far based on the OP of that question.

So basically my next piece of work will be the first to be involved in a commercial purpose, so I want to learn how to make appropriate technology choices that puts me on the safe side of legal concerns, let's take Java for a case example:

I will assume that the only thing I need to worry about is the licensing of JDK.

It seems that the license for JDK is this one, which seems to not put any commercial concerns except for contents of table 1-1 from this link, which are stuff I never heard about, and probably won't cross.

From #2, and from various implications that JDK mainly adheres to GPL, and from what I understood from GPL, it seems Java is in the green when it comes to commercial purposes, provided the owner of the executable has also ownership of the corresponding source code.

Q1: So, are my previous conclusions correct?

Q2: The research process was really exhausting from my end, are there some key elements to pursue when checking these stuff? or are there online resources/communities that already did most of this verification research?

Forward thanks.

答:
Q1:

No, your conclusions are not entirely correct.

Beside the JDK license (which is relevant to determine if it allows you to develop the kind of application you want to develop), you must also consider the licenses of 3rd-party libraries that you might want to use in your application. These will largely determine if you can distribute the application under the conditions you have chosen. For example, you can't distribute a closed-source application that uses a GPL library.

With regard to your third conclusion, actually having the source code is not a consideration. The conditions with regard to the source code of the GPL (and other open-source licences) are satisfied if you can obtain it if you so desire. You are not required to actually have a copy of the source code to be able to use the software.

Q2:

You should not trust an online community of non-lawyers and pretend-lawyers to give you sound legal advise. Only a lawyer you hired for that purpose can be trusted for that.

That said, there are a few tips that might help you:

Very few licenses restrict how software can be used, and if there is a restriction, most often it will be to prohibit use for "ethically difficult" purposes (such as military use or pornography). There are a few licenses that prohibit the incorporation of the software in a commercial product.

One of the aims of Open source software is to give everyone using the software equal rights. So, for licenses on open source software it is unacceptable to put restrictions on how the software can be used (although it can put restrictions on the license that you can use on software the interoperates with it).

For most licenses, there is a layman's explanation floating around on the internet of what you can use it for and what the consequences are. Wikipedia is often a good first start, and if you don't understand it, you can always ask the distributor of the software or here. On the other hand, common sense also gets you quite a long way. The authors of a license usually don't try to trick you in using their software inappropriately.

Title: Languages & Their Licensing?


问:
Change of the complexity class through compiler optimization?
I am looking for an example where an algorithm is apparently changing its complexity class due to compiler and/or processor optimization strategies.</p>

答:
Tail Call Optimization may reduce the space complexity. For example, without TCO, this recursive implementation of a while loop has a worst-case space complexity Ο(#iterations), whereas with TCO it has a worst-case space complexity of Ο(1):

```<code>// This is Scala, but it works the same way in every other language.
def loop(cond: => Boolean)(body: => Unit): Unit = if (cond) { body; loop(cond)(body) }

var i = 0
loop { i < 3 } { i += 1; println(i) }
// 1
// 2
// 3

// E.g. ECMAScript:
function loop(cond, body) {
    if (cond()) { body(); loop(cond, body); };
};

var i = 0;
loop(function { return i < 3; }, function { i++; print(i); });
</code>```

This doesn't even need general TCO, it only needs a very narrow special case, namely elimination of direct tail recursion.

What would be very interesting though, is where a compiler optimization not just changes the complexity class but actually changes the algorithm completely.

The Glorious Glasgow Haskell Compiler sometimes does this, but that's not really what I am talking about, that's more like cheating. GHC has a simple Pattern Matching Language that allows the developer of the library to detect some simple code patterns and replace them with different code. And the GHC implementation of the Haskell standard library does contain some of those annotations, so that specific usages of specific functions which are known to be inefficient are rewritten into more efficient versions.

However, these translations are written by humans, and they are written for specific cases, that's why I consider that cheating.

A Supercompiler may be able to change the algorithm without human input, but AFAIK no production-level supercompiler has ever been built.

Body:
Tail Call Optimization may reduce the space complexity. For example, without TCO, this recursive implementation of a while loop has a worst-case space complexity Ο(#iterations), whereas with TCO it has a worst-case space complexity of Ο(1):

// This is Scala, but it works the same way in every other language.
def loop(cond: => Boolean)(body: => Unit): Unit = if (cond) { body; loop(cond)(body) }

var i = 0
loop { i < 3 } { i += 1; println(i) }
// 1
// 2
// 3

// E.g. ECMAScript:
function loop(cond, body) {
    if (cond()) { body(); loop(cond, body); };
};

var i = 0;
loop(function { return i < 3; }, function { i++; print(i); });

This doesn't even need general TCO, it only needs a very narrow special case, namely elimination of direct tail recursion.

What would be very interesting though, is where a compiler optimization not just changes the complexity class but actually changes the algorithm completely.

The Glorious Glasgow Haskell Compiler sometimes does this, but that's not really what I am talking about, that's more like cheating. GHC has a simple Pattern Matching Language that allows the developer of the library to detect some simple code patterns and replace them with different code. And the GHC implementation of the Haskell standard library does contain some of those annotations, so that specific usages of specific functions which are known to be inefficient are rewritten into more efficient versions.

However, these translations are written by humans, and they are written for specific cases, that's why I consider that cheating.

A Supercompiler may be able to change the algorithm without human input, but AFAIK no production-level supercompiler has ever been built.


答:
Your code specifically implementing MVC pattern then No but is it actually MVC, well that answer is YES.

As Bart van Ingen Schenau points out the data as well as behavior to retrieve the appropriate data are encompassed by the model.  This is correct but the important thing to remember about JSF is that the framework itself is inherently MVC.

JSF Model

The managed bean and Spring injected business logic encapsulates the model.

JSF View

Your XHTML markup represents the View components.  This markup also contains Controller hooks that bind your Model (Managed Beans, ORM entities, etc...) to the View components.

JSF Controller

This is just FacesServlet.  It is the controller that creates the interaction between View and Model so that the web developer doesn't need to worry about this.

Title: MVC pattern with JSF-Spring-MyBatis webapp

Body:
I've a Java webapp with these frameworks and I want to know if my implementation meets with MVC pattern:

Controller Layer (V)

I'm using JSF

```<code>@ManagedBean
public class Controller{
    @ManagedProperty("#{business}")
    private Business business;

    public void insert(){
        business.insert();
    }
}
</code>```

Business Layer (C)

I'm using Spring

```<code>public interface Business{
    public void insert();
}

@Service("business")
public class BusinessImpl implements Business{
    @Autowired
    private DaoMapper mapper;

    @Override
    @Transactional
    public void insert(){
        mapper.insert();
    }
}
</code>```

Data Layer (M)

I'm using MyBatis (This java interface is associated to XML file of MyBatis)

```<code>public interface DaoMapper{
    public void insert();
}
</code>```

My layers implemented MVC pattern? I'm confused :S...


答: A compiler which is aware that the language is using big-num doing strength reduction (replacing multiplications by the index of a loop by an addition) would change the complexity of that multiplication from O(n log n) at best to O(n).</p>

Title: Change of the complexity class through compiler optimization?

Body: I am looking for an example where an algorithm is apparently changing its complexity class due to compiler and/or processor optimization strategies.</p>


问:
Tracking progress via a burndown chart when sprints overlap
Our team has adopted some agile practices to help us develop and deliver our software to our client. We adopt practices as needed (as problems/challenges were identified) rather than jumping wholesale into the agile camp. The big ones for us are maintaining a product and sprint backlog and developing and delivering new versions in roughly one month sprints. We do estimate the items in our sprint backlog to guesstimate what we can deliver within a sprint. However we do not track progress very well so it's difficult to know whether or not we are on target.

The next step in our evolution appears to be to improve our progress tracking ability. We are looking at using burn down charts to aid us. However, our sprints overlap significantly due to established and procedures for our software promotion schedule. We have the following established events:

Development begins on Sprint 1 and continues until code freeze. That said we do test our software throughout this phase with the development and test groups.

Code freeze stops development on Sprint 1 functionality. We have a small window to finish or fix any issues before the next event acceptance promotion 1. In addition development begins on Sprint 2.

Acceptance promotion 1 promotes the application to the client's acceptance environment where it is tested by our test group. Issues identified in testing may be fixed during a small window before acceptance promotion 2. Meanwhile Sprint 2 development continues.

Acceptance promotion 2 promotes the application one last time to the client's acceptance environment to validate any issues identified during acceptance promotion 1. Sprint 2 development continues.

Production promotion promotes the application to production and it is tested by our test group and Sprint 1 is officially completed. This is when it is truly done.

A visual depiction of this can be seen below. The average calendar time between development begins and code freeze is four weeks. The average time between code freeze and production promotion is two weeks.

larger resolution version

This schedule of events is not within our control. Client policy dictates when application software is promoted from Test to Acceptance to Production. No application code may be modified beyond our second fix window. We do not perform the promotions. This is accomplished by '3rd' parties at the client's site, again, due to policy.

In addition, some tasks such as data updates, can and do happen outside of this schedule. Certain data updates follow the code (for instance, when there is a schema dependency) but others such as data bugs or new data can and do occur outside of this schedule. This is due to fewer restrictions as to what may be modified on the clients environment and when. Only application code is restricted to these specific milestones. Data and configuration are exempt and technically may be modified as needed. We are considering tightening this up so that data updates follow the same schedule as the code.

Given this scenario, our overlapping sprints, I have a several questions?

What is the proper way to create/handle a burn down chart when we burn development, testing, and data hours from the previous sprint while also working towards the next one?

I think we have 2 concurrent burn down charts on for each sprint.

Assuming we at most have two burn down charts how do we best display the cumulative burn down when the sprints overlap so as to understand our actual workload progress on each so as to best set us up for success?

If items are found in Sprint 1 after code freeze that need to be addressed in Sprint 2 how does that our Sprint 2 backlog and burn down?

I assume that for critical items we need to bump out less critical Sprint 2 items to make room for the incomplete Sprint 1 items. Non critical items will be bumped to Sprint 3 or later.

What would be the proper start and end dates for the burn down chart?

It seems the best option would be to reflect reality. Sprint 1 is not truly done (including testing and data updates) until production promotion and its final testing. So the start date would be development begins
and the end date be production promotion despite any overlap.

What else am I missing? What else could or will bite us?

答:
By making code freeze a solid line and only promoting tested code you can eliminate the ambiguity of that two week time frame where sprints overlap.  This will however require you to have the testing done sooner and automated testing will allow you to fix a bug and ensure that it stays fixed.

Perhaps adopting a policy that your master branch of development is always ready to be pushed to production and have all testing done prior to committing code to this master branch.  If features run over in time or scope simple don't push them into the master branch.

A burndown chart would be easier to implement given a list of desired features and tasks for a sprint.  If at code freeze - 1 week you have 3/5 features pushed to the master you have a clear idea of where you stand.  If you wish finer grained control breakdown features into a burndown that aggregates into The master burndown.


问:
Simple way to deploy Winform application to website
First of all, I know there is no perfect answer to my question. It is a bit personnal, but I'm sure many programmers face the same dilemma when they get from regular desktop applications to client/server web applications: what is the "best" language/framework to use? There are a lot of great solutions out there, all having more or less the same advantages and features. So, I would like an advice based on my needs and background.

I'm fairly experienced with VB and PHP, and I have some Javascript and C# knowledge. I currently have a perfectly functionnal C# Winform app that I would like to deploy to my website. The application uses the user's webcam to recognize a game card through a perceptual hashing algorithm and displays details of the best matched card from a MySQL database. Here's how I'd like the web version to perform:

the server sends a recordset of the whole datebase's cards ID/hash matches to the client

the client "scans" his card with his webcam and creates a hash

the client searches for a match between this hash and the ones in the recordset

the client returns the best match to the server

the server displays information of the card from the database

My objectives :

limit (if possible) the need for the user to install 3rd party software (flash, java, activex or other plugins)

create a solution that integrates well in a Windows/Apache/PHP environnement

create a solution that is, ideally, cross-platform

using a language/framework combination on which it's simple to write, debug and maintain code

So far, I'm eyeing Python on Eclipse or Javascript on Visual Studio. I read interesting stuff about Ruby on rails, but the learning curve might be a bit steep for me. I don't mind learning a new language and coding the app again from scratch, but I'd like as much as possible to use the skills and code I already have.

Any thoughts? Thanks!

答:
I have an immediate concern with the webcam.  Sadly I am not sure this is possible without the use of third party apps like flash or java.  Not to say those are bad ideas.  You might want to consider the use of JAVA for this.

With that in mind lets talk about converting your current c# winforms app to a web app.  One of the core concepts of programming is seperation of concerns.

This means you have your application divided into three conceptual layers.  They are the Data Access Layer, the Business Logic layer, and the presentation layer.  The data access layer is for data access, db acccess and general getting of data.  The business layer is for accessing the data layer, grabbing the data (without caring about how it got the data) and manipulate the data and then passes that onto presenation layer.  Whichs responsiblity is for end user interaction.

Lets pretend you did this or something like this when developing your application.  That means all that is yet to do is to redesign the presentation layer to be web exposed as opposed to winforms exposed.  The front end is always (in my opinion) the hard part.  So this will not be fun, but could be useful.

the problem you will most likely face is the input/output differences between winforms and web sites.  You lose a lot of easy to get to direct stuff with winforms when you do this.  Alot of it can be done in different ways using a combination of html5, css and javascript.

You can also bridge the gap with a java based front end that calls on your .net backend.  So there are plenty of options for you.

Good luck


问:
How will writing the transaction part in Java benefit the security of the application, when all other parts are being written in PHP?
A friend of mine while working on a PHP application asked me to write one part of the application in Java. The part that involved transactions. He said it will be better to write this portion in Java. He talked about how secure it will be!

Though I was too busy to  help him then, I want to know the essence of this idea. Why he was trying to use Java when he wrote the most part in PHP? Will it really boost up the security? And writing transactions in Java is only concerned with security?

The thing seems very interesting but I really have no idea, what it is! Please provide some insight into the topic.

Note: When I say transaction, it involves everything. From accessing account to transferring money.

答:
Correctly utilizing a Language's strong type system goes a long way towards reducing certain types of bugs - variants of the "provided the wrong argument to that method" bugs.

For example, think of the following function:

```<code>transfer_money(from_account, to_account, amount)
</code>```

In an weakly-/untyped language, it's easy to confuse the from_account and to_account parameters; It's also common to use wrong units in amount (Dollars vs Cents, for example).

These errors would require rigorous testing to be found, or very thorough manual code-reviewing.

OTOH, an (extreme) use of types will result in this kind of method:

```<code>transfer_money(SourceAccount from_account,
               TargetAccount to_account,
               MoneyAmount   amount)
</code>```

The same kind of errors here will produce a compilation error, which makes them a lot less likely to actually reach production.

Now, this isn't to say that Java is inherently safer than PHP; Nor that a similar system cannot be easily implemented in PHP; Nor that it's actually common to use types in this fashion in Java; But it does give Java a tiny edge over PHP for critical paths of code. From a Safety Engineering POV, it makes Java "safer".

Body:
Correctly utilizing a Language's strong type system goes a long way towards reducing certain types of bugs - variants of the "provided the wrong argument to that method" bugs.

For example, think of the following function:

transfer_money(from_account, to_account, amount)

In an weakly-/untyped language, it's easy to confuse the from_account and to_account parameters; It's also common to use wrong units in amount (Dollars vs Cents, for example).

These errors would require rigorous testing to be found, or very thorough manual code-reviewing.

OTOH, an (extreme) use of types will result in this kind of method:

transfer_money(SourceAccount from_account,
               TargetAccount to_account,
               MoneyAmount   amount)

The same kind of errors here will produce a compilation error, which makes them a lot less likely to actually reach production.

Now, this isn't to say that Java is inherently safer than PHP; Nor that a similar system cannot be easily implemented in PHP; Nor that it's actually common to use types in this fashion in Java; But it does give Java a tiny edge over PHP for critical paths of code. From a Safety Engineering POV, it makes Java "safer".


问:
Where should I put my method
I am writing a Java program using the MVC design pattern.

I have classes Item and Supplier. In the database they are connected through a item_supplier table.

I'm writing a method which will give me all suppliers for a specific item (using itemID):

public ArrayList<Supplier> getItemSuppliers(int itemID)

I have a DB layer as well and I have DBItem and DBSupplier. Where should this method go? I will use it only (mostly) on my ItemUI so I am thinking of DBItem as the correct place.

--

Usually when we have the SalesLineItem pattern (Sales * - 1 SalesLineItem 1 - * Item) we have a separate class, but in that case, do I need such as my only interaction with that table (item_supplier) will be with this printing (and one updating) method?

Basically, do I need to do a ItemSupplier model layer class and respectively DBItemSupplier or can I just have those two methods getItemSuppliers and updateItemSuppliers on either DBItem or DBSupplier (and if the latter, where?)

答:
Putting that method on your DBItem class is probably the right thing to do. I assume that the DBItem class encapsulates all the queries necessary to receive the data associated with an item, in which case this is the correct thing to do.

As for whether you need the joining table in your Many-to-Many relationship, probably not. You usually do not need to represent this joining table in your model layer, it is enough to have Item.Suppliers and Supplier.Items collections on your model classes.

EDIT

I should point out, that there is a fairly simple question to ask, in order to decide whether to include the joining table at your model layer: "is this table a weak entity, or a strong entity?". If it is a weak entity then you don't have to include. Now, what is a weak entity? A weak entity is one that would not exist on its own, ie it simply joins to other entities together. In fact, even if it had other properties of the relationship between those two other entities, if it wouldn't make sense to have one or other end of the relationship missing (or both missing even), then it is a weak entity. Of course if your weak entity had properties that you wanted to surface through your model, you might decide to include it anyway.

Title: Where should I put my method


答:
Lets take a simple program which prints the square of a number entered on the command line.

```<code>#include <stdio.h>

int main(int argc, char **argv) {
    int num = atoi(argv[1]);
    printf("%d\n",num);
    int i = 0;
    int total = 0;
    for(i = 0; i < num; i++) {
        total += num;
    }
    printf("%d\n",total);
    return 0;
}
</code>```

As you can see, this is a O(n) calculation, looping over and over again.

Compiling this with gcc -S one gets a segment that is:

```<code>LBB1_1:
        movl    -36(%rbp), %eax
        movl    -28(%rbp), %ecx
        addl    %ecx, %eax
        movl    %eax, -36(%rbp)
        movl    -32(%rbp), %eax
        addl    $1, %eax
        movl    %eax, -32(%rbp)
LBB1_2:
        movl    -32(%rbp), %eax
        movl    -28(%rbp), %ecx
        cmpl    %ecx, %eax
        jl      LBB1_1
</code>```

In this you can see the add being done, a compare and a jump back for the loop.

Doing the compile with gcc -S -O3 to get optimizations the segment between the calls to printf:

```<code>        callq   _printf
        testl   %ebx, %ebx
        jg      LBB1_2
        xorl    %ebx, %ebx
        jmp     LBB1_3
LBB1_2:
        imull   %ebx, %ebx
LBB1_3:
        movl    %ebx, %esi
        leaq    L_.str(%rip), %rdi
        xorb    %al, %al
        callq   _printf
</code>```

One can now see instead it has no loop and furthermore, no adds.  Instead there is a call to imull which multiplies the number by itself.

The compiler has recognized a the loop and the math operator inside and replaced it by the proper calculation.

Note that this included a call to atoi to get the number.  When the number exists already in the code, the complier will pre-calculate the value rather than making actual calls as demonstrated in a comparison between the performance of sqrt in C# and C where sqrt(2) (a constant) was being summed across a loop 1,000,000 times.

Body:
Lets take a simple program which prints the square of a number entered on the command line.

#include <stdio.h>

int main(int argc, char **argv) {
    int num = atoi(argv[1]);
    printf("%d\n",num);
    int i = 0;
    int total = 0;
    for(i = 0; i < num; i++) {
        total += num;
    }
    printf("%d\n",total);
    return 0;
}

As you can see, this is a O(n) calculation, looping over and over again.

Compiling this with gcc -S one gets a segment that is:

LBB1_1:
        movl    -36(%rbp), %eax
        movl    -28(%rbp), %ecx
        addl    %ecx, %eax
        movl    %eax, -36(%rbp)
        movl    -32(%rbp), %eax
        addl    $1, %eax
        movl    %eax, -32(%rbp)
LBB1_2:
        movl    -32(%rbp), %eax
        movl    -28(%rbp), %ecx
        cmpl    %ecx, %eax
        jl      LBB1_1

In this you can see the add being done, a compare and a jump back for the loop.

Doing the compile with gcc -S -O3 to get optimizations the segment between the calls to printf:

        callq   _printf
        testl   %ebx, %ebx
        jg      LBB1_2
        xorl    %ebx, %ebx
        jmp     LBB1_3
LBB1_2:
        imull   %ebx, %ebx
LBB1_3:
        movl    %ebx, %esi
        leaq    L_.str(%rip), %rdi
        xorb    %al, %al
        callq   _printf

One can now see instead it has no loop and furthermore, no adds.  Instead there is a call to imull which multiplies the number by itself.

The compiler has recognized a the loop and the math operator inside and replaced it by the proper calculation.

Note that this included a call to atoi to get the number.  When the number exists already in the code, the complier will pre-calculate the value rather than making actual calls as demonstrated in a comparison between the performance of sqrt in C# and C where sqrt(2) (a constant) was being summed across a loop 1,000,000 times.


问:
Best github repository layout for snippets in multiple programming languages
I have to create a github-presence for an open-source organization. The aim is to distribute code snippets and reference implementations in different programming languages.

These contributions are going to be (ideally) created by people outside of the organization and should be collected.

I know that good practice is to create one repository per project. To this end, each implementation (in a specific programming language) should be considered a standalone project and should get its own repository. The point is that this approach makes hard for external people to contribute, because github pull-requests can only be made against existing repositories.

By creating a single repository with a subdirectory per programming language code contribution becomes easier, but I'm afraid that some IDEs may complain about the directory layout.

I'd like to know whether someone already solved this very specific problem in a satisfactory way.

答:
You want to distribute code snippets and reference implementations. By nature, these are not compile-able. I can assume the following are true:

An IDE will not be able to serve your needs anyway, since the code will be incomplete

Code for each language will have further segregations. e.g. categories or tags. So there will be some extra folder structure for each language

Given the above two, having a single repository will likely complicate things. You either have to go for multiple repositories (safest approach), or go for a single repository with different branches. And forget about the code being cleanly editable in an IDE.

I'd suggest go for separate repositories for the following reasons:

It becomes easier to manage Issues for each language

You can give specific open source contributors access to some of these repositories. For e.g. a prolific Java contributor can be given access only to the Java repository

Free up your branches for other stuff (e.g. versions of the same language)

Its premature to worry about contributors not being able to create new languages. You could already create empty repos for most of the popular languages, and you can have some kind of Form in your site to raise a request for new languages.

Edit: Minor Clarification


答:
I'm not sure I agree with Joel on this one - surely no steps are better than one?

We use Hudson to script our builds (continuously on both Mac and Windows), including building installers and CD images for the few times we actually send out a real box. We always test from the installer in QA.

We also use Hudson to copy the installers to the "beta" area of our live website once per day.

So essentially we can deploy to users every day in no steps. When we make an official release, we just switch the filenames of the installers in CMS to make the current beta installers the release ones, and change the Ant build script to switch to the new version number (which becomes the new beta).

Having this set up and working makes release day a complete non-event (which is exactly what it should be). We've not had a mistake on release day for a while now (it used to be a regular occurrence)!

Title: Describe the best deployment environment you've worked with

Body:
The Joel Test includes the question:

Can you make a build in one step?

Which is important, but I'm wondering, how streamlined have some of the deployment processes been?

All software from shrink-wrap to web applies: what's the best deployment environment you've worked with, and what steps were involved?


问:
Saving user profiles in SQL database
So, I got a table UserProfiles in my database, that, similar to C#'s Settings file, holds a property with the appropriate datatype and the specified setting in the profile.

Now each time I add a new setting, I need to update the database, the model and end up rewriting the queries.

I've then thought about changing the table to only contain two columns: Key and Value with a varchar datatype to store the users settings... But what is considered to be best practice in such design-questions?

Is this approach advisable (for example because it needs custom parsing from string to the needed datatype)?

答:
If I understand this question correctly, then, as previously stated by @user61852, this is a database design issue.

Your 'key, value' idea is not a good idea in this instance and will certainly lead to lots of painstaking debugging. You have the full power of a relation model at your finger tips why not use it to its fullest?

From Database fundamentals (a worthwhile read!):

Data modeling defines all the required information from the real world.

You need to think about the Userprofiles table, the data it models and its purpose. If you are extending this table every time you think of something else to add you have not thought about the problem sufficiently.

Title: Saving user profiles in SQL database


答:
I don't think there's any truth behind that idea. Two main things that would be different by using Java are the JVM and the code itself.

JVM. I'm not an expert in the details of jvm but there are PHP implementation for jvm (e.g. http://www.caucho.com/resin-3.1/doc/quercus.xtp). They promoted security as one of the feature  but they only pointed out buggy php extensions, i.e. not flaw in PHP itself.

The code. If your friend can code secure transaction in Java, you should be able to re-implement it in PHP and it will have the same level of security (good or bad). It's pretty straight forward to check that the two implementations have same behavior, although proofing them to be secure is a whole different story.

Especially within the transaction code scope, I don't think there is proof that Java is inherently more secure than PHP.

Title: How will writing the transaction part in Java benefit the security of the application, when all other parts are being written in PHP?

Body:
A friend of mine while working on a PHP application asked me to write one part of the application in Java. The part that involved transactions. He said it will be better to write this portion in Java. He talked about how secure it will be!

Though I was too busy to  help him then, I want to know the essence of this idea. Why he was trying to use Java when he wrote the most part in PHP? Will it really boost up the security? And writing transactions in Java is only concerned with security?

The thing seems very interesting but I really have no idea, what it is! Please provide some insight into the topic.

Note: When I say transaction, it involves everything. From accessing account to transferring money.


答:
I have previously designed a database with key value string pairs for storing user settings. The rationale for this was that the web application featured many different pages that should each be able to store page-specific settings. As pages are added and removed all the time, the only practical solution was to add the page name to the setting's key and then store the value as a string in a database.

I realize that this design is not type safe and does not scale very well. However, as long as there is only a somewhat limited number of pages per app and only a limited number of settings per page, there should only be at most a few hundred settings entries per user to search through. Even with string comparisons, performance should not really be an issue.

Title: Saving user profiles in SQL database

Body:
So, I got a table UserProfiles in my database, that, similar to C#'s Settings file, holds a property with the appropriate datatype and the specified setting in the profile.

Now each time I add a new setting, I need to update the database, the model and end up rewriting the queries.

I've then thought about changing the table to only contain two columns: Key and Value with a varchar datatype to store the users settings... But what is considered to be best practice in such design-questions?

Is this approach advisable (for example because it needs custom parsing from string to the needed datatype)?


问:
GCC vs clang/LLVM -- pros and cons of each
What are the pros and cons of GCC vs clang/LLVM?</p>

答:
Clang has much better error reporting. E.g. if you make a typo in a function name you call, Clang will report that this is likely a typo (and suggest the correct name), while GCC will complain about unknown function name.

GCC usually produces faster code if you target x86/x86-64. For ARM the situation is ambiguous, often Clang optimizes better. Also, AFAIK Clang does not support optimization for code size.

GCC uses a lot of heuristics. This is good for performance (in a typical case), but awful if you want to do some source-level optimization (e.g. loop unrolling). Even small source code changes can make GCC generate a completely different output. Clang is more predictable, and usually it generates the code you expect.

Unlike Jerry Coffin, I find building GCC from source much harder than Clang. The procedure from Clang's Getting Started page always worked for me. Similar manual for GCC never worked in the first try. GCC has dependencies on particular versions of GMP, MPFR, MPC, Parma Polyhedra Library, and CLooG, and I needed several iterations to find the versions which would work for a particular GCC release (yes, using the latest versions of those libraries does not work).

I have a feeling that Clang is better tested than GCC. Even though I only use official releases of GCC, it sometimes produced faulty code. For Clang I usually use the trunk version (again, because it is easy to build), but I never saw it generating wrong output.

GCC is nearly standard in Linux world, and it adds a lot of non-standard features which are widely used in Linux software. Clang tries to be compatible with GCC, but sometimes it just quietly ignores them. Most importantly, Clang does not support OpenMP. However, it also has extensions which are not supported by GCC, but can be useful (e.g. add-with-carry intrinsic functions __buildin_addc).

If you want to do compiler research, or just curious about how it works, you will find Clang/LLVM source code more accessible. Clang/LLVM code is human-readable, not just compiler-readable.

(AINAL declaimer applies) Clang/LLVM license gives you more freedom about what you can do with the code, e.g. use in commercial or closed-source product. License for GCC runtime libraries adds another layer of restrictions while Clang compiler runtime (compiler-rt library) is under permissive MIT license.

Summary: compile with Clang when you develop the program, and with GCC for the final build (but make sure that its faster and doesn't break). Stick with Clang/LLVM if you do compiler research.


问:
Does SOA service composition actually work in practice?
One of the main SOA service design principles is Service Composability principle
(https://en.wikipedia.org/wiki/Service_composability_principle).

The idea is that by composing new services using existing ones as building blocks, one
can rapidly develop new services. Kind of analogously to how you call exising methods
of objects when you implement new methods. This is where much of productivity boost from SOA is supposed to come from.

Does someone really do this in practice? I have seen this repeated endlessly in written
text, but have not experienced working real world implementations myself. Most of the
text also omits any mention of transaction handling, which seems to me to be the
biggest obstacle in realizing composable services.

First, you really do need to tackle the transactions problem before you can compose any
non-trivial services. Sure, if the example has services "findCurrentTime()" and
"writeLogMessage()" its easy to not worry about transactions, but not when having real
world examples such as "depositMoney()" and "withdrawMoney()".

I know of two options:

Implement real transactions with WS-Atomic Transaction or such

Implement compensation-based solution which compensates call to A with "cancelA()"
or somesuch if call to B fails

Both of these seem very problematic / close to unusable to me:

WS-Atomic Transaction

a lot of complexity, most advice that I found just warns "pain in the ass, dont
do it"

support is limited, for example if you take open source ESBs, main alternatives
ServiceMix, Mule or WSO2 do not support it

compensations

implementing the handling of compensations seems very complex to me. What do we do if service A
succeeds and we never get an answer from service B and do not know if it failed or
succeeded? Handling such logic manually (as implementor of compositing services) makes
me want to slit my wrists - this is the kind of work some tool should do for me!.

I also dont see how you can have compensation methods in non-trivial services. Say
your service A is "depositMoney()" and that succeeds, some other action quickly
transfers the money elsewhere, and then we receive "compensateDepositMoney()", what do
we do now? Seems like a big can of worms.

To me it seems that service composition is such a fundamental SOA principle that you
really do not get the benefits of SOA if you cannot (conveniently) compose services.
What's the reality? 90% of SOA users use "criplled SOA" without real service
componsition? Or most users do in fact use service composition and I am exaggerating
the difficulty of it?

答:
The short answer is Yes!

I have seen this done at several large financial organisations, and, it has worked well.

The transaction issues are complex but usually handled by (expensive) middleware such as Oracles WebLogic EAI or IBMs Websphere ESB.


问:
Handling ground-breaking changes in a production system - Insert intermediate level Management object
As our client request, we are proceeding to change the base of our system. We already have the following structure:

A class has many students. (simple typical one - to - many)

Now we must change it to:

A class has many groups. Each group has many students. (Intermediate
  Object "Group" is inserted).

That seems to be a "simple" change, but it breaks all of the management interface, from both mobile client to web views. And in database structure also.

Our system is a data-management program where we have about 50 - 60 domain objects which are parts of a hierarchy model of around 5 levels. And the intermediate object is inserted in around the 2nd-stage.

My question includes 2 aspects:

1) How to estimate the efforts needed. I'm making a new code branch, then insert the new domain object, after that break the relation of the class-student to insert the new "group" in. Then look in the error-report of Eclipse to locate the troubled code. However, it makes the whole project red, and I'm having troubles giving accurate time-estimation for the task.

2) How to avoid/prevent this situation to happen in the future. It happens once before, and at that time I have spent a week to write database conversion script, as well as making the changes. But at that time the system is still small. Now it has grown big.

答:
The best way to do something like this is to do it in small steps. First, even when you add this group, the students are transitively related to single class. So while there is some kind of grouping on the inside, the outside interface might ignore this and present only Student-Class relationship.

So first step might be keeping Student-Class relationship, but add Student-Group and Group-Class relationship to the side. Yes, there will be duplication, but this should be only temporary. This will allow you to slowly refactor from old relationship into the new relationship. This transitive "state" of your model will expose both of those relationships, so clients can slowly move from the old one to the new one. And when all clients move to the new one, you can remove the old one.


问:
Which approach to follow for developing applications targeting multiple platforms?
For applications targeting multiple platforms, I see mainly two development approaches-

Go for some JAVA-like development platform. Have one code solution and let the intermediate runtime handle different platforms. If something goes wrong in any platform, tweak the code a bit. But keep it same for all.

Make modular code separating core logic and UI. Develop separate UIs for respective platforms which will be calling same core libraries. Build the application separately for each of the target platforms.

So, which one to follow? I know, the answer will start with "It depends". But I want to hear your opinions on these approaches and the factors to be considered to choose any of them.

答:
It depends on what is important to you :)

When we faced this choice for a cross-platform Mac/Windows app about 10 years ago, we had a good look around the various cross-platform options - Java, Qt, wxWidgets etc. The problem we had was that the look and feel of the UI was really important to us, and all of the "cross-platform" apps looked, well, compromised. We ended up biting the bullet and building up our own cross-platform core, with a custom UI for each platform on top (written in PowerPlant for Mac and MFC on Windows). Over time we have got pretty good at this, and the "cross-platform" part has got thicker without compromising the UI.

We're now looking at this decision again for a new project. Looking at the options now, I would probably go with Qt - it's free and really seems to have matured nicely. Java might have been an option but we can't really take the performance hit (we're doing 3D image processing).

If UI is really important to you, I suspect you are going to have to invest quite a lot of time getting things looking right on each platform whether you use something like Qt or roll your own. For an internal or specialist app where users might be more accepting of a less polished UI, it might be fine!


问:
Does software in a professional environment need to be licensed?
Background: I'm writing in-house software - it has absolutely no contact with the world outside the company - but I'm using various libraries, which themselves do have some license structure. So for example GPL requires that software that re-uses the a GPL-licensed piece of code, to also be under GPL-license. Does that require my in-house application to have an explicit GPL-license, or is this understood implicitly? Does using AGPL-licensed code, require my code to be available to co-workers who use the in-house system?

Question: Does my in-house software need to have an explicit license, to be compliant with the licenses of such libraries? In what cases does in-house software need to have its own license?

答:
According to the GPL FAQ:

Does the GPL require that source code of modified versions be posted
  to the public?

The GPL does not require you to release your modified version, or any part of it. You are free to make modifications and use them
  privately, without ever releasing them. This applies to organizations
  (including companies), too; an organization can make a modified
  version and use it internally without ever releasing it outside the
  organization.

But if you release the modified version to the public in some way, the GPL requires you to make the modified source code available to the
  program's users, under the GPL.

So your program that uses GPL code does not need to have a specific license as long as it is used only internally. However, "internally" ends when it runs on a public server:

However, putting the program on a server machine for the public to
  talk to is hardly “private” use, so it would be legitimate to require
  release of the source code in that special case. Developers who wish
  to address this might want to use the GNU Affero GPL for programs
  designed for network server use.

Note that the wording implies this is a corner case and a court might not uphold this view.


问:
Rails + Heroku Architecture
I'm in the process of developing a Rails app that I plan on subsequently deploying to Heroku. I've never run apps on Heroku (outside of the free simple app) so I have some questions on a few things on how I should architect some aspects of my app to run.

I want a service to run on a schedule to check for inactive users to send a 'we haven't seen you in a while' type of email. Would this just be it's own worker dyno in Heroku? Or would that be integrated into the web app as a background job of sorts?

In relation to that, I will have a worker dyno that will handle sending account confirmation emails, among other random emails, would it make sense to have that operation be coupled with the process above? Or would it have to be a completely separate dyno?

I've done plenty of this type of work in .Net hence some of my confusion on this switch to Rails.

答:
The "Heroku way" looks to be the use of Heroku's custom clock processes, coupled with a Ruby gem to interface with the clock process such as Clockwork.

(There is also a way to run less strict scheduled jobs, the Heroku Scheduler. ("Scheduler is a best-effort service. There is no guarantee that jobs will execute at their scheduled time, or at all. Scheduler has a known issue whereby scheduled processes are occasionally skipped. An alternative to Heroku Scheduler is to run your own custom clock process."))

Title: Rails + Heroku Architecture


问:
Is Objective C a reasonable way to learn C?
I want to learn C but I tend to learn best when I have a project to work on. I've never done iPhone development, so I'm hoping to kill two birds with one stone. Will learning objective c also teach me to program c reasonably well, or are they too dissimilar?

EDIT: I'm mostly wondering if objective-c/iphone-development would teach me all the little gotcha's that are inherent to c. I come from a .Net background so I haven't done much in terms of memory management or working with pointers.

答:
90% of what you'll learn doing a project in object-c will be related to Apple. As 90% would be to Android if you learn Google's SDK using Java.

That makes it difficult to gain experience from the remaining 10%.

The reverse way to look at is a C programmer who's never touched object-c would have a lot of learning to do to make an app.

Is this a bad thing, No.

Practical application of a skill is better than just learning a programming language.