答:
There is a general conception amongst many business users and clients that when it looks complete, it is almost complete.  As you likely know, this is far from the truth.  One can have it looking nice, but with no backend and some users think that making it look nice is 80% of the work, not 20% (or the other 80%).

Countless developers can tell horror stories of this - getting a mockup of the pages done in Microsoft Word using screen shots of some other tool, and the client saying "so, you've almost got it done?"

You need to pace it so that all parts are done when its done.  Trying to do all the backend first and then all the front end will lead to the end user thinking you're not doing anything and asking why you are getting paid when there is nothing to show for it.  On the other hand, front end first and you'll find the end user making niggling changes and consuming all our time.

The worst case with a 'one first and the the other' is when you get to the other part, you find that it doesn't fit the design at all.

Thus, build both.  Show progress in the front end, make the back end work with what you are building.  In many cases its a good idea to deliver incremental builds and make sure you're making what the client wants (this gets into Agile).  Going too long with out 'visible advances' can hurt the client relationship (this is for both cases of 'everything looks done early' and 'nothing is done until the very end' - its hard for the client to see the framework being written or the unit tests or data sanitization as progress).

Joel wrote about this in The Iceberg Secret, Revealed:

Important Corollary Two. If you show a nonprogrammer a screen which has a user interface which is 100% beautiful, they will think the program is almost done.

People who aren't programmers are just looking at the screen and seeing some pixels. And if the pixels look like they make up a program which does something, they think "oh, gosh, how much harder could it be to make it actually work?"

The big risk here is that if you mock up the UI first, presumably so you can get some conversations going with the customer, then everybody's going to think you're almost done. And then when you spend the next year working "under the covers," so to speak, nobody will really see what you're doing and they'll think it's nothing.

This is again reiterated in the blog post Don't make the Demo look Done which has this helpful graph:

Note here the two options generally reflect the 'get the ui done' (and then the expectation is that you'll be done soon) and 'get the backend done' (and then the customer is worried about you missing the deadline).

How 'done' something looks should match how 'done' something is.

Every software developer has experienced this many times in their career. But desktop publishing tools lead to the same headache for tech writers--if you show someone a rough draft that's perfectly fonted and formatted, they see it as more done than you'd like. We need a match between where we are and where others perceive we are.

This article also brings up an important point about the type of feedback you get with different levels of doneness of the user interface.  If you have something that looks complete, you're more likely to get feedback about "could you change the font" than "this layout doesn't work - there are too many tabs."

For those who are fighting with this in the Java Swing world, there's a look and feel called Napkin which makes it so that the UI doesn't look complete (even if it is).

The key here is to make it so that it doesn't look done.  Having the UI look complete is a signal to many business users that the application is complete (even if its just a few static pages without any logic behind it or something built in an interface builder).

Further reading (and links from article):

The Iceberg Secret, Revealed

Don't make the Demo look Done

Napkin Look & Feel for Swing

Why xkcd-style graphs are important

Title: Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?


问:
Rest API Architecture from Rest in Practice book
We maintain an API that as part of its purpose makes a call to an external API. This external API takes a few seconds to fulfil the request we make to it. With our current architecture the request is made synchronously, meaning that the http response we return to the user request is blocked until our service get the response from the external API.

I am considering changing our architecture to be able to deal with the request asynchronously... By this I mean accept the user request into our API and put a message on a queue so that we return an http response a lot quicker. The response would contain the address of where the full/complete result can be found. A background task would then pick messages up from the queue and make the call to the external API, then store the result at the address provided in our response. The address could then be polled by the user/client until the desired state of the respource is reached (i.e. when the background task has finished calling the external api and has stored the result).

This architecture I have mainly lifted from the REST in Practice book. The crux however is that our external API only takes 2-3 seconds to return the response. The example in the book describes an ordering process that might take minutes or hours. Is this suggested solution worth the increase in complexity for such a short response time from our external dependency? i.e. will the application still scale with the existing synchronous architecture?

答:
If you really want to separate for whatever reason the current workflow from where the result is presented, you could use the links-section in the JSON-Response.

```<code>{
    "name": "currentStep",

    ...

    "links": [ {
        "rel": "self",
        "href": "/api/job/currentStep"
    },
    {
        "rel": "previousStep",
        "href": "/api/job/previousStep"
    },
    {
        "rel": "result",
        "href": "/api/job/result"
    }
     ]
}
</code>```

This indicates where you are now, where you were before and where the result is going to be.
Implementing it this way, you signal your intention, that the result is under a different location. So the problem of waiting at the current step for results is solved.

What is not covered with this solution is the problem, that neither you nor the user of your API knows, whether there are results at all or when the results will be available under the given URL. So your overall problem is not solved, it is only deferred. When the URL (in my example /api/job/result) is called, it is not sure, whether there is a result or not.

On the one hand, you have a synchronous servicecall, which lasts 2-3 seconds on average, after which you return the result to the user without interruption of the flow or on the other hand a possible gap but immediate answer.

Without further knowledge of the overall architecture and your userbase it is hard to say anything. How critical are 2-3 seconds? In the finance-sector it may be mission-critical in other sectors it may be neglectable.

Another solution comes to my mind, but for that, I have to know more of your application infrastructure:

If there are more service-calls needed, you could make them all asynchronous. Say you have the following setup:

To comple the whole request you have to do steps A,B.C and D. D in this case is, the call to the external service, which takes 2-3s. So if you do them all in order, you have Step A taking 0.5s, B 0.5s and C 0.5s. Thats 1.5s. To which the 2s of call D is added. That makes overall 3.5s to wait.

If you do them all in parallel, you only have to wait for the slowest. In this case, that would be 2s which is significantly faster.

Not to mention long-polling / comet ("oldschool") or websockets.
With e.g. websockets you have the possibility to push the result from the server down the pipe as soon as you have it.

ContentLicense: CC BY-SA 3.0

Body:
If you really want to separate for whatever reason the current workflow from where the result is presented, you could use the links-section in the JSON-Response.

{
    "name": "currentStep",

    ...

    "links": [ {
        "rel": "self",
        "href": "/api/job/currentStep"
    },
    {
        "rel": "previousStep",
        "href": "/api/job/previousStep"
    },
    {
        "rel": "result",
        "href": "/api/job/result"
    }
     ]
}

This indicates where you are now, where you were before and where the result is going to be.
Implementing it this way, you signal your intention, that the result is under a different location. So the problem of waiting at the current step for results is solved.

What is not covered with this solution is the problem, that neither you nor the user of your API knows, whether there are results at all or when the results will be available under the given URL. So your overall problem is not solved, it is only deferred. When the URL (in my example /api/job/result) is called, it is not sure, whether there is a result or not.

On the one hand, you have a synchronous servicecall, which lasts 2-3 seconds on average, after which you return the result to the user without interruption of the flow or on the other hand a possible gap but immediate answer.

Without further knowledge of the overall architecture and your userbase it is hard to say anything. How critical are 2-3 seconds? In the finance-sector it may be mission-critical in other sectors it may be neglectable.

Another solution comes to my mind, but for that, I have to know more of your application infrastructure:

If there are more service-calls needed, you could make them all asynchronous. Say you have the following setup:

To comple the whole request you have to do steps A,B.C and D. D in this case is, the call to the external service, which takes 2-3s. So if you do them all in order, you have Step A taking 0.5s, B 0.5s and C 0.5s. Thats 1.5s. To which the 2s of call D is added. That makes overall 3.5s to wait.

If you do them all in parallel, you only have to wait for the slowest. In this case, that would be 2s which is significantly faster.

Not to mention long-polling / comet ("oldschool") or websockets.
With e.g. websockets you have the possibility to push the result from the server down the pipe as soon as you have it.


问:
API - How to handle scope based functionality?

TLDR;

Where and possibly how should I implement scope based logic in the
  example code?

I have got a ASP.NET Web Api.

The Api uses OData (on top off REST) for data endpoints and OAuth 2.0 authentication.
Now I want to add functionality to handle an Access Token in several different scopes.

Some of the scopes are:

User

Organization

Customer

The result set the API returns should be based on this scope.
The same applies if someone wants to add, update or delete an entity.

Now take for example the following endpoint:

http://myapi/Employees

Someone with a Token in the Organization scope does a GET and should only get the employees that are in the Organization that is defined within the Token. An user in the Customer scope should get the employees for all organizations within the customer defined in the Token. This functionality however is not available for someone with a Token in the User scope.

The same applies to a POST. Someone within the organization scope should only be allowed to add a new employee to his own organization.

The functionality for the different scopes will usually only differ a little bit.
In the case of getting the employees the difference is only a where on organization or otherwise on customer. In the case of a post their should be a check to see if for example the organization is part of the customer that is bound to the customer Token.

Current implementation:

Currently we have a base ApiController which is generic typed.
The base controller calls an Query or CommandHandler with the entity type and all the implementation details are inside this handlers.

ApiController

```<code>public abstract class ApiController<TEntity> : EntitySetController<TEntity, Guid>
    where TEntity : class, IApiEntity
{
    protected readonly IQueryProcessor QueryProcessor;
    protected readonly ICommandProcessor CommandProcessor;

    protected ApiController(IQueryProcessor queryProcessor, ICommandProcessor commandProcessor)
    {
        this.QueryProcessor = queryProcessor;
        this.CommandProcessor = commandProcessor;
    }

    [HttpGet]
    public override IQueryable<TEntity> Get()
    {
        var command = new GetEntityCommand<TEntity>();
        return this.QueryProcessor.Process(command);
    }
}
</code>```

EmployeeController

```<code>public class EmployeeController : ApiController<Employee>
{ }
</code>```

GetEmployeeHandler

```<code>public class GetEmployeeCommandHandler : IQueryHandler<GetEntityCommand<Employee>, IQueryable<Employee>>
{
    public IQueryable<Employee> Handle(GetEntityCommand<Employee> command)
    {
         // Code that knows how to get a collection of employees.
         // This collection contains all employees
    }
}
</code>```

PostEmployeeHandler

```<code>public class PostEmployeeCommandHandler : ICommandHandler<PostEntityCommand<Employee>, Employee>
{
   public Employee Handle(PostEntityCommand<Employee> command)
    {
         // Code that knows how to add an employee to the database.
    }
}
</code>```

The question

Where and possibly how should I implement the scope based logic?
I know there has to be a smart way to do this and a good place to implement this scope based logic, I just don't see it (yet).

答:
I think that at least part of the answer is to make your Access Token 'ambient', so that you can access it from any part of your code without having to pass it along as an argument with every call.

One of the ways to do this is to define a custom IPrincipal that includes your Access Token, and set it on the HttpContext.Current.User* , e.g. see this answer. In MVC, there is usually a filter that allows you to hook in at the correct point.

* If you do this early enough, the principal gets copied to the Thread.CurrentPrincipal automatically, otherwise you might have to set it manually.

Once you have this in place, you could use extension methods to do the scoping. For example, something like this:

```<code>public static IEnumerable<Employee> FilterToScope(this IEnumerable<Employee> employees)
{
    var token = (Thread.CurrentPrincipal as MyTokenPrincipal).Token;
    if(token.IsCustomerScoped)
    {
        //Filter employees on customer
    } else if //etc.
}
</code>```

Body:
I think that at least part of the answer is to make your Access Token 'ambient', so that you can access it from any part of your code without having to pass it along as an argument with every call.

One of the ways to do this is to define a custom IPrincipal that includes your Access Token, and set it on the HttpContext.Current.User* , e.g. see this answer. In MVC, there is usually a filter that allows you to hook in at the correct point.

* If you do this early enough, the principal gets copied to the Thread.CurrentPrincipal automatically, otherwise you might have to set it manually.

Once you have this in place, you could use extension methods to do the scoping. For example, something like this:

public static IEnumerable<Employee> FilterToScope(this IEnumerable<Employee> employees)
{
    var token = (Thread.CurrentPrincipal as MyTokenPrincipal).Token;
    if(token.IsCustomerScoped)
    {
        //Filter employees on customer
    } else if //etc.
}


答:
I strongly suggest that you put this scope logic inside your data schema design (SQL tables for example). Don't do filtering. The reason is mainly scalability.

When there are so many data items, you don't want to ask the DB to load them all, and then you apply scoping on these items in memory. You overload the DB with extra work, and memory too.

Database can query items with scoping parameters (query optimizers work very well for SQL) much better. You will have better speed.

Using the DB will also help you avoid lot of problems with transaction and concurrency.

Title: API - How to handle scope based functionality?

Body:
TLDR;

Where and possibly how should I implement scope based logic in the
  example code?

I have got a ASP.NET Web Api.

The Api uses OData (on top off REST) for data endpoints and OAuth 2.0 authentication.
Now I want to add functionality to handle an Access Token in several different scopes.

Some of the scopes are:

User

Organization

Customer

The result set the API returns should be based on this scope.
The same applies if someone wants to add, update or delete an entity.

Now take for example the following endpoint:

http://myapi/Employees

Someone with a Token in the Organization scope does a GET and should only get the employees that are in the Organization that is defined within the Token. An user in the Customer scope should get the employees for all organizations within the customer defined in the Token. This functionality however is not available for someone with a Token in the User scope.

The same applies to a POST. Someone within the organization scope should only be allowed to add a new employee to his own organization.

The functionality for the different scopes will usually only differ a little bit.
In the case of getting the employees the difference is only a where on organization or otherwise on customer. In the case of a post their should be a check to see if for example the organization is part of the customer that is bound to the customer Token.

Current implementation:

Currently we have a base ApiController which is generic typed.
The base controller calls an Query or CommandHandler with the entity type and all the implementation details are inside this handlers.

ApiController

```<code>public abstract class ApiController<TEntity> : EntitySetController<TEntity, Guid>
    where TEntity : class, IApiEntity
{
    protected readonly IQueryProcessor QueryProcessor;
    protected readonly ICommandProcessor CommandProcessor;

    protected ApiController(IQueryProcessor queryProcessor, ICommandProcessor commandProcessor)
    {
        this.QueryProcessor = queryProcessor;
        this.CommandProcessor = commandProcessor;
    }

    [HttpGet]
    public override IQueryable<TEntity> Get()
    {
        var command = new GetEntityCommand<TEntity>();
        return this.QueryProcessor.Process(command);
    }
}
</code>```

EmployeeController

```<code>public class EmployeeController : ApiController<Employee>
{ }
</code>```

GetEmployeeHandler

```<code>public class GetEmployeeCommandHandler : IQueryHandler<GetEntityCommand<Employee>, IQueryable<Employee>>
{
    public IQueryable<Employee> Handle(GetEntityCommand<Employee> command)
    {
         // Code that knows how to get a collection of employees.
         // This collection contains all employees
    }
}
</code>```

PostEmployeeHandler

```<code>public class PostEmployeeCommandHandler : ICommandHandler<PostEntityCommand<Employee>, Employee>
{
   public Employee Handle(PostEntityCommand<Employee> command)
    {
         // Code that knows how to add an employee to the database.
    }
}
</code>```

The question

Where and possibly how should I implement the scope based logic?
I know there has to be a smart way to do this and a good place to implement this scope based logic, I just don't see it (yet).


问:
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?

Assuming you're working on something large, is it generally accepted practice to get all the functional data harvesting blobs working before any UI, get all the UI working one piece at a time as you go, or something in the middle?

We all know to break work down in to manageable pieces, but the question is ultimately whether UI is included in manageable pieces I suppose.

For the case of the example, consider a GUI application with one root window, but over a dozen tabs in various docks to separate different data components.  Each individual tab has a relatively complex set of moving parts behind it from a functional units perspective.

The example application in this particular question is here with the accompanying blog and the original commercial product.

答:
In large (PHP web-based) applications that I work on, I try to get the classes and methods in place first, which return dummy values. This is to establish a pseudo-contract that the other devs can use to implement the UI for.

A secondary advantage to this method is that we can hone the contract / interface as the UI requirements change (and they always change), even before all the code is written and delivered.


问:
How does one store a website's holding/maintenance page in Git?
I'm trying to tidy up the Git repositories for the few sites that I maintain. For each site, I usually create a separate branch in the repo that holds a "maintenance page" or "holding page", which I checkout if I need to take the site down for any reason. This branch is usually called maintenance_page. Normal development is done against master and the live site is also deployed from there.

Whilst the site code in the maintenance_page branch has the same styling as the main (live) site in master, it doesn't really share any history with the master branch - think of it like a mini version of the live site, but with it's own basically unrelated codebase. From time to time, changes that I make to the styling, images, etc. in master would be useful to have in the maintenance_page branch and in these situations, I usually git cherry-pick from master to maintenance_page.

I've been working with this setup for a while now, however, I'm conscious that the whole idea of having the two branches (master and maintenance_page) coexisting in the same repository, but not having anything really in common with each other is not really the "Git way of doing things". I've thought of storing the maintenance_page branch in it's own repo (as it has very little in common with the master branch), however this just seems to complicate the administration of the repositories and also detracts from the simplicity of being able to simply checkout the maintenance_page branch, when I need to take the site down elegantly.

I've had a good read around (see here) (and here) to try to find out how other people handle this kind of thing, but I'm strangely unable to come up with any pointers on how other achieve this.

Does anyone have any suggestions on better ways to achieve this?

答:
Since the maintenance page is a feature of the web application, there is no reason to put it into a separate branch or repository. Instead, have a dedicated directory, or maybe even just a file at the root. This will make it possible to:

Share all static files such as the images, CSS or JavaScript,

Benefit from common code instead of duplicating it with the risk of the maintenance page being not properly updated when the web application itself changes.

You probably won't be able to share everything, especially since, I presume, your web app uses templates while the maintenance page is static, but it's still much less hassle than to maintain a different branch or repository.

You can then switch between the web application and the maintenance page by changing the configuration of the server (like an automatic redirection of any GET request other than favicon.ico and robots.txt to the maintenance page, and an HTTP 500 for POST requests).

Note that when your web application will grow, you'll be looking into more user-friendly ways to put your web app on maintenance anyway. This includes:

Having a read-only flag, similar to Stack Exchange read-only mode which prevents any one to log in and post, comment and upvote.

A similar technique is used on other large websites as well; for example, on B&H, one of the largest e-commerce websites for photographers, you are sometimes unable to purchase products, while you can still browse the catalog.

Having solid infrastructure which makes it possible to bring one server offline, do maintenance on it, bring it online, and do the same thing with another server.

This approach is more advanced, since it doesn't disturb the end users: for them, the website is always online, and all the operations they were doing when being switched from one server to another are preserved.


问:
What are the advantages to using SQL query builders?
Are there any advantages to using a query builder, rather than using raw SQL?

E.g.

```<code>$q->select('*')
  ->from('posts')
  ->innerJoin('terms', 'post_id')
  ->where(...)
</code>```

vs:

```<code>SELECT * FROM posts WHERE ...
</code>```

I see that many frameworks use these kind of abstraction layers, but I fail to understand the benefits.

答:
I think the practical, day-to-day benefit of query builder - is code reuse and ability to follow DRY principle.

With query builder you can put repeating parts of SQL into methods. And then use these methods to compose complex SQL. An example would be e.g. reusable JOIN clause:

```<code>function joinTaskWithClient($queryBuilder) {
    $queryBuilder->join('task', 'contract', 'task.contract_id = contract.id')
                 ->join('contract', 'client', 'contract.client_id = client.id');
}
</code>```

So the usage would be:

```<code>$queryBuilder->select('client.name')
             ->from('client')
             ->where('task.id=:task')->setParameter('task', 42);
joinTaskWithClient($queryBuilder);
</code>```

As you may note - with query builder you can add parts of SQL in any order (e.g. JOIN part after WHERE one) in contrast to the case when you gather SQL string manually. Also, you may read about builder pattern  to see its intent and benefits.

I agree regarding escaping and sanitizing, but this could be achieved w/o query builder as well. Regarding DB type / dialect abstraction - this is quite theoretical and questionable benefit, hardly ever used in practice.

Body:
I think the practical, day-to-day benefit of query builder - is code reuse and ability to follow DRY principle.

With query builder you can put repeating parts of SQL into methods. And then use these methods to compose complex SQL. An example would be e.g. reusable JOIN clause:

function joinTaskWithClient($queryBuilder) {
    $queryBuilder->join('task', 'contract', 'task.contract_id = contract.id')
                 ->join('contract', 'client', 'contract.client_id = client.id');
}

So the usage would be:

$queryBuilder->select('client.name')
             ->from('client')
             ->where('task.id=:task')->setParameter('task', 42);
joinTaskWithClient($queryBuilder);

As you may note - with query builder you can add parts of SQL in any order (e.g. JOIN part after WHERE one) in contrast to the case when you gather SQL string manually. Also, you may read about builder pattern  to see its intent and benefits.

I agree regarding escaping and sanitizing, but this could be achieved w/o query builder as well. Regarding DB type / dialect abstraction - this is quite theoretical and questionable benefit, hardly ever used in practice.


问:
the perils of using eval() for dynamic object creation -- is this a valid argument in a consenting-adults culture?
I've read on stackoverflow explicit warnings against using eval() to create objects.  The reason that seems to be given is that malicious code could be injected and blindly created objects could compromise a system.  Isn't this malicious-intent argument invalidated by the consenting-adult argument, though?

Some sample code:

```<code>class Test(object):
    def __init__(self, vala, valb, valc):
        self._vala = vala
        self._valb = valb
        self._valc = valc

    def __repr__(self):
        return "<Test(vala={0}, valb={1}, valc={2})>".format(self._vala, self._valb, self._valc)

testlist = [dict(cls="Test", vala="this is vala", valb="this is valb", valc="this is valc"), dict(cls="Test", vala="this is vala II", valb="this is valb II", valc="this is valc II")]

mytestobjects = []

for test in testlist:
    newobj = eval(test['cls'])(**{key: value for key, value in test.items() if key != "cls"})
    mytestobjects.append(newobj)

print(mytestobjects)
</code>```

答:
The consenting-adults argument is that programmers who use your code are consenting adults.  Users may not be.  (They may, for instance, not understand how their data will be used in the program.)

Moreover, the person who supplies the malicious data may not be the person who "consented" to using your program.  If the program grabs data from the internet, for instance, even a "consenting adult" user may inadvertently download malicious data and damage his system.  On the flip side, if the program runs on a server, the "user" may be the server admin, who doesn't want site visitors to be able to hose his server by entering malicious data into a web form or the like.  Either way, the point is that the person doing the consenting is not necessarily the person suffering the effect.


答:
In an Agile environment, you might hear discussions of "walking skeletons" or "thin vertical slices". The idea being that since working software is what is important to the user, you build out the software in a working fashion piece by piece.

In the example application you mentioned, you would start with the window and maybe one tab, and make it all work front-to-back in some fashion. Then over time, you would add functionality and therefore tabs on a case-by-case basis, making each feature work as you build it. This is part of what frequent customer demonstrations give you: a chance to show something new working and get feedback on it instantly.

In short, yes, UI work is absolutely part and parcel of a unit of functional work, if you have a UI.

Start with something small that works, and iterate its functionality up to deliver a full piece of software.

Body:
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?

Assuming you're working on something large, is it generally accepted practice to get all the functional data harvesting blobs working before any UI, get all the UI working one piece at a time as you go, or something in the middle?

We all know to break work down in to manageable pieces, but the question is ultimately whether UI is included in manageable pieces I suppose.

For the case of the example, consider a GUI application with one root window, but over a dozen tabs in various docks to separate different data components.  Each individual tab has a relatively complex set of moving parts behind it from a functional units perspective.

The example application in this particular question is here with the accompanying blog and the original commercial product.


问:
Best way to organize SQL queries stored in your code ? (or should you?)
I am sure I am not the only one who gets frustrated when they see a page of code littered with SQL queries. The ActiveRecord and other ORM patterns help mitigate a good amount of SQL used in a project, but in many cases of complex queries, the use of SQL is seemingly unavoidable.

I am looking for opinions on how SQL queries should be organized with the rest of the code (or externally to it) to keep it from being scattered all over the place? One obvious idea is the use of Views, but often Views can be a source of performance issues when dealing with multiple large indexed tables, etc.

EDIT 1 - I am assuming you've already got it separated into the model layer

答:
It could be good idea to separate your model layer into 3 sub-layers - "entities", "repositories" and "services". This will give you separation of concerns and gather SQL in one place, out of your business logic.

In this scenario all the data retrieval code, including complex SQL - will be located in repositories. So the goal of repository is to hide complex SQL statements behind self-explanatory methods like getUsersWithActiveSubscription().

Entity abstracts real DB table field names with getters and setters, may provide some data conversion between DB field types and types available in your application / programming language. If your ORM supports that - entities may handle associations.

Service layer is the place for the business logic. Service retrieves entities using repositories, acts on them and stores them back.


问:
Combining 3rd party javascript libraries with my code, then using Closure Compiler
I'm using multiple third party javascript libraries in my website, and right now I'm keeping each third party library as a separate .js file, with its own

答:
You may indicate to Closure Compiler to preserve copyright/license info by using @license syntax, as shown in the documentation:

/**

   * @preserve Copyright 2009 SomeThirdParty.

   * Here is the full license text and copyright

   * notice for this file. Note that the notice can span several

   * lines and is only terminated by the closing star and slash:

   */

As for the third-party code being modified by Closure Compiler, you have a choice:

Keep this third-party code as-is in a separate file, and use the feature explained in Solution for Calling out from Compiled Code to External Code: Externs.

For popular libraries, I highly recommend you this alternative; especially, being able to use a popular CDN such as Google's one (for example for JQuery) will only reduce the bandwidth to your servers and make your application faster, since some users may already have the CDN's file cached by their browsers before even visiting your site for the first time.

Contact the authors of the third-party code to ask them if they are interested in producing code which compiles correctly with Closure Compiler.

Modify the code yourself (and don't forget to submit your changes if the project is open sourced).

Note that passing third party libraries through Closure Compiler doesn't necessarily provide a benefit over the original version. The question jQuery compiled with Google Closure Compiler provides an interesting discussion about the benefits and drawbacks of such approach (one should note that the question was written in 2009, so the information is not accurate any longer).


问:
If your workmate is quitting his job, would you notify your boss?
If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>

答:
I probably would not, because 1) I assume it is not your job to manage people (since you refer to your boss), 2) this is one of the best ways to undermine the trust between yourself and your other colleagues. If you're concerned about the company, go to your colleague, express your concerns (DO NOT try to talk him out of quitting -- it is his life), and politely ask him to notify the boss in due time.

[re. 1): i tend to keep to myself stuff that I learn accidentally, but which is basically none of my business]

ContentLicense: CC BY-SA 2.5


问:
If statements in "generic" assembly?
I'm reading a relatively 'friendly' and simple book about compilers named "Let's Build A Compiler" (originally a series of articles).

The compiler written in the book generates instructions in some assembly language (68000 assembly).

Since I don't know this assembly language, I decided that my compiler will also generate 'assembly' instructions (e.g. MOVE #4,D0 has the same meaning: "put the number 4 in register D0"), only they will be executed by a program I will write, instead of by a physical computer. A kind of "virtual machine".

So far I think this shouldn't be a problem, but I have a question regarding this:

What is a "generic" way to handle if statements in assembly? For example, what would be the simplest assembly translation for this code:

```<code>if(a>b){
    // do stuff
}
</code>```

答:
In common assembly, it's accomplished by various conditional jumps, e.g.

```<code>cmp %eax, 1;
je label
</code>```

Which roughly translate to "compare register eax and constant 1;  if equal, jump to label. Otherwise, the next instruction is executed.

The result of cmp is stored in the status register. It's a register containing results from arithmetic operations such as the zero flag ZF or the sign flag SF.

cmp is implemented as a substract. If both operands were the same, ZF is set. If the sign flag is set, it means the result of the operation was negative, thus that second operand was bigger than the first.

The various jump instructions read the sign and zero flags and perform the jump based on their value.

AFAIK there is only one status register.

Title: If statements in "generic" assembly?

Body:
In common assembly, it's accomplished by various conditional jumps, e.g.

cmp %eax, 1;
je label

Which roughly translate to "compare register eax and constant 1;  if equal, jump to label. Otherwise, the next instruction is executed.

The result of cmp is stored in the status register. It's a register containing results from arithmetic operations such as the zero flag ZF or the sign flag SF.

cmp is implemented as a substract. If both operands were the same, ZF is set. If the sign flag is set, it means the result of the operation was negative, thus that second operand was bigger than the first.

The various jump instructions read the sign and zero flags and perform the jump based on their value.

AFAIK there is only one status register.


答:
Lets go back to an earlier day, when things were simple.

Lets go back to the days of the MOS 6502 that powered the Atari, Apple II, and several other systems from the late 70s.  You can still find it in embedded systems and is apparently still produced in volumes of hundreds of millions (while this is old technology, its not outdated).  By understanding how this system worked, it becomes easier to understand how more modern and complex systems worked.

The 6502 had only a few registers:

Program counter

Stack Pointer

Accumulator (this is the 'important' one)

X and Y 'index' registers

Processor Status (this is the other 'important' one in this situation)

C Carry flag

Z Zero flag (set if the last operation had a result of 0)

D Decimal mode

I Interput enable/disable

B Break

V Overflow

S Sign (set of the result of an operation is negative - sometimes that is designated the N flag for negative)

When you did a CMP #$44 this would compare the Accumulator with the value 0x44.  In doing so, it would set the ZCS flags appropriately.  C is set if the Accumulator is greater than or equal to value, and Z is set if the two are equal.  This was not too much more than doing A - M where M is the value (read from memory, or a hard value), set the flags and throw away the result (compare with SBC that would store the result in the Accumulator).

At this point, you've got the status register set, but you need to do something with it.  There were two instructions for this.  BEQ (Branch if EQual) and BNE (Branch if Not Equal).  These two instructions would each test Z of the status register - BNE would branch if Z was 0, BEQ would branch if Z was 1.  While CMP does set more flags, BEQ and BNE don't care about them - just Z.

And really, thats how conditionals work when you are down to that level.  There's a status register that is floating around somewhere many times.  This register doesn't exist when you get into the pipelined, superscalar, and speculative processors.  These tend to go for more explicit branching statements or use arbitrary registers for the status result rather than a dedicated register (see the MIPS instruction set and look at the bgt, blt, beqz and the like).

As an aside, if you are poking about virtual machines and assembly, delve a bit into Core War and the MARS virtual machine.

Title: If statements in "generic" assembly?

Body:
I'm reading a relatively 'friendly' and simple book about compilers named "Let's Build A Compiler" (originally a series of articles).

The compiler written in the book generates instructions in some assembly language (68000 assembly).

Since I don't know this assembly language, I decided that my compiler will also generate 'assembly' instructions (e.g. MOVE #4,D0 has the same meaning: "put the number 4 in register D0"), only they will be executed by a program I will write, instead of by a physical computer. A kind of "virtual machine".

So far I think this shouldn't be a problem, but I have a question regarding this:

What is a "generic" way to handle if statements in assembly? For example, what would be the simplest assembly translation for this code:

```<code>if(a>b){
    // do stuff
}
</code>```


问:
Object Chain through an Interface
Say I have 3+ types of objects:

```<code>function Sea() {
    var logs = [Logs];
    this.getLog = function(ind){return logs[ind]}
}

function Log() {
    var bumps = [Bumps];
    this.getBump = function(ind){return bumps[ind]}
}

function Bump() {
    var frogs = [Frogs];
    this.getFrog = function(ind){return frogs[ind]}
}

function Frog() {
    this.ribbit = function(){alert("Onomatopoeia!")}
}
</code>```

So, Frog doesn't know about Bump, and Bump doesn't know about Log, but Log can access Bump and Frog directly and indirectly, respectively.

Now, let's say that whenever a Frog utters a ribbit, the Log moves slightly (although Frog internally doesn't care what happens outside of itself).

Now, Mrs. Demeter suggests that I don't do this:

```<code>Sea.getLog(5).getBump(2).getFrog(1).ribbit()
</code>```

It reads nice, but there's some problems. Besides the issue of tight coupling, this method also makes it impossible for the ribbit to move the Log unless Frog ends up getting a reference about Log, which means the coupling gets even tighter.

However the alternative "one dot" method looks a tad atrocious:

```<code>Sea.tellFrogOnBumpOnLogToRibbit(1, 2, 5)
</code>```

A reasonable solution that has been suggested here (I think) is to create a concise but tightly coupled interface to... interface, with the more business-logicy code:

```<code>function SeaInterface() {

    var sea = createSea(); //Genesis 1:10

    var logInterfaces = [LogInterfaces];
    this.getLog = function(ind) {return logInterfaces[ind]}

}

function LogInterface() {

    var log = createLog();

    var bumpInterfaces = [BumpInterfaces];
    this.getBump = function(ind) {return bumpInterfaces[ind]}

    //Private method that Frogs will know about internally:
    var move = function(){}
}

function BumpInterface() {

    var bump = createBump();

    var frogInterfaces = [FrogInterfaces];
    this.getFrog = function(ind) {return frogInterfaces[ind]}

}

function FrogInterface(log) {

    var frog = createFrog();

    this.ribbit = function() {
        frog.ribbit();
        log.move(); //I'm allowed to do this because I'm a simple interface
    }

}
</code>```

That way, I could still use chaining and make the code read well (note: chaining is not a necessity):

```<code>Sea.getLog(5).getBump(2).getFrog(1).ribbit()
</code>```

And the Log would still move after a ribbit.

In the end, it's really just an attempt to minimize the detrimental affects that objects knowing about other objects can cause.

Questions:

Is there an equally readable or more readable and fool-proof way to achieve the same thing (multiple objects within objects where occasionally manipulating an inner object affects an outer object)?

Besides requiring more code, and the fact that the interface itself is tightly coupled (acceptable?), what other problems might arise if I were to interface with the actual object through something like this? Also... does this method have a name?

I haven't really seen many approaches like this in the wild, which is what makes me nervous.

答:
I suspect your question is academic, or formal, so you might not be satisfied with my solution which is a practical one.

When you think about it, what you have is a LogConcernedWithFrogRibbits ultimately. The best way I have found to quickly decouple things is through an MVC (like PureMVC for example) which is the 'complex solution' or just go with a simple pub/sub system like Radio.js.

So the Bumps would listen for frog messages and the logs would listen to bump messages. Each message contains its sender, so the reciever can determine if the sender is an object in its collection, if not it ignores it.

All the object types you listed, their instances should probably come from a factory, so you can reference them via the factory if you wished, and all the instances should also listen for (downward) messages that will ribbit the frogs by path.

Something like: "SeaMessage", {Sea:0, Log:10, Bump:2, Frog:9000, Action:'Ribbit'}

Which would be broken down by the correct Sea, and cascaded along its way as a "LogMessage".

I mean I have to pull Einstein's Razor on this one, why beat yourself over the head?
No, its not the most efficient mechanism, but this is Javascript -- what the heck are you building? haha

Its comprehensible, elegant, and easily extended. Just keep good docs on what you are doing on the message front and watch for recursion.

Title: Object Chain through an Interface


问:
Should each method have a separate JUnit test class?
I am writing JUnit unit tests for my classes.

Is it better to have a separate class for each method, or have just one test class for every actual class?

答: I think it's right that each class has its test class. The idea is to centralize all unit tests related to the target class in a single test class. Then, for example, MyClass.java will have its test class called MyClassTest.java.

ContentLicense: CC BY-SA 4.0


问:
Javascript MVC application design (canvas)
I'm having difficulty grasping how to structure/architect a canvas application using an MVC like approach in Javascript. UI will be fairly fluid and animated, the games fairly simplistic but with heavy emphasis on tweening and animation. I get how MVC works in principle but not in practice. I've googled the buggery out of this, read an awful lot, and am now as confused as I was when I started.

Some details about the application area:

multi screen game framework - multiple games will sit within this framework
common UI "screens" include: settings, info, choose difficulty, main menu etc.

multiple input methods

common UI elements such as top menu bar on some screens

possibility of using different rendering methods (canvas/DOM/webGL)

At the moment I have an AppModel, AppController and AppView. From here I was planning to add each of the "screens" and attach it to the AppView. But what about things like the top menu bar, should they be another MVC triad? Where and how would I attach it without tightly coupling components?

Is it an accepted practice to have one MVC triad within another? i.e. can I add each "screen" to the AppView? Is "triad" even an accepted MVC term?!

My mind is melting under the options... I feel like I'm missing something fundamental here. I've got a solution already up and running without using an MVC approach, but have ended up with tightly coupled soup - logic and views and currently combined. The idea was to open it up and allow easier change of views (for e.g. swapping out a canvas view with a DOM based view).

Current libraries used: require.js, createJS, underscore, GSAP, hand rolled MVC implementation

Any pointers, examples etc., particularly with regards to the actual design of the thing and splitting the "screens" into proper M, V or C would be appreciated.

...or a more appropriate method other than MVC

[NB, if you've seen this question before it's because I asked it in 2 other incorrect stackexchange communities... my brain has stopped functioning]

答:
Here is what you've done wrong already -- you have hand-rolled an MVC while in a state of confusion, and without any MVC under your belt.

Take a look at PureMVC, it is language agnostic and can be a good platform to get your feet wet with actually doing MVC.

Its code is small and comprehensible, and this will allow you to tweak it to your needs as you progress.

Start out writing a small simple game with it, minesweeper would be good. A lot of what Travis J said is good, especially about the Model.
I would only add that you need to remember that Controllers (at least in PureMvc) are stateless, they come into existence, do their BRIEF work and go away. They are the knowledgeable ones. They are like functions. "Fill the grid, cuz the Model changed", "Update the Model, cuz a button was pushed"

The Views (Mediators in PureMVC) are the dumbest, and the Model is only slightly smarter. Both abstract the implementation, so you (Controllers) never directly touch UI or DB.

Every element of your UI (like in a winforms app for example) has a View (Mediator - you see why this is a better term now?), but Mediators can also be made for meta-concerns like "Control Color" or "Focus Manager" which operate across UI elements. Think in layers here.

UI and DB events can automatically invoke Controllers (if you use a smart naming scheme), and certain Controllers can be phased out -- a Mediator can be made to directly listen for a Model Data change event and be delivered its data package.

Although this is kind of a cheat and requires the Model to know a bit about what is out there, and the Mediator to understand what to do with a data package, but it will keep you from getting swamped with mundane Controllers in many cases.

Model: Dumb but resusable; Controllers: Smart but less reusable (they ARE the app); Mediators: Dumb but reusable.
Reusability in this case means portable to another app.


问:
What is the recommended approach for helper functions in JavaScript?
What is the recommended approach for helper functions? I would like to choose one technique, and run with it to create my new "class".

Here are the design options I have pondered:

Option 1: Helper function in outer scope, invoke with context of instance

```<code>function createPane (pane) {
    // logic to create pane
    var proto = Object.create(this.paneList);
    $.extend(paneProto, pane);
    return paneProto;
}

Panes.prototype.initialize = function (panes) {
    var _this = this;
    _.each(panes, function () {
        _this.panes.push(createPane.call(_this, this));
    });
}
</code>```

Pros: Simple syntax. createPane is not published on the instance.

Cons: createPane is accessible in other scopes.

Option 2: Helper function in closure, invoke with context of instance

```<code>Panes.prototype.initialize = (function () {

    function createPane (pane) {
        // same logic as last createPane
    }

    return function (panes) {
        // same logic as before - calls createPane
    }

})();
</code>```

Pros: createPane is not published on the instance.

Cons: Lower readability and testability; Testing of this helper must occur in the scope of initialize.

Option 3: Prepend _ to name to indicate a private method

```<code>Panes.prototype._createPane = function (pane) {
    // same logic as last createPane
}

Panes.prototype.initialize = function (panes) {
    // same logic as last, except calls this._createPane
}
</code>```

Pros: Implicit context of _createPane is the instance. Testability from the outside.

Cons: Exposing helper function on the instance.

Option 4: Helper functions as arguments

```<code>Panes.prototype.initialize = (function (createPane) {

    return function (panes) {
        // same logic as before - calls createPane
    }

})(function createPane () {
   // same logic as last createPane
});
</code>```

Pros: createPane is not published on the instance. Helper functions lack access to each other.

Cons: Lower readability and testability; Testing of this helper must occur in the scope of initialize.

答:
Statics belong on the Function IMO, in your case you have a private static, so ...</p>

```<code>Panes._createPane=function(pane){}
</code>```

Body:
Statics belong on the Function IMO, in your case you have a private static, so ...

Panes._createPane=function(pane){}


问:
Tight Coupling Between Javascript, HTML, and CSS: A More Modern Approach?
It's very common to see Javascript bound to certain selectors to find elements, store data, and listen for events. It's also common to see these same selectors used for styling.

jQuery (and its selector engine Sizzle) support and promote this by referencing elements with CSS-type syntax. As such, this technique is particularly difficult to 'unlearn' (or refactor) when building out projects.

I've come to understand that this is a result of the history of HTML and Javascript development, and that browsers have been built to efficiently consume / parse / and render this sort of coupling. But as websites become increasingly complex, this reality can introduce difficulties in organizing and maintaining these separate layers.

My question is: can and should this be avoided in modern websites?

If I'm new to front-end development, and I wish to learn things 'the right way,' is it worth learning to decouple and avoid such dependencies from the start? Does this mean avoiding jQuery in favor of a library that promotes a more decoupled structure?

答:
Someone needs to build a jQuery path manager interface for an indirection and cache layer to the dom.

```<code>pathMgr.register(name,selector [,isDynamic=false]);
pathMgr.get(name [,refresh]);
</code>```

Then,

```<code>String.prototype.reg([isDynamic=false]);
String.prototype.get(name [,refresh]);
</code>```

So,

```<code>// at init....
var pathMgr=new PathMgr();
'sidebar-links #sidebar a'.reg();// new registery of selector '#sidebar a' under name 'sidebar-links'
// more, more

// in code
'sidebar-links'.get().css(etc...);
//or
'sidebar-links'.addStyleRule({});
</code>```

Body:
Someone needs to build a jQuery path manager interface for an indirection and cache layer to the dom.

pathMgr.register(name,selector [,isDynamic=false]);
pathMgr.get(name [,refresh]);

Then,

String.prototype.reg([isDynamic=false]);
String.prototype.get(name [,refresh]);

So,

// at init....
var pathMgr=new PathMgr();
'sidebar-links #sidebar a'.reg();// new registery of selector '#sidebar a' under name 'sidebar-links'
// more, more

// in code
'sidebar-links'.get().css(etc...);
//or
'sidebar-links'.addStyleRule({});


问:
How can I refactor client side functionality to create a product line-like generic design?
Assume the following situation similar to that of Stack Overflow: I have a system with a front-end that can perform various manipulations on the data (by sending messages to REST back-end):

Posting

Editing and deleting

Adding labels and tags

Now in the first version we created it well modularized but the need as of now for 'evolving' the system similar to Stack Overflow. My question is how best to separate the commonality and how to incorporate the variability with respect to the following:

Commonality:

The above 'functionalities' and sending/receiving the data from the server

Look and feel (also a variability as explained below)

HTTP verbs associated with the above actions

Variability:

The RESTful URLs where the requests are sent

The text/style of the UI (the commonality is analogous to Stack Overflow - the functionality of upvotes, posting a question remains the same, but the words, the icons, the look and feel is still different across sites)

I think this is entirely a client-side code organization/refactoring issue. I'm heavily using jQuery, javascript and backbone for front-end development.

My question is how best should I isolate the same to be able to create multiple such aspects to the tool we are currently working on?

答:
Well, the client-side is still served from the application server, isn't it? So basically what you need is ability to provide some parameters to it.

Obviously you'll need to substitute the server URL. Most look can be modified just by loading appropriate style sheets (CSS), which is just another replaced URL. And one more replaced URL can give you customization JavaScript with parameters and possibly overrides to some functions.

That should be enough for most purposes, but in practice conditionally including some bits of the HTML might be easier to maintain, because the variants are right there in one place rather than spread over JavaScript file with customization and another JavaScript file that modifies the DOM accordingly.

OwnerDisplayName: Nupul


答: If you use a good milestone and issue tracking system, you can avoid some of these problem because at a glance, management can see how productive you're being. They'll be able to see that you're 80% finished the backend and that the UI is the next milestone; they'll be able to see that you have a set of UI and backend tasks to finish for a specific feature milestone. But it all starts with the project's requirements, and Doug T's answer raises some good points about that aspect of designing a system.</p>


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

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

答:
Beware of bugs in the above code; I have only proved it correct, not tried it.

  — Donald Knuth

LastEditorDisplayName: Roger Pate


问:
OOD: class hierarchy with method arguments forming another hierarchy
I'd like to find out how do you guys handle the following situation: you have a class hierarchy, call it H1, with some polymorphic method that is supposed to accept an argument which type forms hierarchy H2 in the following way: the higher the class is in H1, the higher H2 argument it accepts.

```<code>+-----------+           +-----------+
|     A     |           |     A'    |
|-----------+           +-----------+
|method(A') |                 ^
+-----------+                 |
      ^                 +-----------+
      |                 |     B'    |
+-----------+           +-----------+
|     B     |                 ^
|-----------+                 |
|method(B') |           +-----------+
+-----------+           |     C'    |
      ^                 +-----------+
      |
+-----------+
|     C     |
|-----------+
|method(C') |
+-----------+
</code>```

Before writing any code I mention that I have two protocol classes with methods check that have much in common, but request parameters are specific for concrete arguments -- transactions.
The language is scala, but the problem is language-agnostic.
At the first glance it should look like that:

```<code>trait BaseMerchantProtocol
{
  def check(transaction: BaseTransaction) = {
    // some common code...
    println(requestParams(transaction))
    // ...and here as well
  }

  protected def requestParams(transaction: BaseTransaction)
}

class SmsCommerceMerchantProtocol extends BaseMerchantProtocol
{
  override protected def requestParams(transaction: SmsCommerceTransaction) = {
    List("result specific for SmsCommerceTransaction class")
  }
}

class TelepayMerchantProtocol extends BaseMerchantProtocol
{
  override protected def requestParams(transaction: TelepayTransaction) = {
    List("result specific for TelepayTransaction class")
  }
}
</code>```

But of course it does not compile as Liskov substitution principle is violated.

Let's try this one:

```<code>trait IMerchantProtocol {
  def check(transaction: SmsCommerceTransaction)
  def check(transaction: TelepayTransaction)
}

class MerchantProtocol extends IMerchantProtocol
{
  def check(transaction: SmsCommerceTransaction) = {
    doCheck(transaction)
  }

  def check(transaction: TelepayTransaction) = {
    doCheck(transaction)
  }

  private def requestParams(transaction: SmsCommerceTransaction) = {
    List("result specific for SmsCommerceTransaction class")
  }

  private def requestParams(transaction: TelepayTransaction) = {
    List("result specific for TelepayTransaction class")
  }

  private def doCheck(transaction: BaseTransaction) = {
    // some common code...
    println(requestParams(transaction))
    // ...and here as well
  }
}
</code>```

But that won't compile as well -- and with the same reason: doCheck accepts BaseTransaction, but requestParamss have more strict preconditions.

The only thing that I came up with and that works is the following:

```<code>class MerchantProtocol extends IMerchantProtocol
{
  def check(transaction: SmsCommerceTransaction) = {
    doCheck(transaction, requestParams(transaction))
  }

  def check(transaction: TelepayTransaction) = {
    doCheck(transaction, requestParams(transaction))
  }

  private def requestParams(transaction: SmsCommerceTransaction) = {
    List("result specific for SmsCommerceTransaction class")
  }

  private def requestParams(transaction: TelepayTransaction) = {
    List("result specific for TelepayTransaction class")
  }

  private def doCheck(transaction: BaseTransaction, requestParams: List[String]) = {
    // some common code...
    println(requestParams)
    // ...and here as well
  }
}
</code>```

But I don't like that all check methods belong to the same class.
How can I split them by classes?

答:
There is one piece in OOP toolset, that allows you to enforce this kind of design : constructors.

Implement handling classes, so it accepts the request class inside it's constructor. This allows you to specify more concrete version of request class, while not breaking any kind of virtual method or class polymorphism. Concrete handler will require concrete request in it's constructor, while passing it's generic form to it's predecessor.

The problem then gets shifted to how to create concrete handler for concrete type of request. You could use "downchast check" or maybe a Visitor pattern, if you want compile-time typechecking. Encapsulating it in Factory class is given. This problem I believe is the core of your concern. If you can ensure correct handler is paired with correct request, then no problems can occur. Using constructors for parameters ensures, that the handler cannot be called incorrectly outside this factory.


答:
As MainMa already said, the maintenance page is a feature of the site. They are not two sites. The maintenance page is a special page of the site and should therefore go with it in the same tree.

Branches are great for parallel history, but not suitable for about anything else. For different variants, the only practical way is having them together in the tree and use some kind of conditional inclusion. I work on project (not web, but the principle is the same) that delivers slightly different versions for more than 10 customers on 5 different platforms. With conditional compilation this works fine, branches would have devolved into madness long ago. In case of web site, the conditional inclusion is controlled by server configuration.

Note that there is no 'git way of doing things'. Just 'version control best practices' that apply to all version control systems whether you use git, subversion or directories, tarballs and patches (like Linus did for 10 years before he wrote git). And these say that branches are for parallel history, not parallel variants. Git makes branches easier to use, but that does not mean they would suddenly become appropriate for things they were not before.

Title: How does one store a website's holding/maintenance page in Git?

Body:
I'm trying to tidy up the Git repositories for the few sites that I maintain. For each site, I usually create a separate branch in the repo that holds a "maintenance page" or "holding page", which I checkout if I need to take the site down for any reason. This branch is usually called maintenance_page. Normal development is done against master and the live site is also deployed from there.

Whilst the site code in the maintenance_page branch has the same styling as the main (live) site in master, it doesn't really share any history with the master branch - think of it like a mini version of the live site, but with it's own basically unrelated codebase. From time to time, changes that I make to the styling, images, etc. in master would be useful to have in the maintenance_page branch and in these situations, I usually git cherry-pick from master to maintenance_page.

I've been working with this setup for a while now, however, I'm conscious that the whole idea of having the two branches (master and maintenance_page) coexisting in the same repository, but not having anything really in common with each other is not really the "Git way of doing things". I've thought of storing the maintenance_page branch in it's own repo (as it has very little in common with the master branch), however this just seems to complicate the administration of the repositories and also detracts from the simplicity of being able to simply checkout the maintenance_page branch, when I need to take the site down elegantly.

I've had a good read around (see here) (and here) to try to find out how other people handle this kind of thing, but I'm strangely unable to come up with any pointers on how other achieve this.

Does anyone have any suggestions on better ways to achieve this?


问:
How to convert a Bazaar repository to GIT repository?
We have a large bazaar repository and we want to convert it to a git repository. The bazaar repository contains the folders of each of the interns. Any documentation/code prepared by interns is committed in their directory so there are a huge number of commits.

What steps should be performed to securely convert the bazaar repository to a git repository so that we do not lose any commit information.

We firstly need to create a backup of the existing bazaar repository and then convert it.

Edit: I followed this link: http://librelist.com/browser//cville/2010/2/9/migrate-repository-bzr-to-git/

It's working fine on my system with Ubuntu. But when I try to run it on the actual server it gives me EOF error and crashes

```<code>Starting export of 1036 revisions ...
fatal: EOF in data (1825 bytes remaining)
fast-import: dumping crash report to .git/fast_import_crash_11804
</code>```

Edit 2: I also tried it on a new CentOS system and received the following error

```<code>fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
</code>```

答: Currently Debian provides the integration via git-remote-bzr package, which lists as it's homepage https://github.com/felipec/git-remote-bzr.</p>


问:
Do I need to care about 'Thread safety' in java web applications
I have general understanding that what thread safety means , but I don't know much about threads in context of a java webapplication. I am just curious to know that do I need to concern about thread safety while working with web application.

Can their be chances that my web application will cause some problems if I have written codes without concerning about "Thread safety"? Do I need to think about that whether I am using a thread safe collection or not?

答:
Yes.

Every HTTP request (processed by Servlet, JSP, whatever) is processed by a different thread, so you can expect the full set of runtime conditions.

As an example, if you keep a list of items and iterate over it, if at the same time another servlet adds or removes an item to list you may get a ConcurrentModificationException

You could minimize this by using only objects instantiated in the servlet, or Stateless EJBs. But even with this, you may have issues of data inconsistence if you do not design your DB transactions correctly.


答:
Yes you certainly do :) Most (all?) JEE web containers will run your classes with concurrent multiple threads. Also, frameworks like Spring MVC use singleton class instances to service all threads. But following a few simple guidelines will keep your code thread-safe.

You cannot store data that belongs to the user in member variables of singleton classes (typically controllers and validators). User data belongs in the model, which must be user specific.

You don't need to worry about thread-safe collections etc unless multiple threads are going to access them. This is unusual in a web application. For instance something like a "whos logged in" collection will need to be thread safe, but a list of values personal to the user need not be.

Local variables declared inside methods don't need to be thread-safe, as each method invocation is automatically allocated a new variable.

If your web framework provides a "synchronise on session" facility (Spring MVC does)
, I suggest you turn it on. This will mean that if the user hits submit twice in quick succession, the first submisstion will finish executing before the second starts. This gives you the chance to handle it intelligently. Without it there is a small but finite chance that two threads will fight over the user's data structure with odd results guaranteed.

Access to global data structures must be designed with threading issues in mind. For instance a cache of values read from a database will definitely need to be thread-safe.

Avoid using files for intermediate storage. Multi-threaded writes to a file are difficult to synchronise, and almost impossible if multiple JVMs are writing to the same file (as can happen in "server farm" or clustered installations). If you have this need, use a database - transaction control is far simpler.

A special case arises when multiple users can update the same data. But this is not exactly a threading issue - try Google for "long running transactions". It is a sizeable topic.

So yes, you need to be thread aware, but in practice it is not a big problem.

Title: Do I need to care about 'Thread safety' in java web applications

Body:
I have general understanding that what thread safety means , but I don't know much about threads in context of a java webapplication. I am just curious to know that do I need to concern about thread safety while working with web application.

Can their be chances that my web application will cause some problems if I have written codes without concerning about "Thread safety"? Do I need to think about that whether I am using a thread safe collection or not?


问:
Efficiency of self-education
Do you think being self-educated in software development is good? Please give an example of what you have learnt successfully by yourself.</p>

答:
I've learn .NET, C#, ASP.NET and ASP.NET MVC successfully by myself.

It's not like somebody was going to teach them to me.

Self-education is the core of programmer learning. University, colleagues, they all give you tips and hints when you need them but you still have to learn the larger part on your own. Books, blogs, articles, documentation, experimentation on your personal time, that's how you learn.

Title: Efficiency of self-education


问:
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?

Assuming you're working on something large, is it generally accepted practice to get all the functional data harvesting blobs working before any UI, get all the UI working one piece at a time as you go, or something in the middle?

We all know to break work down in to manageable pieces, but the question is ultimately whether UI is included in manageable pieces I suppose.

For the case of the example, consider a GUI application with one root window, but over a dozen tabs in various docks to separate different data components.  Each individual tab has a relatively complex set of moving parts behind it from a functional units perspective.

The example application in this particular question is here with the accompanying blog and the original commercial product.

答:
What I tend to do is to start with a crappy UI: something that just dumps the variable data on the screen. No fonts, no alignment, nothing actually graphical for a long while. Just "Welcome user x" and buttons called "load pic" etc. What's good about this is you will find out if something in the backend is broken.

As the development proceeds, you might find more things need to go on, or fewer. But at some stage, you will decide the backend is near completion. Now you have a UI that contains all the attachments needed, and you can spend a lot of time doing all the graphical stuff.

Beware though, it's not foolproof. You need a bit of foresight to see certain issues arising. For instance, you may need to research UI components to display the data in a sensible way.


问:
Is this a candidate for Singleton?
I have an external thermometer connected via USB that is controlled by my SW. Different parts of my system will use it but never at the same time (all in one thread). However, it is a single device communicating over an established connection so for some reason I think either its method (GetTemperature) should be static or I could do it as Singleton.
I will be happy for suggestions. Thanks</p>

答:
No, it's not a good candidate.

What if you buy a second thermometer in order to get the temperature in two different locations?

What if you want to create a mock or a stub of your thermometer in order to unit test parts which rely on it?

With singleton, you'll end up doing something like:

public class TemperatureRealTimeDisplay
{
    // Show the current temperature to the user.
    public void Show()
    {
        var temperature = Thermometer.Instance.Measure();
        ...
    }
}

public class TemperatureChart
{
    // Record the temperature in order to display a chart over time.
    public void OnTimer()
    {
        var temperature = Thermometer.Instance.Measure();
        ...
    }
}

...

var display = new TemperatureRealTimeDisplay();
var chart = new TemperatureChart();
```

<p>This code:</p>

<ul>
<li><p>Cannot be tested, since it relies on the thermometer which cannot be replaced by a mock or a stub,</p></li>
<li><p>Is difficult to maintain or reuse given its dependency on the actual thermometer.</p></li>
</ul>

<p>If, on the other hand, you use instances and Dependency Injection:</p>

<pre class="lang-cs prettyprint-override"><code>public interface IProbe<TResult>
{
    public TResult Measure();
}

public class HardwareThermometer : IProbe<Temperature>
{
    ...
}

public class RealTimeDisplay<TMetric>
{
    public RealTimeDisplay<TMetric>(IProbe<TMetric> probe)
    {
        this.probe = probe;
    }

    public void Show()
    {
        var current = this.probe.Measure();
        ...
    }
}

public class Chart<TMetric>
{
    public Chart<TMetric>(IProbe<TMetric> probe)
    {
        this.probe = probe;
    }

    public void OnTimer()
    {
        var current = this.probe.Measure();
        ...
    }
}

...

var thermometer = new HardwareThermometer();
var temperatureDisplay = new RealTimeDisplay(thermometer);
var temperatureChart = new Chart(thermometer);
</code>```

you remove the dependencies, making it possible to use general classes RealTimeDisplay and Chart which can then be reused for anything else, like measuring the CPU load or the number of WTFs per second during a coding review. With:

public class ProbeStub : IProbe<int>
{
    ...
}
```

<p>they can easily be tested as well.</p>

<p>Can't you use both dependency injection and singleton? You can, but the point of using a singleton is to being able to use the instance anywhere without having to pass it through parameters down the chain. In my example, you only instantiate <code>thermometer</code> once, making a singleton useless.</p>

<p>The fact that the singleton guarantees you that only one instance will ever be created is not particularly useful in my example. <code>RealTimeDisplay</code> and <code>Chart</code> already receive an instance of a thermometer, so the incentive to create another thermometer is low. The only remaining risk is to end up with code like this in the entry point of the application:</p>

<pre class="lang-cs prettyprint-override"><code>var temperatureDisplay = new RealTimeDisplay(new HardwareThermometer());
var temperatureChart = new Chart(new HardwareThermometer());
</code>```

but it's unlikely that a maintainer will do such change.

Title: Is this a candidate for Singleton?

Body:
No, it's not a good candidate.

What if you buy a second thermometer in order to get the temperature in two different locations?

What if you want to create a mock or a stub of your thermometer in order to unit test parts which rely on it?

With singleton, you'll end up doing something like:

public class TemperatureRealTimeDisplay
{
    // Show the current temperature to the user.
    public void Show()
    {
        var temperature = Thermometer.Instance.Measure();
        ...
    }
}

public class TemperatureChart
{
    // Record the temperature in order to display a chart over time.
    public void OnTimer()
    {
        var temperature = Thermometer.Instance.Measure();
        ...
    }
}

...

var display = new TemperatureRealTimeDisplay();
var chart = new TemperatureChart();

This code:

Cannot be tested, since it relies on the thermometer which cannot be replaced by a mock or a stub,

Is difficult to maintain or reuse given its dependency on the actual thermometer.

If, on the other hand, you use instances and Dependency Injection:

public interface IProbe<TResult>
{
    public TResult Measure();
}

public class HardwareThermometer : IProbe<Temperature>
{
    ...
}

public class RealTimeDisplay<TMetric>
{
    public RealTimeDisplay<TMetric>(IProbe<TMetric> probe)
    {
        this.probe = probe;
    }

    public void Show()
    {
        var current = this.probe.Measure();
        ...
    }
}

public class Chart<TMetric>
{
    public Chart<TMetric>(IProbe<TMetric> probe)
    {
        this.probe = probe;
    }

    public void OnTimer()
    {
        var current = this.probe.Measure();
        ...
    }
}

...

var thermometer = new HardwareThermometer();
var temperatureDisplay = new RealTimeDisplay(thermometer);
var temperatureChart = new Chart(thermometer);

you remove the dependencies, making it possible to use general classes RealTimeDisplay and Chart which can then be reused for anything else, like measuring the CPU load or the number of WTFs per second during a coding review. With:

public class ProbeStub : IProbe<int>
{
    ...
}

they can easily be tested as well.

Can't you use both dependency injection and singleton? You can, but the point of using a singleton is to being able to use the instance anywhere without having to pass it through parameters down the chain. In my example, you only instantiate thermometer once, making a singleton useless.

The fact that the singleton guarantees you that only one instance will ever be created is not particularly useful in my example. RealTimeDisplay and Chart already receive an instance of a thermometer, so the incentive to create another thermometer is low. The only remaining risk is to end up with code like this in the entry point of the application:

var temperatureDisplay = new RealTimeDisplay(new HardwareThermometer());
var temperatureChart = new Chart(new HardwareThermometer());

but it's unlikely that a maintainer will do such change.


答:
You can inject a singleton just fine. Don't understand why people are saying don't use it. A singleton is just something guaranteed to have one and only one instance. Using a singleton doesn't rule out injection.

In Java the recommended way to implement is to use an Enum. Again very injectable.

Have it implement a common interface so that more thermometers can be added/or replaced at a latter date/easily mocked.

```<code>public enum Thermometer implements IThermometer{
    DEFAUlT;

    public BigDecimal getTemperature(){
        return null;
    }
}
</code>```

and then just use constructor injection (or your DI framework of choice) :

```<code>public class MyService{
  public MyService(IThermometer thermometer){
    this.thermometer - thermometer;}
  }
  // do some stuff that uses thermometer.getTemperature();
}
</code>```

Injecting like this, using an interface, means you can easily change the code at a later date to use something that it is not a singleton, or is a the old fashioned getInstance() singleton.

Title: Is this a candidate for Singleton?

Body:
I have an external thermometer connected via USB that is controlled by my SW. Different parts of my system will use it but never at the same time (all in one thread). However, it is a single device communicating over an established connection so for some reason I think either its method (GetTemperature) should be static or I could do it as Singleton.
I will be happy for suggestions. Thanks</p>

Body:
You can inject a singleton just fine. Don't understand why people are saying don't use it. A singleton is just something guaranteed to have one and only one instance. Using a singleton doesn't rule out injection.

In Java the recommended way to implement is to use an Enum. Again very injectable.

Have it implement a common interface so that more thermometers can be added/or replaced at a latter date/easily mocked.

public enum Thermometer implements IThermometer{
    DEFAUlT;

    public BigDecimal getTemperature(){
        return null;
    }
}

and then just use constructor injection (or your DI framework of choice) :

public class MyService{
  public MyService(IThermometer thermometer){
    this.thermometer - thermometer;}
  }
  // do some stuff that uses thermometer.getTemperature();
}

Injecting like this, using an interface, means you can easily change the code at a later date to use something that it is not a singleton, or is a the old fashioned getInstance() singleton.


答:
If you're worried about the effect this will have on your work going forward, talk to your colleague and find out when he'll be notifying management.  If he's planning to wait until the last minute, I'd urge him to tell them sooner, but you can't do more than that.  Ultimately this is his perogative, and if he's told you, I'd assume it was in confidence.

On a more proactive note, you could investigate what the standard handover procedure is, and make sure that your colleague has usefully documented any complicated knowledge that isn't shared with other people on the team.

Title: If your workmate is quitting his job, would you notify your boss?

Body: If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>


问:
How do you deal with clients asking for manual data edits in the database?
I've recently started working on a legacy application that frankly doesn't do all that it should. It's lacking a lot of features, has barely any administration capacities and doesn't check half the data it should.

As such, it's very easy for users to do something stupid and get stuck. "Oops, I added this item of the wrong type to this thingie and now it won't let me remove it". Indeed, the application should have checked for this, but allowed adding the wrong item. And now, when it comes to deleting the wrong item, it becomes extremely protective and refuses that anything be removed.

Problem is, the clients (who are actually users within the company) don't care much for that. They need the application to hold the real-world data as it should be, so they ask the developers to "fix it" by changing the data. In this example, deleting the wrong item. In other cases, it will be reassigning items to different parents, fixing various values, etc...

Since the application has almost no admin GUI, everything ends up being done directly in the database (augh!), risking even more issues down-the-line unless you know exactly how it works (which no one really does considering the massive application).

Ultimately, it feels like the database has become a huge Excel file that devs edit day by day at the whims of the clients, because of failures of the application.

It's obvious to me that fixing the application to avoid such situations should be top priority, but it seems the clients prefer asking for a lot of new features instead and it's accepted as such.

What can a developer do in such a situation? Is it even possible to refuse DB edits in favor of fixing things? There are so many bugs that it feels like they're never going to wait that long...

答:
As you're not in a position to change the policy, what you and colleagues need to do is:

Document the cost of the policy: the amount of time you spend making fixes in the DB as opposed to developing,

Document the risk of the policy: the number of times a fix in the DB had unexpected consequences and how severe they were

Document any other negative consequences - developer attrition, loss of confidence by users etc.

and present it to your immediate managers (you don't want to be seen to be going over anyone's head straight to the top in this sort of environment). In an ideal world you'll already have a support system which tracks this sort of thing but I'm assuming your world is far from ideal! It may make someone see sense, it may not, but in doing so you have fulfilled all your responsibility to the company.

If after that, nothing changes, then I'm afraid you either have to accept the dysfunctional workplace and shrug off all the failings, or move on. When the inevitable crisis happens, a copy of the above in writing will at least cover your back.


问:
will having an event with subscribers prevent an object from being GC'ed?
I have an object, which has an event which in turn has subscribers.
I know that the subscribing objects won't get GC'ed since the delegate they stored for the event is connected to them, thus keeping them connected with the object graph, until one explicitly unsubscribes them. This is only logical since otherwise nothing good will happen when the event is fired.

Does this apply to the Event-owner as well?

I would think it does not, since the subscribing objects do not have a connection to it, to my knowledge.
And again using common sense (which I know does not neccessarily relate to IT-reality):
Nothing bad can happen if the event-owner is GC'ed, only the event will never fire (again).

Is this assumption correct?

答:
Yes, I believe your assumption is correct. I also tried to write some (ugly) code to test this hypothesis:

```<code>class MyClassWithEvent
{
  public event Action Fired;

  void OnFired()
  {
    var d = Fired;
    if (d != null)
      d();
  }
}
class MyClassSubscribing
{
  void M()
  {
  }

  public void DoSubscribe(MyClassWithEvent mcwe)
  {
    mcwe.Fired += M;
  }
}

static class Test
{
  static void Main()
  {
    WeakReference<MyClassWithEvent> wrMcwe;
    WeakReference<MyClassSubscribing> wrMcs;
    GetWeakRefs(out wrMcwe, out wrMcs);

    // no garbage collect should occur just now, for we are not allocating new objects

    // keep one of the objects alive; also try keeping the other one alive instead
    MyClassSubscribing keepAlive;
    wrMcs.TryGetTarget(out keepAlive);
    //MyClassWithEvent keepAlive;
    //wrMcwe.TryGetTarget(out keepAlive);

    // loop not really needed
    while (DateTime.Today.Year < 3000)
    {
      GC.Collect();
      MyClassWithEvent x;
      MyClassSubscribing y;
      Console.WriteLine("Is 'class with event' alive: {0}; is 'class subscribing' alive: {1}", wrMcwe.TryGetTarget(out x), wrMcs.TryGetTarget(out y));
    }
    Console.WriteLine(keepAlive); // or just: GC.KeepAlive(keepAlive);
  }

  static void GetWeakRefs(out WeakReference<MyClassWithEvent> wrMcwe, out WeakReference<MyClassSubscribing> wrMcs)
  {
    var mcwe = new MyClassWithEvent();
    wrMcwe = new WeakReference<MyClassWithEvent>(mcwe);
    var mcs = new MyClassSubscribing();
    wrMcs = new WeakReference<MyClassSubscribing>(mcs);
    // link the two objects
    mcs.DoSubscribe(mcwe);
    // objects mcs and mcwe could be collected after this method exits
  }
}
</code>```

Output: Keeps writing:

Is 'class with event' alive: False; is 'class subscribing' alive: True

If you keep the other object alive, neither object is collected, as we knew.

Both objects are collected if we leave out the keepAlive lines entirely.

Body:
Yes, I believe your assumption is correct. I also tried to write some (ugly) code to test this hypothesis:

class MyClassWithEvent
{
  public event Action Fired;

  void OnFired()
  {
    var d = Fired;
    if (d != null)
      d();
  }
}
class MyClassSubscribing
{
  void M()
  {
  }

  public void DoSubscribe(MyClassWithEvent mcwe)
  {
    mcwe.Fired += M;
  }
}

static class Test
{
  static void Main()
  {
    WeakReference<MyClassWithEvent> wrMcwe;
    WeakReference<MyClassSubscribing> wrMcs;
    GetWeakRefs(out wrMcwe, out wrMcs);

    // no garbage collect should occur just now, for we are not allocating new objects

    // keep one of the objects alive; also try keeping the other one alive instead
    MyClassSubscribing keepAlive;
    wrMcs.TryGetTarget(out keepAlive);
    //MyClassWithEvent keepAlive;
    //wrMcwe.TryGetTarget(out keepAlive);

    // loop not really needed
    while (DateTime.Today.Year < 3000)
    {
      GC.Collect();
      MyClassWithEvent x;
      MyClassSubscribing y;
      Console.WriteLine("Is 'class with event' alive: {0}; is 'class subscribing' alive: {1}", wrMcwe.TryGetTarget(out x), wrMcs.TryGetTarget(out y));
    }
    Console.WriteLine(keepAlive); // or just: GC.KeepAlive(keepAlive);
  }

  static void GetWeakRefs(out WeakReference<MyClassWithEvent> wrMcwe, out WeakReference<MyClassSubscribing> wrMcs)
  {
    var mcwe = new MyClassWithEvent();
    wrMcwe = new WeakReference<MyClassWithEvent>(mcwe);
    var mcs = new MyClassSubscribing();
    wrMcs = new WeakReference<MyClassSubscribing>(mcs);
    // link the two objects
    mcs.DoSubscribe(mcwe);
    // objects mcs and mcwe could be collected after this method exits
  }
}

Output: Keeps writing:

Is 'class with event' alive: False; is 'class subscribing' alive: True

If you keep the other object alive, neither object is collected, as we knew.

Both objects are collected if we leave out the keepAlive lines entirely.


问:
Why is 0 false?
This question may sound dumb, but why does 0 evaluates to false and any other [integer] value to true is most of programming languages?

String comparison

Since the question seems a little bit too simple, I will explain myself a little bit more: first of all, it may seem evident to any programmer, but why wouldn't there be a programming language - there may actually be, but not any I used - where 0 evaluates to true and all the other [integer] values to false? That one remark may seem random, but I have a few examples where it may have been a good idea. First of all, let's take the example of strings three-way comparison, I will take C's strcmp as example: any programmer trying C as his first language may be tempted to write the following code:

if (strcmp(str1, str2)) { // Do something... }
```

<p>Since <code>strcmp</code> returns <code>0</code> which evaluates to <code>false</code> when the strings are equal, what the beginning programmer tried to do fails miserably and he generally does not understand why at first. Had <code>0</code> evaluated to <code>true</code> instead, this function could have been used in its most simple expression - the one above - when comparing for equality, and the proper checks for <code>-1</code> and <code>1</code> would have been done only when needed. We would have considered the return type as <code>bool</code> (in our minds I mean) most of the time.</p>

<p>Moreover, let's introduce a new type, <code>sign</code>, that just takes values <code>-1</code>, <code>0</code> and <code>1</code>. That can be pretty handy. Imagine there is a spaceship operator in C++ and we want it for <code>std::string</code> (well, there already is the <code>compare</code> function, but spaceship operator is more fun). The declaration would currently be the following one:</p>

<pre class="lang-cpp prettyprint-override"><code>sign operator<=>(const std::string& lhs, const std::string& rhs);
</code>```

Had 0 been evaluated to true, the spaceship operator wouldn't even exist, and we could have declared operator== that way:

sign operator==(const std::string& lhs, const std::string& rhs);
```

<p>This <code>operator==</code> would have handled three-way comparison at once, and could still be used to perform the following check while still being able to check which string is lexicographically superior to the other when needed:</p>

<pre class="lang-cpp prettyprint-override"><code>if (str1 == str2) { // Do something... }
</code>```

Old errors handling

We now have exceptions, so this part only applies to the old languages where no such thing exist (C for example). If we look at C's standard library (and POSIX one too), we can see for sure that maaaaany functions return 0 when successful and any integer otherwise. I have sadly seen some people do this kind of things:

#define TRUE 0
// ...
if (some_function() == TRUE)
{
    // Here, TRUE would mean success...
    // Do something
}
```

<p>If we think about how we think in programming, we often have the following reasoning pattern:</p>

<pre class="lang-none prettyprint-override"><code>Do something
Did it work?
Yes ->
    That's ok, one case to handle
No ->
    Why? Many cases to handle
</code>```

If we think about it again, it would have made sense to put the only neutral value, 0, to yes (and that's how C's functions work), while all the other values can be there to solve the many cases of the no. However, in all the programming languages I know (except maybe some experimental esotheric languages), that yes evaluates to false in an if condition, while all the no cases evaluate to true. There are many situations when "it works" represents one case while "it does not work" represents many probable causes. If we think about it that way, having 0 evaluate to true and the rest to false would have made much more sense.

Conclusion

My conclusion is essentially my original question: why did we design languages where 0 is false and the other values are true, taking in account my few examples above and maybe some more I did not think of?

Follow-up: It's nice to see there are many answers with many ideas and as many possible reasons for it to be like that. I love how passionate you seem to be about it. I originaly asked this question out of boredom, but since you seem so passionate, I decided to go a little further and ask about the rationale behind the Boolean choice for 0 and 1 on Math.SE :)

答:
Strangely, zero is not always false.

In particular, the Unix and Posix convention is to define EXIT_SUCCESS as 0 (and EXIT_FAILURE as 1). Actually it is even a standard C convention!

So for Posix shells and exit(2) syscalls, 0 means "successful" which intuitively is more true than false.

In particular, the shell's if wants a process return EXIT_SUCCESS (that is 0) to follow its "then" branch!

In Scheme (but not in Common Lisp or in MELT) 0 and nil (i.e. () in Scheme) are true, since the only false value is #f

I agree, I am nitpicking!

Title: Why is 0 false?


问:
Why (most?) retro computer emulators are single threaded?
All real computer hardware works in parallel. So why most emulators of retro systems (like NES) are single threaded (or I'm not right?)? You have main loop and you counting CPU cycles and after certain cycles activating other hardware like PPU.

Same thing applies to IBM PC and (MDA/CGA/VGA) emulation?

答:
Because most retro-computers had only one CPU (i.e. one core, in today's terminology).

Emulating in parallel a sequential computation is not reasonable (and realistically not feasible).

The graphical cards (or other devices) at that time did not "compute", only "display" (or do input/output). No need to emulate it in parallel.

And the rare exceptions (for instance Channel I/O on IBM/360 did some simple computation in parallel) don't deserve a complex multithreaded emulator.

Also, emulators are often complex to code but today they run faster than the emulated hardware, so there is no reason to spend efforts in accelerating them by multithreading.

It might be different if you wanted to emulate at the lowest hardware level, e.g. emulating the physics of each transistor.

BTW, you could try to write your own (maybe multithreaded!) simulator in free software (perhaps by contributing to unisim)


答:
I've seen the exact same situation, and what we did was assigning one person to do only data correction.

That way clients got their data correction requirements done fast, and the rest of developers, freed up from that burden, could fix the app more quickly.

Once most errors that generate bad data were fixed, the person assigned to data correction was assigned back to developing/maintaining.

Is that is prohibitive, then an alternative battlefront could be (based on real-life experience):

Create motinoring scripts that detect bad data even before the user calls you

Create scripts that make different types of data correction a breeze

Create triggers that reject bad inserts or updates (which may also help recreate the bugs), until bugs are fixed

Title: How do you deal with clients asking for manual data edits in the database?

Body:
I've recently started working on a legacy application that frankly doesn't do all that it should. It's lacking a lot of features, has barely any administration capacities and doesn't check half the data it should.

As such, it's very easy for users to do something stupid and get stuck. "Oops, I added this item of the wrong type to this thingie and now it won't let me remove it". Indeed, the application should have checked for this, but allowed adding the wrong item. And now, when it comes to deleting the wrong item, it becomes extremely protective and refuses that anything be removed.

Problem is, the clients (who are actually users within the company) don't care much for that. They need the application to hold the real-world data as it should be, so they ask the developers to "fix it" by changing the data. In this example, deleting the wrong item. In other cases, it will be reassigning items to different parents, fixing various values, etc...

Since the application has almost no admin GUI, everything ends up being done directly in the database (augh!), risking even more issues down-the-line unless you know exactly how it works (which no one really does considering the massive application).

Ultimately, it feels like the database has become a huge Excel file that devs edit day by day at the whims of the clients, because of failures of the application.

It's obvious to me that fixing the application to avoid such situations should be top priority, but it seems the clients prefer asking for a lot of new features instead and it's accepted as such.

What can a developer do in such a situation? Is it even possible to refuse DB edits in favor of fixing things? There are so many bugs that it feels like they're never going to wait that long...


答:
Delphi.
I've learn Pascal in high-school and see once the IDE, like it, download some tutorials and start learning. And today, continuing the learning process. When you self-learn there are good parts and bad parts:
1) self-learning is the best method to learn, because you really understand what's happening there (good part)
2) you can make big errors by misunderstanding something/get a bad habit and then if you're continue in this manner, is very difficult to correct this.(bad part)

best regards,

Radu

Title: Efficiency of self-education

Body: Do you think being self-educated in software development is good? Please give an example of what you have learnt successfully by yourself.</p>