问:
Inject or not dependencies in a component based framework
I'm currently developing a small component-based framework the Android platform. The framework has some ready for use and some abstract (has some internal logic, but the developer needs to add some code to make it fully functional) components. All communication between the components is satisfied using interfaces. My question is:

Knowing that some components have dependencies, my framework should automatically provide them?

E.g.: I have an A component that "needs" B component. At first, I thought of two solutions:

My framework should create and inject the B component automatically when the developer instantiate the component A. If B is an abstract component, I would create and provide a default instance of it.

The framework should explain in the API that A component needs B component and then, leave to the developer to instantiate B component and pass it as a dependency to A.

In the second solution the developer could also create a new component that respects the contract (interfaces) with the A component and then use it.

Which of these solutions would lead to better maintenance, flexibility, and expansion of both the framework and the developers code? I accept other solutions.

答:
Do both

If you are making a framework, flexibility is key. Most frameworks provide interfaces and default implementations along with empty constructors wired to defaults, but allow for you to overwrite behavior by passing in your own implementations, or passing in a framework-provided alternative implementation.

```<code>public interface IReader { string Read(); }
public interface IWriter { void Write(String str); }

public class DefaultReader: IReader
{
    public string Read()
    {
        File.ReadAll("c:\myfile.cnf");
    }
}

public class DefaultWriter: IWriter
{
    public void Write(String str)
    {
        File.Write("c:\myfile.cnf", str);
    }
}

public class MyFrameWorkClass
{
    private IReader reader;
    private IWriter writer;

    public MyFrameWorkClass():
        this(new DefaultReader(), new DefaultWriter())
    {
    }

    public MyFrameWorkClass(IReader reader, IWriter writer)
    {
        this.reader = reader;
        this.writer = writer;
    }
}
</code>```

The reason frameworks work this way is simple: they can't provide any DI because that inherently ties them to a DI framework. The only thing they can do (and should do) is provide classes that can be DI'd easily. If you are going for ultimate flexibility, the above code would also have public properties that can be assigned. That way, any DI-framework can be plugged in and use the framework with either constructor-based or property-based injection.

If you want to provide an amount of DI out-of-the-box for your objects, you'll need to create separate components that do the binding for your framework. For example, if I were using Castle Windsor for DI I would provide an Installer-class that can be plugged in.

Body:
Do both

If you are making a framework, flexibility is key. Most frameworks provide interfaces and default implementations along with empty constructors wired to defaults, but allow for you to overwrite behavior by passing in your own implementations, or passing in a framework-provided alternative implementation.

public interface IReader { string Read(); }
public interface IWriter { void Write(String str); }

public class DefaultReader: IReader
{
    public string Read()
    {
        File.ReadAll("c:\myfile.cnf");
    }
}

public class DefaultWriter: IWriter
{
    public void Write(String str)
    {
        File.Write("c:\myfile.cnf", str);
    }
}

public class MyFrameWorkClass
{
    private IReader reader;
    private IWriter writer;

    public MyFrameWorkClass():
        this(new DefaultReader(), new DefaultWriter())
    {
    }

    public MyFrameWorkClass(IReader reader, IWriter writer)
    {
        this.reader = reader;
        this.writer = writer;
    }
}

The reason frameworks work this way is simple: they can't provide any DI because that inherently ties them to a DI framework. The only thing they can do (and should do) is provide classes that can be DI'd easily. If you are going for ultimate flexibility, the above code would also have public properties that can be assigned. That way, any DI-framework can be plugged in and use the framework with either constructor-based or property-based injection.

If you want to provide an amount of DI out-of-the-box for your objects, you'll need to create separate components that do the binding for your framework. For example, if I were using Castle Windsor for DI I would provide an Installer-class that can be plugged in.


问:
is coding important?
Is coding important to be good at computer science? Should one implement the algorithm to know it well ?

I remember one cs professor's idiom that "I never code"

答:
Coding is not super important to be a true computer scientist. And thinking in code can constrain thinking as they seek to develop useful abstract concepts. Most excellent coders do not have the intellectual chops to analyze complex algorithms, or develop concepts such as programming languages, advanced searching and sorting  algorithms, finite automata theory, distributed computing theory, R-Trees,  fault-tolerance protocols, reliable communication protocols, digital signal processing algorithms, cryptographic theory, performance analysis and optimization, efficient caching, map-reduce, reliable security protocols etc. Excellent coders and computer engineers can usually use these theories in the systems that they are trying to build and do it quite effectively, but that is really the realm of the computer systems engineer or computer programmer.

Coding is critically important to being a computer programmer. Understanding how to encode the useful abstract concepts produced by the computer scientists into working code is also useful.

One big problem in computer science is that they often have to find solutions to math problems that have little utility in solving today's programming problems. Even if they coded a solution, nobody would really be able to use it. Think about digital signal processing theory. It was invented by folks like Fourier, Hilbert and Shannon, but the application to computerized DSP problems was not widely possible until about 20 years ago.

The big problem in computer education is that most people taught by computer scientists will not become computer scientists. But too many computer scientists don't get this. Coding may not be important to them, but if you are in their class, it is almost certainly going to be important to you.

Another big problem in computer education is that many true computer scientists lack the industrial experience to be useful in teaching software development. They are essentially trying to teach something that they really don't know. That causes them to lose credibility. Things that are important in an industrial setting just don't often register with some of these computer scientists.

The long and the short, coding is important for most people who become "computer scientists" because most of those people will become computer programmers and computer system engineers.

ContentLicense: CC BY-SA 2.5

Title: is coding important?


问:
C: "this" vs "<instance name>"
I'm using C in a minimal, efficient OOP style to build a game engine. A problem I've begun to face as the engine code settles is my (erstwhile) choice to use this. For example, I have:

```<code>void Engine_initialise(Engine * this);

void Window_terminate(Window * this);
</code>```

Window * this contains a reference to the singleton Engine. Now, let's say I reference this Engine member from both Engine_initialise(..) and Window_terminate(..);. In the former it will be this->member, yet in the latter it will be (window->)engine->member.

This inconsistency annoys me; if it is the same, it should look the same. And as I work purely in a text editor without IDE, I want a single find-replace across all files, instead of multiple find-replaces.

Let's consider another example, where there isn't only one argument of the given type.

```<code>Blob_compare(Blob * this, Blob * that);
</code>```

vs.

```<code>Blob_compare(Blob * blob, Blob * blobOther); //or blob1 and blob2, or whatever
</code>```

...in spite of my preference for losing this, the former looks better as it is descriptive and concise.

Question: Are there any particularly strong arguments for continuing to use this as the name of current object instance in my various functions? I'm thinking of replacing all this with engine (or similar). I would like to settle on a coding standard in this regard, for all C code.

I am asking about the usefulness of this as the primary function argument; the names of other parameters of similar type are not of major importance here in spite of my second example. To me it seems sensible, if the function is prefixed with Blob_, to assume that blob refers to the current instance. And no, I really don't care one iota about renaming types - these are well fixed.

答:
If they are supposed to be singletons, and you really want to do things in your (conceptual) style, you might want to use Context object.

(First and foremost: apologies. C is not my native language; C++ is.)

Basically,

```<code>struct Context
{
    Engine * engine;
    Window * window;
    // any other things that are considered singletons
    // according to your conceptual style
};

void Engine_initialize(Context * context);
void Window_terminate(Context * context);
</code>```

For reference, take a look at jpeglib and libtiff on their use of some root level objects which contain pointers to all other relevant stuff needed by the code.

As a sidenote, using this as the identifier name in C code (and header files) will create griefs for people who try to integrate your C code into C++ projects. See this question for opinions on this.

ContentLicense: CC BY-SA 3.0

Title: C: "this" vs "<instance name>"

Body:
If they are supposed to be singletons, and you really want to do things in your (conceptual) style, you might want to use Context object.

(First and foremost: apologies. C is not my native language; C++ is.)

Basically,

struct Context
{
    Engine * engine;
    Window * window;
    // any other things that are considered singletons
    // according to your conceptual style
};

void Engine_initialize(Context * context);
void Window_terminate(Context * context);

For reference, take a look at jpeglib and libtiff on their use of some root level objects which contain pointers to all other relevant stuff needed by the code.

As a sidenote, using this as the identifier name in C code (and header files) will create griefs for people who try to integrate your C code into C++ projects. See this question for opinions on this.


问:
Can higher order functions ever be pure?
I was thinking about pure functions especially in the context of C++, which of course is not a purely functional language, and was wondering if higher order functions in C++ can ever be considered pure? Take for example std::find_if: it would be very pure except it takes another function, which might not be pure. There seems to be no constraint on the predicate std::find_if takes that prevents doing nasty, impure things inside the function, like this:

```<code>const std::vector<int> v = { 1,2,3,4,5 };
auto result = std::find_if(v.begin(), v.end(), [](int arg)
{
   return arg < someGlobalVariable;
} );
</code>```

So maybe someone with more experience in functional programming languages could clarify this for me: Does the notion of 'pure functions' make sense when dealing with higher order functions?

EDIT: I should have stated more clearly that I am not looking for an explanation of const correctness in C++. I just wanted to know if the definition of a pure function makes sense when talking about higher order functions in C++. I changed the example to illustrate that const is not solving my problem here!

答:
There is a constraint on the predicate, but it's textually enforced by standard text and may be enforced by a sufficiently capable compiler as Quality-of-Implementation.

Many things are only guarded by phrasing in the standard. Some of the rationale is that while its possible to constrain the predicate to ones that take the argument by value or const reference, it would make it harder to use existing predicates and spawn a horde of adapters just to get the function to fit.

Similiarly, the standard doesn't forbid modification of the predicate, but it warns that it may and probably will make copies of it, so mutation needs to be done via external or captured state.

When designing a C++ library, it's commonly said that you cannot envision all the places it'll be used, just that you should try to not constrain them too hard.

I would guess that a concept or trait that would declare a pure function would not gain the implementation anything, as it's already designed around the programmer promising that the predicate doesn't modify the collection. Similarly, a diagnostic that indicates that a predicate is impure would fire on pretty much everything and doesn't aid much.

C++11 25.1/6 states (paraphrased): If the Effects section of an algorithm says that a value pointed to by any iterator passed as an argument is
modified, then that algorithm has an additional type requirement, it shall satisfy the requirements of a mutable iterator (24.2).

C++11 25.1/8 (and /9) states: ... a predicate may not apply any non-constant function through the dereferenced iterator.

find_if (25.2.5) has no such effects section, so even if the predicate was allowed to mutate, it would still not be legal.


问:
Will HTML5/JS Eventually Replace All Client Side Languages?
I'm just wondering about the future of it all. IMHO, there are 4 forces that define where technology goes: Microsoft, Apple, Google, Adobe.

It looks like in Apple's iPhone/iPad iADs can now be programmed in HTML5. So does that mean HTML5 will eventually replace objective-c?

Also, Microsoft has now shifted it's focus from WPF/Silverlight to HTML5 and I assume Visual Studio 2011 will be all about tooling support for HTML5. Because that's what Microsoft do. (Tools). In a few months IE9 the last major browser will support HTML5.

Similarly Adobe is getting on the HTML5 bandwagon and allows to export flash content to HTML5 in their latest tools.

And we all know how much in bed Google is with html5. Heck, their latest Operating System (Chrome OS) is nothing but a big fat web browser.

Apps for Mobile (i.e., iPhone, Android, WM7) are very hard for a company to program especially for many different devices (each with their own language) so I'm assuming this won't last too long. I.e., HTML5 will be the unifying language. Which is somewhat sad for app developers because now users will be able to play the "cool" html5 apps for free on the web and it'll be hard to charge for them.

So are strongly-typed languages really doomed, and in the future, say 5-10 years, will client side programming only be in HTML5? Will all of us become javascript programmers? :) Because the signs are sure pointing that way...

答:
I think it's misguided to suggest that HTML5/JS will replace ALL client-side languages.  Will a lot of applications go that way in future years?  Yes, probably.  Will all of them?  No.

The other major point to note is that the landscape is constantly changing.  HTML5 is a great technology that promises to solve a lot of the issues developers are currently having when trying to write applications that work cross-platform.  Sure, HTML5/JS can solve many of those problems, but the landscape will change and a new set of problems will crop up.  HTML5 will eventually seem dated.

In 10 years, ask yourself whether HTML5/JS was the solution to all the problems and I can all but guarantee the answer will be no.  In 20 years the question itself will probably seem ridiculous.

OwnerDisplayName: Shnitzel

LastEditorDisplayName: Shnitzel


答:
You're right, this is an issue when one wants to reason about purity of functions in a language that permits impure functions. Technically almost all languages allow impurity, but the purely functional ones usually explicitly mark the impure ones in the type system, such that the Haskell function map :: (a -> b) -> [a] -> [b] does, implicitly, require that the function to be mapped is pure.

Informally, we can certainly say: find_if is pure only if the predicate function is pure. So how might we teach the compiler about this?

Since C++ does not mark impure functions (nor pure ones, for that matter, but let's pretend we are adding that feature), and we probably don't want to restrict find_if to only accept pure functions (since that would be backwards incompatible), we are left with what I'll dub purity polymorphism. That is, find_if is pure iff the function passed in is pure. I'm not aware of a language doing this, but in principle it is no different from polymorphism over types (a.k.a. generics). Sufficently sophisticated effect systems probably have equivalent capability, just generalized to more and more fine-grained judgements than "pure" and "impure".

Title: Can higher order functions ever be pure?

Body:
I was thinking about pure functions especially in the context of C++, which of course is not a purely functional language, and was wondering if higher order functions in C++ can ever be considered pure? Take for example std::find_if: it would be very pure except it takes another function, which might not be pure. There seems to be no constraint on the predicate std::find_if takes that prevents doing nasty, impure things inside the function, like this:

```<code>const std::vector<int> v = { 1,2,3,4,5 };
auto result = std::find_if(v.begin(), v.end(), [](int arg)
{
   return arg < someGlobalVariable;
} );
</code>```

So maybe someone with more experience in functional programming languages could clarify this for me: Does the notion of 'pure functions' make sense when dealing with higher order functions?

EDIT: I should have stated more clearly that I am not looking for an explanation of const correctness in C++. I just wanted to know if the definition of a pure function makes sense when talking about higher order functions in C++. I changed the example to illustrate that const is not solving my problem here!


问:
C# - design to parse and write csv and manipulating data
I've designed the below code for one of the requirement. I have to write different tests for the code and I would need feedback on where I can improve the design.

Requirement:

Read the customer details from csv, calculate his average expenses on different items on yearly and write to csv again.

Read the customer details from csv, calculate his total expenses on faimly and write to csv again.

As both the ExpenseCalculator uses CsvReaderWriter function, is it better to create the abstract class which implements csvReaderWriter functionality and derive from abstract class or is it better to use Interface?

```<code>    public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Expenses { get; set; }
    // other details
}

public interface ICsvReaderWriter<T>
{
    IEnumerable<T> ParseCsv(string filePath);
    void WriteCsv(string filePath, IEnumerable<Customer> customers);
}

public class ReaderWriter : ICsvReaderWriter<Customer>
{
    public IEnumerable<Customer> ParseCsv(string filePath)
    {
        throw new NotImplementedException();
    }

    public void WriteCsv(string filePath, IEnumerable<Customer> customers )
    {
        throw new NotImplementedException();
    }
}

public interface IExpenseCalculator
{
    void CalculateExpenses(string filePath);
}

public class ItemExpenseCalculator : IExpenseCalculator
{
    private readonly ICsvReaderWriter<Customer> _csvReaderWriter;
    public ItemExpenseCalculator(ICsvReaderWriter<Customer> csvReaderWriter)
    {
        this._csvReaderWriter = csvReaderWriter;
    }

    public void CalculateExpenses(string filePath)
    {
        var customers = _csvReaderWriter.ParseCsv(filePath);
        // do manipulation
        _csvReaderWriter.WriteCsv(filePath, customers);
    }
}

public class FamilyExpenseCalculator: IExpenseCalculator
{
    private readonly ICsvReaderWriter<Customer> _csvReaderWriter;

    public FamilyExpenseCalculator(ICsvReaderWriter<Customer> csvReaderWriter)
    {
        this._csvReaderWriter = csvReaderWriter;
    }

    public void CalculateExpenses(string filePath)
    {
        var customers = _csvReaderWriter.ParseCsv(filePath);
        // do manipulation
        _csvReaderWriter.WriteCsv(filePath, customers);
    }
}

public class Program
{
    private void Main()
    {
        IExpenseCalculator itemExpenseCalculator = new ItemExpenseCalculator(new ReaderWriter());
        itemExpenseCalculator.CalculateExpenses(@"D:\");

        IExpenseCalculator familyExpenseCalculator = new FamilyExpenseCalculator(new ReaderWriter());
        familyExpenseCalculator.CalculateExpenses(@"D:\");
    }
}
</code>```

答:
It's not a very good design, because it doesn't adhere to Single Responsibility Principle .

ICsvReaderWriter has two responsibilities, as the name itself indicates. I wouldn't lump them together into one class. Besides, the Reader / Writer distinction is sort of idiomatic in the .NET world (think StreamReader / StreamWriter - you won't find a StreamReaderWriter in the standard library).

IExpenseCalculator doesn't only calculate expenses, which is quite easy to tell because its method takes a filePath parameter. The Single Responsibility Principle states that a class should have one, and only one reason to change. Your IExpenseCalculator, however, has several potential reasons to change. It's not just if expenses are to be calculated differently, but also if the output of these calculations has to be retrieved or persisted differently... or not persisted but passed further along etc. And you can't easily unit test your ItemExpenseCalculator (to ensure that it works), because it pulls its input from the file system and pushes the output there as well.

Inheritance hierarchy seems to be upside down to me, too. The interface is ICsvReaderWriter, but the implementation is simply a ReaderWriter. So the base interface is more specific than the child class, because its name already defines the concrete format, whereas the derived class sports a universal name omitting technical details.

Why would the interface care about the storage format? I'd expect this to be designed the other way round: a generic IWriter interface that could be implemented by a concrete CsvWriter, or an XmlWriter, or a JsonWriter  if there is a need.

See the principle of abstraction for reference. Key takeaway: "the higher the level, the less detail. The lower the level, the more detail."

There's also a slip-up in the interface definition:

```<code> public interface ICsvReaderWriter<T>
 {
     IEnumerable<T> ParseCsv(string filePath);
     void WriteCsv(string filePath, IEnumerable<Customer> customers);
 }
</code>```

Shouldn't that rather be

```<code>void WriteCsv(string filePath, IEnumerable<T> objects);
</code>```

Naming is a bit off. If the interface is a Reader, not a Parser, why is the method named Parse? It introduces semantic noise. Synonyms are good in creative writing, but in software development we should strive for unambiguity.

And a minor remark... not really a design issue, just a matter of code style.

```<code>private readonly ICsvReaderWriter<Customer> _csvReaderWriter;
</code>```

```<code>public ItemExpenseCalculator(ICsvReaderWriter<Customer> csvReaderWriter)
{
    this._csvReaderWriter = csvReaderWriter;
}
</code>```

Some prefer to prefix fields with an underscore (_csvReaderWriter), some don't like it and then they have to explicitly use this to differentiate between fields and parameters of the same name. To each his own, it's a matter of taste and consistency. However doing both at once makes no sense. It's like wearing belt and braces. If you're referencing the current object explicitly with this, what purpose does the underscore serve?

Body:
It's not a very good design, because it doesn't adhere to Single Responsibility Principle .

ICsvReaderWriter has two responsibilities, as the name itself indicates. I wouldn't lump them together into one class. Besides, the Reader / Writer distinction is sort of idiomatic in the .NET world (think StreamReader / StreamWriter - you won't find a StreamReaderWriter in the standard library).

IExpenseCalculator doesn't only calculate expenses, which is quite easy to tell because its method takes a filePath parameter. The Single Responsibility Principle states that a class should have one, and only one reason to change. Your IExpenseCalculator, however, has several potential reasons to change. It's not just if expenses are to be calculated differently, but also if the output of these calculations has to be retrieved or persisted differently... or not persisted but passed further along etc. And you can't easily unit test your ItemExpenseCalculator (to ensure that it works), because it pulls its input from the file system and pushes the output there as well.

Inheritance hierarchy seems to be upside down to me, too. The interface is ICsvReaderWriter, but the implementation is simply a ReaderWriter. So the base interface is more specific than the child class, because its name already defines the concrete format, whereas the derived class sports a universal name omitting technical details.

Why would the interface care about the storage format? I'd expect this to be designed the other way round: a generic IWriter interface that could be implemented by a concrete CsvWriter, or an XmlWriter, or a JsonWriter  if there is a need.

See the principle of abstraction for reference. Key takeaway: "the higher the level, the less detail. The lower the level, the more detail."

There's also a slip-up in the interface definition:

 public interface ICsvReaderWriter<T>
 {
     IEnumerable<T> ParseCsv(string filePath);
     void WriteCsv(string filePath, IEnumerable<Customer> customers);
 }

Shouldn't that rather be

void WriteCsv(string filePath, IEnumerable<T> objects);

Naming is a bit off. If the interface is a Reader, not a Parser, why is the method named Parse? It introduces semantic noise. Synonyms are good in creative writing, but in software development we should strive for unambiguity.

And a minor remark... not really a design issue, just a matter of code style.

private readonly ICsvReaderWriter<Customer> _csvReaderWriter;

public ItemExpenseCalculator(ICsvReaderWriter<Customer> csvReaderWriter)
{
    this._csvReaderWriter = csvReaderWriter;
}

Some prefer to prefix fields with an underscore (_csvReaderWriter), some don't like it and then they have to explicitly use this to differentiate between fields and parameters of the same name. To each his own, it's a matter of taste and consistency. However doing both at once makes no sense. It's like wearing belt and braces. If you're referencing the current object explicitly with this, what purpose does the underscore serve?


问:
How should I test the HTML output my class creates?
As a learning project, I am trying to create something similar to the WebGrid that comes with ASP.NET MVC. Now this component MyGrid<T> looks like this:

```<code>public class MyGrid<T> where T : class
{
  public MyGrid(IEnumerable<T> dataSource) { ... }
  public bool AutoGenerateColumns { get; set; }
  public MvcHtmlString HtmlMarkup { get; }
  // some more stuff
}
</code>```

I have so far written some tests that test basic functionality of the grid, as well as check for some thrown exceptions. But I wonder how I should best test for the correct output, as it comes as MvcHtmlString. An example of how I checked for an empty grid is the following test:

```<code>[TestMethod]
public void AutoGenerateColumnsFalseProducesEmptyTableWhenNoColumnsAreSpecified()
{
  var grid = new MyGrid<object>(new object[] { "a", "b" });
  grid.AutoGenerateColumns = false;
  string markup = grid.HtmlMarkup.ToHtmlString();
  XDocument xdoc = XDocument.Parse(markup);

  XElement table = xdoc.Descendants().First();
  Assert.IsTrue(table.Name == "table");

  // children: thead, tbody, tfoot
  foreach (XElement child in table.Descendants())
  {
    Assert.IsFalse(child.HasElements);
  }
}
</code>```

This seems quite clunky to me, plus I don't know if using XDocument is a good way to test this here. To create the markup, I use TagBuilder instead.

So to check for an empty grid is not as short/elegant as I'd like it to be. Any tips on how to make this test better are very welcome. But how would I test for more complex stuff, like to check for correct output?

The TagBuilder seems to produce some whitespace, so one way to test would be to strip the output of all whitespace and then compare with a handwritten HTML string. But again, this seems very clunky (and leaves much room for typing errors on my part).

Do you have any suggestions on how to test the (more complex) HTML output for correctness? Is there a more elegant/better way than XDocument to parse the output perhaps?

答:
The more modern approach is to utilize the HTML Agility Pack.  The syntax is closer to the dom selections that would be in a JS Library like JQuery.

Here's some examples:

https://stackoverflow.com/questions/846994/how-to-use-html-agility-pack

https://html-agility-pack.net/online-examples

This can also be loaded as a Nuget package.

ContentLicense: CC BY-SA 4.0


问:
Starting a Windows task from Linux, what are my options?
We have server that runs data processing tasks, using Python, Django and Celery, on Linux. Once a batch of data comes in, a number of Celery tasks are scheduled and they run, some of them in parallel, some depend on the results of earlier tasks, this all works.

Now we have to implement a new task -- a proprietary Windows-only program needs to be called on some of our data files, resulting in some more files. Only one instance of this program can run at the same time (basically we have to rewrite its config.ini before we can start it each time, and there is only one such .ini). It must run on Windows, can't run under Wine.

Sharing the files is easy, there is a network mount that both sides can talk to.

But I'm not sure what the best way is to start the task from the Linux server, and know that it has finished, that would work nicely with the way we currently do the other tasks.

One option might be to give the Windows machine a tiny webserver, let it listen to a request so it can start up once it receives something, have its use its own Celery or similar, and let it call another URL on the Linux task server once it has finished.

But that seems a bit clunky, do I have better options?

答:
Utilizing a webserver for this purpose is actually a standard approach, it is just a simple form of Service Oriented Architecture. Of course, this term might pretend more than there is actually behind it.

To keep this lightweight, without the need using a fullblown Webserver, you can use a tool like node.js. It is the most simple solution I can think of for your problem, node.js provides all the "glue" you need to make that work.

For example, setting up a webserver with 6 (six!) lines of code is shown at the above entry page. For setting up a REST service with node.js, you will find plenty of tutorials on the Web. Assumed your Windows program is a command line program without GUI (otherwise your scenario does not make much sense to me), you can run it the usual manner with spawn and exec, asynchronously. Moreover, I am pretty sure you can make such a server interact with Celery with just a few lines of code.


问:
When should services persist data?
Is there a preferable way of when a service should persist data?

Update

Does this depend on if the services are public or internal?

Some services take entity objects as parameters to do some action on that object, update it's status or add some data to it. Should that service also persist changes to that object to the database(SaveChanges, Flush, ...) or should the caller who got/created that entity decide if and when to persist it?

Making the inner service persist the data includes problems like: harder tests, can't use implicit database transactions, maybe many database roundtrips instead of one.

It is best to describe this with an example:

```<code>public void PerformAction(int productId, int actionId)
{
    var product = productRepository.GetProduct(productId);
    var action = actionRepository.GetAction(actionId);

    actionService.PerformAction(product, action);

    //Should this be necessary?
    productRepository.Update(product);
}
</code>```

This would be obvious but then the PerformAction could not have dependencies other than the model:

```<code>public void PerformAction(int productId, int actionId)
{
    var product = productRepository.GetProduct(productId);
    var action = actionRepository.GetAction(actionId);

    product.PerformAction(action);

    //Obviously necessary!
    productRepository.Update(product);
}
</code>```

答:
Unless you have a strong reason, you should use an ORM (Entity Framework, NHibernate).

When you work with an ORM, the objects that were returned from the database will be "observed" and you just run the "SaveChanges();"
leaving the dirty work to the ORM;

The ORM will automatically check which entities need to be persisted and if there is no change to be made it just does nothing.

Because, even in your second example, the entity product could have a business rule where it does not change any attribute in certain cases.

```<code>public void PerformAction(int productId, int actionId)
{
    var product = productRepository.GetProduct(productId);
    var action = actionRepository.GetAction(actionId);

    actionService.PerformAction(product, action);

    productRepository.Context.SaveChanges();
}
</code>```

If you prefer not to use an ORM, you can "reinvent the wheel" and use the same design patterns that they use:

https://en.wikipedia.org/wiki/Proxy_pattern

http://martinfowler.com/eaaCatalog/unitOfWork.html

About where you should run the "SaveChanges", it depends on which layers each their services are.

An approach that I like to use is put all "SaveChanges" in the application layer (of DDD).

References: https://dzone.com/articles/responsibilities-application

Title: When should services persist data?

Body:
Unless you have a strong reason, you should use an ORM (Entity Framework, NHibernate).

When you work with an ORM, the objects that were returned from the database will be "observed" and you just run the "SaveChanges();"
leaving the dirty work to the ORM;

The ORM will automatically check which entities need to be persisted and if there is no change to be made it just does nothing.

Because, even in your second example, the entity product could have a business rule where it does not change any attribute in certain cases.

public void PerformAction(int productId, int actionId)
{
    var product = productRepository.GetProduct(productId);
    var action = actionRepository.GetAction(actionId);

    actionService.PerformAction(product, action);

    productRepository.Context.SaveChanges();
}

If you prefer not to use an ORM, you can "reinvent the wheel" and use the same design patterns that they use:

https://en.wikipedia.org/wiki/Proxy_pattern

http://martinfowler.com/eaaCatalog/unitOfWork.html

About where you should run the "SaveChanges", it depends on which layers each their services are.

An approach that I like to use is put all "SaveChanges" in the application layer (of DDD).

References: https://dzone.com/articles/responsibilities-application


问:
Async library guidance

I'm creating a library that contains a class that exposes several Async methods:

public class MyClass {
  public async Task<Foo> DoFooAsync() { /*...*/ }
  public async Task<Bar> DoBarAsync() { /*...*/ }
}
```

I have two (main) questions about this:

I understand that not everybody likes to (or needs to) work asynchronously; it's easy for someone using my library to invoke these methods synchronously. However, it won't be very much of an effort to provide synchronous wrappers for the async method so that the class also provides a public Foo DoFoo() and public Bar DoBar() method.

Should I provide these methods or should I let people implement their own?

If I provide these methods, should I:

Create a private T ExecuteFunctionSynchronously<T>(Func<T> func) method and have the synchronous methods invoke this ExecuteFunctionSynchronously internally or ...

...should every synchronous method just call the async method 'waterfall style' (so DoFoo() executes return DoFooAsync().Result (or something like that) internally?

The class will, later, have a 'message loop' which continually reads data coming from an (awaited) socket. I want this message loop to go on 'eternally'. I want the class to be easily used by everyone.

What kind of 'style' should I use for this messageloop to notify users of MyClass that something has happened?

Events (e.g. MyClass.FooReceived += myhandler)?

Callbacks (e.g. MyClass.StartListening(myhandler))?

Something 'awaitable' (e.g. while (await MyClass.GetFoo()) { ... })?

Reactive (Rx)?

Something other than above, namely ...

I'm primarily asking for "style" guidance; how would you approach this and how do you think a (primarily) async library should provide (API wise) interaction while keeping internals and messageloops out of the user's mind without exposing too much of what's going on internally.

答:
Should I provide these methods or should I let people implement their own?

I'm trying to find the post (I think it was Stephen Cleary on SO), but one of the answers had made the point that he preferred to make his operations synchronous and let the client decide if they want to call them asynchronously or not.

It stuck with me because it was Stephen Cleary and I liked the idea that your code can be used in the same old way without having to think about it, or it can be wrapped in an async wrapper, which requires a bit more thought but it's work you're choosing to take on.

This, versus the opposite situation where you have to think about and put more effort into using a library in the standard synchronous way we're generally used to.

Title: Async library guidance


问:
.NET Dependency Management Systems
I have some .NET projects that are starting to get large enough to merit looking into Dependency Management solutions, so we don't have to copy binaries from one project to another. Here's what I've found so far:

NPanday is based on a port of Maven. I can't tell how recently it was worked on, but the last release was in May 2011.

NuGet seems to be under active development, and it appears to have support directly from Microsoft. Some people complained that it "only addresses dependency resolution," but I don't know what else it should address, or whether it has added more features since that point. It does appear to have recently added the ability to import binaries as part of the build process so we don't have to commit them to our repositories.

Refix appears to still be in Beta, after having received no attention since Sept 2011.

Would somebody with recent experience using any of these dependency management tools (or any others that work well) share your experience? Is NuGet mature enough to use it for dependency management? If not, what does it lack?

答:
NuGet is still the best option at this point.

The main issue with NuGet as a dependency manager is that it was envisioned to be a "development time" dependency manager, not a "build time" dependency manager.

A developer would restore a NuGet package thru Visual Studio...and this could run a PowerShell script during the restore that modifies files in the project.

This is unlike other dependency management systems that I have seen, as adding a dependency and resolving it can alter the system referencing the dependency.

There is no built-in mechanism to ensure or check idempotency in the PowerShell script, so running it more than once on the same set of files may not be deterministic.

It seems many use NuGet to pull packages thru Visual Studio during development time, but I'm not aware of a solid recommendation for how that is supposed to work on a build server.

Title: .NET Dependency Management Systems


答:
I would suggest to avoid using this as a formal name in C, because this is a C++ keyword. You could use e.g. self (or me or recv, or ipse -it is self in Latin) instead of this

If you code your C code without using C++ keywords, you are much more likely to be able to use your code with a C++ compiler.

In particular, quite often a C header file foo.h (with some static inline functions) which does not use any C++ keyword is very likely to be usable from a C++ program (perhaps by surrounding the #include "foo.h" directive with extern "C" {  & };, because C++ has been (originally) designed to be upward compatible with C (this is slightly less true with C++11 and C11).

Title: C: "this" vs "<instance name>"

Body:
I'm using C in a minimal, efficient OOP style to build a game engine. A problem I've begun to face as the engine code settles is my (erstwhile) choice to use this. For example, I have:

```<code>void Engine_initialise(Engine * this);

void Window_terminate(Window * this);
</code>```

Window * this contains a reference to the singleton Engine. Now, let's say I reference this Engine member from both Engine_initialise(..) and Window_terminate(..);. In the former it will be this->member, yet in the latter it will be (window->)engine->member.

This inconsistency annoys me; if it is the same, it should look the same. And as I work purely in a text editor without IDE, I want a single find-replace across all files, instead of multiple find-replaces.

Let's consider another example, where there isn't only one argument of the given type.

```<code>Blob_compare(Blob * this, Blob * that);
</code>```

vs.

```<code>Blob_compare(Blob * blob, Blob * blobOther); //or blob1 and blob2, or whatever
</code>```

...in spite of my preference for losing this, the former looks better as it is descriptive and concise.

Question: Are there any particularly strong arguments for continuing to use this as the name of current object instance in my various functions? I'm thinking of replacing all this with engine (or similar). I would like to settle on a coding standard in this regard, for all C code.

I am asking about the usefulness of this as the primary function argument; the names of other parameters of similar type are not of major importance here in spite of my second example. To me it seems sensible, if the function is prefixed with Blob_, to assume that blob refers to the current instance. And no, I really don't care one iota about renaming types - these are well fixed.


问:
How do I manage the technical debate over WCF vs. Web API?
I'm managing a team of like 15 developers now, and we are stuck at a point on choosing the technology, where the team is broken into two completely opposite teams, debating over usage of WCF vs. Web API.

Team A which supports usage of Web API, brings forward these reasons:

Web API is just the modern way of writing services (Wikipedia)

WCF is an overhead for HTTP. It's a solution for TCP, and Net Pipes, and other protocols

WCF models are not POCO, because of [DataContract] & [DataMember] and those attributes

SOAP is not as readable and handy as JSON

SOAP is an overhead for network compared to JSON (transport over HTTP)

No method overloading

Team B which supports the usage of WCF, says:

WCF supports multiple protocols (via configuration)

WCF supports distributed transactions

Many good examples and success stories exist for WCF (while Web API is still young)

Duplex is excellent for two-way communication

This debate is continuing, and I don't know what to do now. Personally, I think that we should use a tool only for its right place of usage. In other words, we'd better use Web API, if we want to expose a service over HTTP, but use WCF when it comes to TCP and Duplex.

By searching the Internet, we can't get to a solid result. Many posts exist for supporting WCF, but on the contrary we also find people complaint about it. I know that the nature of this question might sound arguable, but we need some good hints to decide. We're stuck at a point where choosing a technology by chance might make us regret it later. We want to choose with open eyes.

Our usage would be mostly for web, and we would expose our services over HTTP. In some cases (say 5 to 10 percent) we might need distributed transactions though.

What should I do now? How do I manage this debate in a constructive way?

答:
A good architect delays technology decisions until they're absolutely necessary to make.

In other words, don't make the decision until a client needs to actually connect. You can build a fully tested service layer without actually putting a transport/commnication mechanism over it. 95%+ of the work can be done "beneath" the adapter, outside the framework.

Come time to expose those services to remote clients, you can pick the trendiest framework off the shelf and write thin wrappers over a versatile service layer.

Hell, if your "real" service layer is done well, you can even try several wrappers at a minimal expense.

That's the dogmatic answer, anyway. In practice, you may want to pick the simplest tool off the shelf to facilitate early and frequent integration tests -- but, still limit your dependence on it and treat it strictly as a simply thin communication layer over the real services.

If you take this approach, you'll probably find that you pick the simplest tool to use initially and no one will fuss, because the team knows they can implement a more sophisticated or trendy tool or framework later, if necessary, with minimal effort.


问:
Is using a lot of free third party libraries a good thing?
For your proprietary projects at work?

Problems I can imagine are: more dlls (can be a problem when for example you have to include a big DLL but you only need few functions in that library), a lot of license statements you have to take care of when releasing your product, the reliability of the library, etc.

Any other potential problems? What is your opinion?
(info: I'm using .NET at work)

答:
It's good as long as you have good management on it. As you concern, it may take time to harness other works, and bad libraries sometimes even produce unexpected results.

I try to use the popular library that have a huge community. So when there's a problem, I can ask provider/other users for support.


答: If you explicitly save data, the best place to perform that is in a call at the end of the highest level method, the entry point to your service. That means you must divide your service methods into two categories, those that are public, entry level methods, and those that are internal methods, that should not save data.</p>

Title: When should services persist data?

Body:
Is there a preferable way of when a service should persist data?

Update

Does this depend on if the services are public or internal?

Some services take entity objects as parameters to do some action on that object, update it's status or add some data to it. Should that service also persist changes to that object to the database(SaveChanges, Flush, ...) or should the caller who got/created that entity decide if and when to persist it?

Making the inner service persist the data includes problems like: harder tests, can't use implicit database transactions, maybe many database roundtrips instead of one.

It is best to describe this with an example:

```<code>public void PerformAction(int productId, int actionId)
{
    var product = productRepository.GetProduct(productId);
    var action = actionRepository.GetAction(actionId);

    actionService.PerformAction(product, action);

    //Should this be necessary?
    productRepository.Update(product);
}
</code>```

This would be obvious but then the PerformAction could not have dependencies other than the model:

```<code>public void PerformAction(int productId, int actionId)
{
    var product = productRepository.GetProduct(productId);
    var action = actionRepository.GetAction(actionId);

    product.PerformAction(action);

    //Obviously necessary!
    productRepository.Update(product);
}
</code>```


问:
Is using object of main class better than using static main method?
I have noticed in java programs at least, that people tend to prefer to start their programs by creating and instance of the class that contains the main method, and activating a non-static method within it, like so

```<code>    class MainClass {
        void start() {
            //start the program flow
        }
        public static void main(String[] args) {
            new MainClass().start();
        }
    }
</code>```

Than to simply start the program flow through the main method from a static context, like so

```<code>    class MainClass {
        public static void main(String[] args) {
            //start the program flow
        }
    }
</code>```

I was wondering, why do people prefer the former method as the latter seems simpler, and is there something that should determine which one I should use?

答:
Your class (though it is main class) is not always supposed to be executed by jvm directly.
May be in future some other class needs to launch your application or to start() object of your class.
So people use former method taking care of future in thier mind.
Now which one you should use depends on class and your application use.</p>


问:
Haskell build and artifact environment similar to Maven
I used to be a Java developer for a long time, but recently, I joined a Haskell team.
In the java world, if you have a large project,
with several teams working on it, a common approach is to use an artifact server such as Maven to ease and speed-up the development.
Numerous build tools, such as Ant, Maven, Gradle, can build the project and
upload a jar file to the artifact server that can be used by the rest of the team
without pain.
Therefore,
by splitting the project into smaller sub-projects, the build time is also drastically reduced.

On the Haskell side,
we are using cabal to build the project.
Our project takes about 10-15 minutes to build without optimization on.
It takes a few hours if compiler optimization is turned on, which is painful.

I wonder,
how we can do the same thing as we do in Java here.
Is there an easy way to compile and upload the binary of the packages (libraries) to
an artifact server and use the prebuilt binaries at the build time?
I know that since Haskell generates machine code (rather than byte code in Java)
there might be compatibility issues,
but we can probably have different binaries for different architectures/OSs stored on the
artifact server.

答:
You might consider using Nix, which is a general-purpose, cross-platform package manager with decent support for Haskell.

Nix has a custom programming language for defining packages (which just so happens to be pure, functional and lazy). Defining new packages and extending existing ones is pretty easy (eg. to alter dependencies, get the source from a different git repo, etc.).

Packages are identified by hashes, which include dependencies. Hence multiple versions, or the same version with different dependencies, can live side by side without conflict. Nix can look up the desired hash on a "binary cache" server, to see if that particular package with those particular dependencies has already been built; if so, it'll download the build product rather than compiling.

Currently, the nixpkgs repository includes most/all of Hackage, several GHC versions (7.10.1, 7.8.4 and some JS backends) and a cabal2nix utility which does a pretty good job of generating Nix packages from .cabal files. There's also the Nix-based "hydra" CI server, which you could use to trigger builds based on SCM commits.


问:
Why use a unique hashkey for form submissions?
I have multiple forms and use AJAX to submit them. I asked my boss if he needed any specific format for the form ID and he told me to generate a unique hash and keep it in session; check it whenever the form comes back to make sure it's a valid form submission and not someone just hitting an endpoint.

What does that mean and why is it useful? How does it help me security wise?

I have read a couple of articles like The 3 things you should know about hashCode() but I'm still not sure...

答: The technique your boss has told you to use is one of the common ways of preventing cross site request forgery. I think you're probably getting confused by the multiple meanings of "hash" which in this case probably refers to a secure hash (eg SHA256) rather than a hash that you might use for a hash table.</p>


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
No, not at all. If you don't need the performance and there is a library you can use the other language then don't bother with C/C++. I only do it nowadays when I target embedded systems that can't (easily?) run languages. Sometimes I use C because I am writing a plugin but really no.

However, I wouldn't use Python, Perl, etc. to avoid using C. My preference is actually C#, because I like a good library (which is a strength of .NET), and I like statically typed languages. Boo is a good alternative. But really Haskell, OCaml, D, ML and such are all fine.


问:
Preemptive scheduling with "do not disturb"
In this answer about threading it is said:

In preemptive scheduling, a thread can be interrupted at any time, either by a timer interrupt or any other interrupt or during a system call. The part of the system that performs the context switch must save all the registers and other settings, and restore the context of the new thread.

It's harder to write programs for systems with preemptive scheduling: they're prone to race conditions. On the other hand, these systems are more robust in that even if a thread is buggy and goes into an infinite loop, that doesn't prevent other threads from running.

Is it possible to create a preemptive scheduler in which threads can hang a "do not disturb" sign on their door. If the sign is there, the scheduler doesn't perform a context switch. It would be a bit like a prehistoric version of Java's synchronized keyword.

I imagine this could be easier to program for because you can mark critical sections and always have them executed directly after each other. For example, if you're changing multiple microcontroller's configuration registers, it may be that halfway through this change the settings are not as you ever want them to be for a long time. You don't want a context switch to occur right in that moment.

Has something like this been done?

As for the implementation, it seems that setting and clearing a bit when entering or leaving the critical section would be enough. The scheduler checks this bit before performing a context switch, and doesn't act if it's 0. Would that indeed be enough?

A more advanced scheduler could keep track of how long a thread is in the critical section. If that's "too long", he may still perform the context switch, possibly notifying the thread first. This "too long" may be defined by the scheduler or the thread - I see advantages for both approaches.

答:
There's a lot of variety of schedulers because there's a lot of variety of needs, from real-time systems where the whole system is written in one go and the precise order and timing of scheduling is known when the device is built, to high-end systems where all threading is preemptive except for some very short sections deep inside the kernel.

It certainly is possible for a thread to declare that it is in a critical section and it doesn't want to be interrupted. By definition, this isn't a fully preemptive scheduler anymore, but some kind of hybrid mode which is based on preemption but where preemption can be disabled.

In fact, virtually every system contains at least some low-level code that must not be preempted because it's doing something to the hardware, such as the example you give of modifying multiple registers that need to be done in one go. This isn't limited to microcontrollers. Interrupt handlers and context switching code almost always contain a critical section, even if it's just a few instructions. At the bare metal level, a critical section simply means disabling interrupts. Interrupt handlers start with interrupts disabled, or, if not, there is at least some mechanism that prevents the same interrupt from interrupting a previous instance of itself.

Operating systems designed for single-core hardware may use critical sections to implement message passing mechanisms, because passing a message usually involves modifying multiple data structures (associated with the sender and the recipient) in a consistent way. On multi-core systems, this can't be done because the sender and receiver may be running on different cores.

Going higher level, there are operating systems where threads can get a guarantee that they won't be interrupted, and the API offers system calls like start_critical_section/end_critical_section. This can only be done if the thread is trusted not to go into an infinite loop or otherwise hog the CPU. Such a critical section might in fact be interrupted by interrupts, but the scheduler returns to the same thread after the interrupt.

Critical sections that are interruptible after a timeout are possible. I don't know how common they are; they would make sense in “soft real-time” systems such as multimedia processing where threads need to process audio or video frames in a timely manner, and dropping a frame is frowned upon but not ruled out.

Informing a thread that it's been preempted is difficult to do usefully. Setting a bit in a well-known location is easy. The problem is how the thread can react. It's indicated that it didn't want to be interrupted, so it presumably isn't going to check that bit. A possible design is for the thread to have checkpoints; for example, in an outer loop during frame processing, a media processing thread can check if its current frame has been dropped. Another possible design is to kill the thread (but possibly leave its stack behind for analysis) and run another thread as an exception handler. Yet another design is to raise an exception inside the thread; this requires tight coupling between the scheduling mechanism and the thread's execution environment.

There are other ways to constrain the ways in which threads can be preempted at a high level. A simple one is priorities: a scheduler will only preempt a thread to run a higher-priority thread. If thread A doesn't want to be interrupted by thread B, A declares a higher priority than B.

In a multi-application system where each application can have multiple threads, it can make sense to have a hybrid scheduler that is preemptive between applications, but cooperative between threads of the same application. This way an application thread that never yields will only prevent only threads in the same application from running. Applications can use shared memory with context switches only at predictable times for its inner workings, while inter-application communication is done via OS messaging primitives only.

OwnerDisplayName: Gilles


答: One example of a system that used to work this way is the Linux kernel, which used to have a pair of functions called cli() and sti(). On single processor systems, these simply disabled and reenabled interrupts, thus preventing the current thread being stopped (on multiprocessor machines they were a little more complex). They were deprecated early in development of the kernel and completely removed during the 2.5.x development versions of the kernel.</p>

Title: Preemptive scheduling with "do not disturb"

Body:
In this answer about threading it is said:

In preemptive scheduling, a thread can be interrupted at any time, either by a timer interrupt or any other interrupt or during a system call. The part of the system that performs the context switch must save all the registers and other settings, and restore the context of the new thread.

It's harder to write programs for systems with preemptive scheduling: they're prone to race conditions. On the other hand, these systems are more robust in that even if a thread is buggy and goes into an infinite loop, that doesn't prevent other threads from running.

Is it possible to create a preemptive scheduler in which threads can hang a "do not disturb" sign on their door. If the sign is there, the scheduler doesn't perform a context switch. It would be a bit like a prehistoric version of Java's synchronized keyword.

I imagine this could be easier to program for because you can mark critical sections and always have them executed directly after each other. For example, if you're changing multiple microcontroller's configuration registers, it may be that halfway through this change the settings are not as you ever want them to be for a long time. You don't want a context switch to occur right in that moment.

Has something like this been done?

As for the implementation, it seems that setting and clearing a bit when entering or leaving the critical section would be enough. The scheduler checks this bit before performing a context switch, and doesn't act if it's 0. Would that indeed be enough?

A more advanced scheduler could keep track of how long a thread is in the critical section. If that's "too long", he may still perform the context switch, possibly notifying the thread first. This "too long" may be defined by the scheduler or the thread - I see advantages for both approaches.


问:
Common mistakes with javascript arithmetic
I've ran into several oddities using javascripts floating point arithmetic, but I can never recall them off the top of my head!

What are some common mistakes when using JavaScript to do math?

答:
A common mistake (although with strings & integers, not floats) is forgetting that JavaScript doesn't have strong typing. So you can run into situations where:

```<code>var myVar = 7;       // 7
myVar += 5;          // 12

var myVar = "7";     // 7
myVar += 5;          // 75

var myVar = "cat";   // cat
myVar += 5;          // cat5
</code>```

All of these are perfectly valid statements in JavaScript.

But it gets weirder, because while "7" and "cat" are both strings, not all strings are treated the same:

```<code>var myVar = 77;
parseInt(myVar);     // 77

var myVar = "77";
parseInt(myVar);     // 77

var myVar = "cat";
parseInt(myVar);     // NaN

var myVar = "77cat";
parseInt(myVar);     // 77
</code>```

Not to mention that (as @Tatu wrote):

```<code>var myVar = "077";
parseInt(myVar);     // 63
</code>```

Body:
A common mistake (although with strings & integers, not floats) is forgetting that JavaScript doesn't have strong typing. So you can run into situations where:

var myVar = 7;       // 7
myVar += 5;          // 12

var myVar = "7";     // 7
myVar += 5;          // 75

var myVar = "cat";   // cat
myVar += 5;          // cat5

All of these are perfectly valid statements in JavaScript.

But it gets weirder, because while "7" and "cat" are both strings, not all strings are treated the same:

var myVar = 77;
parseInt(myVar);     // 77

var myVar = "77";
parseInt(myVar);     // 77

var myVar = "cat";
parseInt(myVar);     // NaN

var myVar = "77cat";
parseInt(myVar);     // 77

Not to mention that (as @Tatu wrote):

var myVar = "077";
parseInt(myVar);     // 63


问:
Is it a bad practice to compile TypeScript NodeJS app to a single JS file?
I'm currently exploring TypeScript and I was wondering why not compile the whole app to a single JS file instead of compiling every .ts file to it's corresponding .js.

Example for such an app is TypeDoc, which basically compiles to a single bin/typedoc.js file.

The common concept is to compile each .ts file in a .js file with --module commonjs as an argument to the typescript compiler.

Is there something that I need to worry about if I build a scalable ( big ) web application which compiles to a single file ?

答:
There are certain benefits that you can gleen from having one combined javascript file over many smaller files. It does come with a few drawbacks, though.

Pros:

Better maintenance in your markup - Maintaining .js file references is easier. Just put one/few references across your main wrapper designs, and you don't have to worry about adding anything new later.

Caching advantages - If you have your HTTP headers set up properly when serving up your JS files, you will have browsers caching your javascript automatically. This means that all of your client side logic will download once initially, and be carried over to other pages 'for free'.

Cutting out round trips - Every javascript file you load on it's own is another round trip to the server, so you are cutting down potential round trips if you need multiple files for a particular page.

Cons:

First/All page loads are longer - All of your logic had to come in at once, so it will be a larger file than a fraction of whatever you could have had previously. If you have a caching strategy, you only take this hit once on the first page load.

Issues with cached JS - If you are caching, which you likely are, if that file changes in an important way that needs to be reflected immediately to the updated application, you may run into issues. Make sure to use cache buster query strings in this case. Consider reading the 'Time created' date from the file system to have this process be automatic.

Be careful with certain JS concepts - You probably don't want to put any logic in your library that would actually run on loading. Think JQuery's 'Document Ready' functionality. That will effectively run on every page, and you likely don't want that in most scenarios. I personally use an MVC like pattern where I have a controller 'module' per page that I have an Init() function for pages that need special handling on page load. Just call it from your page in a small script tag, and you're done.

I haven't noticed a particular difficulty in debugging that you seem to be concerned with. My advice would be to create a minified and unminified version of your combined .js file. Then you may want to have your application cleverly tell weather you are in a development environment or not, and add the '.min.js' or just '.js' to the end of your file. There will be few times when you will need to debug something specifically in production, and this should cover 95% of your debugging cases or more.


问:
Is there any practical way for a linked node structure to be immutable?
I decided to write a singly-linked list, and had the plan going in to make the internal linked node structure immutable.

I ran into a snag though. Say I have the following linked nodes (from previous add operations):

```<code>1 -> 2 -> 3 -> 4
</code>```

and say I want to append a 5.

To do this, since node 4 is immutable, I need to create a new copy of 4, but replace its next field with a new node containing a 5. The problem is now, 3 is referencing the old 4; the one without the appended 5. Now I need to copy 3, and replace its next field to reference the 4 copy, but now 2 is referencing the old 3...

Or in other words, to do an append, the entire list seems to need to be copied.

My questions:

Is my thinking correct? Is there any way to do an append without copying the entire structure?

Apparently "Effective Java" contains the reccomendation:

Classes should be immutable unless there's a very good reason to make them mutable...

Is this a good case for mutability?

I don't think this is a duplicate of the suggested answer since I'm not talking about the list itself; that obviously has to be mutable to conform to the interface (without doing something like keeping the new list internally and retrieving it via a getter. On second thought though, even that would require some mutation; it would just be kept to a minimum). I'm talking about whether or not the internals of the list must be immutable.

答:
You must watch this great video from 2015 React conf by Immutable.js's creator Lee Byron. It will give you pointers and structures to understand how to implement an efficient immutable list which do not duplicate content.
The basics ideas are :
- as long as two lists use identical nodes (same value, same next node), the same node is used
- when the lists start differing, a structure is created at the node of divergence, which holds pointers to the next particular node of each list

This image from a react tutorial may be clearer than my broken English :


问:
How imperative is the need of specifications being written down in case of a new project?
I have a new project to deal with. I'm the only one to deal with it currently (a kind of a personal project). It's likely that in the future there will be more contributors to it.

Taking in account the best practices when it comes to talk about project management, how much is there a need for the project specifications to be written down? Is it imperative, or is it something that is left to the choice of development team?

N.B. By specifications I mean the set of guidelines that a developer uses in order to get implemented the targeted object of project involved.

Note: I'm not asking about subjective choices (although such examples are well appreciated). I'm asking about some theoretical aspects, if there are any, regarding this issue.

答:
As with all things software, It depends on the complexity and context of a given project.  The more tied you are to the risks of the project's success the better served you are by clear declarations of need/intent and deliverable results.

Are you an employee of the people/company that want's the project done?  If so, having an iterative approach without a clear specification is acceptable.

Are you working on a fixed price bid?  Having a clear specification is VERY important here.

Everything else is in between.  In your specific case it may be best to at least lay out what you want to accomplish.  If there's a UI pencil sketch it out.  If there are interactions, like for a game, define the basic rules.  Think about and maybe prototype some of your data models.  As a single developer you can go a long way without a formal design, but when you start bringing people in, having a clear base architecture and some design guidelines are a good idea.  As is reviewing contributed code.


问:
Should I be taking these as arguments or define them in a sub class?
So I am making a mario clone in pygame and I have a base class Character and two sub classes, Mario and Luigi. The methods that the Character class defines require a significant amount of attributes from a sub class (around 20) to be defined. For example, the initial y velocity of the Character instance must be defined. Should I be passing all these attributes to the Character class as parameters or should I just have them defined in the sub class (ie. Mario or Luigi)? Or what about a mix? My thinking is that since these properties are all required for a Character instance to have, that they should all be passed as parameters in the constructor of the class.

Here's some pseudo-code to demonstrate what I mean:

```<code>class Mario(Character):

    def __init__(self):
        Character.__init__(self, 1, 2, 3, 4, 5, ... 20)

class Character:

    def __init__(self, var1, var2, var3, var4, var5, ... var20):
        pass
</code>```

OR

```<code>class Mario(Character):

    def __init__(self):
        var1 = 1
        var2 = 2
        var3 = 3
        var4 = 4
        ...
        var20 = 20
        Character.__init__(self)

class Character:

    def __init__(self):
        pass
</code>```

答:
I would suggest defining your common properties in the base class and simply assign them as such in the constructor for your child class.  I would also put sanity checks ensuring that your necessary properties are set before you can use a given character on your field/map.

You shouldn't need to pass all of the properties to the constructor as this will reduce clarity in your actual code...  Seeing a constructor setting properties defined in the base is probably more clear, especially if they don't all need to be set, or if there are additional properties.


问:
How do references work in R?
I'm finding R confusing because it has such a different notion of reference than I am used to in languages like C, Java, Javascript... Ruby, Python, C++, well, pretty much any language I have ever programmed in ever.

So one thing I've noticed is variable names are not irrelevant when passing them to something else. The reference can be part of the data. e.g. per this tutorial

```<code>a <- factor(c("A","A","B","A","B","B","C","A","C"))
results <- table(a)
</code>```

Leads to $a showing up as an attribute as $dimnames$a.

We've also witnessed that calling a function like a <- foo(alpha=1, beta=2) can create attributes in a of names alpha and beta, or it can assign or otherwise compute on 1 and 2 to properties already existing. (Not that there's a computer science distinction here - it just doesn't really happen in something like Javascript, unless you want to emulate it by passing in the object and use key=value there.)

Functions like names(...) return lvalues that will affect the input of them.

And the one that most got me is this.

```<code>x <- c(3, 5, 1, 10, 12, 6)
y = x[x <= 5]
x[y] <- 0
</code>```

is different from

```<code>x <- c(3, 5, 1, 10, 12, 6)
x[x <= 5] <- 0
</code>```

Color me confused. Is there a consistent theory for what's going on here?

答:
I'm not certain I can answer why things were created the way they were (and are), but I can provide some insight as to when they would be useful. But up front, R is a language originally intended for statistical analysis, so "models" are commonly in the lime-light. (This is by far not a current requirement, and there are many other reasons one would lean towards or against R.)

Creation of Result's Attributes

When creating a "model", whether it be regressing, PCA, factor analysis, etc, there are often times when you want to expand on the model results through a programmatic method. Perhaps this means to draw a regression/smooth line, print a summary, add or remove factors from a regression, etc. However, if you look at the return value from (say) a regression, it may not contain enough information to replicate the conditions necessary.

For example, consider a simple regression using the built-in dataset, mtcars:

```<code>lm1 <- lm(mpg ~ cyl, data=mtcars)
</code>```

The output itself is rather terse (though can be more verbose)

```<code>lm1
## Call:
## lm(formula = mpg ~ cyl, data = mtcars)
## Coefficients:
## (Intercept)          cyl
##      37.885       -2.876
</code>```

Let's say we want to provide a more detailed summary from this. We can look at:

```<code>summary(lm1)
## Call:
## lm(formula = mpg ~ cyl, data = mtcars)
## Residuals:
##     Min      1Q  Median      3Q     Max
## -4.9814 -2.1185  0.2217  1.0717  7.5186
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)  37.8846     2.0738   18.27  < 2e-16 ***
## cyl          -2.8758     0.3224   -8.92 6.11e-10 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## Residual standard error: 3.206 on 30 degrees of freedom
## Multiple R-squared:  0.7262, Adjusted R-squared:  0.7171
## F-statistic: 79.56 on 1 and 30 DF,  p-value: 6.113e-10
</code>```

where it should be obvious that the majority of the information in the "summary" can not be derived from the original "output" of the linear regression. One could argue that this should be the default output from lm; I can't argue, but ...

If you want to look at other statistics-related analyses from this -- including Q-Q plots, scale-location plots, or residuals, the above output most certainly doesn't give you sufficient information, but simply typing plot(lm1) will give you four (with others available) often helpful plots:

(Simple, contrived, perhaps.) The use of out-of-the-way attributes make it possible to recreate the necessary conditions that built the linear model sufficiently for other related functions to do their jobs.

Could you use different functions to instead generate information to support this output versus the simpler output above? Sure, but it is certainly convenient.

Often, these attributes are strictly required for data manipulation. For instance, in R, the names of columns and/or rows are attributes, which are added either explicitly at variable creation, implicitly during model manipulation, or explicitly adjusted after-the-fact. Indexing and subsetting can be done by number or by name (if present). In python/pandas, these attributes are just as much part of the data.

Bottom line, though, is that implicit assignment of attributes based on passed arguments happens specifically with only some functions; I believe the majority of functions do not do this, though I haven't fished through them all to know for certain.

Variable Names' Relevance

The reason that a is in the dimnames is because you provided the variable named a to the function table, not because it was originally assigned to it. You get the helpful reference to the variable name when applicable to provide context and reference:

```<code>a <- factor(c("A","A","B","A","B","B","C","A","C"))
table(a)
## a
## A B C
## 4 3 2

table(factor(c("A","A","B","A","B","B","C","A","C")))
##
## A B C
## 4 3 2
</code>```

Occasionally this is just icing, to be honest, but often it can really help find perspective on what did what. For instance, in many languages when you call a function (whether pass-by-value or pass-by-reference), when inside the called function you may not be able to provide perspective in error messages, context, or change the process based on what was provided.

(Note: you can argue all day long that "change the process based on what was provided", aka polymorphism, can be problematic, and "explicit" is often better than "implicit". I'm not fighting that war, but the capability is there and used often.)

The creation of a list is a clear example: it takes its arguments and creates named entries. In Python, for example, a named list requires key/value pairs for its dictionaries, and the keys are provided as literal strings, ala { "key":2.0, "key2": 3.1415 }. In R, a similarly-intended list would be built as list(key=2.0, key2=3.1415). In this case, it is taking the names of the arguments being provided and including them for relevance in the output, so that you know which element is which. (This is a more direct example, but the argument names are being inserted into the attributes of the returned value.)

Take this one step further (and combine with my previous point about attributes), and you'll realize that the process of assigning direct return values (such as dictionary keys) or indirect attributes (such as what can be found with attributes(lm1)) is effectively for the same purpose: to provide relevance, context, and recreatability (at times) in the returned value.

Note that often, attributes survive variable mutation without affecting the mutation itself. For instance, a matrix (mtx <- matrix(1:6, nrow=2)) has as attributes its dimensions, column names, and row names. If I do simple math, such as mtx + 2, the math operation is done strictly on the data, and the attributes are unaffected. Operations that will have an affect on the attributes, such as taking the transpose, will adjust them accordingly.

names() and LHS Functions

Some functions operate solely on the right-hand side (RHS) of the equals (or <-) assignment. This is effectively the default for most programming languages out there. Some functions, however, allow for being on the left-hand side of the assignment operator. Think of the indexing function, [, which is really just a function. It indexes into a vector/array and either sets or gets the specific index. The fact that many languages treat this like an atomic "thing" in the language versus a "function" is one thing that sets R apart. (If you type in `[` on the R command prompt, it will tell you that it is merely a function ... a primitive function, perhaps, but other LHS-based functions are used, including names, colnames, and attr.)

Vector Indexing

Lastly, as a couple of comments have started discussing, your indexing has a little (commonly-hit) flaw in it:

```<code>x <- c(3, 5, 1, 10, 12, 6)
y = x[x <= 5]
y
## [1] 3 5 1
x[y]
## [1]  1 12  3
</code>```

Notice that y is contains three integers: 3, 5, 1. The last command x[y] is saying to retrive the third, fifth, and first elements of the vector named x. So, you created a vector of index positions with which you would peer into x. If you typed in x[c(3,5,1)], would you not expect to get the response from this that you did?

Imagine, instead, that you did this instead:

```<code>x <- c(3, 5, 1, 10, 12, 6)
y = x[x <= 5] + 10
y
## [1] 13 15 11
x[y]
## [1] NA NA NA
</code>```

Perhaps this provides some clarity as to why y in this case is not containing indices into x, but instead values derived (and adjusted) from x.

Your second example is a great example of subsetting vectors (and lists and data.frames and ...).

```<code>x <- c(3, 5, 1, 10, 12, 6)
x <= 5
## [1]  TRUE  TRUE  TRUE FALSE FALSE FALSE
x[x <= 5] <- 0
x
## [1]  0  0  0 10 12  6
</code>```

Notice that x <= 5 is returning a logical vector of the same length as the original vector. Subsetting in R permits logical indices, so the logical vector is essentially saying "I want the first", "I want the second", ..., "I don't want the fourth", "I don't want the fifth", etc. If you run x[x <= 5] without the assignment, it would give you the first, second, and third elements, in order. The fact that it allows you to replace the three positions with a single value (recycled) is a convenience; other languages require the assigned value to have the same dimensionality (R occasionally requires this as well).

Bottom Line

R is certainly different in many aspects from other programming languages. It is loosely-typed, dynamic in so many ways to look, pass-by-value (most of the time), heavily influenced by scheme/lisp (ergo death-by-parentheses), and it appears to be heavily influenced to streamline statistical methods. That's not to say that other languages don't do it well; quite the opposite, many do it very well.

Are there things that, were we designing a new statistics-centric language, might be different? Certainly. Consider Julia; certainly not statistics-only, arguably faster in many ways. The bottom line is that it has nuances that are both differently-motivated as well as more-recently-defined, arguably with the lessons learned from so many other languages, including R.

Title: How do references work in R?

Body:
I'm not certain I can answer why things were created the way they were (and are), but I can provide some insight as to when they would be useful. But up front, R is a language originally intended for statistical analysis, so "models" are commonly in the lime-light. (This is by far not a current requirement, and there are many other reasons one would lean towards or against R.)

Creation of Result's Attributes

When creating a "model", whether it be regressing, PCA, factor analysis, etc, there are often times when you want to expand on the model results through a programmatic method. Perhaps this means to draw a regression/smooth line, print a summary, add or remove factors from a regression, etc. However, if you look at the return value from (say) a regression, it may not contain enough information to replicate the conditions necessary.

For example, consider a simple regression using the built-in dataset, mtcars:

lm1 <- lm(mpg ~ cyl, data=mtcars)

The output itself is rather terse (though can be more verbose)

lm1
## Call:
## lm(formula = mpg ~ cyl, data = mtcars)
## Coefficients:
## (Intercept)          cyl
##      37.885       -2.876

Let's say we want to provide a more detailed summary from this. We can look at:

summary(lm1)
## Call:
## lm(formula = mpg ~ cyl, data = mtcars)
## Residuals:
##     Min      1Q  Median      3Q     Max
## -4.9814 -2.1185  0.2217  1.0717  7.5186
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)  37.8846     2.0738   18.27  < 2e-16 ***
## cyl          -2.8758     0.3224   -8.92 6.11e-10 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## Residual standard error: 3.206 on 30 degrees of freedom
## Multiple R-squared:  0.7262, Adjusted R-squared:  0.7171
## F-statistic: 79.56 on 1 and 30 DF,  p-value: 6.113e-10

where it should be obvious that the majority of the information in the "summary" can not be derived from the original "output" of the linear regression. One could argue that this should be the default output from lm; I can't argue, but ...

If you want to look at other statistics-related analyses from this -- including Q-Q plots, scale-location plots, or residuals, the above output most certainly doesn't give you sufficient information, but simply typing plot(lm1) will give you four (with others available) often helpful plots:

(Simple, contrived, perhaps.) The use of out-of-the-way attributes make it possible to recreate the necessary conditions that built the linear model sufficiently for other related functions to do their jobs.

Could you use different functions to instead generate information to support this output versus the simpler output above? Sure, but it is certainly convenient.

Often, these attributes are strictly required for data manipulation. For instance, in R, the names of columns and/or rows are attributes, which are added either explicitly at variable creation, implicitly during model manipulation, or explicitly adjusted after-the-fact. Indexing and subsetting can be done by number or by name (if present). In python/pandas, these attributes are just as much part of the data.

Bottom line, though, is that implicit assignment of attributes based on passed arguments happens specifically with only some functions; I believe the majority of functions do not do this, though I haven't fished through them all to know for certain.

Variable Names' Relevance

The reason that a is in the dimnames is because you provided the variable named a to the function table, not because it was originally assigned to it. You get the helpful reference to the variable name when applicable to provide context and reference:

a <- factor(c("A","A","B","A","B","B","C","A","C"))
table(a)
## a
## A B C
## 4 3 2

table(factor(c("A","A","B","A","B","B","C","A","C")))
##
## A B C
## 4 3 2

Occasionally this is just icing, to be honest, but often it can really help find perspective on what did what. For instance, in many languages when you call a function (whether pass-by-value or pass-by-reference), when inside the called function you may not be able to provide perspective in error messages, context, or change the process based on what was provided.

(Note: you can argue all day long that "change the process based on what was provided", aka polymorphism, can be problematic, and "explicit" is often better than "implicit". I'm not fighting that war, but the capability is there and used often.)

The creation of a list is a clear example: it takes its arguments and creates named entries. In Python, for example, a named list requires key/value pairs for its dictionaries, and the keys are provided as literal strings, ala { "key":2.0, "key2": 3.1415 }. In R, a similarly-intended list would be built as list(key=2.0, key2=3.1415). In this case, it is taking the names of the arguments being provided and including them for relevance in the output, so that you know which element is which. (This is a more direct example, but the argument names are being inserted into the attributes of the returned value.)

Take this one step further (and combine with my previous point about attributes), and you'll realize that the process of assigning direct return values (such as dictionary keys) or indirect attributes (such as what can be found with attributes(lm1)) is effectively for the same purpose: to provide relevance, context, and recreatability (at times) in the returned value.

Note that often, attributes survive variable mutation without affecting the mutation itself. For instance, a matrix (mtx <- matrix(1:6, nrow=2)) has as attributes its dimensions, column names, and row names. If I do simple math, such as mtx + 2, the math operation is done strictly on the data, and the attributes are unaffected. Operations that will have an affect on the attributes, such as taking the transpose, will adjust them accordingly.

names() and LHS Functions

Some functions operate solely on the right-hand side (RHS) of the equals (or <-) assignment. This is effectively the default for most programming languages out there. Some functions, however, allow for being on the left-hand side of the assignment operator. Think of the indexing function, [, which is really just a function. It indexes into a vector/array and either sets or gets the specific index. The fact that many languages treat this like an atomic "thing" in the language versus a "function" is one thing that sets R apart. (If you type in `[` on the R command prompt, it will tell you that it is merely a function ... a primitive function, perhaps, but other LHS-based functions are used, including names, colnames, and attr.)

Vector Indexing

Lastly, as a couple of comments have started discussing, your indexing has a little (commonly-hit) flaw in it:

x <- c(3, 5, 1, 10, 12, 6)
y = x[x <= 5]
y
## [1] 3 5 1
x[y]
## [1]  1 12  3

Notice that y is contains three integers: 3, 5, 1. The last command x[y] is saying to retrive the third, fifth, and first elements of the vector named x. So, you created a vector of index positions with which you would peer into x. If you typed in x[c(3,5,1)], would you not expect to get the response from this that you did?

Imagine, instead, that you did this instead:

x <- c(3, 5, 1, 10, 12, 6)
y = x[x <= 5] + 10
y
## [1] 13 15 11
x[y]
## [1] NA NA NA

Perhaps this provides some clarity as to why y in this case is not containing indices into x, but instead values derived (and adjusted) from x.

Your second example is a great example of subsetting vectors (and lists and data.frames and ...).

x <- c(3, 5, 1, 10, 12, 6)
x <= 5
## [1]  TRUE  TRUE  TRUE FALSE FALSE FALSE
x[x <= 5] <- 0
x
## [1]  0  0  0 10 12  6

Notice that x <= 5 is returning a logical vector of the same length as the original vector. Subsetting in R permits logical indices, so the logical vector is essentially saying "I want the first", "I want the second", ..., "I don't want the fourth", "I don't want the fifth", etc. If you run x[x <= 5] without the assignment, it would give you the first, second, and third elements, in order. The fact that it allows you to replace the three positions with a single value (recycled) is a convenience; other languages require the assigned value to have the same dimensionality (R occasionally requires this as well).

Bottom Line

R is certainly different in many aspects from other programming languages. It is loosely-typed, dynamic in so many ways to look, pass-by-value (most of the time), heavily influenced by scheme/lisp (ergo death-by-parentheses), and it appears to be heavily influenced to streamline statistical methods. That's not to say that other languages don't do it well; quite the opposite, many do it very well.

Are there things that, were we designing a new statistics-centric language, might be different? Certainly. Consider Julia; certainly not statistics-only, arguably faster in many ways. The bottom line is that it has nuances that are both differently-motivated as well as more-recently-defined, arguably with the lessons learned from so many other languages, including R.


问:
is coding important?
Is coding important to be good at computer science? Should one implement the algorithm to know it well ?

I remember one cs professor's idiom that "I never code"

答: Your professor may be right a bit, in that to be a professor you don't need to code, but knows much about the theory. But that will not work outside the university perimeters. </p>

Title: is coding important?


问:
Why is there no WSDL type support for Web Api?
So I am just getting started with .Net WebApi and one thing that I am noticing straight away is that there is no Contract defining how the API looks and should be consumed (Request/Responses from each Action), this is usually in the form of a WSDL for WCF/Soap.

It seems to me like this is something that would be very valuable and make life a lot easier for consumers of your API.

Is there a reason there isn't one? Is there a programming paradigm or principle that I am unaware of? Is there a way I could create one?

答:
SOAP/WS-* and RESTful APIs are not the same.  If you want to build SOAP/WS-* WSDL supporting APIs the tool of choice in the Microsoft stack is WCF, mounted with an HTTP binding option (there are XML and JSON binding options, XML being the WSDL supporting option).

In practice, consuming a WSDL from a different implementation language or platform has been problematic.  WS-* security layers over the top even more so.

My own experience has mostly been with .Net, Node, Java and PHP in this regard, and I can say that when you have platforms that don't have to define the details of a child type, or will use "Object" as the definition, it gets problematic to say the least.  Beyond this, for the most part nobody really understands all of SOAP/WS-* relying heavily on tooling to make it work.  This tooling has a lot of overhead, and different systems operate differently.

These are some of the reasons people looked to try simpler implementations.  REST services (ala Web API) offer endpoints around objects/state.  The idea being it's easier to define a set of simpler object structures represented in JSON format, and the endpoints to use against these structures than it is to try to use WSDL from an alien environment that doesn't work, then try to dig in and work around the problem.

Ironically, this is one of the areas I've used Node in a lot as a translation service, simply because it was flexible enough to accept dirty implementations as a client, and I could write simple clients against my adapted payload that worked better.  EX: C# gets JSON text, that I use JSON.Net to convert to an object representation that I defined actually worked when I couldn't use a WSDL import.

In practice this happens a lot.


问:
Using 'reduce' vs 'for' loop for returning boolean
I was wondering what people think about using a reduce function vs loop for returning true if a condition exists.

Example:

```<code>var a = [1, 5, 7, 4, 2, 5, 3];

var greaterThan5 = a.reduce(function(prev, val) {
    return (prev || val > 5);
}, false);

vs

var greaterThan5 = false;
for(var i = 0; i < a.length; i++) {
    if(a[i] > 5) {
        greaterThan5 = true;
        break;
    }
}

vs

var i = 0;
var greaterThan5 = false;
while(!greaterThan5 && i < a.length) {
    greaterThan5 = (a[i] > 5);
    i++;
}
</code>```

The for loop and while loop will exit when the condition is true, but I think the reduce syntax is easier to read and gives less room for run-time errors.

答:
For most functional languages, neither.

There is usually a reducing function which short circuts as you want it to.

In F# this is List.exists so you example would be

```<code>List.exists (fun x -> x > 5) a
</code>```

In Haskell (with partial application of > to make a point free solution)

```<code>any (> 5) a
</code>```

Body:
For most functional languages, neither.

There is usually a reducing function which short circuts as you want it to.

In F# this is List.exists so you example would be

List.exists (fun x -> x > 5) a

In Haskell (with partial application of > to make a point free solution)

any (> 5) a


答:
First of all, why not use Array.prototype.some(), which seems to perfectly match what you're actually trying to do.

The some() method tests whether some element in the array passes the test implemented by the provided function.

Of course, that doesn't really answer your question: whether to use the for loop, or the call to Array.protoype.reduce()? Let me also try to answer that. The question is mostly regarding weighing performance against clarity of code.

For performance: measure, not just using random arrays, but using arrays that make sense in your project. No need in selecting a method that works fast on 1,000,000 element arrays, when all you need to process are arrays of up to 10 elements.

More importantly, only worry about performance when performance is an issue.

With respect to clarity. I actually think the explicit for-loop is more clear than the Array.prototype.reduce(). But, what matters most is, what the people on your team will find the most clear. If one of your team finds an explicit for-loop more clear, it's probably better to use that, if only because it uses a less advanced set of features.

Title: Using 'reduce' vs 'for' loop for returning boolean

Body:
I was wondering what people think about using a reduce function vs loop for returning true if a condition exists.

Example:

```<code>var a = [1, 5, 7, 4, 2, 5, 3];

var greaterThan5 = a.reduce(function(prev, val) {
    return (prev || val > 5);
}, false);

vs

var greaterThan5 = false;
for(var i = 0; i < a.length; i++) {
    if(a[i] > 5) {
        greaterThan5 = true;
        break;
    }
}

vs

var i = 0;
var greaterThan5 = false;
while(!greaterThan5 && i < a.length) {
    greaterThan5 = (a[i] > 5);
    i++;
}
</code>```

The for loop and while loop will exit when the condition is true, but I think the reduce syntax is easier to read and gives less room for run-time errors.