答:
Badly, mostly.

It was pretty common to see sloppy, error-prone code like this:

```<code>struct Node {
  int data;
  Node *next;
  Node* prev;
};

\\ ...

Node* pWotsit = findBestCheese(pHead);
pWotsit->pNext->pPrev = pWotsit->pPrev;
pWotsit->pPrev->pNext = pWotsit->pNext;
</code>```

remove, insert, etc. functions were used in some cases but because there was generally a fair profusion of different list structs there generally ended not being functions for all of them, or a single class with a void* data element or a union'd set of datatypes.

In many cases the list structure was injected into the class in the list, so you'd get something like:

```<code>struct Cat
{
  int breed;
  int age;
  // ... etc.
  Cat* pNext;
  Cat* pPrev;
};
</code>```

In short, while anything object orientated could be implemented in a clean, object-orientated fashion, in practice a lot of lists were implemented in an ad hoc and error prone manner in C and similar languages.

Body:
Badly, mostly.

It was pretty common to see sloppy, error-prone code like this:

struct Node {
  int data;
  Node *next;
  Node* prev;
};

\\ ...

Node* pWotsit = findBestCheese(pHead);
pWotsit->pNext->pPrev = pWotsit->pPrev;
pWotsit->pPrev->pNext = pWotsit->pNext;

remove, insert, etc. functions were used in some cases but because there was generally a fair profusion of different list structs there generally ended not being functions for all of them, or a single class with a void* data element or a union'd set of datatypes.

In many cases the list structure was injected into the class in the list, so you'd get something like:

struct Cat
{
  int breed;
  int age;
  // ... etc.
  Cat* pNext;
  Cat* pPrev;
};

In short, while anything object orientated could be implemented in a clean, object-orientated fashion, in practice a lot of lists were implemented in an ad hoc and error prone manner in C and similar languages.


问:
What is the difference between C# and Visual C#?
Let's say I want to start learning C# so that I can program Unity with it. I look for a well-reviewed book and it says: "Learn Visual C#!". I ask myself what the difference between Visual C# and C# is. If I know Visual C#, do I also know C#? </p>

答:
Visual C#, like Visual C++, is simply Microsoft's implementation of the C# language, along with the IDE and design-time tools used for developing C#. The terms are usually interchangeable, since in Windows land, for many years, Visual Studio was almost the only development tool, and is still the most dominant one. So, when learning Visual C#, anything you learn that is the language itself will be identical in other C# environments. The .NET Framework libraries will be mostly the same in other environments, and the tools (Visual Studio IDE, debugger, etc.) are specific to the Microsoft implementation.

The "Visual XXX" terminology was part of the product branding used by Microsoft starting in the 1990s to refer to their development IDEs, stressing their GUI-based nature, as opposed to many text-based IDEs or IDE-less development environments that were popular. This originally included standalone tools like Visual Basic (1991) or Visual C++ (1993), but they were later merged into Visual Studio. When the .NET languages were released in 2000, they were released under the same branding.

ContentLicense: CC BY-SA 4.0


答:
C# is a programming language.

Visual C# is Microsoft's implementation of the language. Microsoft uses the “Visual” prefix as a brand name for programming-related products, e.g. “Visual Basic .NET” or “Visual Studio”.

There are a number of other C# implementations as well, most importantly Mono. While both Mono and Visual C# implement the same language, there can be smaller incompatibilities, esp. with regards to the available libraries.

Title: What is the difference between C# and Visual C#?

Body: Let's say I want to start learning C# so that I can program Unity with it. I look for a well-reviewed book and it says: "Learn Visual C#!". I ask myself what the difference between Visual C# and C# is. If I know Visual C#, do I also know C#? </p>


问:
UML class diagram - instantiation dependency relationship: who depends on who?
I did some reading on the <<instantiate>> relationship in UML class diagrams. It's a dependency relationship where one side depends on the other.

However, I'm not sure who depends on who: does the instantiating class depend on the instantiated class, or is it the other way around? I found contradicting answers to this.

Let's call the instantiating class ClassA and the instantiated class ClassB.

On one hand, ClassA must have a new ClassB() statement in it's code. Which means it has to 'know about' ClassB - a classic example when explaining what dependency is. So that means ClassA (the instantiating class) depends on ClassB.

However logically the existence of instances of ClassB might depend on an operation done by ClassA.

Which is correct: the instantiating class is said to depend on the instantiated class (meaning the dashed arrow will be pointing from the instantiating class to the instantiated class), or the instantiated class is said to depend on the instantiating class (so the arrow will be pointing the opposite direction)?

答:
I believe your confusion stems from the contradiction between the example and the language of the UML 2.4.1 specification, where it states the following for "instantiate",

In the example below, the Car class has a dependency on the CarFactory class. In this case, the dependency is an instantiate dependency, where the Car class is an instance of the CarFactory class.

```<code>[ CarFactory ] -- <<instantiate>> ---> [ Car ]
</code>```

Figure 7.38 - An example of an instantiate dependency

This is an old quirk in the specification but it hasn't been fixed thus far. The text obviously contradicts the figure and common sense, the Car can be instantiated on its own, and it's the CarFactory factory class that depends on the existence of the Car class and not vice versa.

Which is correct: the instantiating class is said to depend on the instantiated class (meaning the dashed arrow will be pointing from the instantiating class to the instantiated class), ...

Notice the arrow direction,

A dependency is shown as a dashed arrow between two model elements. The model element at the tail of the arrow (the
  client) depends on the model element at the arrowhead (the supplier). [UML 2.4.1 7.3.12]

So the ("yes") answer to your quoted question above is that the instantiating class depends on the instantiated class.

ContentLicense: CC BY-SA 3.0

Body:
I believe your confusion stems from the contradiction between the example and the language of the UML 2.4.1 specification, where it states the following for "instantiate",

In the example below, the Car class has a dependency on the CarFactory class. In this case, the dependency is an instantiate dependency, where the Car class is an instance of the CarFactory class.

[ CarFactory ] -- <<instantiate>> ---> [ Car ]

Figure 7.38 - An example of an instantiate dependency

This is an old quirk in the specification but it hasn't been fixed thus far. The text obviously contradicts the figure and common sense, the Car can be instantiated on its own, and it's the CarFactory factory class that depends on the existence of the Car class and not vice versa.

Which is correct: the instantiating class is said to depend on the instantiated class (meaning the dashed arrow will be pointing from the instantiating class to the instantiated class), ...

Notice the arrow direction,

A dependency is shown as a dashed arrow between two model elements. The model element at the tail of the arrow (the
  client) depends on the model element at the arrowhead (the supplier). [UML 2.4.1 7.3.12]

So the ("yes") answer to your quoted question above is that the instantiating class depends on the instantiated class.


问:
How a freelancer can learn industry standards?
Being a freelancer, I don't have access to corporate training programs where employees learn best practices. Most of the time I am advised to look into the available code on the Internet. Ideal places would be: CodePlex and SourceForge.

But this proves to be of limited rather very little help. I want my existing code to be analyzed and a better solution be suggested to improve the quality of the code.

How to learn coding that matches standards?

答:
Check out the relevant open-source projects in your programming language of choice and domain in places like github, sf.net etc

Actively participate in working with other developers in open-source, subscribe yourself to mailing lists, read the latest ideas in IBM Developeworks, ACM Queue and Dr Dobbs... Best of luck!

ContentLicense: CC BY-SA 2.5


问:
How to make consistent progress towards the goal of becoming better, as opposed to just coding for fun?
I'm in senior year in high school. I enjoy programming (Java) very much and aspire to do it as a career in the future. However this isn't the topic of this question.

My question is: how can I start making consistent progress towards the goal of becoming a great programmer?

What I mean is this:

I work on my own projects, enjoy doing so and feel like I'm slightly improving with every project I finish.

However, I don't feel like I'm consistently moving towards 'the goal of becoming a great programmer'. I want to have a sense of 'working towards the goal'.

What I feel right now is more like "I'm coding stuff which is a lot of fun and I'm improving, but I don't feel like I'm 'making progress towards my goal'".

"Slightly improving over time because I'm coding stuff" doesn't really feel like "making progress towards a goal".

To those of you who are experienced developers: what advice can you give me on making consistent progress towards the goal of becoming great at programming, as opposed to just coding stuff for fun?

答:
I would suggest taking advantage of the software community in your area. Look for a user group or software craftsmanship group that meets regularly and does pair programming exercises. Pairing with talented developers will definitely improve your skills faster.

If you don't have a local group you can still find developers to pare with online using screen sharing. Find a project on Github that interests you and ask one of the developers to pair with you on fixing a bug or creating a new feature.

Getting involved in the community will also have benefits outside of improving coding skills. Improving communication and collaboration skills is as important if not more important to become a great developer.


问:
Is it considered 'reasonable' to implement a major part of a program largely by subclassing a library class?
I'm planning to implement a word processor using Java, and Swing for the GUI.

I was thinking how I can implement the text area where the user types the text.

My idea was to subclass JTextArea. It already has a lot of functionality for setting text, changing font size, etc. I will than add all the additional functionality, such as the ability to be affected by button presses on the UI, etc.

This seems reasonable to me, however I have a question regarding this:

Is it considered reasonable in a 'serious' program, to implement a major part of the program by subclassing an existing class of a common library? Is it a 'serious' and 'professional' thing to do?

Of course professional developers use and subclass existing code all the time, no point in reinventing the wheel.

But here I'm talking about implementing a major part of the application, probably the largest part, largely by subclassing an existing library class.

I am not a professional, and I know I don't have to work 'as professionals do'. But I am interested in how professionals view this.

1- Is something like this considered reasonable in a 'professional' application?

2- Have you ever seen this in practice in a 'professional' application?

答:
If it will work for what you want, then it's a reasonable thing to do.

We see far because we stand on the shoulders of the giants who came before us.  As serious professional programmers, we can and should take advantage of every available tool or library (within reason) that will make our job of producing a finished product quicker & easier.

BUT...

While I'm not personally familiar with JTextArea, I doubt it's up to the task of being a complete word processor in a can.

According to the documentation,

It is intended to be a lightweight component ...

You'll need to test it to see what happens when you try to use it with 100+ pages of formatted text.  Also, what happens when you try to print?  Will word wrap, page breaks, etc. work as expected?

My guess is that you'll be disappointed.

Many years ago Apple put out a TechNote essentially saying that their multi-column scrolling list box was not a spreadsheet.  Their arguments were similar - the lightweight tool won't scale up to application levels, performance will be terrible, and writing an entire app is more complicated than putting a wrapper around an existing UI element.


问:
How did programmers implement Linked list ideas before the object oriented paradigm?
Linked lists, as far as I have seen, are largely implemented using object-oriented ideas. (having an object that holds some information and the address of the next link). How were Linked-lists implemented before the object-oriented paradigm came out? Were they only invented(?) once the OOP was developed?</p>

答:
Linked lists have been around at least as long as OS's and well before HLL's were invented.  I can only guess what importance Knuth placed on them, but they were the first concept he discussed in The Art of Computer Programming (Vol 1, Chapter 2).  If you really want to know the answer to, "How were Linked-lists implemented before the object-oriented paradigm came out?" I'd suggest purchasing at least volume 1 of TAOCP.  The entire work is invaluable.

(FWIW - I don't work for Dr. Knuth, or his publisher)

jmoreno's answer is accurate.


答:
First and foremost, I don't know Swing and the capabilities or enhanceabilities of JTextArea, so I can't comment on your decision to make it the central point of your solution (which @DanPichelman seems to question in his answer). For the argument's sake I assume that it's fine.

Whatever is wrong with it, such technical details are better discussed on StackOverflow - we focus on general design here, and thus I'll try to tackle the OOD aspect of your question.

You need to ensure that your class does not get too big. It can seriously hurt the maintanability of your code. How do you know when it's too big?

The simpliest factor is the sheer size of its code. There is no magic number that separates "overly big" from "still fine", but there's common sense and some rules of thumb. I'm quite liberal in this aspect, but by my standards any class being bigger than 200 or 300 lines of code raises a red flag.

The conceptual rule is the Single Responsibility Principle. What is the responsibility of your class - let's give it a working title of JRichTextArea?

It's displaying rich text. Displaying. That's its field of expertise. It shouldn't know a thing about the outside world, as it breaks encapsulation and adds a secondary responsibility to it.

The only form in which its "ability to be affected by button presses on the UI" should be implemented is exposing some public API allowing other agents to pass it content (in some understandable format) that it's able to display, or render. There is no reason under the sun why it would have to know about button presses on the UI, or the very existence of any buttons, for that matter.

For instance, formatting rules (that's the business logic in this case) are not of its concern. JRichTextArea is a View, and it should be nothing but. Proper View is dumb and has no opinion about the data it displays. The alternative is known as a smart view anti-pattern.

Even rendering your content is not necessarily its job. If you wanted to add an option allowing your user to create and edit complex mathematical equations, should the mechanism be embedded in JRichTextArea?

These equations would not only be drawn on the screen, inside the text area. Printing documents would require drawing them in a graphic buffer. So the mechanism would better be moved into some separate EquationsRenderer class.

What about the content itself; the formatted text? It's data - it's not equal to its visual representation. The user will probably need to save formatted documents to disk. They are actually going to save the data, not its graphic representation from JRichTextArea.

The content belongs then to some sort of a Model class. That would be consistent with the MVC pattern. It's not a Holy Grail, but a good, universally recognized way to achieve separation of concerns.

Furthermore, interactions with the UI are a job for some sort of a controller class, delegating user commands to the model (eg. RichDocument). The controller gets notified that such and such button was pressed (make the selected text bold, for example), and it tells RichDocument what to do with the data.

JRichTextArea is at the end of this chain and its only job is to obediently display the results of this chain of operations.

This is one example of what I would call a 'serious' and 'professional' approach here.

Title: Is it considered 'reasonable' to implement a major part of a program largely by subclassing a library class?

Body:
I'm planning to implement a word processor using Java, and Swing for the GUI.

I was thinking how I can implement the text area where the user types the text.

My idea was to subclass JTextArea. It already has a lot of functionality for setting text, changing font size, etc. I will than add all the additional functionality, such as the ability to be affected by button presses on the UI, etc.

This seems reasonable to me, however I have a question regarding this:

Is it considered reasonable in a 'serious' program, to implement a major part of the program by subclassing an existing class of a common library? Is it a 'serious' and 'professional' thing to do?

Of course professional developers use and subclass existing code all the time, no point in reinventing the wheel.

But here I'm talking about implementing a major part of the application, probably the largest part, largely by subclassing an existing library class.

I am not a professional, and I know I don't have to work 'as professionals do'. But I am interested in how professionals view this.

1- Is something like this considered reasonable in a 'professional' application?

2- Have you ever seen this in practice in a 'professional' application?


答:
Some classes are designed to be inherited, and it's OK to inherit them and base a large portion of the project on the inherited classes.

JTextArea(and the rest of the Swing component classes) is not one of them. Unless you aim to create a new reusable component you shouldn't inherit a component class.

JTextArea - like many of the Swing component classes - provides a vast selection of hooks(a.k.a. listeners) that you can use to build on it's functionality. This is the preferred way to use JTextArea - not inheritance.

That being said - sometimes it's more comfortable to inherit the class but use it via the hooks. That means you don't override any method, but use the constructor to add listeners to your JTextArea. This approach allows you to add fields and new methods to the component, that both the listeners and other classes could use. This is common with container component classes(eg. JFrame, JPanel), where child components are created in the constructor and the important ones are stored in fields, but if your JTextArea is big enough this approach can be useful to you - as long as you avoid overriding JTextArea's methods!


问:
Database Design for Web based RSS Feed Agreegator
I am working on an open source application which can allow users to add RSS feeds. All users of the site can read the content of those RSS feeds. It's not just for user's own feeds.

Using PHP and SimplePie library I have created a simple app. I am trying to implement category based listing.

I have a list of RSS/Atom feeds in a database. Each post in the feed can have a category/label associated to it and a single feed can have multiple posts falling under multiple categories.

Question:
I want to get only the posts of category "Science".

In worst case, if I have 1000 RSS feeds, should I read posts from each feed and check the category of each post?

Storing all posts of each feeds and its categories is not a good solution.

How best can we have a database design for this?

Database schema is provided below. Nothing is fixed and I am free to change any schema or design.

http://sqlfiddle.com/#!2/2b519/1

NOTE: The fiddle is just for reference and does not need to worry. Its optional as I thought it might help to make others understand.

答:
Looking at your sample DDL in sqlfiddle, it seems like you are trying to store categories about posts, but reckon its a bad idea to store the posts themselves.

Given what it seems you are seeking, I think you will need a posts table with attributes likes (URL, category(ies), title, teaser/details) .. with the feed table's feed-id or feed-url as a foreign key.  This posts table can be indexed on a post-id which could also serve as its primary key

If you allow a given post to belong to more than one category, then having a separate categories table makes sense and categories IDs can then be foreign keys in the categories columns of posts.

Why do you reckon its a bad idea to store all posts?  I do think that if you are unwilling to store individual posts, then your options are limited into tagging entire feeds with categories, and that does not sound like what you are seeking to do.

Again, if the volume will grow rapidly and you are worrying about indexing and performance, perhaps you should look into graph DBs or some other NOSQL DBs as faster alternatives ..


问:
How to know what to test in TDD?
I've heard about TDD more than one year ago, but until now I didn't manage to get myself started with it. Indeed, one of my greatest doubts is always what to test. The examples given always shows test to verify if some business rule is being correctly implemented.

So, for instance, in an auction software we have the business rule "an user can only post a bid on a item if the value is greater than the value of the last bid". That is fine, this kind of thing is easy to imagine we need to ensure to be working. Those are things the end user of the system would care.

But sometimes we are working on the infrastructure of the system. Authentication and authorization, selection of resources for users, security verifications and so on. On these cases it doesn't seems obvious at first what should we test.

So, currently I'm not yet using TDD because always when I think to do so I find myself questioning "ok, now what tests should I write" and I never know how to answer this question. How can I know which tests I should write when starting to build an app?

答:
The reason I think you have asked a great question here is that you really pinpointed the major impediment to delving into TDD--what do you test next? Answering that question is much easier with just a few notions clear in your head.

(1) TDD, contrary to the name, is not about testing.

“Folks who do TDD for a while typically come to the conclusion that
  the only thing that TDD has to do with testing is the appearance of
  the word test in its name. That’s a bit of an exaggeration, but it’s a
  common one used by TDD’ers to help clarify the issue. We use unit
  testing frameworks to do TDD, and we write the example code in methods
  that can be executed by the test runners that come with unit testing
  frameworks, but that’s about the end of the commonalities between TDD
  and testing.”
  ― Scott Bellware, Behavior-Driven Development

(2) The goal of TDD is not to come up with tests; it is to come up with specifications (or behaviors).

“The entities we write are not actually tests. They are
  specifications. What we are doing is replacing traditional specs with
  automated specs.  The process of writing the specification is an
  analysis task, one that leaves behind a suite of tests as a
  side-effect artifact...” ― Scott Bain, Overcoming Impediments to
  TDD

(3) To determine what to test next (or even where to start) the question then simplifies to: What is the next most important thing the system does not yet do?
(Let me touch explcitly upon a point implicit in Telastyn's answer: your question suggests you are trying to align unit tests with user stories, but they exist at different levels in the architectural hierarchy. Unit tests--the byproduct of TDD--are much closer to the implementation, much more fine-grained.) So the "next most important thing" refers to implementable thing, not user-story-level thing.

(4) The answer to the question in (3) should be some behavior B. Write that behavior B as a sentence S0. If the sentence is too long or convoluted split it up into multiple sentences S0, S1, S2 ...

Each such sentence Sn names one test.

So with these simple ideas in mind, not only can you figure out what to test, you also come away with the test method name... leaving you with "just" the implementation left to do.

Title: How to know what to test in TDD?


问:
Implementing a basic interpreter - should I learn regular expressions?
For fun and for practice, I'm thinking of maybe implementing a very basic programming language to run on a simple interpreter written in Java.

My question is this:

Is it a 'must' to know regular expressions when designing an interpreter, for parsing the text? Should I learn this topic before starting to implement the interpreter?

Or is it enough to just run through the text, break down into strings, etc, i.e. do 'basic parsing' without regular expressions?

答:
The actual parsing usually wouldn't be done with regular expressions, or with code that is equivalent to some regular expression. You'd use them for lexing, i.e. for identifying numbers, variable names, punctuation, keywords, and so on without parsing them any further.

It's not required to actually use regular expressions in a lexer. But they are a very useful tool for describing and visualizing the syntax. Moreover, as regular expressions are basically very primitive parsers, learning the concepts surrounding them (e.g. repetition and choice) will benefit you when you turn towards parsing, since some parsing concepts are analogous to (though broader than) regex concepts.

There's also the fact that you can use regular expressions for many tasks beyond lexing; many common string processing tasks can be solved easily using them. So, in summary: You may be able to do without, but it's recommended. You don't necessarily need to learn beforehand though, you can try learning them as you implement the lexer.


问:
MVC & 3 tier architecture in game - What is the business layer
I am making a game and have been following examples which use the MVC architecture pattern. I am now trying to get my head around how this would fit in with a 3-tier architecture. From what I have gathered so far:

MVC and 3-tier are separate ideas and are compatible

MVC has a triangular communication structure, whereas 3-tier is a stack

MVC can be used within the 3-tier structure, with the MVC parts contained in the UI layer as in the diagram:

My Model for the game contains all the classes describing the abstract game world - all the items, characters, their positions and velocities in the world, the  score, etc.

But now what would constitute the business tier below this? As this is all the things I would normally associate with the business layer.

Should the diagram in this case perhaps show the View and Controller in the UI layer, with the Model contained in the Business layer below them?

答:
Quoting Martin Fowler's famous article:

In MVC, the domain element is referred to as the model. Model objects are completely ignorant of the UI.

So the answer is, the "Business Logic" clasically belongs in the model layer. (Which, itself can consist of arbitrarily more stuff, definitely not just anemic domain objects). You putting your domain objects there seems correct to me.

That said, the MVC architectural pattern rarely fits anything practical, let alone a game. Games have different architectural problems and MVC does not address them in practice.

You should focus on separation of concerns and structuring your logic in a modular way, focusing on a form of separated presentation that fits your problem. MVC is one of the most overused terms in UI programming and people tend to use it for anything that does separated presentation. Thinking about "what MVC" is is not very useful. Focus on your architecture rather than a specific pattern.


问:
What makes Web crawling legal?

When Google, Bing or Yahoo are crawling content from Web sites, what makes it legal? Is there a public registry of only allowed crawlers?

When researchers are crawling Deep Web, what makes their efforts legal?

When tester automate their tests with Selenium or JMeter and hit same site multiple times, what makes their effort illegal?

In each of those cases, an automate is consuming Internet bandwidth of the Web site, and copying their content. But some are considered legal, and other are not.

答:
At the risk of stating obvious tautologies, something is only illegal if there is a law against it.  When someone puts up a website, it is considered open to the public by default.  If there is content that should only be available to certain people, it's up to the web designer to secure it in some way.

When content is secured, and someone without authorization accesses it through hacking, this is generally considered morally equivalent to finding the door to somebody's house locked and then breaking in, and there are laws against doing so in most jurisdictions.

The intent of the website owner matters for a lot.  A good deal of "deep web" content is content that site owners would like to make available, but isn't easily accessible to normal web crawlers.  On the other hand, if an owner puts a rule in robots.txt to exclude certain content from a crawler, and the crawler indexes it anyway, this is considered more or less equivalent to wandering onto someone's property when there's a NO TRESPASSING sign in clear view.  But most websites welcome search engine traffic, because it drives actual users to the site, which helps accomplish the purpose of the site, whatever that purpose may be.  (Usually making money, spreading information, or both.)

As for overuse of automated testing tools, this is something very different from a web crawler.  A crawler has algorithms to only hit any given page once, and its principal purpose is to index sites so as to drive traffic to them, which most webmasters consider is worth the cost in bandwidth and processor power.  But hitting the same page repeatedly by some tool that's not going to bring in new users does nothing to further the purposes of the site, and so the costs that it places on the site owner are essentially wasted.  Unless the site owner actually asked for it, (for example, as part of a test of his site's capabilities,) it's generally considered unwelcome and harmful.

Title: What makes Web crawling legal?


答:
I didn't know automated tests that hit the same site multiple times is illegal, but it does make sense if you think about it.

I think it is because it can be included in the Denial Of Service realm if you hit it very frequently (e.g. multiple times a second for "testing" purposes).

Crawling the internet means just that: crawling. You don't hit a page multiple times a minute since you would waste precious resources on nothing (a page would not change that often).

Title: What makes Web crawling legal?

Body:
When Google, Bing or Yahoo are crawling content from Web sites, what makes it legal? Is there a public registry of only allowed crawlers?

When researchers are crawling Deep Web, what makes their efforts legal?

When tester automate their tests with Selenium or JMeter and hit same site multiple times, what makes their effort illegal?

In each of those cases, an automate is consuming Internet bandwidth of the Web site, and copying their content. But some are considered legal, and other are not.


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
One thing that hasn't been mentioned in this thread is what happens if your script breaks. In many cases, further execution of script on the page might be disabled, hence needing a way to fallback to a more simplistic way of navigating.

A script may break for various reasons, but the most obvious ones are incompleted requests for the .js files, various addons that might change the DOM (AdBlock, etc.) or introduce objects that aren't well namespaced.

This has nothing to do with people explicitly disabling script or whatever. As a side note, many modern routers, firewall software, etc. often have a feature to disable/filter out script, Flash, etc. from websites, so it might even be configured on a network layer leaving the user unaware of this (think public cafés, schools or other environments where other paranoid people have configured the access to Internet).

That is usually my main argument for developing sites that degrade gracefully, at least with the basic functionality of the site (layout and navigation).


答:
When tester automate their tests with Selenium or JMeter and hit same
site multiple times, what makes their effort illegal?

When a tester hits the same (external site that doesn't belong to him) with multiple test, he just made a bad test. That stuff should mocked.

Title: What makes Web crawling legal?


问:
What should I use as a random seed in a Brainfuck?
As I understand it, most pseudo-random algorithms work by taking one or more truly random longs, such as the date, time, MAC-Address, serial-number, etc., passing them through a complex series of calculations, and returning the result.

However, this isn't possible in Brainf*ck. The language only has 8 valid syntax characters, but I won't bother you with a full description, which can be found here. The gist is that there aren't any functions to access system time or any other number that I can think of as a seed. I can't think of where to get good seeds to put into functions. Does anyone have any suggestions?

Thanks in advance.

Note: feel free to edit this questions so that it applies to more languages; I just can't put my finger on the right word to use.

答:
The only input function available to a Brainf*ck program is to read from the standard input. If your program does not need user input, then you could connect stdin to a random device and read random bytes from that. For example:</p>

```<code>bf program </dev/urandom
</code>```

Body:
The only input function available to a Brainf*ck program is to read from the standard input. If your program does not need user input, then you could connect stdin to a random device and read random bytes from that. For example:

bf program </dev/urandom


答:
A psuedo-random number generator only appears to be random. It's intended to be uncorrelated with other processes so, e.g. you can use it to generate random test data and then, if needed, fix a bug and reproduce the test.

You can build a random number generator from a psuedo-random number generator by seeding it with external data. It looks like doing that in Brainfuck requires reading characters via the , operator.

Title: What should I use as a random seed in a Brainfuck?

Body:
As I understand it, most pseudo-random algorithms work by taking one or more truly random longs, such as the date, time, MAC-Address, serial-number, etc., passing them through a complex series of calculations, and returning the result.

However, this isn't possible in Brainf*ck. The language only has 8 valid syntax characters, but I won't bother you with a full description, which can be found here. The gist is that there aren't any functions to access system time or any other number that I can think of as a seed. I can't think of where to get good seeds to put into functions. Does anyone have any suggestions?

Thanks in advance.

Note: feel free to edit this questions so that it applies to more languages; I just can't put my finger on the right word to use.


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答:
FORTRAN common blocks.  If you made a simple mistake, one part of an application could clobber another part's globals.

FORTRAN assigned goto statement / COBOL alter statement.  Self-modifying code.  Danger, warning, flying spaghetti monsters!!


问:
Why are more programmers not freelance these days?
Leaving the whole pie to only a few of them, amplifying the huge differences between the two status. Pay is a (huge) one, not having to do overtime is another.

I leave the question open to hopefully get many great answers on all the different subjects that affects that feeling and decision not to go.

While this question is really global, I'll be interested in any studies, facts, articles, opinions regarding local markets such as US, India and even Australia in which I'm in love with.

答:
Well, here in the US I have known many freelance programmers who could not get enough work to support their families. I have hired several who gave up freelancing for this reason.

I have considered doing it, but it is very difficult to get started without a potentially long interruption or reduction in income. Until you have a stable of satisfied clients you will not have the luxury of opening your door each time you need more work.

Also, I have tried getting started by doing smaller projects through freelance sites but the competition for those is insane with ridiculous low-ball bids and immature buyers who have no idea what they want or what it costs.
.


问:
Avoiding coupling

It is also true that a system may become so coupled, where each class
is dependent on other classes that depend on other classes, that it is
no longer possible to make a change in one place without having a
ripple effect and having to make subsequent changes in many places.[1]
This is why using an interface or an abstract class can be valuable in
any object-oriented software project.

Quote from Wikipedia

Starting from scratch

I'm starting from scratch with a project that I recently finished because I found the code to be too tightly coupled and hard to refactor, even when using MVC. I will be using MVC on my new project aswell but want to try and avoid the pitfalls this time, hopefully with your help.

Project summary

My issue is that I really wish to keep the Controller as clean as possible, but it seems like I can't do this. The basic idea of the program is that the user picks wordlists which is sent to the game engine. It will pick random words from the lists until there are none left.

Problem at hand

My main problem is that the game will have 'modes', and need to check the input in different ways through a method called checkWord(), but exactly where to put this and how to abstract it properly is a challenge to me. I'm new to design patterns, so not sure whether there exist any might fit my problem.

My own attempt at abstraction

Here is what I've gotten so far after hours of 'refactoring' the design plans, and I know it's long, but it's the best I could do to try and give you an overview (Note: As this is the sketch, anything is subject to change, all help and advice is very welcome. Also note the marked coupling points):

Wordlist

```<code>class Wordlist {
    // Basic CRUD etc. here!
    // Other sample methods:
    public function wordlistCount($user_id) {} // Returns count of how many wordlists a user has
    public function getAll($user_id) {} // Returns all wordlists of a user
}
</code>```

Word

```<code>class Word {
    // Basic CRUD etc. here!
    // Other sample methods:
    public function wordCount($wordlist_id) {} // Returns count of words in a wordlist
    public function getAll($wordlist_id) {} // Returns all words from a wordlist
    public function getWordInfo($word_id) {} // Returns information about a word
}
</code>```

Wordpicker

```<code>class Wordpicker {

    // The class needs to know which words and wordlists to exclude
    protected $_used_words = array();
    protected $_used_wordlists = array();

    // Wordlists to pick words from
    protected $_wordlists = array();

    /* Public Methods */
    public function setWordlists($wordlists = array()) {}
    public function setUsedWords($used_words = array()) {}
    public function setUsedWordlists($used_wordlists = array()) {}

    public function getRandomWord() {} // COUPLING POINT! Will most likely need to communicate with both the Wordlist and Word classes

    /* Protected Methods */
    protected function _checkAvailableWordlists() {} // COUPLING POINT! Might need to check if wordlists are deleted etc.
    protected function _checkAvailableWords() {} // COUPLING POINT! Method needs to get all words in a wordlist from the Word class

}
</code>```

Game

```<code>class Game {

    protected $_session_id; // The ID of a game session which gets stored in the database along with game details
    protected $_game_info = array();

    // Game instantiation
    public function __construct($user_id) {
        if (! $this->_session_id = $this->_gameExists($user_id)) {
            // New game
        } else {
            // Resume game
        }
    }

    // This is the method I tried to make flexible by using abstract classes etc.
    // Does it even belong in this class at all?
    public function checkWord($answer, $native_word, $translation) {} // This method checks the answer against the native word / translation word, depending on game mode

    public function getGameInfo() {} // Returns information about a game session, or creates it if it does not exist
    public function deleteSession($session_id) {} // Deletes a game session from the database

    // Methods dealing with game session information
    protected function _gameExists($user_id) {}
    protected function _getProgress($session_id) {}
    protected function _updateProgress($game_info = array()) {}

}
</code>```

The Game

```<code>/* CONTROLLER */
/* "Guess the word" page */

// User input
$game_type = $_POST['game_type']; // Chosen with radio buttons etc.
$wordlists = $_POST['wordlists']; // Chosen with checkboxes etc.

// Starts a new game or resumes one from the database
$game = new Game($_SESSION['user_id']);
$game_info = $game->getGameInfo();

// Instantiates a new Wordpicker
$wordpicker = new Wordpicker();

$wordpicker->setWordlists((isset($game_info['wordlists'])) ? $game_info['wordlists'] : $wordlists);
$wordpicker->setUsedWordlists((isset($game_info['used_wordlists'])) ? $game_info['used_wordlists'] : NULL);
$wordpicker->setUsedWords((isset($game_info['used_words'])) ? $game_info['used_words'] : NULL);

// Fetches an available word
if (! $word_id = $wordpicker->getRandomWord()) {

    // No more words left - game over!
    $game->deleteSession($game_info['id']);
    redirect();

} else {

    // Presents word details to the user
    $word = new Word();
    $word_info = $word->getWordInfo($word_id);

}
</code>```

The Bit to Finish

```<code>/* CONTROLLER */
/* "Check the answer" page */

// ??????????????????
</code>```

( http://pastebin.com/cc6MtLTR )

Make sure you toggle the 'Layout Width' to the right for a better view. Thanks in advance.

Questions

To which extent should objects be loosely coupled? If object A needs info from object B, how is it supposed to get this without losing too much cohesion?

As suggested in the comments, models should hold all business logic. However, as objects should be independent, where to glue them together? Should the model contain some sort of "index" or "client" area which connects the dots?

Edit:
So basically what I should do for a start is to make a new model which I can more easily call with oneliners such as $model->doAction(); // Lots of code in here which uses classes!

How about the method for checking words? Should it be it's own object? I'm not sure where I should put it as it's pretty much part of the 'game'. But on another hand, I could just leave out the 'abstraction and OOPness' and make it a method of the 'client model' which will be encapsulated from the controller anyway. Very unsure about this.

答:
You can take a look at several patterns or elemnts from Domain Driven Design (DDD) that may help you:

A particularly good one is Services:

Services are classes that belongs to the domain layer (let's say your model in this case) and that hold those operations that doesn't belong to any of your entities (Evans, 2004)

So, you may create interfaces for those operations that doesn't belong to your CRUD operation classes and the implementations for such interfaces would be the glue you were looking for.

Title: Avoiding coupling


问:
Objective-C style: Do I implement factory methods or init methods?
I'm new to Objective-C programming, and creating various classes for an iOS application I'm working on.

When creating objects, it seems like many classes in the built-in frameworks use the "static factory method" pattern, like this:

```<code>MyObject* m = [MyObject objectWithName:@"foo" id:@7 description:@"bar"];
</code>```

however, many classes also simply have overrides on init, like this:

```<code>MyObject* m = [[MyObject alloc] initWithName:@"foo" id:@7 description:@"bar"];
</code>```

I can see that if I want to cover all my bases, I'd implement both, and have the objectWithName... method call initWithName..., however this seems quite tedious.

I was wondering - is there any style or guidance from around when I should implement the factory method pattern vs an init overload? I've googled for this, but have been unable to find anything (most likely because the terms are quite generic and google doesn't search well for them)

Any advice or opinions would be much appreciated

答:
From https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/ClassFactoryMethods/ClassFactoryMethods.html:

Factory methods can be more than a simple convenience. They can not
  only combine allocation and initialization, but the allocation can
  inform the initialization. As an example, let’s say you must
  initialize a collection object from a property-list file that encodes
  any number of elements for the collection (NSString objects, NSData
  objects, NSNumber objects, and so on). Before the factory method can
  know how much memory to allocate for the collection, it must read the
  file and parse the property list to determine how many elements there
  are and what object type these elements are.

Another purpose for a class factory method is to ensure that a certain
  class (NSWorkspace, for example) vends a singleton instance. Although
  an init... method could verify that only one instance exists at any
  one time in a program, it would require the prior allocation of a
  “raw” instance and then, in memory-managed code, would have to release
  that instance. A factory method, on the other hand, gives you a way to
  avoid blindly allocating memory for an object that you might not use.


答:
I was wondering - is there any style or guidance from around when I
  should implement the factory method pattern vs an init overload?

Every class should have a designated initializer, i.e. an instance method whose name starts with "init" that leaves a newly allocated object in a valid state. You can add other initializers that provide additional functionality, but these should call the designated initializer. You can also create factory methods when that's helpful.

So that's the guideline:

always provide a designated initializer

provide additional initializers and factory methods if you need or want them

Title: Objective-C style: Do I implement factory methods or init methods?

Body:
I'm new to Objective-C programming, and creating various classes for an iOS application I'm working on.

When creating objects, it seems like many classes in the built-in frameworks use the "static factory method" pattern, like this:

```<code>MyObject* m = [MyObject objectWithName:@"foo" id:@7 description:@"bar"];
</code>```

however, many classes also simply have overrides on init, like this:

```<code>MyObject* m = [[MyObject alloc] initWithName:@"foo" id:@7 description:@"bar"];
</code>```

I can see that if I want to cover all my bases, I'd implement both, and have the objectWithName... method call initWithName..., however this seems quite tedious.

I was wondering - is there any style or guidance from around when I should implement the factory method pattern vs an init overload? I've googled for this, but have been unable to find anything (most likely because the terms are quite generic and google doesn't search well for them)

Any advice or opinions would be much appreciated


问:
Maintaining sorted Array speed
I have a for loop running over a list of objects like:

```<code>[{a: 2001, b: "hello"}, {a: 54, b: "hi"}....]
</code>```

In this loop, I filter out objects based on certain field values (like, b == hello?) and create a new list of filtered objects.  Once the for loop is complete, I sort the remaining objects by the value of a.  This is an oversimplified example, so presorting by field a isn't possible.

My question is, is it faster to do the sort after the loop is complete vs doing something like a binary search at the end of each iteration and then insert the object then?  That would avoid sorting at the end, but I don't really know if that ends up costing more.

答:
It is in general faster to build a collection of values first, then sort. If you insert into an ordered container, you'll be paying the price for maintaining an ordered collection (which, depending on the underlying implementation may take ~2 lg n compares, or, as you seem to be implying by saying "binary search," ~lg n compares and then ~n/2 swaps).

If, on the other hand, you simply store your items in an unordered manner and then sort, you allow faster algorithms to sort all your items at the end for ~n lg n compares, which, if we amortize to the n elements you've been inserting, this method would take ~lg n compares per element (and fewer swaps) cost, cheaper than both options for maintaining the ordered collection.

Of course, profiling will always tell you what works best on your machine. However, for sufficiently large data sets it would be best to filter, then sort.

Minor note: Technically, when inserting into an ordered container, the operations won't be dependent on the total number of items n but rather the current number of items k, increasing from 1 to n. However, the average cost for these operations comes out to be ~lg n to within a constant factor - see Stirling's approximation.

Title: Maintaining sorted Array speed


问:
How to avoid churn when you are defining a schema while others are trying to program against it
I'm in charge of defining an XML schema for some data; the plan is to have various systems (all under our control) upload XML files that match this schema to a central server for processing. I don't have much knowledge of the design of these other systems, so I'm working collaboratively with those system experts to make this XML schema reasonable to both consume (on our side) and produce (on their side).

The schema is not entirely clear-cut, and I'm defining the data we want to collect at the same time as defining the schema. There are a million ways to do it so there's a definite "do something, think about it, talk to so-and-so, refactor, repeat" process in place.

All of that said, we have an unfortunate situation where myself and a few others are defining things and a few other developers are implementing it. I'd like to write some code but haven't found the time. This leads to the frustrating cycle whereby the design changes in the ivory tower and then the guys writing the code have to go and change it again and again. Avoiding details for various reasons, the developers writing the implementation aren't in a position to effectively define the requirements of the schema and the data we must collect.

Should I be the one writing and playing with this stuff as I figure out how it should be done? This would be ideal to me, but we're under pressure to get things done and it's quicker to have a few people working on it rather than just me.

Do we have too many cooks in the kitchen with the XML file providers influencing the schema? Ease of XML file creation should be a consideration of the schema, right?

Is there a better way to solve this problem, or is churn a necessary evil when you're trying to fly the plane as you build it?

What is the correct development process to apply here which will minimize wasted time?

答:
I am not sure if it is a way to definitively reduce churn and how applicable it would be to your current situation, but these are some things I would try to do -

Minimum Viable Product

I am not sure if this is fully relevant to your current situation since it looks like you are already in the middle of things but I am going to put it in anyway since it provides a context to some of the other points.

I would push to identify the bare minimum of data needed and try to build the smallest end to end integration possible first. Once that is done it becomes a lot easier to handle further changes as a lot of the initial questions around approach and risk have been addressed.

Tight communication loop

Since you have mentioned that you are not in a position to work on coding the modification to the systems or building a prototype yourself the next best thing is to work closely with the people who have to do this.

While building up the schema specification I would try to keep the communication loop as tight and small as possible. Identify a small team that can handle the project end to end and work closely with them (preferably in the same room).

If you have multiple teams for different systems I would identify certain folks from each team and work with them. If the teams are too small for this I would try to get a specific block of time to focus on the schema integration and build it in focussed sprints.

Build for easy modification/extension

Since you know this is a rapidly changing and sometimes ambiguous schema it is important to design the schema and the code to generate it such that they can be easily modified.

If this is done well, after the initial minimum viable product built out, it would be much easier for the developers to extend the system and reduce the churn time.


问:
Design and relationship of a cursor and its referred object
I need to implement a Cursor class to perform operations on a Document object, which is implemented internally as a simple list of rows. The Cursor class must have methods such as moving around the Document, add lines, remove lines, insert text in a given position etc.

The problem I have is relative to the details of the design. To me, it seems that the cursor must know the implementation details of the referred class. In C++, these classes must be friend classes, but I don't like it for obvious reasons (encapsulation etc.). I can't envision an interface for the Document class to keep its implementation private that also doesn't defeat the purpose of a Cursor class, that is, I end up having the interface of the Cursor on the Document class itself.

Is leaking Document implementation details mandatory when implementing a Cursor? If not, what should the Document interface be?

答:
Sounds like Cursor represents a position in a Document. The Document class should ultimately be responsible for all primitive operations like inserting, deleting, grabbing text and moving around. Most of these operations require a position as input and some also return a position as output. Cursor could just be a concrete data class which just holds the position and the Document, basically a pair. The other approach is to make Cursor a first class abstraction. In that case its API will just mirror that of Document, and each method will be just a thin wrapper around the corresponding method on Document, but the methods on Cursor will omit the position parameter since they will fill that with the position from the Cursor.
The basic pattern is something like

```<code>cursor.someMethod(arg1, ...) = cursor.doc.someMethod(cursor.pos, arg1, ...)
</code>```

except if the Document method returns a position then the Cursor method should package that together with the document and to return a cursor like

```<code>cursor.otherMethod(arg1, ...) = new Cursor(cursor.doc,
                                           cursor.doc.otherMethod(cursor.pos, arg1, ...))
</code>```

The drawback of this approach is the boiler plate on the implementation side, but it makes the library much nicer to use on the client side. Since the required boilerplate is simple and systematic you may be able to avoid writing it manually by either generating it, or doing the delegation through reflective calls if you are using a language with decent reflection capacities or a reasonably powerful preprocessor.

You still need to decide what a position is. It can be just a number representing the character position in the whole document (eg Emacs), a pair representing the line and position on the line, or a in C/C++ a pointer directly into the underlying container. I would recommend making position a member type on Document if your language supports that. That way each Document implementation can supply its own position type definition. Cursor treats positions as completely abstract, it just hold them and passes them to Document methods. only Document cares how they are implemented.

Body:
Sounds like Cursor represents a position in a Document. The Document class should ultimately be responsible for all primitive operations like inserting, deleting, grabbing text and moving around. Most of these operations require a position as input and some also return a position as output. Cursor could just be a concrete data class which just holds the position and the Document, basically a pair. The other approach is to make Cursor a first class abstraction. In that case its API will just mirror that of Document, and each method will be just a thin wrapper around the corresponding method on Document, but the methods on Cursor will omit the position parameter since they will fill that with the position from the Cursor.
The basic pattern is something like

cursor.someMethod(arg1, ...) = cursor.doc.someMethod(cursor.pos, arg1, ...)

except if the Document method returns a position then the Cursor method should package that together with the document and to return a cursor like

cursor.otherMethod(arg1, ...) = new Cursor(cursor.doc,
                                           cursor.doc.otherMethod(cursor.pos, arg1, ...))

The drawback of this approach is the boiler plate on the implementation side, but it makes the library much nicer to use on the client side. Since the required boilerplate is simple and systematic you may be able to avoid writing it manually by either generating it, or doing the delegation through reflective calls if you are using a language with decent reflection capacities or a reasonably powerful preprocessor.

You still need to decide what a position is. It can be just a number representing the character position in the whole document (eg Emacs), a pair representing the line and position on the line, or a in C/C++ a pointer directly into the underlying container. I would recommend making position a member type on Document if your language supports that. That way each Document implementation can supply its own position type definition. Cursor treats positions as completely abstract, it just hold them and passes them to Document methods. only Document cares how they are implemented.


答:
One solution is to make the curser pass the x and y coordinates to the document it is over, and let the document decide what row it is in. You could also have the curser call separate methods or pass in a parameter to tell the document if it is a request to remove a row, insert text, delete a row, ext.

To take this line of thought to another level, you could also create classes for your rows. The rows and document would both implement a mouse listener abstract class. This would allow the mouse to pass a click event to the document to determine the row it is in, and pass it to the row to determine the character position on the row the event was on.

Title: Design and relationship of a cursor and its referred object

Body:
I need to implement a Cursor class to perform operations on a Document object, which is implemented internally as a simple list of rows. The Cursor class must have methods such as moving around the Document, add lines, remove lines, insert text in a given position etc.

The problem I have is relative to the details of the design. To me, it seems that the cursor must know the implementation details of the referred class. In C++, these classes must be friend classes, but I don't like it for obvious reasons (encapsulation etc.). I can't envision an interface for the Document class to keep its implementation private that also doesn't defeat the purpose of a Cursor class, that is, I end up having the interface of the Cursor on the Document class itself.

Is leaking Document implementation details mandatory when implementing a Cursor? If not, what should the Document interface be?


问:
Maze generation given intersection tree
Background Information:
I'm building a 2D maze generator. I have tried Prim's algorithm, Wilson's algorithm, and a recursive backtracker algorithm for generating my maze, however was not satisfied with the difficulty of any. I have decided to create my own. I decided that two things make a maze hard. First, mazes can have lots of intersections and choices to make. Second, they can be disorienting and cause you to lose your way. I decided to create a tree to represent the intersections and dead ends in a maze and connect each node in the tree with a randomly generated path to disorient users.

The problem:
If I begin to generate the cells in the maze for the tree, I may find that a node doesn't have the room it needs to connect to or create its children. How do I fix or avoid this problem?

My Thoughts:
There seems like there might be a way to do this by dividing the maze into sections and subdividing them, but that still doesn't guarantee enough room at the end of the division. I could also try to start small and work my way up, sectioning off smaller areas and then creating connections between them, but that could still run into pathing issues with not having enough room to connect the sections together or even creating really long paths between sections.

I am using a hexagonal grid, but any solution you guys come up for rectangular grids should be easy to transfer to a hexagonal one.

I wasn't sure if this should be posted in the theoretical computer science section or here, and opted for the more general one.

答:
There are many maze descriptions in the wikipedia article maze generation algorithm, but I'm going to describe one that works for any shape maze with any number of dimensions.

You start off giving each room room in the maze a distinct number.

You then find the set of all walls between the rooms that have different numbers on either side.

From this set, you select a random wall and remove it.

For the two rooms on either side, you change all rooms with the higher number value to the lower number value.

Repeat steps 2-4 until all rooms have the same (lowest) value.

This works for 2 or 3 dimensional mazes (never tried 4, but I see no reason why it wouldn't) and for rectangular and hexagonal mazes (but could also be irregular shapes too - nothing in there dictates the shape, number of adjacent walls, or even that each room is the same).

It will generate a maze that has a one path from any two points and only one path (there are no loops).  Aesthetically, I like the mazes generated by it as I find some of the others lead to either long walls or long corridors.

An example of this maze generation on a 3x3 square maze:

```
+---+---+---+
|   +   +   |
| 0 a 1 b 2 |
|   +   +   |
++c+-+d+-+e++
|   +   +   |
| 3 f 4 g 5 |
|   +   +   |
++h+-+i+-+j++
|   +   +   |
| 6 k 7 l 9 |
|   +   +   |
+---+---+---+
```

At the start, the set of walls is abcdefghijkl.  You pick a random wall, lets say 'd'.  The maze then becomes:

```
+---+---+---+
|   +   +   |
| 0 a 1 b 2 |
|   +   +   |
++c++   ++e++
|   +   +   |
| 3 f 1 g 5 |
|   +   +   |
++h+-+i+-+j++
|   +   +   |
| 6 k 7 l 9 |
|   +   +   |
+---+---+---+
```

The set of walls is now abcefghijkl.  After two more steps, for walls b and g, the maze is:

```
+---+-------+
|   +       |
| 0 a 1   1 |
|   +       |
++c++   ++e++
|   +       |
| 3 f 1   1 |
|   +       |
++h+-+i+++j++
|   +   +   |
| 6 k 7 l 9 |
|   +   +   |
+---+---+---+
```

Note that now, since e has a 1 on each side, it is no longer a candidate in the set of walls that can be removed.

Title: Maze generation given intersection tree

Body:
There are many maze descriptions in the wikipedia article maze generation algorithm, but I'm going to describe one that works for any shape maze with any number of dimensions.

You start off giving each room room in the maze a distinct number.

You then find the set of all walls between the rooms that have different numbers on either side.

From this set, you select a random wall and remove it.

For the two rooms on either side, you change all rooms with the higher number value to the lower number value.

Repeat steps 2-4 until all rooms have the same (lowest) value.

This works for 2 or 3 dimensional mazes (never tried 4, but I see no reason why it wouldn't) and for rectangular and hexagonal mazes (but could also be irregular shapes too - nothing in there dictates the shape, number of adjacent walls, or even that each room is the same).

It will generate a maze that has a one path from any two points and only one path (there are no loops).  Aesthetically, I like the mazes generated by it as I find some of the others lead to either long walls or long corridors.

An example of this maze generation on a 3x3 square maze:

+---+---+---+
|   +   +   |
| 0 a 1 b 2 |
|   +   +   |
++c+-+d+-+e++
|   +   +   |
| 3 f 4 g 5 |
|   +   +   |
++h+-+i+-+j++
|   +   +   |
| 6 k 7 l 9 |
|   +   +   |
+---+---+---+

At the start, the set of walls is abcdefghijkl.  You pick a random wall, lets say 'd'.  The maze then becomes:

+---+---+---+
|   +   +   |
| 0 a 1 b 2 |
|   +   +   |
++c++   ++e++
|   +   +   |
| 3 f 1 g 5 |
|   +   +   |
++h+-+i+-+j++
|   +   +   |
| 6 k 7 l 9 |
|   +   +   |
+---+---+---+

The set of walls is now abcefghijkl.  After two more steps, for walls b and g, the maze is:

+---+-------+
|   +       |
| 0 a 1   1 |
|   +       |
++c++   ++e++
|   +       |
| 3 f 1   1 |
|   +       |
++h+-+i+++j++
|   +   +   |
| 6 k 7 l 9 |
|   +   +   |
+---+---+---+

Note that now, since e has a 1 on each side, it is no longer a candidate in the set of walls that can be removed.


问:
Are there any algorithms for splitting or combining words into their more common form?
Are there any existing algorithms which can look through a list of words and split or combine words into their more common form?

For example, I have a list of many business names in the health care industry. The word "healthcare" is often written "health care". There are also business names which might be split or combined, such as "Walmart" and "Wal mart".

Are there any algorithms which can look at my list of words and identify that "healthcare" is more often written as two words, and that "Wal mart" is more often written as a single word?

I'm looking for the names of existing algorithms (which can help when searching the web), or links to existing white-papers or blog posts.

I'd prefer an algorithm that doesn't depend on a dictionary or other external list of words or business names.

EDITS:

Background:

I already have some code that is moderately successful at this task. The code was thrown together without much rigor. I hoped there were some established algorithms, which would likely be more academic and complete then what I've come up with. This question is not about the method I've come up with, but saying "it's impossible" doesn't convince me.

Clarification:

The "more common form" of a word is the way the word(s) are most often written. For example, "Walmart" appeared many times, and "Wal mart" appeared many times, but "Walmart" appeared more often then "Wal mart" and so "Walmart" is the "more common form" of the word.

I don't expect this algorithm to produce perfect results. Like any machine learning problem, I expect the results to be dependent on the quality of data I give it, and how much data I have.

答: You can always tell if two words are mashed together because there will be two consonants next to each other that are not part of a slide and are not the same. Slides are consonant combinations like st, dr, and th. If there are three consonants or more, you know it is two combined words. The two words can be divided between the slide and consonant or the two slides if there is four consonants. If there is two consonants, it is either a slide, two of the same letters, like ll, or combined words. Dividing it into two words would then be trivial.</p>


问:
If functional testing is referred as black box..how can it be done on unit test level?
Preparing myself for ISTQB, I found a bit odd many things in their textbooks. E.g. they call black box testing as functional testing when you are not concerned with structured but only observe the ouput based on inputs.
But later they say that functional testing is done at levels..well, how can I do unit testing without the knowledge how it works if I can just see it (and must see it). It is white box but then it is in the conflict..</p>

答:
Black box testing means that you don't need to know what is inside the box in order to build your test. It doesn't specify how big or how small the box is.

Unit testing means that you test units of code one by one. This is by contrast with integration testing in which you test several units interacting together. It doesn't specify how small or how big the units are.

Functional testing defines testing criteria based on the function of the code under test, by contrast with structural testing in which testing criteria are based on the code structure. Functional testing is a black box testing technique.

Code coverage is a group of testing criteria that belongs to the glass box testing category (not white box testing as white is as opaque as black).


问:
Organizing uncommented, dirty code?
I would like to ask you some questions about dirty code. There are some beginners who coded on a medium project. The code is a very huge ball of mud. They are not advanced programmers. They just know how to use keyboard an a little about java. They just wrote code with 12 000 lines in their main class, though, 6 000 lines belongs to NetBeans itself.

My job is to analyze the code and suggest a good way to maintain the code. My idea is to scrap the project and start a new one with OOP methodology. Recently I collected some notes and ideas about the problem, from this site and some others.

Now, I have the followings questions:

Should we repair the code, and change it to a OOP? We are now debugging it.

The code has no comments, no documentation, no particular style of programming, and so forth. Changing it is really expensive and time consuming. What do we can do about this?

How can I teach them to follow all the rules (commenting, OOP, good code quality, etc.)?

The code is erroneous and error prone. What can we do? Testing? We almost write two or three A4 papers for correction, but it seems endless.

I should have to say that I am new with them. I think I have broken the rules about adding people too late to the project, as well. Do you think I have to leave them?

答:
I have been there several times. My rule is: if the software is not trivial (more than 1 week work for the resource you have) and it does work, then keep it and proceed with incremental refactoring.

If the software doesn't really work (very high number of bugs, unclear requirements etc.) than it's better to rewrite it from scratch. The same if it's quite small.

The point in refactoring (as in the Fowler's book and Kerievsky's one http://www.industriallogic.com/xp/refactoring/) is that it keep the system working, maybe the refactoring will take double time but the risks are zero.

Rewriting from scratch could introduce many risks, from misunderstanding requirements to wrong implementation (after all most of the team will be the same).

I actually saw a complex procedure being rewritten from scratch twice and still not working as expected.

Title: Organizing uncommented, dirty code?


问:
How can the following algorithm be optimized?
I am currently working on a tic tac toe auto-mover game. I have come upon a decent algorithm that allows the computer to easily build towards, and claim victory spots.
The problem however is that when the opponent is dangerously close to victory, the computer continues to build towards it's own victory instead of blocking the opponents, is there any way the following algorithm can be optimized to counter that?

The algorithm works as follows:

Initialize a 3x3 integer array

Loop over all possible combinations on the board (0|0, 1|1, 0|2... e.tc).

If combination is a immediate victory, stop and return this position.

Else initiate a loop (That loops either 1000, 10000 or 100000 times, depending on difficulty)

Continually move from both sides randomly till victory is achieved. If victory is by the computer, increment the score counter.

Select the board position with the highest score

This algorithm works fine and can build towards victory (example:

```<code>·|x|o    ·|x|o    ·|x|o
·|·|·    x|·|o    x|x|o
·|·|·    ·|·|·    ·|·|o
</code>```

However when confronted with a board like this

```<code>·|x|o
o|x|·
·|·|·
</code>```

The optimal move should be to break x's chain, but the computer builds towards raising it's own chain i.e moving at 1|2 (The board is 3x3, indexes start from zero. So that'd be the second row's third coloumn).

Is there any way to optimize this algorithm such that this weakness goes away?

答: Sure there is a way. Your problem is that your definition of "I win" is too narrow. As you've pointed out, a row of three is only a win for you if your opponent doesn't already have one - therefore your metric must track potential rows achieved by you and your opponent, and avoid states in which they get a row completed first.


答:
look if you could 1-move win : play this move

look if you could prevent him last-move win : play this move

look if you could 2-move win : play first of these 2 moves (which one could vary according to difficulty or which one prevent the other to win)

look if you could prevent him to 2-move win : play first of these 2 moves (...)

play anywhere

Title: How can the following algorithm be optimized?

Body:
I am currently working on a tic tac toe auto-mover game. I have come upon a decent algorithm that allows the computer to easily build towards, and claim victory spots.
The problem however is that when the opponent is dangerously close to victory, the computer continues to build towards it's own victory instead of blocking the opponents, is there any way the following algorithm can be optimized to counter that?

The algorithm works as follows:

Initialize a 3x3 integer array

Loop over all possible combinations on the board (0|0, 1|1, 0|2... e.tc).

If combination is a immediate victory, stop and return this position.

Else initiate a loop (That loops either 1000, 10000 or 100000 times, depending on difficulty)

Continually move from both sides randomly till victory is achieved. If victory is by the computer, increment the score counter.

Select the board position with the highest score

This algorithm works fine and can build towards victory (example:

```<code>·|x|o    ·|x|o    ·|x|o
·|·|·    x|·|o    x|x|o
·|·|·    ·|·|·    ·|·|o
</code>```

However when confronted with a board like this

```<code>·|x|o
o|x|·
·|·|·
</code>```

The optimal move should be to break x's chain, but the computer builds towards raising it's own chain i.e moving at 1|2 (The board is 3x3, indexes start from zero. So that'd be the second row's third coloumn).

Is there any way to optimize this algorithm such that this weakness goes away?


问:
Traversing an AST using Visitors
I'm writing a compiler for a C-like language, and I'm looking for an elegant way to traverse my abstract syntax tree. I'm trying to implement the Visitor pattern, although I'm not convinced that I'm doing it correctly.

```<code>struct Visitor {
    // Expressions
    virtual void visit(AsgnExpression&);
    virtual void visit(ConstantExpression&);
    ...
    virtual void visit(Statement&);
    ...

    virtual void finished(ASTNode&);

protected:
    virtual void visit(ASTNode&) = 0;
};
</code>```

visit is overloaded for each type, and by default each overload will call visit(ASTNode&) which subclasses are forced to implement. This makes it easier to do quick and dirty things, although defining a visit for each type is tedious. Each subclass of ASTNode must implement an accept method which is used to traverse the tree structure.

```<code>class ASTNode {
public:
    virtual ~ASTNode();
    virtual void accept(Visitor& visitor) = 0;
};
</code>```

However, this design is quickly becoming tedious because the accept methods are often very similar.

Who should be responsible for traversing the structure, the nodes or the visitor? I'm leaning towards having ASTNode provide an iterator for accessing its children, and then having the visitor traverse the structure. If you have any experience designing Abstract Syntax Trees, please share your wisdom with me!

答:
Who is responsible for the traversal depends for a large part on the analysis you want to do in your visitors, the details of the language structure and also a part personal preference.

In particular, if there are cases where the visitor to a parent node needs to take an action halfway through the processing of the children, then you must put the traversal logic in the visitor.
For example, if your language has a construct where a newly introduced variable is available only in some of the child nodes of the node that introduces the variable.

Another case is when you need a mixture of pre-order and post-order traversal. With traversal in the nodes, each node must call the visitor twice, once before and once after the children. In that case, it might be easier to let the visitor do the traversal.

Otherwise, it is mostly a matter of preference. The traversal can be either in the nodes or in the visitor.

Title: Traversing an AST using Visitors


问:
What's the most used programming language in high performance computing? And why?
I believe a lot of Fortran is used in HPC, but not sure if that's only for legacy reasons.

Features of modern programming languages like garbage collection or run-time polymorphism are not suitable for HPC since speed matters so not sure where C# or Java or C++ come in.

Any thoughts?

答:
In my years of experience, up to 5 years ago, it has always been Fortran and C. Which one depended mostly on whether the people came more from engineering or more from CS school of thought (I don't know how to put this better, okey? :-)

In what we were doing Fortran was almost exclusively used.

From what I read around nowadays, with the new updates to the Standard F2003/08 and with the introduction of Co-Arrays, it seems to be gaining momentum again.

Also, one, if not somewhat biased article - The Ideal HPC Programming Language


问:
How did programmers implement Linked list ideas before the object oriented paradigm?
Linked lists, as far as I have seen, are largely implemented using object-oriented ideas. (having an object that holds some information and the address of the next link). How were Linked-lists implemented before the object-oriented paradigm came out? Were they only invented(?) once the OOP was developed?</p>

答:
Linked lists, as far as I have seen, are largely implemented using object-oriented ideas. (having an object that holds some information and the address of the next link).

What have you seen that is not object-oriented? If the only things you've seen are OO then it is not surprising that the only implementations of simple data structures you've seen are OO.

Were they only invented(?) once the OOP was developed?

Linked lists predate OO programming by many decades.

How were Linked-lists implemented before the object-oriented paradigm came out?

In the 1950's the Lisp programming language was implemented on the IBM 704. The fundamental data structure of Lisp is the cons cell, which is a grouping of two values. The machine word size of the IBM 704 was 36 bits and there were special instructions, CAR and CDR that would extract 15 bit values from a 36 bit word. The value stored in the CAR bits was the head of the list and the value stored in CDR was the tail, so in that way a cons cell could be used as a node in a linked list.

For a more detailed discussion of how linked lists were implemented on the IBM 704 in the 1950s, see http://en.wikipedia.org/wiki/CAR_and_CDR.


问:
Designing XML - confused between attributes and elements
I have to design an xml structure to set standard data exchange with my client.

We deal with payments and its related data.

At now, my XML data looks like this:

```<code><PAYMENTS>
 <CURRENCY>DOLLARS</CURRENCY>
 <PAYMENTTYPE>CHEQUE</PAYMENTTYPE>
 <PAYMENT>
   <AMOUNT>100</AMOUNT>
   // ALL OTHER DETAILS GO HERE
 </PAYMENT>
 <PAYMENT>
   <AMOUNT>100</AMOUNT>
   // ALL OTHER DETAILS GO HERE
 </PAYMENT>
</PAYMENTS>
</code>```

But one of my colleague managed to write a different version.

```<code><PAYMENTS CURRENCY = DOLLARS
          PAYMENTTYPE = CHEQUE>
 <PAYMENT>
   <AMOUNT>100</AMOUNT>
   // ALL OTHER DETAILS GO HERE
 </PAYMENT>
 <PAYMENT>
   <AMOUNT>100</AMOUNT>
   // ALL OTHER DETAILS GO HERE
 </PAYMENT>
</PAYMENTS>
</code>```

(The currency and paymenttype tags are moved as attributes because they are not going to repeat again like payment)

But, I wonder what is the best method to represent this ? My way or the second one?

Are there any guidelines to this?

(Not sure if this helps: But, I am using C# for coding)

答:
Welcome to the number one problem of using XML as a data serialization format! Attributes vs contained elements - so useful in markup, so annoying in data serialization...

At any rate, assuming you are forced to go with the herd and use XML for data serialization, there are only three reasons to prefer attributes over elements:

If the field has it's own subfields.

If the field can repeat.

If the field is something you want to treat as heredoc.

All these cases apply for the design, not for the example set of data you have in hand. If a field in your data doesn't happen to follow any of these rules, but the design allows one of the rules to apply it, it should be an element.

The reason to prefer attributes over elements(unless one of the cases apply) is that even with LINQ to XML it's much easier to use attributes. Programming languages usually make it easier to say "I have an object, give me the contents of one of it's fields" than to say "Here is a pile of objects, fetch me one that fits a certain criteria".

Both CURRENCY and PAYMENTTYPE are - as you say - non-repeatable by design, and they are not compound, and they don't really need to be heredoc - so they should, by all means, be attributes. So should be, by the way, AMOUNT of PAYMENT, so you should probably write:

```<code><PAYMENTS CURRENCY = "DOLLARS"
    PAYMENTTYPE = "CHEQUE">
    <PAYMENT AMOUNT="100">
        // ALL OTHER DETAILS GO HERE
    </PAYMENT>
    <PAYMENT AMOUNT="100">
        // ALL OTHER DETAILS GO HERE
    </PAYMENT>
</PAYMENTS>
</code>```

and consider which of these "ALL OTHER DETAILS" should really "GO HERE", and which should also be attributes.

Body:
Welcome to the number one problem of using XML as a data serialization format! Attributes vs contained elements - so useful in markup, so annoying in data serialization...

At any rate, assuming you are forced to go with the herd and use XML for data serialization, there are only three reasons to prefer attributes over elements:

If the field has it's own subfields.

If the field can repeat.

If the field is something you want to treat as heredoc.

All these cases apply for the design, not for the example set of data you have in hand. If a field in your data doesn't happen to follow any of these rules, but the design allows one of the rules to apply it, it should be an element.

The reason to prefer attributes over elements(unless one of the cases apply) is that even with LINQ to XML it's much easier to use attributes. Programming languages usually make it easier to say "I have an object, give me the contents of one of it's fields" than to say "Here is a pile of objects, fetch me one that fits a certain criteria".

Both CURRENCY and PAYMENTTYPE are - as you say - non-repeatable by design, and they are not compound, and they don't really need to be heredoc - so they should, by all means, be attributes. So should be, by the way, AMOUNT of PAYMENT, so you should probably write:

<PAYMENTS CURRENCY = "DOLLARS"
    PAYMENTTYPE = "CHEQUE">
    <PAYMENT AMOUNT="100">
        // ALL OTHER DETAILS GO HERE
    </PAYMENT>
    <PAYMENT AMOUNT="100">
        // ALL OTHER DETAILS GO HERE
    </PAYMENT>
</PAYMENTS>

and consider which of these "ALL OTHER DETAILS" should really "GO HERE", and which should also be attributes.


问:
How to handle exception in REST API
Given a REST API, which throws an exception when handling a request from a client. Whenever the REST API throws an exception, it's logged and the application (in this case a console application) closes to prevent further damage.

Should I send a response to the client whose request resulted in an exception, indicating that an error occured or should I let the client hang and deal with it (timeout)?

答:
I've never seen any API letting the client hanging in a case of an error. <s>Unless you have a very specific case where this makes sense</s>¹ This simply doesn't make sense, and such behavior would only result in a practically unusable API:

This would slow the development of the client applications. Unless I read very, very carefully the documentation (and the documentation is excellent), I'll make mistakes which would result in timeouts, and thus slow development.

This would also make the client apps slow if they cause exceptions when used by an end user.

So no, don't do that.

What you should do is to handle the error gracefully. This means sending a response containing:

A specific HTTP code, like 404, 403, 500, etc.

The detail explaining what happened. Usually, this shouldn't be the exception itself, since it may contain sensitive information and you may want to provide something more understandable to your users.

Eventually the internal code. This may help when providing support. “I tried to access the list of products and got the error 7016.” is shorter to tell to the support than “I tried to access the list of products and got the error ‘The category is missing in the request. When querying for the list of products, the category should be provided.’”.

Eventually the link to the web page of your website which contains additional documentation, examples and workarounds.

Example:

HTTP 404
{
    "error": "The category is missing in the request. When querying for the list of products
, the category should be provided.",
    "code": 7016,
    "help": "http://api.example.com/docs/errors/7016"
}
```

The http://api.example.com/docs/errors/7016 page explains further how to avoid this error, i.e. what GET or POST parameter should be used in the request to specify the identifier of the category.

¹ I can imagine two cases: a super-secure API which needs to prevent its users from trying to break it and an API which wants to prevent DDOS. In the first case, it looks like a weak way to protect anything. In the second case, hanging without answering won't prevent the client from sending other requests meanwhile.

Title: How to handle exception in REST API

Body:
I've never seen any API letting the client hanging in a case of an error. <s>Unless you have a very specific case where this makes sense</s>¹ This simply doesn't make sense, and such behavior would only result in a practically unusable API:

This would slow the development of the client applications. Unless I read very, very carefully the documentation (and the documentation is excellent), I'll make mistakes which would result in timeouts, and thus slow development.

This would also make the client apps slow if they cause exceptions when used by an end user.

So no, don't do that.

What you should do is to handle the error gracefully. This means sending a response containing:

A specific HTTP code, like 404, 403, 500, etc.

The detail explaining what happened. Usually, this shouldn't be the exception itself, since it may contain sensitive information and you may want to provide something more understandable to your users.

Eventually the internal code. This may help when providing support. “I tried to access the list of products and got the error 7016.” is shorter to tell to the support than “I tried to access the list of products and got the error ‘The category is missing in the request. When querying for the list of products, the category should be provided.’”.

Eventually the link to the web page of your website which contains additional documentation, examples and workarounds.

Example:

HTTP 404
{
    "error": "The category is missing in the request. When querying for the list of products
, the category should be provided.",
    "code": 7016,
    "help": "http://api.example.com/docs/errors/7016"
}

The http://api.example.com/docs/errors/7016 page explains further how to avoid this error, i.e. what GET or POST parameter should be used in the request to specify the identifier of the category.

¹ I can imagine two cases: a super-secure API which needs to prevent its users from trying to break it and an API which wants to prevent DDOS. In the first case, it looks like a weak way to protect anything. In the second case, hanging without answering won't prevent the client from sending other requests meanwhile.


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
Only if the client explicitly requests it

Unless you have a significant number of users that will be effected, it's simply extra effort.


答:
I'm not sure what you mean by

Else initiate a loop (That loops either 1000, 10000 or 100000 times, depending on difficulty)

It seems like you're working with a rudimentary genetic algorithm; in this case, you need a better fitness function. In particular, for each possible outcome of the game (your "all combinations"),

if the opponent can win in one move

should have a higher priority than

you can win in one move

When you say

Continually move from both sides randomly till victory is achieved. If victory is by the computer, increment the score counter.

That randomly is your problem. Try to prevent it from happening.


问:
CI runner on same server of GitLab?
I'm setting up a GitLab server in my company and now I'm adding GitLab CI to it.

Before start this task I'd like to understand if there are any disadvantages running my runners on the same server used by GitLab and GitLab CI.

I've read that there are security concerns but we use it only internally so I don't think this could be a problem.

Am I missing something?

答:
Imagine the following situations:

An internal developer wants to harm the company (because considers being underpaid, because his boss sleeps with his wife; the reason doesn't matter) He commits a unit test which, when ran, instead of testing the application, searches for GitLab repository and erases it. At the next commit, surprise, all source code of the project is lost (but you do backups and you tested them, right?)

Or the same developer notices that backups of the repository are configured on the same machine. He changes this configuration through a unit test, so that the backup contains now a different repository, and waits for a month—the time the backups are kept. Now that all the backups are corrupted, he can commit his unit test which wipes out the source code from the server.

Or an intern wants to sell the source code to the competition. You've carefully configured the access, limiting it to only what he needs for his work. At the same time, he has unlimited access to the repository itself through the unit tests, being able to do the complete dump.

Unless unit tests are run in a context of limited permissions and can't access anything beyond the directories and files they need for the tests, mixing CI server with the server which keeps your repository is indeed dangerous.

Another issue is that version control server is expected to be fast. CI server installed on the same machine may slow the commits.

Title: CI runner on same server of GitLab?


答:
Given that there is no central “all knowing” server for git this is not a bad as it would be with some other source code control systems.

Provided there is an automatic syk of the git server off-site to anther git server (that is tested) I would not be concerned about this setup in a small company.

Ideally I would like to see the developers push their changes to the offset server git server, then the CI server to pull the charges from the offset server – that way the offsite server is tested when every check in is done.

If the developers then always did their pull from the onsite server to save time, that is not an issue.

Title: CI runner on same server of GitLab?

Body:
I'm setting up a GitLab server in my company and now I'm adding GitLab CI to it.

Before start this task I'd like to understand if there are any disadvantages running my runners on the same server used by GitLab and GitLab CI.

I've read that there are security concerns but we use it only internally so I don't think this could be a problem.

Am I missing something?


问:
Getting coders to do code review
I am running a project where I pay developers to contribute to my semi open source project. My problem is that it is easy to hire developers, but it is very difficult to get anyone to do code reviewing. I have repeatedly attempted to get the senior developers to review the code of the junior developers. I have attempted to pay them more, give them higher status etc. But they just seem to want to code instead of reviewing code.

Now I am considering forcing all developers that want to code, to also review code, but I have a feeling that it is a bad idea.

My question is, therefore, how can I motivate capable people to review the code of others? How is this done in successful open source projects like Linux, PostgreSQL, LibreOffice etc.

答:
Perhaps one way around the clear reluctance of your existing developer base to review code would be to introduce a 'tutoring/ reviewing' position that operates separately.

In this way the individual taken on for the tutoring position would generate interest from individuals seeking to improve upon their abilities while also having a clearly defined role of reviewing the work of the junior developers.

This would leave your senior developers free to focus on their strengths - developing.

Title: Getting coders to do code review