问:
Is CSV a good alternative to XML and JSON?
Is CSV considered a good option against XML and JSON for programming languages?

I generally use XML and JSON  (or sometimes a plain text file) as flat file storage. However, recently I came across an CSV implementation in PHP. I generally have seen CSV used for inputs in Excel files though, but I have never used it with programming. Would it be better than XML or JSON in any way?

答:
No.

CSV is not really a single format. There is a wide variety of styles for escaping, separators, and other formatting issues that many CSV files in the wild have.

If you are going to be using this as a flat file storage, using JSON will serve you much better. JSON maps to and from objects with much less hassle than you will have kludging CSV to do so.


答:
The answer is, it depends.

CSV is great for certain use cases.  For example as a "streaming" format for large datasets, it's easier to stream than XML/JSON, and CSV files take much less storage space.  I use it to stream datasets in the gigabyte range where other formats are impractical.

It's also really common in certain industries when dealing with legacy systems and workflows. Try importing JSON into MS Excel.

The ODI recently commented about CSV, calling 2014 "The year of CSV"

For "proper" CSV formatting, consider using the CSV mime type in your HTTP responses.

ContentLicense: CC BY-SA 3.0

Title: Is CSV a good alternative to XML and JSON?

Body:
Is CSV considered a good option against XML and JSON for programming languages?

I generally use XML and JSON  (or sometimes a plain text file) as flat file storage. However, recently I came across an CSV implementation in PHP. I generally have seen CSV used for inputs in Excel files though, but I have never used it with programming. Would it be better than XML or JSON in any way?


答:
In General NO. Why? JSON and XML are there basically to get rid of the dreaded CSV. They're the structured approaches of what has been done unstructured with CSV for a long time.
Yes, there are some use-cases where CSV is still prefered but in general in 9 out of 10 cases you're better off not using CSV.</p>


问:
Are design patterns essential for good code?
Are design patterns (e.g. factory pattern, observer, etc...) required to be known to write good code?

I often have no idea of what people mean when they talk about inserting pattern name here pattern and sometimes I realize I‘ve implemented that pattern without knowing it even had a name.

I‘m a self-taught programmer so I try to learn about patterns as I go, but are they necessary?

I find them over-engineered sometimes, like just fancy design concepts that programmers sometimes overestimate and force themselves to use them even if they can write clean and working code that is however not a common pattern.

答:
No. Patterns are best applied to write code that others (and yourself down the road) can understand.

Applying a pattern willy nilly will make it a fancy design concept, but when a pattern fits a problem it is better to use than come up with a creative solution.

Patterns are generally cliches, they work and you likely have used quite a few without realizing it, but this is not an excuse to ignore learning about them as you will find some that you don't know of and it will broaden your own knowledge of programming rather than figuring out everything yourself. As a self-taught programmer this is a vital piece of development to come to terms with


答:
Design patterns are not required in order to write good code.

They are names given to certain known good solutions to common programming problems. Chances are good that you have in fact used some design patterns without known (for example - the iterator pattern is built into several languages as it is so prevalent).

Knowing the names and meanings of design patterns is simply an aid to professional conversation (and for naming of variables and methods) - when you and the other party are familiar with design patterns, it is clearer what is going on.

What you shouldn't do is look for ways to implement a specific design pattern - you should be looking in the other direction - finding the patterns that already exist in the code and optionally, rename the code if they make it clearer.

So, you don't have to study or know the patterns and their names in order to be a good coder - if you are a good coder, however, chances are good that you are already using many patterns without knowing so.

Title: Are design patterns essential for good code?

Body:
Are design patterns (e.g. factory pattern, observer, etc...) required to be known to write good code?

I often have no idea of what people mean when they talk about inserting pattern name here pattern and sometimes I realize I‘ve implemented that pattern without knowing it even had a name.

I‘m a self-taught programmer so I try to learn about patterns as I go, but are they necessary?

I find them over-engineered sometimes, like just fancy design concepts that programmers sometimes overestimate and force themselves to use them even if they can write clean and working code that is however not a common pattern.


答:
Most certainly not.

CSV is a table format that maps very well to data sets or other tabular data. But not all data is tabular! Most generally, we want to serialize object graphs. This can be difficult in the following cases:

circular references

shared subgraphs (e.g. two objects that both contain the same object as a member)

objects of different types to be serialized to the same document

We further want to be able to reliably de-serialize the objects from our storage format.

XML

Is primarily an extensible markup language. It can be shoe-horned to store general data structures as well. Language support for IDs means that complex graphs can be created, although it's best used for trees. A document can be tested for correctness against a specification. There are various problems with this format that can make it impractical, such as the extreme verbosity.

JSON

Is primarily a way to store simple object trees. There is no support for general graphs. JSON has no concept of type beyond primitives string, integer, float, boolean, null and the collection types array and object.

YAML

Most easily understood as an extension of JSON. Has a notion of aliases that allow object graphs of arbitrary complexity to be created. Has a concept of metadata like tags that can be used for proper typing.

CSV

Has nothing, except a single table. If we want to store object graphs, we would have to use a schema like

```<code>#ID,Type,Field1,Field2,...,FieldN

1,String,foo
2,String,bar
3,Array<String>,1,2
</code>```

There are many dialects of CSV that disagree on delimiters, line terminators, quoting, escape characters, and many other issues that make it unsuitable for general (binary) data. All of this makes it rather difficult to process CSV data.

So basically, easy things are difficult or impossible with CSV when using it as a general serialization format.

This criticism does not apply when using it to store truly tabular data like time sheets or a series of measurements. Here, CSV (often in the variant of tab separated values) is usually more compact and easier to use than the other data formats.

Body:
Most certainly not.

CSV is a table format that maps very well to data sets or other tabular data. But not all data is tabular! Most generally, we want to serialize object graphs. This can be difficult in the following cases:

circular references

shared subgraphs (e.g. two objects that both contain the same object as a member)

objects of different types to be serialized to the same document

We further want to be able to reliably de-serialize the objects from our storage format.

XML

Is primarily an extensible markup language. It can be shoe-horned to store general data structures as well. Language support for IDs means that complex graphs can be created, although it's best used for trees. A document can be tested for correctness against a specification. There are various problems with this format that can make it impractical, such as the extreme verbosity.

JSON

Is primarily a way to store simple object trees. There is no support for general graphs. JSON has no concept of type beyond primitives string, integer, float, boolean, null and the collection types array and object.

YAML

Most easily understood as an extension of JSON. Has a notion of aliases that allow object graphs of arbitrary complexity to be created. Has a concept of metadata like tags that can be used for proper typing.

CSV

Has nothing, except a single table. If we want to store object graphs, we would have to use a schema like

#ID,Type,Field1,Field2,...,FieldN

1,String,foo
2,String,bar
3,Array<String>,1,2

There are many dialects of CSV that disagree on delimiters, line terminators, quoting, escape characters, and many other issues that make it unsuitable for general (binary) data. All of this makes it rather difficult to process CSV data.

So basically, easy things are difficult or impossible with CSV when using it as a general serialization format.

This criticism does not apply when using it to store truly tabular data like time sheets or a series of measurements. Here, CSV (often in the variant of tab separated values) is usually more compact and easier to use than the other data formats.


答:
Yes, patterns are essential.  I'll refer you to What if I will not use Software Design Patterns? by Eric Lippert in which he points out:

Variables are a design pattern.

Methods are a design pattern.

Operators -- addition, subtraction, etc -- are a design pattern.

Statements are a design pattern.

Values are a design pattern.

References are a design pattern.

Expressions are a design pattern.

Classes are a design pattern.

Everything you do in programming at all times is a design pattern.
  Most of the time the pattern is so ingrained into your thinking that
  you've stopped thinking of it as "a design pattern". The things that
  you have to learn like "the singleton pattern" and so on are simply
  patterns that haven't (yet) been baked into whatever language you're
  using.

This goes to your point of that you've used design patterns without even knowing its name.  You've also used ones that you did know had names but didn't realize they were patterns.

The key is how people think about patterns... and to an extent I blame education (or maybe the lack of) at times where they expect Design Patterns to be like Legos - "we'll get a Abstract Factory, and Flyweight, and a Singleton and a Facade... and it will all just fit together."  One can often see this in questions asked "What pattern do I need for problem XYZ" before they've really started coding or thinking about the project as a whole.

Looking at the original book A Pattern Language (wikipedia) about building architecture, a Pattern is something that you use to solve a particular design.  You want to put a window in a stud wall?  Well, then you put in some cripples and a header and a bottom plate and so on (wikipedia).  This is a pattern and you do it because you want to put in a window in a wall.

Note that in the above example, the problem came first, then the design pattern.  I need this, this is is how I'll fix it.  The other way around "I'll put some cripples, bottom plate and so on here so that I have a window because I'll need a window" is the wrong way to go about the pattern of a window.  Likewise, it's the wrong way to go about using patterns in software development.

The other thing to realize is that if you have two people working on putting in a stud wall, they can quickly communicate and understand what is going on when they put in a window.  They both know and understand the problem and the pattern and how to apply it.  The same is again true with software.  We've got a problem that we need too many Integer objects being created?  We'll put in a Flyweight.  And thus, two programers have communicated, and know how to solve the problem because they are able to speak of Patterns.


问:
Software Licenses: No Distribution and Private Selling Using Dual Licenses
I recently wrote a couple of WordPress Themes in PHP and was wondering what license I should put on it. I don't mind users reusing my code, but I don't want them to be able to sell and redistribute my themes as I want to retain that right. I heard somewhere that an all rights reserved link would stop the distributing etc... Is that true or do I need to include another license and dual license my Themes?

So to sum it up I want to use a license to stop others from selling and distributing my themes, while at the same time letting others use the code if they want to.

答:
First off:

copyright != license

They are two separate concepts, and each affect creations in separate ways.

I used the site tags so you can click-through for additional research.

Some definitions:

Copyright

Copyright is a legal concept, ... that grants the creator of an original work exclusive rights to its use and distribution

Licensing

an authorization (by the licensor) to use the licensed material (by the licensee).

And the phrase "All rights reserved, ..." is an assertion of copyright over a particular creation.  In other words, when you place the term "All rights reserved, 2014 Kernonnes" then you are stating that a) you created the work, b) you are claiming your full rights under copyright law (generally the Berne convention applies), and c) you are not releasing your rights to the creation.

Your question:

So to sum it up I want to use a license to stop others from selling and distributing my themes, while at the same time letting others use the code if they want to.

You're not clear in how you intend to allow others to access your code so I'll cover a range of options.

You are correct in that you need some sort of license to permit some amount of distributing and using your code.

Here are some options:

You want to give away your code, and you don't care what others do with it.

You can pick from a wide range of free, open-source software licenses.  But I'll skip over the rest of this area since you specifically said you don't want end users doing some things with your code.

You want to give away your code, but you don't want others to give it away

You're going to need a more specific open-source license than the more popular OSS licenses.  OSI (linked above) provides a good overview of the various licenses that are available.

You do not want to write your own license.  Don't even bother considering it - it's a rabbit hole that will lead you to much frustration and a likely unenforceable license.

You want to give away your code, and you want to sell your code, and you don't want others giving it away.

In this case, you need to consider dual licensing.  It's possible one of the open-source licenses will assist you in this effort, but they may not.  You'll need to do a lot more research before you head down this route.


问:
How can I make my PHP development environment more efficient?
I want to start a home-brew pet project in PHP.

I've spent some time in my life developing in PHP and I've always felt it was hard to organize the development environment efficiently.

In my previous PHP work, I've used a windows desktop machine and a linux server for development.

This configuration had it's advantages: it's easy to configure Apache (and it's modules)/PHP/MySql on a linux box, and, at the time, this configuration was the same like on production server.

However, I never successfully set up a debug connection between my Eclipse install and X-debug on server. Transferring files from my local workspace to the server was also very annoying (either ftp or Bazaar script moving files from repository to web root).

For my new setup, I'm considering installing everything on my local machine. I'm afraid that it will slow down workstation performance (LAMP + Eclipse), and that compatibility problems will kick-in.

What would you recommend? Should I develop using two separate machines? On one? Do you have experience using one of above configurations in your work?

答:
Lets take all your concerns one by one.

I do not know about your machine configuration but I have definitely found Eclipse to be more resource hungry. Someone has already mentioned PHPStorm. It is not heavy as Eclipse and has nice set of features too.

For debugging purposes also, PHPStorm is easily configured with Xdebug.Please have a look at this link. You will find most of your remote debugging answers here.

If you want to test in different environments, you can easily create VMs using vagrant. It is very useful esp when you want to replicate production environment and it works like charm. IMHO, you do not need two machines for dev.

Moving files from local workspace to server, you might want to use git and create your own build process going further.

ContentLicense: CC BY-SA 2.5


问:
Should Repositories return IQueryable?
I have been seeing a lot of projects that have repositories that return instances of IQueryable. This allows additional filters and sorting can be performed on the IQueryable by other code, which translates to different SQL being generated. I am curious where this pattern came from and whether it is a good idea.

My biggest concern is that an IQueryable is a promise to hit the database some time later, when it is enumerated. This means that an error would be thrown outside of the repository. This could mean an Entity Framework exception is thrown in a different layer of the application.

I have also run into issues with Multiple Active Result Sets (MARS) in the past (especially when using transactions) and this approach sounds like it would lead to this happening more often.

I have always called AsEnumerable or ToArray at the end of each of my LINQ expressions to make sure the database is hit before leaving the repository code.

I am wondering if returning IQueryable could be useful as a building block for a data layer. I have seen some pretty extravagant code with one repository calling another repository to build an even bigger IQueryable.

答:
What I've seen done (and what I'm implementing myself) is the following:

```<code>public interface IEntity<TKey>
{
    TKey Id { get; set; }
}

public interface IRepository<TEntity, in TKey> where TEntity : IEntity<TKey>
{
    void Create(TEntity entity);
    TEntity Get(TKey key);
    IEnumerable<TEntity> GetAll();
    IEnumerable<TEntity> GetAll(Expression<Func<TEntity, bool>> expression);
    void Update(TEntity entity);
    void Delete(TKey id);
}
</code>```

What this allows you to do is to have the flexibility of doing an IQueryable.Where(a => a.SomeFilter) query on your repo by doing concreteRepo.GetAll(a => a.SomeFilter) without exposing any LINQy business.

Title: Should Repositories return IQueryable?

Body:
What I've seen done (and what I'm implementing myself) is the following:

public interface IEntity<TKey>
{
    TKey Id { get; set; }
}

public interface IRepository<TEntity, in TKey> where TEntity : IEntity<TKey>
{
    void Create(TEntity entity);
    TEntity Get(TKey key);
    IEnumerable<TEntity> GetAll();
    IEnumerable<TEntity> GetAll(Expression<Func<TEntity, bool>> expression);
    void Update(TEntity entity);
    void Delete(TKey id);
}

What this allows you to do is to have the flexibility of doing an IQueryable.Where(a => a.SomeFilter) query on your repo by doing concreteRepo.GetAll(a => a.SomeFilter) without exposing any LINQy business.


答:
I would strongly advise against it.
I might be OK to output CSV at some point (if the user requests it). But it is a bad fit for storage / import purposes.
This is mostly due to the fact that "CSV" is very ill-defined. Does the "C" indicate "comma" or "character" separated? How do you treating text strings which are containing escape characters like "?
Every damned CSV implementation treats escape characters etc. differently, which leads to files which can be ex- but not imported etc.

Excel is a good demonstration: In the english version it uses "," as separator. In Germany, it uses ";". So a german version chokes on english CSV files, and vice versa ...

It's main strength is human readability, which should not be discounted. But I would not rely on it as a storage format, it is too brittle for that purpose. If you have to export files for humans, you might use CSV but even then I would try to use a library which writes to xlsx files (they are freely available).


答:
Eclipse has a Remote Systems plugin.  This will let you directly load, edit, and save files over FTP and SSH just as if they were local files.  No  need to ever use FTP to transfer edited files to the server.

I generally recommend to PHP devs to not work with a local (same machine) WAMP install.  Instead, get used to working with a 'remote' machine via SSH (even if its on your LAN), as that's likely how you'll have to manage a live server.

Title: How can I make my PHP development environment more efficient?

Body:
I want to start a home-brew pet project in PHP.

I've spent some time in my life developing in PHP and I've always felt it was hard to organize the development environment efficiently.

In my previous PHP work, I've used a windows desktop machine and a linux server for development.

This configuration had it's advantages: it's easy to configure Apache (and it's modules)/PHP/MySql on a linux box, and, at the time, this configuration was the same like on production server.

However, I never successfully set up a debug connection between my Eclipse install and X-debug on server. Transferring files from my local workspace to the server was also very annoying (either ftp or Bazaar script moving files from repository to web root).

For my new setup, I'm considering installing everything on my local machine. I'm afraid that it will slow down workstation performance (LAMP + Eclipse), and that compatibility problems will kick-in.

What would you recommend? Should I develop using two separate machines? On one? Do you have experience using one of above configurations in your work?


问:
Where should I start reading AngularJS's source code?
After reading this article I realized that I really didn't read any "serious" source code during my 3-years as a professional developer.

Recently I started a new web-project which makes heavy use of AngularJS, so I decided to start my reading - or, better, decoding [as the blogger wrote] - activity from something that is both challenging and professionally useful.

Now I just need to be pointed in the right direction. Should I just start from the start of the source code or is there a better starting point?

答:
For AngularJS, I think the best place to start is $scope.$apply(), as this ties together changes to the model and the view. From there, move to one of the simpler directives, perhaps ng:value.

Keep the documentation open while you're doing this.


问:
Anemic domain models - what sort of methods a domain object might need?
This question might seem strange, but it's something I've faced sometimes. I've been trying to adopt DDD, however I'm always facing the problem of anemic domain models. The problem is that when I start to think about what should be the behaviors of the domain objects, nothing comes to mind. I've started then to seek on the internet what should be put inside the behavior of the domain objects and many people say that are rules and validations.

The problem is that I've faced the situation many times where to customer who wants the system doesn't want any validation. Once I've asked a customer: "what are the required properties for this object?" and he said "no, I don't want anything like that, sometimes I want to just place one property and leave the others because I'm without time".

Then I've asked: "and what sould be the format of data for this property?" and he said "I don't want anything checked, I want to be free to put as I like". So the customer didn't want validation at all, so I coudln't implement it.

In that case, there's no validations, there are no rules in place. Then I've looked at the controllers (it was built with MVC) to see if there was any logic specific to the domain entities, and there wasn't any. Just logic to read and write data. So in cases like that, is it a problem to have anemic domain models?

Also, I'm working with .NET. In .NET we can put validation with Data Annotations, and we can write getters like properties. So methods to do validation when setting data aren't requireds, because the Data Annotations do the job, also methods to calculate data aren't required, because properties with just a special get can do the job. So what the behaviors become after all?

答:
If the app has no business rules or business processes beyond CRUD, then there really is not behavior to capture in the domain. This is generally not the case in enterprise applications, but may be fairly common in simple web apps.  DDD is really more focused on the former.

Thus the work for a CRUD-based web app will probably revolve around building a useful and usable UI.  The back end should be pretty much a no-brainer.


问:
How to introduce Scrum in a company accustomed to Scrumbutt or Scrumfall?
A colleague of mine works as a consultant. He is recently asked to help a software development company to improve their processes. The company is aware of some of the issues, like the number of bugs or the fact that they can't release their lead product more often than once per year, but nobody there knows what to do.

My colleague identified that they have a primitive in-house process which they call Scrum, but which isn't.

My colleague wants to suggest moving to “the real Scrum”. If he does that, he will encounter two issues:

Managers will reply that they already use Agile, and that it wasn't helpful.

It would be particularly tricky¹ to explain both to the managers and to the CEO of the company that it was not the real Scrum which was used until now, but rather a mix between Scrumfall and Scrumbutt.

What to do?

¹ In this company, two of the three managers claim they know perfectly well Agile and Scrum and apply it flawlessly to their respective teams. Claiming that they know nothing about any of those two subjects would create a hard to handle situation. My colleague's role is also not only to give his opinion, but to apply the “good” methodology for the next three months within this company. Starting by claiming that managers are incompetent in this context is not a solution.

答:
Do you do retrospectives?

If so, use the retrospective to raise and address this issue. Don't talk about doing real Scrum, because they already think they are. Raise specific problems and point out that more text book versions of Scrum already do this.

I was a Scrum Master (actually a manager of an in-house process called PP2). In that position, I did a number of things:

Start doing Scrum. My team didn't care, as there was already a lot of variation in the way the in house process was applied. New joiners and external consultants really appreciated it being Scrum - a process they already knew.

Printed out and stuck up a Scrum poster. Something that clearly showed how you are supposed to do Scrum in simple terms. No debate about this; I didnt make these posters, I just printed them out to help my team.

It sounds like the management are claiming to be doing Scrum; I would hope that means they want to be doing Scrum. Can you nudge them into the right path?

You should show the value of Scrum the best way to do this is to prove it in a new project or product.


问:
How to name arrays or list when the nouns are both singular and plural?
Generally variables are named in the singular Car car; and arrays and list with the pluras: List<Car> cars; or Car[] cars; But what about nouns like fish or media* that are already plural?

*already lost the battle to have the class called Medium.

答:
There are a couple of ways to tackle this problem.  None of them are perfect, but you can find a workable solution.  The key is that your team needs to come up with a standard approach to resolving this and to stick with it.

Here are some of the options:

Different capitalization

The singularly named variable will start with one case (lower case) while the plural variable will start with the other case (upper case).

```<code> var Fish = new List<fish>();  //plural
 var fish = Fish[0];           //singular
</code>```

Deliberate use of improper grammar

Example:

```<code> var Fishes = new List<fish>();  //plural
 var fish = Fishes[0];           //singular
</code>```

or

```<code> var Meese = new List<Moose>();  //plural
 var Moose = Meese[0];           //singular
</code>```

Use group name instead

Example:

```<code> var SchoolOfFish = new List<Fish>();  //plural
 var Fish = SchoolOfFish[0];           //singular
</code>```

Body:
There are a couple of ways to tackle this problem.  None of them are perfect, but you can find a workable solution.  The key is that your team needs to come up with a standard approach to resolving this and to stick with it.

Here are some of the options:

Different capitalization

The singularly named variable will start with one case (lower case) while the plural variable will start with the other case (upper case).

 var Fish = new List<fish>();  //plural
 var fish = Fish[0];           //singular

Deliberate use of improper grammar

Example:

 var Fishes = new List<fish>();  //plural
 var fish = Fishes[0];           //singular

or

 var Meese = new List<Moose>();  //plural
 var Moose = Meese[0];           //singular

Use group name instead

Example:

 var SchoolOfFish = new List<Fish>();  //plural
 var Fish = SchoolOfFish[0];           //singular


答:
```<code> > Should Repositories return IQueryable?
</code>```

NO if you want to do testdriven development/unittesting because there is no easy way to create a mock repository to test your businesslogic (= repository-consumer) in isolation from database or other IQueryable provider.

Title: Should Repositories return IQueryable?

Body:
I have been seeing a lot of projects that have repositories that return instances of IQueryable. This allows additional filters and sorting can be performed on the IQueryable by other code, which translates to different SQL being generated. I am curious where this pattern came from and whether it is a good idea.

My biggest concern is that an IQueryable is a promise to hit the database some time later, when it is enumerated. This means that an error would be thrown outside of the repository. This could mean an Entity Framework exception is thrown in a different layer of the application.

I have also run into issues with Multiple Active Result Sets (MARS) in the past (especially when using transactions) and this approach sounds like it would lead to this happening more often.

I have always called AsEnumerable or ToArray at the end of each of my LINQ expressions to make sure the database is hit before leaving the repository code.

I am wondering if returning IQueryable could be useful as a building block for a data layer. I have seen some pretty extravagant code with one repository calling another repository to build an even bigger IQueryable.

Body:
 > Should Repositories return IQueryable?

NO if you want to do testdriven development/unittesting because there is no easy way to create a mock repository to test your businesslogic (= repository-consumer) in isolation from database or other IQueryable provider.


问:
Why have hardware-accelerated vector graphics not taken off?
I'm working on an app that involves real-time manipulation of vector paths at 60fps, and I'm very surprised by how little information there is on the subject. At first, I tried to implement my idea using CoreGraphics, but it didn't perform adequately for my purposes. I then discovered that there was a Khronos standard for hardware-accelerated vector graphics called OpenVG, and thankfully a kind soul had written an OpenGL ES semi-implementation called MonkVG.

But despite the fact that OpenVG is a very practically useful API, it seems more or less abandoned by Khronos. According to Wikipedia, since 2011, the working group "decided to... not make any regular meeting [sic] for further standardization". The documentation, best I can find, consists of just a single reference card. And what's more, there are barely any examples of OpenVG anywhere on the internet. I can find hundreds of OpenGL tutorials in the blink of an eye, but OpenVG seems conspicuously missing.

You'd think that hardware-accelerated vectors would be more important in today's world of rapidly-increasing resolutions, and it does seem that many companies are implementing their own ways of doing this. For example, Qt and Flash have schemes for hardware-accelerated vectors, and many of Adobe's tools have hardware acceleration as an option. But it seems like the wheel is getting reinvented when a standard already exists!

Is there something I'm missing about OpenVG that makes it unsuitable for real-world use? Or is it just that the standard didn't catch on in time and now it's destined for obscurity? Do you think there's room for a standardized API for hardware-accelerated vector graphics in the future, or will it just be easier to use traditional raster-based techniques? Or are vectors simply on their way out, before they were ever in?

答:
update: See bottom of reply

This answer comes a bit too late, but I hope to shine light to others (particularly now that C++ standard committee wants to incorporate Cairo into std):

The reason nobody really cares about "accelerated vector graphics" is because of how GPUs work.
GPUs work using massive parallelization and SIMD capabilities to colour each pixel. AMD typically works in blocks of 64x648x8 pixels while NVIDIA cards typically work in 32x32 4x4 pixels [See update at the bottom]

Even if they're rendering a 3D triangle, the GPU works on whole quads that this triangle covers. So if a triangle doesn't cover all 8x8 pixels in the block (or 4x4 in the case of nvidia) the GPU will compute the colour of uncovered pixels and then discard the result.
In other words, the processing power for uncovered pixels is wasted. While this seems wasteful, it works incredibly good for rendering large 3D triangles when paired with a massive number of GPU cores (more detailed info here: Optimizing the basic rasterizer).

So, when we look back at vector based rasterization, you'll notice that when drawing lines, even if they're thick, there is a massive blank space. A lot of processing power wasted, and more importantly bandwidth (which is the major cause of power consumption, and often a bottleneck)
So, unless you're drawing an horizontal or vertical line with a thickness multiple of 8, and it perfectly aligns to 8 pixel boundaries, a lot of processing power and bandwidth will be wasted.

The amount of "waste" can be reduced by calculating the hull to render (like NV_path_rendering does), but the GPU is still constrained to 8x8/4x4 blocks (also probably the NVIDIA's GPU benchmarks scale better with higher resolutions, the pixels_covered / pixels_wasted ratio is much lower).

This is why many people don't even care about "vector hw acceleration". GPUs simply aren't well suited for the task.

NV_path_rendering is more the exception than the norm, and they've introduced the novel trick of using the stencil buffer; which supports compression and can significantly reduce bandwidth usage.

Nonetheless, I remain skeptic of NV_path_rendering, and with a bit of googling shows that Qt when using OpenGL (aka the recomended way) is significantly faster than NVIDIA's NV_path_rendering: NV Path rendering
In other words, NVIDIA's slides were "accidentally" comparing XRender's version of Qt. Ooops.

Instead of arguing that "everything vector drawing with hw acceleration is faster", Qt developers are more honest admitting HW accelerated vector drawing is not always better (see how their rendering works explained: Qt Graphics and Performance – OpenGL)

And we've not touched the part of "live editing" vector graphics, which requires triangle strip generation on the fly. When editing complex svgs, this could actually add serious overhead.

Whether it is better or not, it highly depends on the applications; as to your original question "why it hasn't taken off", I hope it is now answered: there are many disadvantages and constraints to take into account, often making a lot of people skeptical and may be even biasing them into not implementing one.

update: I've been pointed out the numbers are completely off base, as the mentioned GPUs don't rasterize in 64x64 & 32x32 blocks but rather 8x8 = 64 and 4x4 = 16. This pretty much nullifies the conclusions of the post.
I will soon update this post later with more up to date information.

ContentLicense: CC BY-SA 4.0


答:
My suggestion would be to try to use a more meaningful name for the list variables.  I know this is sometimes hard to do, though.

For example, instead of List<Car> cars, use something like List<Car> parkedCars.  Instead of Fish[] fish, use something like Fish[] availableFish.

Title: How to name arrays or list when the nouns are both singular and plural?

Body:
Generally variables are named in the singular Car car; and arrays and list with the pluras: List<Car> cars; or Car[] cars; But what about nouns like fish or media* that are already plural?

*already lost the battle to have the class called Medium.


问:
Different ways to see a monad
While learning Haskell I have faced a lot of tutorials trying to explain what are monads and why monads are important in Haskell. Each of them used analogies so it would be easier to catch the meaning.
At the end of the day, I have end up with 3 differents view of what a monad is:

View 1: Monad as a label

Sometimes I think that a monad as a label to a specific type.
For example, a function of type:

```<code>myfunction :: IO Int
</code>```

myfunction is a function that whenever is performed it will yield an Int value.
The type of the result is not Int but IO Int. So, IO is a label of the Int value warning the user to know that the Int value is the result of a process where a IO action has been made.

Consequently, this Int value has been marked as value that came from a process with IO therefore this value is "dirty". Your process is not pure anymore.

View 2: Monad as a private space where nasty things can happen.

In a system where all the process are pure and strict sometimes you need to have side-effects. So, a monad is just a little space that is allow to you for doing nasty side-effects.
In this space your are allow to escape the pure world, go the impure, make your process and then come back with a value.

View 3: Monad as in category theory

This is the view that I don't fully understand.
A monad is just a functor to the same category or a sub-category.
For example, you have the Int values and as a subcategory IO Int, that are the Int values generated after a IO process.

Are these views correct? Which is more accurate?

答:
Don't confuse a monadic type with the monad class.

A monadic type (i.e. a type being an instance of the monad class) would solve a particular problem (in principle, each monadic type solves a different one): State, Random, Maybe, IO. All of them are types with context (what you call "label", but that is not what makes them to be a monad).

For all of them, there is the need of "chaining operations with choice" (one operation depends on the result of the previous). Here comes into play the monad
class: have your type (solving a given problem) be an instance of the monad class and the chaining problem is solved.

See What does the monad class solve?

Title: Different ways to see a monad


问:
Why is inheritance only defined at compile-time?
I found this statement from the gang of four's "Design Patterns" particularly odd; for some context, the authors are comparing inheritance versus composition as reuse mechanisms [p. 19]:

"...you can't change the implementations inherited from parent classes
  at run-time, because inheritance is defined at compile-time."

They go on to say of composition:

"Object composition is defined dynamically at run-time through objects
  acquiring references to other objects."

I am not sure why this phase distinction is important. I am familiar with compiling and inheritance but work as a JavaScript developer, so maybe I'm missing something fundamental.

答:
In Javascript, there seemingly isn't much difference, because there is no compilation. From what I read, what's commonly called inheritance in JS is just creating a prototype chain between different objects.

But in languages like C#, you can create an inheritance hierarchy at compile time through classes inheriting from each other, but you can also change behavior of objects at runtime through patterns like the strategy pattern.


问:
Emulating communication between Android and microcontroller using threads or services or... other?
I am not sure what is the best way for the tasks below: threads, AsyncTasks, Loopers, services? Why? Are there other candidates?

I need threads/Tasks/Services/other for:

Plotting data, (refreshing should be done let's after after specific amount of data has been read)

Generating data, (must being done during whole application runtime indefinitely)

Reading data, (as above)

Saving data on SD card / doing some logs

Interacting with UX

More detailed scenario I must emulate communication between an external device and Android.
External device (I don't have access to that device for some time - I am waiting for it to arrive, that's why I want to emulate the communication - which is a control and measurement system board with ARM microprocessor) generates some data packed in frames in ASCII format.
Android needs to pool? (Maybe there's a way to say: "Hey I have generated data for you. Take it!"? - If yes, could you advise me?) the external device to read data.

答:
This can be achieved by using interrupts[1]. Interrupts can be used with timers, digital inputs and the serial port[2]. Depending on the Arduino variant, some or all of the pins can be used for interrupts.

For regularly occuring tasks, use timer interrupts. For the serial port, use NewSoftSerial.

1. We interrupt this program to bring you a tutorial on… Arduino interrupts

2. NewSoftSerial


问:
Who actually performs the task of log rotation?
I know log rotation is a feature seen in application servers like Oracle's Weblogic. I would like to understand:

What is actually meant by log rotation?

What is it useful?

Who performs the task?

Is this duty performed by the logging frameworks that the developers use or is it handled by the servers themselves? Would log rotation be available in a server like Weblogic if the application doesn't use any logging framework(not java.util.logging) and simply rely on System.out.println() and System.err.println() etc?

答:
Log rotation simply means that log files, once they are too old or too big (there are actually several metrics that can apply here), will be renamed or even deleted and new incoming log data is directed into a new fresh file (at the same location).

The main purpose of log rotation is a) avoiding disk overflow and b) keeping the log files small enough so viewers can still open them.

Given this quick summary, I think it's obvious that the beneficiary of log rotation is not the developer but the admin who has to keep the application running. It's thus usually their responsibility. I.e., as a developer you can just log. You may even suggest a default configuration that redirects log output to a file. And if the application system provides its own log rotation you may suggest a configuration for that, too. It is, however, the admin/user that runs the application and thus has to decide whether keeping ten or hundreds of log files makes sense for them (and their systems). I'd conclude that, even though some applications come with their own rotation systems, running logrotate or similar on a server is "more to the purpose" than having log file rotation "dictated" by the developer.


问:
What is the difference between Avalanche and WaterScrumFall?
Recently I learnt about a new methodology based on waterfall and scrum: Water-Scrum-Fall.

Some say that is the new "reality" and is what scrum pragmatist use nowadays....

But, from the definition of "Avalanche":

The Avalanche model is a Software Engineering project management
  anti-pattern, it is a combination of a sequential process such as the
  Waterfall model and Agile software development methodologies [...]

What do you think about these two models? Aren't those the same?

More info:

http://www.infoq.com/news/2011/12/water-scrum-fall-is-the-norm
http://www.slideshare.net/harsoft/water-scrumfall-isrealityofagileformost

答:
Water-Scrum-Fall is essentially when agile/scrum development processes are only applied to the development team's work(usually the implementation step in waterfall), and most of the previous project management 'waterfall' system remains in place. Those articles are primarily listing it as the reality for most shops where the development team does not have full control of the process, so agile cannot be used across the entire project. I don't believe either one is really trying to say it should be adopted, but it is somewhat common. The second article is more focused on the benefits/drawbacks so companies that find themselves in this model can improve what they have without massive process redesign.

Avalanche is best described as a faulty implementation of scrum where each 'sprint' is most of a waterfall. Each stage/department iterates rapidly on its own subset of work and has to communicate the results of those steps to the other departments. The result is often that each phase of the 'waterfall' is happening at the same time for the entire product. It is also characterized by extreme breakdowns in communication. Features are often being redesigned while being implemented or tested by departments that can't keep track of what stage each feature is at. The result is mass chaos and confusion, extremely difficult to manage projects, and poor morale as work is regularly(read: very frequently) invalidated by changing requirements/design.

The key difference between the two is that Water-Scrum-Fall is scrum in waterfall, which doesn't fundamentally break either model. Avalanche is waterfall in scrum, which is a slow motion catastrophe.


问:
What is the proper copyright information?
I want to know what should I write in copyright part? I mean the copyright part when you right click on the executable, click properties, and click the details tab.

I was developing a little tool that parses some information from output files. It's been a year now and somehow it became something more than a simple, personal tool. We are using it for academic purposes and hopefully it's going to be cited in several academic papers.

BTW, I do not want to make it freeware. Also, I am the only developer of the software. I have used Visual Studio 2010 Ultimate that I obtained for free with the academic license provided by my university.

答:
You are not required to put a notice on your copyrighted works, nor does your copyright diminish if you fail to put a notice on them.  But a copyright notice can have benefits.

When a work is published under the authority of the
  copyright owner, a notice of copyright
  may be placed on all publicly distributed copies or phonorecords. The use of
  the notice is the responsibility of the copyright owner and does not require permission
  from, or registration with, the Copyright Office.

Use of the notice informs the public that a work is protected by copyright,
  identifies the copyright owner, and shows the year of first publication. Furthermore,
  in the event that a work is infringed, if the work carries a proper notice,
  the court will not give any weight to a defendant’s use of an innocent infringement defense—that is, to a claim that the defendant did not
  realize that the work was protected. An innocent infringement
  defense can result in a reduction in damages that the
  copyright owner would otherwise receive.

For works first published on or after March 1, 1989, use
  of the copyright notice is optional.

http://www.copyright.gov/circs/circ03.pdf

The copyright notice should contain:

The symbol © (letter C in a circle); the word “Copyright”; or the abbreviation “Copr.”

The year of first publication.

The name of the copyright owner, an abbreviation by which the name can be recognized, or a generally known alternative designation of
  owner.

Example: © 2012 Jane Doe


答:
I'd also have to say that it depends on what you are trying to achieve. For many problems it doesn't matter much what you choose if the problem is small enough and your choice fits well with the existing system.

Taking a legacy system and trying to shoehorn in a new format can sometimes be a problem as you've introduced more complexity and have a new input system to debug. I've seen this a lot when new people prefer something different than what exists, or when a new format appears and they want to experiment with it. This may or may not be a good idea, it depends on circumstances.

Years ago I worked on a research graph database system that depended on CSV files of various formats. The CSV file importer would build graphs for us and it had many years of work done to debug and optimize the code. It was both fast and flexible and we'd happily use it to bootstrap large research projects. When XML appeared on the scene we added an XML importer but it was not necessarily an improvement in terms of speed or expressing complexity, and certainly XML was not any better at expressing graph structures than CSV. JSON is a lot nicer (and terser) than XML but is similar in many respects so I'd expect a similar result when creating an new importer on that system.

At one point in time we had a customer bring in a massive amount of data in (as we called it) "cobol" format, files with lines of variable length containing markers that indicated how to interpret the bytes that followed on that line. It came from a time when storage was expensive so compactness was a requirement. We imported that data by converting it into CSV format on the fly and feeding it into the CSV importer. That was easy to do and minimized the amount of debugging and maintenance, which are good things. If we had to import that kind of data all of the time we might have built it into the system directly to get performance and efficiency gains.

So, it depends on what you're doing and on what the underlying system does. In my example the CSV importer was solidly engineered and dependable. I'd hesitate to tell you that one format was better or worse without understanding what is going on in the other layers I am building. I love JSON and prefer it, but I know that given certain complex data structures and large enough data sets, CSV files can be made to work very well, too.


问:
Do you have to ban atomics to get good tool support for race detectors?
It seems that Helgrind treats atomics the same way as normal read/write operations. So, using atomics will result in lots of false positives.

I don't know exactly how ThreadSanitizer deals with atomics, but I have found a method called tsan_atomic32_load. I assume that it can distinguish between atomics and normal read/write operations.

In practice, however, the best way seems to be to avoid atomics in order to use tools to detect race conditions. Otherwise, you end up with to many false positives.

There are specialized tools to verify concurrent data structures, e.g., Spin. Although it looks powerful, it seems to be out-of-scope for regular applications.

How do big projects deal with the problem of false-positives? Do they disencourage the use of atomics, do they use suppression files, or do they simply not bother with race detectors?

答:
An approach that you haven't mentioned is to explicitly annotate your code to tell the tool what your custom locking/refcounting code is meant to do. Helgrind has an example of how to do this in its manual:

It is also possible to mark up the effects of thread-safe reference counting using the ANNOTATE_HAPPENS_BEFORE, ANNOTATE_HAPPENS_AFTER and ANNOTATE_HAPPENS_BEFORE_FORGET_ALL, macros. Thread-safe reference counting using an atomically incremented/decremented refcount variable causes Helgrind problems because a one-to-zero transition of the reference count means the accessing thread has exclusive ownership of the associated resource (normally, a C++ object) and can therefore access it (normally, to run its destructor) without locking. Helgrind doesn't understand this, and markup is essential to avoid false positives.

Here are recommended guidelines for marking up thread safe reference counting in C++. You only need to mark up your release methods -- the ones which decrement the reference count. Given a class like this:

```<code>class MyClass {
   unsigned int mRefCount;

   void Release ( void ) {
      unsigned int newCount = atomic_decrement(&mRefCount);
      if (newCount == 0) {
         delete this;
      }
   }
}
</code>```

the release method should be marked up as follows:

```<code>   void Release ( void ) {
      unsigned int newCount = atomic_decrement(&mRefCount);
      if (newCount == 0) {
         ANNOTATE_HAPPENS_AFTER(&mRefCount);
         ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(&mRefCount);
         delete this;
      } else {
         ANNOTATE_HAPPENS_BEFORE(&mRefCount);
      }
   }
</code>```

ThreadSanitizer says:

ThreadSanitizer supports DynamicAnnotations which can make any tricky synchronization (including lock-less synchronization) to be ThreadSanitizer-friendly.

As far as coding style and big projects go:

A search for ANNOTATE_HAPPENS_BEFORE in the Chromium source turns up plenty of results (e.g. this atomic refcount code), so it's definitely possible for a large project to use this approach.

Putting these annotations in your coding style is probably a good idea if you intend to use hand-rolled synchronisation primitives.

At the same time, having to use these annotations a lot indicates that you have a lot of custom thread synchronisation code, which might be bad in itself.

Body:
An approach that you haven't mentioned is to explicitly annotate your code to tell the tool what your custom locking/refcounting code is meant to do. Helgrind has an example of how to do this in its manual:

It is also possible to mark up the effects of thread-safe reference counting using the ANNOTATE_HAPPENS_BEFORE, ANNOTATE_HAPPENS_AFTER and ANNOTATE_HAPPENS_BEFORE_FORGET_ALL, macros. Thread-safe reference counting using an atomically incremented/decremented refcount variable causes Helgrind problems because a one-to-zero transition of the reference count means the accessing thread has exclusive ownership of the associated resource (normally, a C++ object) and can therefore access it (normally, to run its destructor) without locking. Helgrind doesn't understand this, and markup is essential to avoid false positives.

Here are recommended guidelines for marking up thread safe reference counting in C++. You only need to mark up your release methods -- the ones which decrement the reference count. Given a class like this:

class MyClass {
   unsigned int mRefCount;

   void Release ( void ) {
      unsigned int newCount = atomic_decrement(&mRefCount);
      if (newCount == 0) {
         delete this;
      }
   }
}

the release method should be marked up as follows:

   void Release ( void ) {
      unsigned int newCount = atomic_decrement(&mRefCount);
      if (newCount == 0) {
         ANNOTATE_HAPPENS_AFTER(&mRefCount);
         ANNOTATE_HAPPENS_BEFORE_FORGET_ALL(&mRefCount);
         delete this;
      } else {
         ANNOTATE_HAPPENS_BEFORE(&mRefCount);
      }
   }

ThreadSanitizer says:

ThreadSanitizer supports DynamicAnnotations which can make any tricky synchronization (including lock-less synchronization) to be ThreadSanitizer-friendly.

As far as coding style and big projects go:

A search for ANNOTATE_HAPPENS_BEFORE in the Chromium source turns up plenty of results (e.g. this atomic refcount code), so it's definitely possible for a large project to use this approach.

Putting these annotations in your coding style is probably a good idea if you intend to use hand-rolled synchronisation primitives.

At the same time, having to use these annotations a lot indicates that you have a lot of custom thread synchronisation code, which might be bad in itself.


答:
Let's consider a strongly typed language like C#. Here you would define inheritance like this:

class BaseClass
{
    public string SomeMethod()
    {
        return "Hello";
    }
}

class DerivedClass : BaseClass  // Inherits BaseClass
{
    public string AdditionalMethod()
    {
        return "World";
    }
}
```

<p>Usage:</p>

<pre class="lang-cs prettyprint-override"><code>  var d = new DerivedClass();
  Console.WriteLine(d.SomeMethod()); // --> Hello
  Console.WriteLine(d.AdditionalMethod()); // --> World
</code>```

The class DerivedClass inherits the method SomeMethod from BaseClass. This fact is defined at compile time. Sometimes the term "design time" is used instead. The latter term makes clear that the inheritance is already defined in the code text by the programmer.

In contrast, let's look how composition works

interface IReturnsString
{
    string GetString();
}

class ComposedClass
{
    private IReturnsString _a, _b;

    public ComposedClass(IReturnsString a, IReturnsString b) // Constructor
    {
        _a = a;
        _b = b;
    }

    public string SomeMethodA()
    {
        return _a.GetString();
    }

    public string SomeMethodB()
    {
        return _b.GetString();
    }

    public void ChangeBehavior()
    {
        _a = new ClassC(); // ClassC is supposed to implement IReturnsString.
    }
}
```

<p>At runtime you can pass different implementations to the composed class. The composed class could even choose to change its behavoir at runtime.</p>

```var x = new ComposedClass(new ClassA(), new ClassB());
Console.WriteLine(x.SomeMethodA()); // Prints something

x.ChangeBehavior();
Console.WriteLine(x.SomeMethodA()); // Prints something else

var y = new ComposedClass(new ClassD(), new ClassE());
// y behaves in a different way than x
```

Title: Why is inheritance only defined at compile-time?

Body:
I found this statement from the gang of four's "Design Patterns" particularly odd; for some context, the authors are comparing inheritance versus composition as reuse mechanisms [p. 19]:

"...you can't change the implementations inherited from parent classes
  at run-time, because inheritance is defined at compile-time."

They go on to say of composition:

"Object composition is defined dynamically at run-time through objects
  acquiring references to other objects."

I am not sure why this phase distinction is important. I am familiar with compiling and inheritance but work as a JavaScript developer, so maybe I'm missing something fundamental.

Body:
Let's consider a strongly typed language like C#. Here you would define inheritance like this:

class BaseClass
{
    public string SomeMethod()
    {
        return "Hello";
    }
}

class DerivedClass : BaseClass  // Inherits BaseClass
{
    public string AdditionalMethod()
    {
        return "World";
    }
}

Usage:

  var d = new DerivedClass();
  Console.WriteLine(d.SomeMethod()); // --> Hello
  Console.WriteLine(d.AdditionalMethod()); // --> World

The class DerivedClass inherits the method SomeMethod from BaseClass. This fact is defined at compile time. Sometimes the term "design time" is used instead. The latter term makes clear that the inheritance is already defined in the code text by the programmer.

In contrast, let's look how composition works

interface IReturnsString
{
    string GetString();
}

class ComposedClass
{
    private IReturnsString _a, _b;

    public ComposedClass(IReturnsString a, IReturnsString b) // Constructor
    {
        _a = a;
        _b = b;
    }

    public string SomeMethodA()
    {
        return _a.GetString();
    }

    public string SomeMethodB()
    {
        return _b.GetString();
    }

    public void ChangeBehavior()
    {
        _a = new ClassC(); // ClassC is supposed to implement IReturnsString.
    }
}

At runtime you can pass different implementations to the composed class. The composed class could even choose to change its behavoir at runtime.

var x = new ComposedClass(new ClassA(), new ClassB());
Console.WriteLine(x.SomeMethodA()); // Prints something

x.ChangeBehavior();
Console.WriteLine(x.SomeMethodA()); // Prints something else

var y = new ComposedClass(new ClassD(), new ClassE());
// y behaves in a different way than x


答:
Some languages are pretty strongly static, and only allow the specification of the inheritance relationship between two classes at the time of definition of those classes. For C++, definition time is practically the same as compilation time. (It's slightly different in Java and C#, but not very much.) Other languages allow much more dynamic reconfiguration of the relationship of classes (and class-like objects in Javascript) to each other; some go as far as allowing the class of an existing object to be modified, or the superclass of a class to be changed. (This can cause total logical chaos, but can also model real world nasties quite well.)

But it is important to contrast this to composition, where the relationship between one object and another is not defined by their class relationship (i.e., their type) but rather by the references that each has in relation to the other. General composition is a very powerful and ubiquitous method of arranging objects: when one object needs to know something about another, it has a reference to that other object and invokes methods upon it as necessary. As soon as you start looking for this super-fundamental pattern, you'll find it absolutely everywhere; the only way to avoid it is to put everything in one object, which would be massively dumb!
(There's also stricter UML composition/aggregation, but that's not what the GoF book is talking about there.)

One of the things about the composition relationship is that particular objects do not need to be hard-bound to each other. The pattern of concrete objects is very flexible, even in very static languages like C++. (There is an upside to having things very static: it is possible to analyse the code more closely and — at least potentially — issue better code with less overhead.)
To recap, Javascript, as with many other dynamic languages, can pretend it doesn't use compilation at all; just pretence, of course, but the fundamental language model doesn't require transformation to a fixed intermediate format (e.g., a “binary executable on disk”). That compilation which is done is done at runtime, and can be easily redone if things vary too much. (The fascinating thing is that such a good job of compilation can be done, even starting from a very dynamic basis…)

Some GoF patterns only really make sense in the context of a language where things are fairly static. That's OK; it just means that not all forces affecting the pattern are necessarily listed. One of the key points about studying patterns is that it helps us be aware of these important differences and caveats. (Other patterns are more universal. Keep your eyes open for those.)


答:
Copyright law varies in different jurisdictions. Not every country requires the copyright symbol that is used in the US.

But the main issue is: do you own the copyright in the first place?

You mention "my University". If you have developed this software in your role as student or member of academic staff, you need to check the policy of your University regarding copyright. Many universities claim ownership of all student and staff works. This is often enforced by the agreement that is part of the application process.

In addition, universities often have a specific form or wording to be used in the copyright notice, along with a disclaimer.

Bottom line: you need to check with your University.

But to answer your question: a copyright notice has to include the word copyright, the name of the entity, and the year the work was published.

Title: What is the proper copyright information?

Body:
I want to know what should I write in copyright part? I mean the copyright part when you right click on the executable, click properties, and click the details tab.

I was developing a little tool that parses some information from output files. It's been a year now and somehow it became something more than a simple, personal tool. We are using it for academic purposes and hopefully it's going to be cited in several academic papers.

BTW, I do not want to make it freeware. Also, I am the only developer of the software. I have used Visual Studio 2010 Ultimate that I obtained for free with the academic license provided by my university.


问:
What's the origin of foo and bar?

Possible Duplicate:

  Using “Foo” and “Bar” in examples

I know AT&T labs used them in their Unix days, but do they have even deeper histories?

答:
From Wikipedia:

The origins of the terms are not known with certainty, and several anecdotal theories have been advanced to identify them. Foobar may have derived from the military acronym FUBAR and gained popularity due to the fact that it is pronounced the same. In this meaning it also can derive from the German word furchtbar, which means awful and terrible and described the circumstances of the Second World War.

FOO is an abbreviation of Forward Observation Officer, a British Army term in use as early as the First World War. The etymology of foo is explored in the Internet Engineering Task Force (IETF) Request for Comments 3092, which notes usage of foo in 1930s cartoons including The Daffy Doc (with Daffy Duck) and comic strips, especially Smokey Stover and Pogo. From there the term migrated into military slang, where it merged with FUBAR.

"Bar" as the second term in the series may have developed in electronics, where a digital signal which is considered "on" with a negative or zero-voltage condition is identified with a horizontal bar over the signal label; the notation for an inverted signal foo would then be pronounced "foo bar".

Title: What's the origin of foo and bar?


问:
How do you reduce geographic latency in web application (MVC ASP.net) backed by a single database
I'm working on a modest sized web application that receives circa 30k unique users per day, this is an MVC C# application hosted on 3 web servers and backed by a single SQL server, everything is hosted in one data center.

The issue is we are seeing dom complete times upto 3 times slower in some parts of the world. We have done all the usual "quick wins" as suggested by yslow - and are now looking to make architectural changes.

Our initial plan is to create a web api that wraps our server tier, and then host the web tier in a second data center in a different part of the world closer to the users with the poor latency. The hope is that this in combination with caching and will help reduce latency. I appropriate that there will be latency between the api service tier and web tier, but the hope is that these will be lightweight http calls.

Does this make sense?

答:
Yes, it does make sense. And you could do some more.

The difficulty with lightweight HTTP calls is that unless the connection is kept open for the calls (not uncommon today), each call needs to reestablish the three way handshake for TCP, and renegotiate the bandwidth (starting from a low point).

This can be improved upon by having your computer in the remote datacenter create an always open connection itself to the computer at your main datacenter.  By remaining open, the connection doesn't need to renegotiate the bandwidth and can properly scale up and remain scaled up to the maximum bandwidth.

Working with two known endpoints, it is also possible to compress the data that goes between them to further improve the resource.

There are other aspects of TCP tuning that can be done to further improve performance between known endpoints and across a known connection.

Unfortunately, I'm not a system or network administrator and can't offer particulars for this.  This description is based on a product that I used at a previous company.  If you poke around, you can find other press releases with hints how Netli did it.

That said, Netli was purchased by Akamai and incorporated their technology into the Akamai stack.  You may find Akamai (or other CDNs) are able to provide that functionality for you.

Note that its possible to do this as "just a proxy" at the remote site without having to put another system doing work.


问:
How to most effectively debug code?
Bugs creeping into code can be minimized, but not entirely eliminated as it is written - programmers are, although many would disagree, only humans.

When we do detect an error in our code, what can we do to weed it out? How should we approach it to make most effective use of our valuable time and enable us to spend less time trying to find it and more time coding? Also, what should we avoid when debugging?

Note here that we're not talking about preventing bugs; we're talking about what to do when bugs do appear. This is a wide field, I know, and may be highly dependent on language, platform and tools. If so, keep to encompassing answers such as mindsets and general methods.

答:
I like most of the other answers, but here are some tips on what to do BEFORE you do any of that.  Will save you beaucoup de time.

Determine if there really is a bug.  A bug is ALWAYS a difference between system behavior and requirements; the tester ought to be able to articulate expected and actual behavior.  If he is unable to provide support for the expected behavior, there is no requirement and there is no bug-- just someone's opinion.  Send it back.

Consider the possibility that the expected behavior is wrong.  This could be due to a misinterpretation of the requirement.  It could also be due to a defect in the requirement itself (a delta between a detailed requirement and a business requirement).  You can send these back too.

Isolate the problem.  Only experience will teach you the fastest way to do this-- some people can almost do it with their gut.  One basic approach is to vary one thing while keeping all other things constant (does the problem occur on other environments?   with other browsers?  in a different test region?  at different times of the day?)  Another approach is to look at stack dumps or error messages-- sometimes you can tell just by the way it is formatted which component of the system threw the original error (e.g. if it's in German you can blame that third party you work with in Berlin).

If you have narrowed it down to two systems that collaborate, inspect the messages between the two systems via traffic monitor or log files, and determine which system is behaving to spec and which one is not.  If there are more than two systems in the scenario, you can perform pairwise checks and work your way "down" the application stack.

The reason why isolating the problem is so critical is that the problem may not be due to a defect in code that you have control over (e.g. third party systems or the environment) and you want to get that party to take over as quickly as possible.  This is both to save you work and to get them on point immediately so that resolution can be achieved in as short a time frame as possible.  You don't want to work on an issue for ten days only to find it's really an issue with someone else's web service.

If you have determined that there really is a defect and it really is in code that you control, you can further isolate the problem by looking for the last "known good" build and inspecting source control logs for changes that may have caused the issue.  This can save a lot of time.

If you can't figure it out from source control, now is the time to attach your debugger and step through the code to figure it out.  Chances are by now you have a pretty good idea of the problem anyway.

Once you know where the bug is and can think of a fix, here's a good procedure for fixing it:

Write a unit test that reproduces the problem and fails.

Without modifying the unit test, make it pass (by modifying application code).

Keep the unit test in your test suite to prevent/detect regression.

Title: How to most effectively debug code?


答:
Bug, error, problem, defect - whatever you want to call it, it doesn't make much difference. I'll stick to problem since that's what I'm used to.

Figure out what the perception of the problem is: translate from a customer's 'Bob is still not in the system' to 'When I try to create a user record for Bob, it fails with a duplicate key exception, although Bob isn't already in there'

Figure out if it's really a problem or just a misunderstanding (indeed, Bob isn't in there, there is nobody called bob, and insert should work).

Try to get minimal reliable steps you can follow to reproduce the problem - something like 'Given a system with a user record 'Bruce', when a user record 'Bob' is inserted, then an exception occurs'

This is your test - if possible, put it in an automated test harness that you can run again and again, this will be invaluable when debugging. You can also make it part of your test suite to ensure that that particular problem doesn't reappear later on.

Get your debugger out and start putting breakpoints - figure out the code path when you run your test, and identify what's wrong. While you do that, you can also refine your test by making it as narrow as possible - ideally a unit test.

Fix it - verify your test passes.

Verify the original problem as described by the customer is also fixed (very important - you might just have fixed a subset of the problem). Verify you didn't introduce regressions in other aspects of the program.

If you're very familiar with the code, or if the problem or fix is obvious, you can skip some of those steps.

How should we approach it to make most effective use of our valuable time and enable us to spend less time trying to find it and more time coding?

I take issue with that, as it implies that writing new code is move valuable than having a high quality working program. There is nothing wrong with being as effective as possible at fixing problems, but a program doesn't necessarily get better by just adding more code to it.

Title: How to most effectively debug code?

Body:
Bugs creeping into code can be minimized, but not entirely eliminated as it is written - programmers are, although many would disagree, only humans.

When we do detect an error in our code, what can we do to weed it out? How should we approach it to make most effective use of our valuable time and enable us to spend less time trying to find it and more time coding? Also, what should we avoid when debugging?

Note here that we're not talking about preventing bugs; we're talking about what to do when bugs do appear. This is a wide field, I know, and may be highly dependent on language, platform and tools. If so, keep to encompassing answers such as mindsets and general methods.


问:
Why Should I Avoid Inline Scripting?
A knowledgeable friend recently looked at a website I helped launch, and commented something like "very cool site, shame about the inline scripting in the source code".

I'm definitely in a position to remove the inline scripting where it occurs; I'm vaguely aware that it's "a bad thing".  My question is: what are the real problems with inline scripting?  Is there a significant performance issue, or is it mostly just a matter of good style?  Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site?  If you pulled up to a website, and took a peek at the source code, what factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job?

Okay, that question turned into multiple questions in the writing.  But basically, inline scripting - what's the deal?

答:
It's generally good to try to keep HTML and JS generally separated.  HTML is for the view, JS is for the application logic.  But in my experience extreme decoupling of html and javascript (for the sake of purity) does not make it more maintainable; it can actually be less maintainable.

For example, I sometimes use this pattern (borrowed from ASP.net) in setting up event handlers:

```<code><input type="button" id="yourId" onclick="clickYourId()" />
</code>```

or

```<code><input type="button" id="yourId" onclick="clickYourId(this)" />
</code>```

There's no mystery what is triggering an event to happen.  The reason is that six months later you can inspect the element (eg, in Chrome) and see immediately what javascript event is triggered.

On the other hand, imagine you are reading someone's else's code, which is a hundred thousand lines, and you come across a magical element that fires off a javascript event:

```<code><input id="yourId"  />
</code>```

How can you easily tell me what javascript method this is calling?  Chrome has made this easier, but perhaps the event is bound to the id, or perhaps it's bound to the first child of the container.  Maybe the event is attached to the parent object.  Who knows?  Good luck finding it.  :)

Also, I would argue that hiding javascript completely from the designer may actually increase the likelihood of them breaking it on an update.  If someone edits code for an magically active element, what indication in the code do they have that would let them know this is an active element on the page?

So in short, best practice is to separate HTML and Javascript. But also understand rules of thumb are sometimes counterproductive when carried to the extreme.  I'd argue for a middle-road approach.  Avoid large amounts of inline js.  If you do use inline, the function signature should be very simple like:

```<code>1. emptyFunction()
2. doCallWithThis(this)
3. atTheExtremOnlyPassOneNumber(2)
</code>```

Title: Why Should I Avoid Inline Scripting?

Body:
It's generally good to try to keep HTML and JS generally separated.  HTML is for the view, JS is for the application logic.  But in my experience extreme decoupling of html and javascript (for the sake of purity) does not make it more maintainable; it can actually be less maintainable.

For example, I sometimes use this pattern (borrowed from ASP.net) in setting up event handlers:

<input type="button" id="yourId" onclick="clickYourId()" />

or

<input type="button" id="yourId" onclick="clickYourId(this)" />

There's no mystery what is triggering an event to happen.  The reason is that six months later you can inspect the element (eg, in Chrome) and see immediately what javascript event is triggered.

On the other hand, imagine you are reading someone's else's code, which is a hundred thousand lines, and you come across a magical element that fires off a javascript event:

<input id="yourId"  />

How can you easily tell me what javascript method this is calling?  Chrome has made this easier, but perhaps the event is bound to the id, or perhaps it's bound to the first child of the container.  Maybe the event is attached to the parent object.  Who knows?  Good luck finding it.  :)

Also, I would argue that hiding javascript completely from the designer may actually increase the likelihood of them breaking it on an update.  If someone edits code for an magically active element, what indication in the code do they have that would let them know this is an active element on the page?

So in short, best practice is to separate HTML and Javascript. But also understand rules of thumb are sometimes counterproductive when carried to the extreme.  I'd argue for a middle-road approach.  Avoid large amounts of inline js.  If you do use inline, the function signature should be very simple like:

1. emptyFunction()
2. doCallWithThis(this)
3. atTheExtremOnlyPassOneNumber(2)


答:
What are the real problems with inline scripting?

Inline scripting is bad and should be avoided because it makes the code more difficult to read.

Code that is difficult to read is difficult to maintain. If you can't easily read it and understand what's going on, you won't be able to easily spot bugs. If it's difficult to maintain, it will waste more of your time later when there are problems.

The difficulty usually comes from nested encodings. There is a problem in the next line of code, can you spot it?

```<code><a onclick='alert("What\'s going wrong here?")'>Alert!</a>
</code>```

Ideally code is written in a way that makes it easy to spot when there's a mistake. Joel Spolsky wrote a great article that emphasizes this point back in 2005. The code examples could use some significant improvement, as they're showing their age being 9 years old, but the underlying concept still stands strong: write code in a way that makes it easy to pick out bugs.

Is there a significant performance issue, or is it mostly just a matter of good style?

Inline scripting leads to repetition. Instead of changing one line of code to affect 100 pages, you'll likely need to change 100 pages individually. This along with poor readability seriously affect performance of the maintainer. Programming time has a real cost that affect the bottom line of a business faster than the few milliseconds from most code optimizations. Certainly optimizing bottlenecks is important, but the performance difference of the code is negligible in this case.

Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site?

No. If it's stupid and it works, it isn't stupid.

The programming corollary to this is: if it's stupid code and it works, it isn't stupid code. Focus on the real issues before trying to fix something that isn't broken. When the inline code eventually needs an update, whether that's in six hours, six months, or six years, fix the code in a way that makes future maintenance on it easier.

What factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job?

I tend to prefer to define "professional" merely as someone who is paid to perform a task, rather than assume that they possess any significant ability in what they're being paid to do. Many professionals are certainly capable of performing good work, but more often than not I find myself recoiling in horror at the terrible job that other professionals have done rather than something that an amateur has come up with. Much of my work to date has involved salvaging train-wreck projects that were botched by the initial developers, so your mileage may vary.

With all that said, it's generally easy to pick out enterprise quality programming

Title: Why Should I Avoid Inline Scripting?

Body:
A knowledgeable friend recently looked at a website I helped launch, and commented something like "very cool site, shame about the inline scripting in the source code".

I'm definitely in a position to remove the inline scripting where it occurs; I'm vaguely aware that it's "a bad thing".  My question is: what are the real problems with inline scripting?  Is there a significant performance issue, or is it mostly just a matter of good style?  Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site?  If you pulled up to a website, and took a peek at the source code, what factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job?

Okay, that question turned into multiple questions in the writing.  But basically, inline scripting - what's the deal?

Body:
What are the real problems with inline scripting?

Inline scripting is bad and should be avoided because it makes the code more difficult to read.

Code that is difficult to read is difficult to maintain. If you can't easily read it and understand what's going on, you won't be able to easily spot bugs. If it's difficult to maintain, it will waste more of your time later when there are problems.

The difficulty usually comes from nested encodings. There is a problem in the next line of code, can you spot it?

<a onclick='alert("What\'s going wrong here?")'>Alert!</a>

Ideally code is written in a way that makes it easy to spot when there's a mistake. Joel Spolsky wrote a great article that emphasizes this point back in 2005. The code examples could use some significant improvement, as they're showing their age being 9 years old, but the underlying concept still stands strong: write code in a way that makes it easy to pick out bugs.

Is there a significant performance issue, or is it mostly just a matter of good style?

Inline scripting leads to repetition. Instead of changing one line of code to affect 100 pages, you'll likely need to change 100 pages individually. This along with poor readability seriously affect performance of the maintainer. Programming time has a real cost that affect the bottom line of a business faster than the few milliseconds from most code optimizations. Certainly optimizing bottlenecks is important, but the performance difference of the code is negligible in this case.

Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site?

No. If it's stupid and it works, it isn't stupid.

The programming corollary to this is: if it's stupid code and it works, it isn't stupid code. Focus on the real issues before trying to fix something that isn't broken. When the inline code eventually needs an update, whether that's in six hours, six months, or six years, fix the code in a way that makes future maintenance on it easier.

What factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job?

I tend to prefer to define "professional" merely as someone who is paid to perform a task, rather than assume that they possess any significant ability in what they're being paid to do. Many professionals are certainly capable of performing good work, but more often than not I find myself recoiling in horror at the terrible job that other professionals have done rather than something that an amateur has come up with. Much of my work to date has involved salvaging train-wreck projects that were botched by the initial developers, so your mileage may vary.

With all that said, it's generally easy to pick out enterprise quality programming


问:
Separating UI from logic in JavaScript modules
I'm refactoring some custom JavaScript modules written to support our mapping functionality. I'm looking to make them much more unit-testable and be able to plug pieces in and out more easily.

My question is related to having UI manipulation and business logic be in the same module. I know that having the UI part makes unit testing a little more difficult. I would think also decoupling the UI part would enable other people to add their own UI layer if they wanted to change the look and feel while still keeping the core functionality.

Edit: I'm more working with Dojo modules since that what the mapping API is built on top of. I figured since Dojo comes with it we would use that. I'm finding that Dojo modules don't lend themselves to being easily tested (I tried using Doh and it is the most unintuitive testing framework I've ever worked with). I'm thinking of making more vanilla JS modules and only tried to use what I absolutely need to from Dojo. That's where I got the idea to maybe separate the UI layer from the logic for each module as well.

Does anyone have suggestions on how those can be decoupled?

答:
Keep your data in HTML, your styles in CSS, and your interactions in JS.

What this means is that you'll need to toggle styling hooks, such as classes or attributes to change the UI state. That way, when you want to change how the UI looks, you only need to update CSS, and can generally avoid script changes.

There will be a few cases where you may need to animate a style via JS. Particularly for positioning. Try to keep the JavaScript focused on the state of the code, rather than how it should look. When you go to unit test, it'll give you something concrete to check for. I.E. manually trigger an event on an element in a widget, and check that the widget entered the appropriate state from that event by checking that it has the right classes and attribute values.


答:
Here's a few reasons.

Inline script cannot be minified (converted to a shorter version through symbol reduction).  Not a concern on broadband but consider a mobile device in a low bandwidth area, or users who are on global data roaming-- every byte may count.

Inline script cannot be cached by the browser unless the page itself is cacheable (which would make for a very dull page).  External Javascript files need only be retrieved once, even if the page content changes every time.  Can seriously affect performance on low bandwidth connections.

Inline script is harder to debug because the line number associated with any error is meaningless.

Inline script is reputed to interfere with accessibility (508/WAI) considerations, although that does not mean all inline script causes issues.  If you end up with a screen reader announcing script content you have a problem!  (Never seen this happen though).

Inline script cannot be tested independently of its page; external Javascript files can be run through independent testing, including automated tests.

Inline script can lead to poor separation of concerns (as described by many of the other answers here).

Title: Why Should I Avoid Inline Scripting?


问:
Achieving multiple tasks within one loop
With relation to what's considered good OOP engineering principles, SOLID, DRY, KISS etc
I am wondering whether to complete multiple tasks within one loop when easily done.

The problem is that this conflicts with some principles (SRP), but could also partially lean in favor of others (DRY, KISS).

A simple example would be

We have a array of image file paths and we want to complete 4 overall tasks per image

get size of image
resize the image
apply a watermark to the image
apply a border to the image
```

This could be achieved by using one for each loop on the array, and applying each function one after the other, or we could do this with four separate foreach loops, one for getting the size, one performing a resize and so on for the other tasks.

I am trying to adhere to these principles as much as possible to remove any bad habits and improve my coding skills.

答:
If your program is already working and a predictable result can be expected (in other words there are no bugs) you are left with two things to improve your code:

1) Optimisation - try to make your code run faster, take less memory, perform less operations etc.
2) Code readability - make your code more readable and understandable to reduce the WTF per Minute rating.

Funny thing, these two often contradict each other. To make the code more readable, you need to separate it into smaller classes, divide functions into smaller functions etc.
Optimization, on the other hand, would rather have many things stored locally to perform less calls to other classes, get some object nested in a parent object etc.

You example is interesting, because having 4 loops one after each other would make the code less readable, take more space (curly braces are often taking one line each) and perform less if the compiler wouldn't compile it as one loop anyway. In your case, PHP doesn't have a compiler, so it might actually affect performance, even if a little bit.

A simple advice would be: don't over engineer, strive to get your program working as first priority, make it readable and understandable and then optimize the bottle necks; sacrifice readability for optimization on performance critical code providing comments for that part.

A good book that helped many to understand how to be a better programmer: Clean Code: A Handbook of Agile Software Craftsmanship


答:
I beg to differ to what Creative Magic said. Unfortunately, our craft ain't easy and it is the same book that leads me to the conclusion that you should not do those 4 tasks within the loop itself, as that indeed violates the SRP.

Nevertheless, a simple change of your design satisfies all your desires: Let's start by implementing the four operations on their own, but for just one image (file). No loops, just the nitty gritty detail. Apart from maybe the first operation, all of these take an image as input, and return a slightly modified image - which as it just so happens, is the input to the next operation.

Mathematically, we call this a function composition. I don't know if there is a PHP library to directly support this, but nevertheless what you end up with is a composed function which needs to be applied to each of the images. So you have one loop with one statement and one responsibility.

As an example of how this may look like in another language, consider this pseudo code (similar to Google's guava library for Java) :

```<code>composedFunction = Functions.compose(applyBorderFunction, applyWaterMarkFunction,
                      resizeImageFunction, fileToImageFunction)
resultingImages = allMyImageFiles.transform(composedFunction)
</code>```

If your language is not capable of expressing higher-order functions, then you can think of the transform call as one loop, and within that loop you may have to loop over your individual functions. Nevertheless, the responsibility of that resulting function is not implementing the individual transformations of your image, but simply applying those operations, whatever they may be.

So you end up with a clear separation of those two things: one, individual (and again properly separated) definitions of the operations you perform on your images, and two, the application of these operations.

As usual, you can find a design that is SOLID, and still DRY/KISS/whatever. It does take a lot of experience though to play around with different design options in your mind to find one that satisfies your needs.

Title: Achieving multiple tasks within one loop

Body:
With relation to what's considered good OOP engineering principles, SOLID, DRY, KISS etc
I am wondering whether to complete multiple tasks within one loop when easily done.

The problem is that this conflicts with some principles (SRP), but could also partially lean in favor of others (DRY, KISS).

A simple example would be

We have a array of image file paths and we want to complete 4 overall tasks per image

get size of image
resize the image
apply a watermark to the image
apply a border to the image
```

This could be achieved by using one for each loop on the array, and applying each function one after the other, or we could do this with four separate foreach loops, one for getting the size, one performing a resize and so on for the other tasks.

I am trying to adhere to these principles as much as possible to remove any bad habits and improve my coding skills.

Body:
I beg to differ to what Creative Magic said. Unfortunately, our craft ain't easy and it is the same book that leads me to the conclusion that you should not do those 4 tasks within the loop itself, as that indeed violates the SRP.

Nevertheless, a simple change of your design satisfies all your desires: Let's start by implementing the four operations on their own, but for just one image (file). No loops, just the nitty gritty detail. Apart from maybe the first operation, all of these take an image as input, and return a slightly modified image - which as it just so happens, is the input to the next operation.

Mathematically, we call this a function composition. I don't know if there is a PHP library to directly support this, but nevertheless what you end up with is a composed function which needs to be applied to each of the images. So you have one loop with one statement and one responsibility.

As an example of how this may look like in another language, consider this pseudo code (similar to Google's guava library for Java) :

composedFunction = Functions.compose(applyBorderFunction, applyWaterMarkFunction,
                      resizeImageFunction, fileToImageFunction)
resultingImages = allMyImageFiles.transform(composedFunction)

If your language is not capable of expressing higher-order functions, then you can think of the transform call as one loop, and within that loop you may have to loop over your individual functions. Nevertheless, the responsibility of that resulting function is not implementing the individual transformations of your image, but simply applying those operations, whatever they may be.

So you end up with a clear separation of those two things: one, individual (and again properly separated) definitions of the operations you perform on your images, and two, the application of these operations.

As usual, you can find a design that is SOLID, and still DRY/KISS/whatever. It does take a lot of experience though to play around with different design options in your mind to find one that satisfies your needs.


问:
Exception handling in a program that needs to run 24/7
I have read that we should only catch exceptions that can be handled, which makes catching the base exception class (C# in this case) a bad idea (on top of other reasons). I am currently part of a project in which I so far have yet to see anything but the base exception being caught. I mentioned that it is considered bad practice to do so, but the response was "This service needs to run 24/7, so that is the way it is.".

Since I did not have a good response for how to properly handle exceptions in a program that needs to run 24/7, I am now here. I have not managed to find any information / suggestions on how to deal with exception handling in "critical" programs / services that needs to run around the clock (and in this case I believe it may be ok if the service is down for a minute or two, so not even critical). I understand it depends on the exact nature of the program. The requirements for a program that can cause life threatening issues are quite different compared to a log scanner for an online game.

Two examples:

1: A type-ahead service for customers of the Brittish railways, used when they searching online for railway stations.

2: A program that automatically controls the railway switches for the above railways based on realtime information provided from various sensors in the tracks, trains etc.

The first program would probably not cause a major issue if it went down for a minute or two, wheras the latter could cause human casualties. Suggestions on how to deal with each? Pointer to where I can find more information and thoughts on this issue?

答:
With regards to point 2: don't use C#. It's not a realtime language and you will get hurt if you try to use it as such.

For point 1: you could go the erlang way: let it crash, then restart