答:
I understand why you want to do this.  The way you are doing it is not what I would do.

Rather than collect a list of exception objects, I would process those objects as they happen.  By collecting a list to process later you run the risk of losing them before they get processed.  At that point, without intending to do so, your program has swallowed the exceptions.  The user will know nothing bad has happened.  When they find out, the hard way, their experience with your program will be a poor one.

Whatever you want to do with the exceptions, do it as soon as they happen.  Continue the loop if you like but process/log those exceptions regardless.

Title: Handling exceptions in a loop without breaking the loop (try to process all members)

Body:
Scenario:

I have a loop that iterates over an Array of COM objects and does some work using them.

My fear, working with COM objects, is that some exception will creep up (possibly on another user's environment) and cause the loop to break mid-way through processing these objects.

So, let's say (hypothetically) an exception occurs on file 32 of 173.

I see three options:

Show the exception, inform the user that only 32 files were
processed, and we then have to manually do the work on the remaining 141 files.

Undo all the work done on the first 32 files, inform the user the
request couldn't be completed and show the exception. This is less
than ideal because by the time we are at this procedure, a lot of
up-front work has been done (creating files, incrementing serial
numbers, etc.) which would be cumbersome and difficult to undo.  In the end, we end up with all 172 files needing manual work.

Catch the exception, store it in a List, continue to try to
process the rest of the files, then after trying to process all files,  inform the user of any exceptions that occurred and any files which couldn't be processed. Best case we only have one file to manually do work on, and worst
case we are left with 141 files - same as the first option.

Event horizon:

I'm new to programming. In fact I just wrote (am writing) my first add-in which I posted up on SE::Code Review.

Now, I'm of the mindset that option three makes the most sense - let's at least give hope a chance and see what happens with the rest of them, no?

So here's my implementation (well simplified, but this is the pattern):

```<code>Sub Main()
    Dim Exceptions as New List(of Exception)
    Try
        TryThatFunkyCOMthing (Exceptions)

        If Exceptions.Count>0 Then
            For Each ex As Exception in Exceptions
                MessageBox.Show(ex.ToString)
            Next
        End If

    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try
End Sub

Private Sub TryThatFunkyCOMthing (ByRef ExceptionBuffer as List(of Exception))
    For each COMthingy in COMthings
        Try
           COMthingy.DoSomething
        Catch ex As SpecificException
            COMthingy.WeAreBlewedUp
        Catch ex As Exception
            ExceptionBuffer.Add(ex)
        End Try
    Next
End Sub
</code>```

One of the reviewers on CR gave me some feedback saying I should NOT be doing this.  He said I should want the loop to stop if an exception occurs.

He linked to this SO Q&A regarding handling general exceptions, which I read (a few times now) and I think this solution falls under "failing gracefully".  As mentioned above, I'm not trying to swallow exceptions, just control how/when they are handled so that my program behaves in a manner I can predict and depend on, even in the event of a catastrophic or unexpected exception.

What I'd like to know:

If this is bad practice, why?

Out of the three options I provided, which would you choose? - OR - Is there a mysterious and much better fourth option I'm missing?


问:
How does Chrome V8 work? And why was JavaScript not JIT-Compiled in the first place?
I have been researching Interpreters/Compilers, then I stumbled across JIT-Compilation - specifically Google Chrome's V8 Javascript Engine.

My questions are -

How can it be faster than standard Interpretation?

Why wasn't JIT-Compilation used in the first place?

My Current Understanding

Every Javascript Program starts out as source code, then, regardless of the method of execution, is ultimately is translated to machine code.

Both JIT-Compilation and Interpretation must follow this path , so how can JIT-Compilation be faster (also because JIT is time-constrained, unlike AOT-Compilation) ?

It seems that JIT-Compilation is a relatively old innovation, based off of Wikipedia's JIT-Compilation Article.

"The earliest published JIT compiler is generally attributed to work on LISP by McCarthy in 1960."

"Smalltalk (c. 1983) pioneered new aspects of JIT compilations. For example, translation to machine code was done on demand, and the result was cached for later use. When memory became scarce, the system would delete some of this code and regenerate it when it was needed again."

So why was Javascript  Interpreted to begin with?

I'm very confused, and I've done a lot of research on this, but I haven't found satisfactory answers.

So clear, concise answers would be appreciated. And if additional explanation about Interpreters, JIT-Compilers, etc. needs to be brought in, that's appreciated as well.

答:
With understanding of what is going on at runtime, it is possible to make changes to the code or the interpretation of the code that allow it to be executed faster or compiled better than what is known at the ahead of time compile time.

Quite a bit can be said on this - it is the subject of significant amounts of research.  My own explanation here that I began to write pales in comparison with the answer given in Understanding the differences: traditional interpreter, JIT compiler, JIT interpreter and AOT compiler

Quite simply, JavaScript was not initially compiled or looked at for JIT because it was never meant to be anything that complex or important.

The original intent of JavaScript was to link to Java applets on a web page.  The ability to click on some button or enter a value in a form field and then do work in a Java applet method can be seen in Invoking Applet Methods From JavaScript Code.  It was also possible, through JavaScript to go the other way of invoking JavaScript code from an applet.

JavaScript's original intent was to link applets and the html pages that contained them.  For such a small task, one doesn't need great performance (if you wanted performance, invoke the applet method which is JIT'ed).

It was only after Netscape started to do significant work with JavaScript as its own language and promote it for development (including Server Side JavaScript in the Netscape Enterprise Server - which, incidentally did ahead of time compilation) that JavaScript came into light as a serious target.  It took many years after that for the necessary tools to make it useful.

ContentLicense: CC BY-SA 3.0


问:
Does low latency code sometimes have to be "ugly"?
(This is mainly aimed at those who have specific knowledge of low latency systems, to avoid people just answering with unsubstantiated opinions).

Do you feel there is a trade-off between writing "nice" object orientated code and writing very fast low latency code? For instance, avoiding virtual functions in C++/the overhead of polymorphism etc- re-writing code which looks nasty, but is very fast etc?

It stands to reason- who cares if it looks ugly (so long as its maintainable)- if you need speed, you need speed?

I would be interested to hear from people who have worked in such areas.

答:
What matters the end-user?

Performance

Features / Functionality

Design

Case 1: Optimized bad code

Hard maintenance

Hardly readable if as an open-source project

Case 2: Non-optimized good code

Easy maintenance

Bad user experience

Solution?

Easy, optimize performance critical pieces of code

e.g.:

A program that consists of 5 Methods, 3 of them are for data management, 1 for disk reading, the other for disk writing

These 3 data management methods use the two I/O methods and depend on them

We would optimize the I/O methods.

Reason:
I/O methods are less likely to be changed, nor they affect the design of the app, and all in all, everything in that program depends on them, and thus they seem performance critical, we would use whatever code to optimize them.

This means we get good code and manageable design of the program while keeping it fast by optimizing certain parts of code

I am thinking..

I think bad code makes it hard for humans to polish-optimize and small mistakes might make it even worse, so a good code for a novice/beginner would be better if just well written that ugly code.


问:
Xamarin/Mono LGPL Compliance
The LGPL seems to stipulate that I have to distribute my app in a way that the LGPLed code can be replaced. Xamarin keeps saying that to distribute a mac app in the store, I need to use Xamarin.Mac and buy a license. Now, if I have a closed source app and I distribute a .app bundle where the Mono runtime is present as a .dylib rather than statically compiled into some executable, I'm compliant, yes? I don't understand their restriction.

MonoDevelop/Monomac distributes apps in a way that requires the user to jump through the hoops of installing the Mono runtime, but this seems totally unnecessary if I just bundle mono in as a replacable library.

答:
Merely providing an LGPL'd library as a .dylib does not make you compliant.  You must also include the source code and any tools necessary to allow someone to modify the library for their own purposes and use those modifications in your program.

It's very likely that the Apple ecosystem does not support such an arrangement, which is why Xamarin recommends that you use their commercial tools for this purpose.

Title: Xamarin/Mono LGPL Compliance


问:
Design: Lisp (or other scripting language) as an interactive interface for C++?
I'm working on a medium size C++ project (will probably end up around 50k lines) and I have to provide an interactive terminal interface. The program produces scientific data as an output and the interactive interface is to let a researcher tweak a visual representation of what's going to be calculated before actually completing the calculation.

I'm not keen on interactive programs that define their own language since they're all different (leading to confusion) and if they support a lot of functions almost require the developer to implement a "proper" parser-interpreter for the syntax.

I would also like the ability to define "smart" configuration files using this program (thus avoiding the need to externally script it).

It seems to me that the correct answer is to implement an existing scripting language with its own support library that can make callbacks into C++. Since I've been playing with Common Lisp recently I decided to have a go at doing this using ECL (insanely overkill for my purposes) and I have bound functions into Lisp and built a Lisp REPL that is capable of executing these callbacks.

Whilst this more or less works, this doesn't really seem to be the use-case ECL was designed for, since I have to make quite a lot of effort to extract the user's input in a safe manner, and I'm using very few of its features.

This is not a request for a library suggestion (though I would happily accept those as well as an answer), but a methodology question. My users are not overly used to a lot of programming languages (the department uses primarily IDL), and it's uncommon that any other language is used.
A full Common Lisp implementation seems like quite a sledgehammer to crack a nut and the syntax will be quite foreign to the users (which in many ways is what I wanted to avoid by using a pre-defined language).

Am I looking at the problem of building a REPL-like environment from the wrong direction - should I instead build my program into a library and use an interactive language with FFI against it?

Essentially:

I want to add an REPL like system to my C++ program for the user to setup their data.

I would rather avoid defining my own dialect/syntax/language for this purpose, instead using a ready-made interpreter and just calling back into C++

It would be nice to have the ability to use it for "smart" configuration files, that have logic inside them (basic control flow and arithmetic).

As easy to use as possible for non-programmers.

If you have solved this problem/had a similar dilemma in the past I would be interested to hear your thoughts (I understand this is quite an opinion based subject).
Thanks!

答:
If you really want to tick some people off, use FORTH.

You get an interactive control interface (in reverse Polish notation, admittedly) AND a programming (scripting) language.

Alternatively, you could dig up one of David Betz's little XLISP or XScheme packages.  As I heard it, this is basically what Autodesk used to make AutoLISP for AutoCAD, a few decades back.

Xerox discovered, on one of their "office automation" products, that secretaries had no trouble at all learning to program in LISP, as long as they (Xerox) didn't call it "programming", but rather something like "extensions" or "customizations".  I think it was the Dandelion, but don't quote me.


问:
Is this a valid situation for returning rather than throwing an exception?
This is not something I would ever normally do, but I have a situation where some existing legacy code is being reused in a new application. The code is shared and needs to be used by both the legacy and new application. The legacy application is a reporting application and errors are reported as messages no differently to informational messages in the UI. The new application actually executes actions based on these calculations: so errors are now critical to program execution.

We have hundreds of business logic methods that sort a person into a series of buckets, where the buckets are contained in a dictionary (key is bucket number, value is true if they are in that bucket according to the calculation):

```<code>public Dictionary<int, bool> Calculation(IPerson person, out string message)
{
    try
    {
        var buckets = new Dictionary<int, bool>();

        // Do logic to determine what buckets the person is in
        // message is used by the legacy application UI...can be set to anything
    }
    catch(Exception)
    {
        message = "Some non-consistent error message";
    }

    return buckets;
}
</code>```

In each method there is an all encompassing exception block that swallows the exception (yes...I know).

For the purposes of these calculations an exception failure does not mean that the whole calculation should be discarded: if there is an exception and the person doesn't end up in all the buckets they should we don't care. The message is used to communicate back to the UI that for this person, the whole calculation may not have completed and that is considered enough. Message may also contain non error information...its not specifically an error message and when there is an error there is no consistent text to look for.

With the new application, we potentially want to take a different execution path if there was an exception: at the very least we want to consistently detect and display errors to the UI in an obvious and distinct fashion, not just as whatever text was assigned to the message variable. Also we would like to log the exception details in this new application.

I am not allowed to make a change that will alter the behaviour of the legacy application, but I can refactor the method signatures. I am proposing that the exception be caught as it is now, but to return it is an out parameter:

```<code>public Dictionary<int, bool> Calculation(IPerson person, out string message, out Exception exception)
{
    try
    {
        var buckets = new Dictionary<int, bool>();

        // Do logic to determine what buckets the person is in
        // message is used by the legacy application UI...can be set to anything
    }
    catch(Exception ex)
    {
        message = "Some non-consistent error message";
        exception = ex;
    }

    return buckets;
}
</code>```

I know this is totally non-standard and absolutely not the way exceptions are intended to be used, but in a situation where we want to report that an exception occurred that was handled...why not pass back the exception itself? keep in mind also I can't change the behaviour of the legacy application.

Thoughts? Is this still a terrible idea? Is there a better way of doing this given the constraints?

答: I think your best bet is to simply use the catch block to log the exception and any other information that will help you trace the error, including a stack trace.  This satisfies your callers, who don't have to change their method signatures, and further satisfies the developers, who now have a way to diagnose problems involving thrown exceptions.


问:
Why does Java define BigInteger / BigDecimal values of 10?
Question perhaps slightly left of field - but I'm curious as to the logic behind why Java's BigInteger/BigDecimal classes feel the need to define a constant of TEN?

Example taken from java.math.BigInteger:

```<code>/**
 * The BigInteger constant zero.
 *
 * @since   1.2
 */
public static final BigInteger ZERO = new BigInteger(new int[0], 0);

/**
 * The BigInteger constant one.
 *
 * @since   1.2
 */
public static final BigInteger ONE = valueOf(1);

/**
 * The BigInteger constant two.  (Not exported.)
 */
private static final BigInteger TWO = valueOf(2);

/**
 * The BigInteger constant ten.
 *
 * @since   1.5
 */
public static final BigInteger TEN = valueOf(10);
</code>```

Now I'm assuming it might be something to do with use in scaling functions or the like, but it did make me curious - especially since TEN seems to first appear in 1.5 whereas ONE and ZERO existed much earlier (I can also see why 1 and 0 would be more immediately useful than 10, too)

Anyone know?

答:
BigInteger and BigDecimal are immutable objects.  Once instantiated, if you want to do something with it, you create a new object.  This isn't a problem per say, and actually avoids many other problems (especially when threading), and numbers tend to be things that are constants - you don't change them.

It is very common for code that is working with BigDecimal and BigInteger to need to use the values 0, 1, 2, and 10.  If these were not defined as constants in the class, programmers would often find themselves instantiating those objects again and again.  This can be a problem because it means you are creating objects unnecessarily where there are perfectly acceptable and commonly used objects.

I once worked on a code base where miles and kilometers were frequently used. Prior to a clean up, we had over a dozen different places where there was a static BigDecimal MILES_IN_ONE_KM = new BigDecimal("0.621371") in one way, shape, form or another - fortunalty there were only those and they were statics rather than being created every time we converted from one distance unit to another...

This is a rather special case of the Object Pool Pattern.  Other examples of it can be found in the Integer cache (primary used in boxing / unboxing), and the Color class where things such as 'RED' and 'BLUE' are defined.

By allocating these commonly used objects in the class, it provides a rather low cost to have a few extra objects floating around rather than creating and destroying scores every time you want to multiply a number by 10 or add 1.


答:
Your requirements describe Lua. Lua is designed to be embeddable as well as work as a declarative configuration language.

Other options I’ve seen or used include Tcl, Python, and JavaScript.

All of these languages can be embedded to various degrees of work and tend to be fairly easy for non-programmers (who think they can program) to use.

Title: Design: Lisp (or other scripting language) as an interactive interface for C++?

Body:
I'm working on a medium size C++ project (will probably end up around 50k lines) and I have to provide an interactive terminal interface. The program produces scientific data as an output and the interactive interface is to let a researcher tweak a visual representation of what's going to be calculated before actually completing the calculation.

I'm not keen on interactive programs that define their own language since they're all different (leading to confusion) and if they support a lot of functions almost require the developer to implement a "proper" parser-interpreter for the syntax.

I would also like the ability to define "smart" configuration files using this program (thus avoiding the need to externally script it).

It seems to me that the correct answer is to implement an existing scripting language with its own support library that can make callbacks into C++. Since I've been playing with Common Lisp recently I decided to have a go at doing this using ECL (insanely overkill for my purposes) and I have bound functions into Lisp and built a Lisp REPL that is capable of executing these callbacks.

Whilst this more or less works, this doesn't really seem to be the use-case ECL was designed for, since I have to make quite a lot of effort to extract the user's input in a safe manner, and I'm using very few of its features.

This is not a request for a library suggestion (though I would happily accept those as well as an answer), but a methodology question. My users are not overly used to a lot of programming languages (the department uses primarily IDL), and it's uncommon that any other language is used.
A full Common Lisp implementation seems like quite a sledgehammer to crack a nut and the syntax will be quite foreign to the users (which in many ways is what I wanted to avoid by using a pre-defined language).

Am I looking at the problem of building a REPL-like environment from the wrong direction - should I instead build my program into a library and use an interactive language with FFI against it?

Essentially:

I want to add an REPL like system to my C++ program for the user to setup their data.

I would rather avoid defining my own dialect/syntax/language for this purpose, instead using a ready-made interpreter and just calling back into C++

It would be nice to have the ability to use it for "smart" configuration files, that have logic inside them (basic control flow and arithmetic).

As easy to use as possible for non-programmers.

If you have solved this problem/had a similar dilemma in the past I would be interested to hear your thoughts (I understand this is quite an opinion based subject).
Thanks!


问:
How to contact an open-source organisation (e.g. Apache) about a new project?
I've developed some software within my company and we have agreed that the future of the work is to open source it into the public domain.

Is there an official contact procedure to contact the Apache Software Foundation, apache.org, to propose a new project?

Looking at apache.org I've not been able to find a contact email or enquiry form, so I've resorted to searching lists of people involved in Apache projects and by chance some of them have blogs which may have a contact facility. Seems a bit haphazard way to make an important proposal about a new project, to me.

I'm considering Apache as an Open Source Software (OSS) organisation first because

the project is based on existing Apache libraries and is therefore a practical business problem demonstration applying those libraries, existing on the same open source platform is mutually beneficial - for example library updates may be easier, the project may be easier to find as a related project

Apache Software License appears to be the most suitable license to use, given that the libraries that the project uses use the same and that ASL seems to be more flexible and pragmatic than GPL and possibly attracts more developers including those with commercial motivation

Java-based: the project is Java based and Apache is a large, possibly even the largest, independent non-profit open source supporter of Java.

I would consider other platforms too and if so would want to know how to contact them.

Background Reading

I've been researching how to Open Source, some notable references so far: (but so far not seen how to contact an OSS organisation once you are nearly ready to publish)

http://oreilly.com/catalog/9780596517960/toc.html?CMP=ILC-search_spot1&ATT=intel-property-book  - book describes all the major OSS licenses and industry stories

http://producingoss.com/ - general advice

https://stackoverflow.com/questions/3813613/looking-for-case-studies-of-managing-open-sourcing-code-from-a-company  - my post about how others did it

https://stackoverflow.com/questions/1914104/how-to-license-code-source-but-keep-control-of-it/1914145#1914145  - I got the accepted answer here

答:
From http://incubator.apache.org/

The Incubator project is the entry path
  into The Apache Software Foundation
  (ASF) for projects and codebases
  wishing to become part of the
  Foundation's efforts. All code
  donations from external organisations
  and existing external projects wishing
  to join Apache enter through the
  Incubator.

Java projects usually end up under the Jakarta umbrella.

ContentLicense: CC BY-SA 2.5


答:
How about a different change to the methods:

Gut all the existing methods, move the code into new methods.  The existing methods contain only the exception-swallower and otherwise call the new methods to do the work.  This leaves the legacy form that you can call if you want it swallowed or the new form if you want it to throw when it should throw.

This requires less in the way of actual modification to the code (although it does require more moving of code) and as far as I'm concerned is much cleaner than your approach.

Title: Is this a valid situation for returning rather than throwing an exception?

Body:
This is not something I would ever normally do, but I have a situation where some existing legacy code is being reused in a new application. The code is shared and needs to be used by both the legacy and new application. The legacy application is a reporting application and errors are reported as messages no differently to informational messages in the UI. The new application actually executes actions based on these calculations: so errors are now critical to program execution.

We have hundreds of business logic methods that sort a person into a series of buckets, where the buckets are contained in a dictionary (key is bucket number, value is true if they are in that bucket according to the calculation):

```<code>public Dictionary<int, bool> Calculation(IPerson person, out string message)
{
    try
    {
        var buckets = new Dictionary<int, bool>();

        // Do logic to determine what buckets the person is in
        // message is used by the legacy application UI...can be set to anything
    }
    catch(Exception)
    {
        message = "Some non-consistent error message";
    }

    return buckets;
}
</code>```

In each method there is an all encompassing exception block that swallows the exception (yes...I know).

For the purposes of these calculations an exception failure does not mean that the whole calculation should be discarded: if there is an exception and the person doesn't end up in all the buckets they should we don't care. The message is used to communicate back to the UI that for this person, the whole calculation may not have completed and that is considered enough. Message may also contain non error information...its not specifically an error message and when there is an error there is no consistent text to look for.

With the new application, we potentially want to take a different execution path if there was an exception: at the very least we want to consistently detect and display errors to the UI in an obvious and distinct fashion, not just as whatever text was assigned to the message variable. Also we would like to log the exception details in this new application.

I am not allowed to make a change that will alter the behaviour of the legacy application, but I can refactor the method signatures. I am proposing that the exception be caught as it is now, but to return it is an out parameter:

```<code>public Dictionary<int, bool> Calculation(IPerson person, out string message, out Exception exception)
{
    try
    {
        var buckets = new Dictionary<int, bool>();

        // Do logic to determine what buckets the person is in
        // message is used by the legacy application UI...can be set to anything
    }
    catch(Exception ex)
    {
        message = "Some non-consistent error message";
        exception = ex;
    }

    return buckets;
}
</code>```

I know this is totally non-standard and absolutely not the way exceptions are intended to be used, but in a situation where we want to report that an exception occurred that was handled...why not pass back the exception itself? keep in mind also I can't change the behaviour of the legacy application.

Thoughts? Is this still a terrible idea? Is there a better way of doing this given the constraints?


问:
Advantage of generic base class
What's the advantage of having a generic base class and a derived class having itself as the generic parameter on the base class.

e.g.

```<code>public abstract class MyBase<T> {}
public MyDerived : MyBase<MyDerived> {}
</code>```

答: I might be completely off here, but I'd say the big thing here is the fact that this allows you to share one abstract code base/interface between all your derived classes, but at the same time you prevent them from being directly related, i.e. you prevent the usage of the base class to make a reference pointing to objects of any derived class.</p>

Title: Advantage of generic base class


答:
You could embed some interpreter in your application. If you like Lisp as I do, you should consider embedding GNU guile or librep etc...

See also this & that & that answers


问:
In *nix, is there a practice for storing static libraries?
Lets say you are building an application that staticly links against libraries that you provide it. Where should you store these static libraries? Should you make a directory in the parent directory of your application called "libs" or "dependencies" and store it there? Is there a practice for doing this?</p>

答:
For Linux you have the Filesystem Hierarchy Standard defining conventions about files.

Read also the Program Library HowTo.

Actually, I believe that you should prefer shared libraries to static ones.

Notice that a library makes mostly sense when it can be reused by several applications. Otherwise, it might not be worth making a library (e.g. for some code unique to your application).

If you have only static libraries, their location is specific to your build procedure, so don't matter much (you won't need any static library to run your executable). Of course it is very different for shared libraries.

If you need to embed or extend the Python interpreter (and this is not much related to static libraries), you should read the relevant Python documentation.


答:
The same advantage of any base class: code reuse.

Why would I duplicate code that could be shared across multiple implementations of a generic base class?

The reason why you would have any concrete implementations that inherit from the generic base would be if you wanted to add specific functionality for that concrete type.  (or to have an abstract function in the base that is implemented differently across concrete implementations)

Title: Advantage of generic base class

Body:
What's the advantage of having a generic base class and a derived class having itself as the generic parameter on the base class.

e.g.

```<code>public abstract class MyBase<T> {}
public MyDerived : MyBase<MyDerived> {}
</code>```


答:
First, you have a false dilemma.
If your users are not programmers and know only IDL, any other language (custom or existing) will look foreign to them. But that does not mean that they cannot learn something else. In fact, you would say that this is not really a problem: you'll have to write a tutorial and point them to documentation and other materials. All the languages below have good documentation. Common Lisp is a standardized language.

Lua

This is covered in another answer, but I would still recommend it. The language is made to be embedded, and works well with C++.

Python

Boost.Python is a popular way of integrating C++ code and Python. From what I heard, it seems that Python and especially NumPy is also popular for scientific computing.

Clasp

Even if you don't intend to use Common Lisp, please have a look at CLASP (video), which is an implementation of Common Lisp for C++.

A full Common Lisp implementation seems like quite a sledgehammer to
  crack a nut and the syntax will be quite foreign to the users (which
  in many ways is what I wanted to avoid by using a pre-defined
  language).

I see it the other way: instead of having half a language that barely works (this is not directed at above languages, but about custom ones), a full Common Lisp implementation gives you a stable and mature environment. I don't know what your scientific data is about, but your user could even work with Maxima directly from your environment, which has an infix syntax if you want.

Library/FFI

Am I looking at the problem of building a REPL-like environment from
  the wrong direction - should I instead build my program into a library
  and use an interactive language with FFI against it?

This is a possible way to do it, but I honestly cannot say which way is better for you.


问:
why regex, when using global search and {0,} quantifier, match the end of the string?
I have asked a question here about js, regex, quantifiers and global search. I've understood finally how this works, but, let's take a concrete example and then I`ll write my question.

Based on the same example

```<code>var str = 'ddd';
var r = /d*/g;
console.log(str.match(r))
</code>```

it outputs this array: ["ddd", ""]

I understand that the first item in the array is because it matches the letter d and the last item (that empty string) is because it matches the end of the string, which is nothing, so * makes sense because it matches 0 or more occurrences...

So, my questions are:

Why this is happening?

Why it just have to query the end of the string to finally obtain a
true matching?

In my opinion, the end of the string(ddd) should not be queried; because it's not like my string is containing an empty space at the end 'ddd '. If my string was empty, it was logical to match, but not in this case. My logic here is this:

for every character in the string, do this search/regex (d*) ...so why does it just continue with the end of the string? It should stop on the last charachter of my string, which in this case is d...

答:
Your regex matches the '' empty string with d*, because the * quantifier means zero or many times and that's zero d here.

And it's matched because when you use the g modifier it will not stop in the first match and continue matching, that's why you will get the second match.

This is a DEMO without the g modifier and it doesn't match the ''.

So if you don't want it to match the second one you can just remove the g modifier or better use one of the following regexes:

```<code>var r = /(^d*$)/g;
//Or the following one
var r = /(d+)/g;
</code>```

You will force it to get only strings that exactly contains the letter d.

You can see the DEMO here.

Body:
Your regex matches the '' empty string with d*, because the * quantifier means zero or many times and that's zero d here.

And it's matched because when you use the g modifier it will not stop in the first match and continue matching, that's why you will get the second match.

This is a DEMO without the g modifier and it doesn't match the ''.

So if you don't want it to match the second one you can just remove the g modifier or better use one of the following regexes:

var r = /(^d*$)/g;
//Or the following one
var r = /(d+)/g;

You will force it to get only strings that exactly contains the letter d.

You can see the DEMO here.


问:
Replacing C with JavaScript as an introductory programming language
I am a new teacher at polytechnic where we teach web development and basic software programming.

For years, the institution where I teach have taught C as their introductory programming language to people who are assumed to have no knowledge in programming.

I am investigating if there is a better option, and was thinking about JavaScript because it covers most of a similar structure to what we teach in C.

The reason I was thinking of JS is that a big part of the pathway that we teach goes into web development and JavaScript is used quite heavily in todays web development world.

The only direct difference I would encounter would be missing the user input via console that can be done in C.
I suppose that would have to be replace by a simple HTML page, so that is not a biggy.

Is there any reason your experience, why JavaScript would be a bad way to start given the limited information I have given you? Or why would it be a good start?

I can see come pro's and con's to the change, so I am after some other programmers opinions.

Also, even though C is the intro language and does not leave the command line interface in the paper, the students are then expected to transition that knowledge into JavaScript and C# in the following year in 2 other subjects.

答:
I think JavaScript is not the best language to start learning programing concepts, mainly because of its "unusual" prototype approach.

C is meanwhile completely there were assembler was in earlier days. So I think not very interesting for most of the students. Where I think C++ now took the role of C. But I think C++ is not that interesting or fancy for students.

What I think is important to teach your students are the basic concepts of: Debugger, Breakpoints, Memory etc.

I think Microsoft's Community Edition together with C# as language would be a pretty good choice. Every student can also install it for free on his own machine.

If you dive directly into JavaScript you miss a lot of the fundamental parts that someone who has to do with Software should know. A C# Console Application I think is a good start.

But another point: Diving directly into web development I think is not a good strategy. It is too complex I think. Your students would miss the point what it really means to code and debug something.

If you still want to use JavaScript I think NodeJS development could be pretty interesting for your students.


问:
Using PHP without mixing presentation logic
I'm conceptually designing a website / application and trying to come up with the correct separation of concerns.

The basic technologies I'm settling on are: MySQL, PHP (Laravel), HTML/JS (jQuery).
It's been a few years since I've written PHP, and since then I've gotten very used to MVC and MVVM approaches.

I would like to stay away from using PHP as a templating engine. My reason for this is that I want to keep presentation solely to JS and HTML code, with none of it mixed in with server-side code.
To achieve this, my thinking is to stick with using PHP to create services, then call those services from JS / AJAX on the pages.

As far as I can tell, this approach would allow me to keep PHP to handling data and the client will handle all of the logic and presentation.

My main concern is that I am having a difficult time finding any resources outlining similar approaches used in the real world.
Almost every single instance I can find of PHP being used has it implemented as a templating engine, dropping HTML and data onto pages when they're being sent from the server.

Are there any obvious flaws in my approach that I've missed?

I'm entirely open to changing my thinking on this one - no code has been written yet so the architecture is mine to play with :)

Thanks!

答:
The reason you are probably not finding those examples is because that would mean implementing a complete templating system in PHP, which is far beyond the scope of a lot of tutorials.

A good templating engine does not mingle PHP into the view, but there will always be binding logic in your views. There are plenty of templating frameworks out there and there are even frameworks that go as far as providing MVC approaches so you might have more luck looking into that.

On my latest project I've used Symfony so that's the first one that comes to mind. The standard template engine for Symfony is Twig, which is also available as a standalone templating framework. (I'm not affiliated with Symfony or Twig in any way, it's just the last framework I've used for PHP-based MVC development)


答:
It all depend of the purpose of the course.

If the goal is to teach programming fundamentals, consideration about actual usefullness of the language should be largely ignored. Javascript is nice because it is used in browsers. On the other hand it has a lot of problems that will distract your students from the core message of your course. Learning javascript later is not that hard once you understand the fundamentals about programming.

In this perspective, a better solution would be to stick to c (because it is low level), use python (because it is simple and consistent, and you will be able to focus on design), lisp (same but more abstract), haskell (if you want to focus on type systems) etc.

If the goal is to enable web designers to improve their skills, then obviously javascript is the way to go.

Title: Replacing C with JavaScript as an introductory programming language

Body:
I am a new teacher at polytechnic where we teach web development and basic software programming.

For years, the institution where I teach have taught C as their introductory programming language to people who are assumed to have no knowledge in programming.

I am investigating if there is a better option, and was thinking about JavaScript because it covers most of a similar structure to what we teach in C.

The reason I was thinking of JS is that a big part of the pathway that we teach goes into web development and JavaScript is used quite heavily in todays web development world.

The only direct difference I would encounter would be missing the user input via console that can be done in C.
I suppose that would have to be replace by a simple HTML page, so that is not a biggy.

Is there any reason your experience, why JavaScript would be a bad way to start given the limited information I have given you? Or why would it be a good start?

I can see come pro's and con's to the change, so I am after some other programmers opinions.

Also, even though C is the intro language and does not leave the command line interface in the paper, the students are then expected to transition that knowledge into JavaScript and C# in the following year in 2 other subjects.


问:
What if the "catch" block is empty - "{}"
Is it proper to use below syntax for try catch??    </p>

```<code>try
{
    int a;
    int b;
    int c=a+b;
}
catch (exception ex)
{
//Nothing here
}
</code>```

答:
No, no and no

It is never appropriate to ignore exceptions like this. As a bare minimum, you should log the exception so that you can figure out what went wrong at a later point. Exception handling isn't sports fishing, you don't catch exceptions for the fun of it. You catch them because you intend to do something with them.


问:
Could there be a use case for C# style auto-properties in Python
I've been doing a lot of work in C# recently (my primary language is Python) and I love that I can do something like

public string MyProperty{ get; set; }
```

<p>Going back to Python I miss that sort of functionality.  I don't like that I would have to do </p>

<pre class="lang-py prettyprint-override"><code>class MyClass:

    @property
    def foo(self):
        return self._foo

    @foo.setter
    def foo(self, value):
        self._foo = value

a = MyClass()
a.foo = 7
print(a.foo)
</code>```

I thought that this was something I could do pretty easily with a descriptor, like so.

class MyClass:
    foo = AutoProperty()

a = MyClass()
a.foo = 7
print(a.foo)
```

<p>Unfortunately, I realized while implementing this that I was violating my favorite design principle - KISS.  After all, what I'd been thinking about were just instance variables.  </p>

<pre class="lang-py prettyprint-override"><code>class MyClass(): pass

a = MyClass()
a.foo = 7
print(a.foo)
</code>```

The reason we don't always use properties by default in Python is that, usually, getting and setting instance variables isn't nearly as involved as languages like Java make it - mostly because the concept of private, protected, and public fields don't really exist in Python, except by (weak) conventions and language features, and because changing from a "field" to a "property" isn't a breaking change in Python.

If we later decide that we do need more complex validation while setting or calculations while getting, then we can easily do that by implementing properties and not affecting the interface of our class.

I'm still wondering though - is there any sort of way this technique, or a modified version of this technique, could be used to provide a useful and Pythonic feature?

答:
In Python, switching between an attribute and a property isn't a breaking change, it doesn't alter the interface at all, so there's not much point to an auto-property system. You can start with a public attribute, then later on switch to a property without needing to alter the code that interfaces with your class at all.

This is also why defining get_ and set_ methods in Python is discouraged; the property is a much neater way of protecting access, and means that you don't have to implement those methods from the beginning in case you later need them to do something non-trivial. See e.g. Do you use the get/set pattern (in Python)? on SO.

If you did decide to implement an AutoProperty you should add __delete__, too; I use the following as a base for other descriptors:

```<code>class BaseDescriptor(object):
    """Descriptor base class, providing basic set, get and del methods.

    Arguments:
      name (str): The attribute to redirect access to (usually the name
        to which the descriptor is assigned with a leading underscore,
        indicating private-by-convention).

    Example:

        >>> class TestClass(object):
        ...     foo = BaseDescriptor('_foo')

        >>> inst = TestClass()
        >>> inst.foo = 'bar'
        >>> inst.foo
        'bar'
        >>> del inst.foo
        >>> inst.foo
        Traceback (most recent call last):
          ...
        AttributeError: 'TestClass' object has no attribute '_foo'

    """

    def __init__(self, name):
        self.name = name

    def __get__(self, obj, typ=None):
        return getattr(obj, self.name)

    def __set__(self, obj, val):
        setattr(obj, self.name, val)

    def __delete__(self, obj):
        delattr(obj, self.name)
</code>```

Updated version for review at
  https://codereview.stackexchange.com/q/98892/32391

Body:
In Python, switching between an attribute and a property isn't a breaking change, it doesn't alter the interface at all, so there's not much point to an auto-property system. You can start with a public attribute, then later on switch to a property without needing to alter the code that interfaces with your class at all.

This is also why defining get_ and set_ methods in Python is discouraged; the property is a much neater way of protecting access, and means that you don't have to implement those methods from the beginning in case you later need them to do something non-trivial. See e.g. Do you use the get/set pattern (in Python)? on SO.

If you did decide to implement an AutoProperty you should add __delete__, too; I use the following as a base for other descriptors:

class BaseDescriptor(object):
    """Descriptor base class, providing basic set, get and del methods.

    Arguments:
      name (str): The attribute to redirect access to (usually the name
        to which the descriptor is assigned with a leading underscore,
        indicating private-by-convention).

    Example:

        >>> class TestClass(object):
        ...     foo = BaseDescriptor('_foo')

        >>> inst = TestClass()
        >>> inst.foo = 'bar'
        >>> inst.foo
        'bar'
        >>> del inst.foo
        >>> inst.foo
        Traceback (most recent call last):
          ...
        AttributeError: 'TestClass' object has no attribute '_foo'

    """

    def __init__(self, name):
        self.name = name

    def __get__(self, obj, typ=None):
        return getattr(obj, self.name)

    def __set__(self, obj, val):
        setattr(obj, self.name, val)

    def __delete__(self, obj):
        delattr(obj, self.name)

Updated version for review at
  https://codereview.stackexchange.com/q/98892/32391


答:
Very  very rarely. The only exception i use on a
regular basis is creating a directory that might or might not exist and then I only catch the specific exception that might be thrown in case the directory exists.</p>

Title: What if the "catch" block is empty - "{}"

Body:
Is it proper to use below syntax for try catch??    </p>

```<code>try
{
    int a;
    int b;
    int c=a+b;
}
catch (exception ex)
{
//Nothing here
}
</code>```


答:
This would simply eat up any exception being raised. Without any notification or logging.

If that exception appears at runtime, It would be really difficult to detect that It occurred and resolve the issue.

So we never eat up the exception until it is really intended. Even if it is intended, we log that in the log files.


答:
Yes and No.

Leaving the catch block completely empty ...

```<code>catch( Exception )
{
}
</code>```

... should be a hanging offence.

Having an empty catch block that contains a meaningful, detailed comment about why it's OK to ignore this particular exception (and any sub-classes thereof) might be acceptable, but only in very limited circumstances.

Re-throwing the same exception should only be done when you have a list of catch blocks and you need to "smuggle" a smaller Exception past the attention of a "larger" Exception handler (say, throwing a FileNotFound Exception to the "Outside World" but doing something different with any other IOException).

The most important part of Exception Handling is the "Handling" part and, if you're not doing anything useful when catching an Exception, then you shouldn't be catching it at all.  (Is "smothering" an exception useful?  YMMV).

Body:
Yes and No.

Leaving the catch block completely empty ...

catch( Exception )
{
}

... should be a hanging offence.

Having an empty catch block that contains a meaningful, detailed comment about why it's OK to ignore this particular exception (and any sub-classes thereof) might be acceptable, but only in very limited circumstances.

Re-throwing the same exception should only be done when you have a list of catch blocks and you need to "smuggle" a smaller Exception past the attention of a "larger" Exception handler (say, throwing a FileNotFound Exception to the "Outside World" but doing something different with any other IOException).

The most important part of Exception Handling is the "Handling" part and, if you're not doing anything useful when catching an Exception, then you shouldn't be catching it at all.  (Is "smothering" an exception useful?  YMMV).


答:
I would advise you to stuck to:

"Start simple. Build complexity on top of it."

JS with its prototype based inheritance is just to complex to begin with it. IMHO a good programming class should start low-complexity, low-level (C-console - as you already do - for example) and slowly move up to high complexity, high-level (C++ OOP, JS, PHP, etc.) - if you can somehow meaningfully connect the steps inbetween, that's a huge plus factor. That's a lot more important then teaching the latest hype-language IMHO.

Teaching more then one language (if there is enough time for it) can be particularly usefull to show the different approaches the languages take: interpretation vs. compilation, strong vs. weak typing, OOP vs. functional, class vs. prototype based inheritance, etc.

I would like to tell you how I was introduced to development ¹ - I really enjoyed it and I think it was a well thought concept and kept the class highly motivated at any step:

We started with a lot of theory building (compilers, debugging, etc). and then slowly begun building c console apps.

In the next step we were handed a RFID reader connected via RS232 to write an access-control software based on RFID cards (--> somewhat introduction to low-level component communication).

We then added a database for logging and user management purposes (--> entry-level introduction to SQL).

Afterwards our goal was to build a GUI to add/edit the user-base and train/program cards (--> introduction to IDEs using Borland C++ Builder)

We then got a second reader and were told the two should work together and one should centrally handle the authentication (--> introduction to socket programming).

... (There were a few more steps, but I don't want to bore you - I guess you get what I'm trying to point out) ...

The final project was switching from C/C++ to PHP² to build a dynamic website to control the system via a webinterface (the PHP app spoke via TCP socket to the control server build earlier).

What I would like to point out: It was one big project from the (simple) start to the end, always stacking more complex parts onto the previous ones³.

(¹) - In my 3,5 years vocational education to a system-administrator - so programming wasn't our main study goal.

(²) - The step from C to PHP is in particular very easy, because they share a lot of the syntax.

(³) - Which of course often showed the limitations of the previous simple solutions.


答:
The advantage compared to what? I interpret your question as: "in which situation does such a construct make sense?". I found a standard example in Eric Lippert's blog. Replace MyBase by IComparable (it does not really matter if the latter is an abstract class or an interface), this leads to

```<code>public MyDerived : IComparable<MyDerived> {}
</code>```

which simply means: "MyDerived objects can be compared with other objects of type MyDerived" - a simple, not very special situation, which I guess will not need any deeper explanation.

More general: whenever you can think of a meaningful method in a class which takes a second object of that same class (or can return a second object of that class), you have a candidate for your scenario. When this method seems to be generic, and you decide to refactor this method to an abstract base class, this will straightforward lead to the construct.

Title: Advantage of generic base class

Body:
The advantage compared to what? I interpret your question as: "in which situation does such a construct make sense?". I found a standard example in Eric Lippert's blog. Replace MyBase by IComparable (it does not really matter if the latter is an abstract class or an interface), this leads to

public MyDerived : IComparable<MyDerived> {}

which simply means: "MyDerived objects can be compared with other objects of type MyDerived" - a simple, not very special situation, which I guess will not need any deeper explanation.

More general: whenever you can think of a meaningful method in a class which takes a second object of that same class (or can return a second object of that class), you have a candidate for your scenario. When this method seems to be generic, and you decide to refactor this method to an abstract base class, this will straightforward lead to the construct.

ContentLicense: CC BY-SA 4.0


问:
Hiding query strings logically?
I feel uncomfortable when using query string parameters as:

http://xyz.com/default.aspx?carId=1129&country=uk&uniqueId=98745DVF4563VVf1259

I would rather use something that should not make sense to anyone who is trying to make some sense from the URL:

?a=1129&b=uk&c=98745DVF4563VVf1259

(after all this query sting info is for my use only)

Firstly is this a good thing to do? (I mean to hide logic of you query string)

If it is, then is there a way, that internally developers can use carId, country and uniqueId in code, but externally the url uses a, b and c respectively?

So if someone goes to

?a=1129&b=uk&c=98745DVF4563VVf1259

when I do Request.QueryString["carId"]

I should get 1129.

Can this be done?

答:
Many Methods can be used for query strings..
I prefer to use scrambling/descrambling.
You need to do is Just scramble the whole string like..

```<code>string strQS = "id=23&Name=hagsh";
string QueryString1 = ScrambleString(strQS);
Response.Redirect("test.aspx?Query=" + QueryString1 );
</code>```

at other end just reverse the steps...

Just google it for Scramble/Descramble algorithm..You can get ready dll..

Title: Hiding query strings logically?

Body:
Many Methods can be used for query strings..
I prefer to use scrambling/descrambling.
You need to do is Just scramble the whole string like..

string strQS = "id=23&Name=hagsh";
string QueryString1 = ScrambleString(strQS);
Response.Redirect("test.aspx?Query=" + QueryString1 );

at other end just reverse the steps...

Just google it for Scramble/Descramble algorithm..You can get ready dll..


问:
Is unwanted behavior, while work is in progress, declarable as a "bug"?
This might be only a question of definition, but maybe there's a consensus?

Given the situation, software Foobar Plus is under construction, we're not working on an update, but on the first release of it.

Now, a specific feature(A) was implemented;

Feature(A) caused a unwanted behavior in feature(B).

It has no influence on feature(A), but is caused by it.

Feature(B) isn't implemented yet, the behavior got noticed due interpreting debug logs.

The question now is; is this unexpected behavior called a bug, or just a change in feature(B)'s environment?

Edit:
This question isn't about blaming anyone but about finding the proper definition for this case.

答:
It can be both.

If Feature(A) caused some unwanted side-effects by implementation I would call it a bug

If Feature(A) caused some unwanted side-effects by design I would call it a a feature-change


答:
1) How can it be faster than standard Interpretation?
Well, a thought up example would be as follows; suppose we have 2 applications ApplicationCompiled and ApplicationInterpreted. Both of these programs do exactly the same thing, and share the same source code. ApplicationCompiled takes 6 seconds to compile.

Let's say that the timings of Scenario A is:

For ApplicationCompiled: 4 seconds

For ApplicationInterpreted: 12 seconds

So in total ApplicationCompiled takes 10 seconds to run Scenario A (6 seconds compilation, 4 seconds running) and ApplicationInterpreted takes 12 seconds in total to run. I don't have a specific example to show you, and I'm not sure under which cases the above would be true - it also depends heavily on how intelligent the interpret and compiler are.

Obviously this is very simplified, but imho the same idea can be applied to JIT compiling / interpreting. The next question would then be "how do we determine - with low cost - if this branch should be JIT compiled or interpreted"? I'm out of my league here :)

2) Why wasn't JIT-Compilation used in the first place?
Don't know, but I recon it's simply a matter of resources and maturity of the available progress in making a hard-to-optimize language like JavaScript apply advances techniques such as these. There were probably a lot of lower hanging fruits at the time.

Title: How does Chrome V8 work? And why was JavaScript not JIT-Compiled in the first place?

Body:
I have been researching Interpreters/Compilers, then I stumbled across JIT-Compilation - specifically Google Chrome's V8 Javascript Engine.

My questions are -

How can it be faster than standard Interpretation?

Why wasn't JIT-Compilation used in the first place?

My Current Understanding

Every Javascript Program starts out as source code, then, regardless of the method of execution, is ultimately is translated to machine code.

Both JIT-Compilation and Interpretation must follow this path , so how can JIT-Compilation be faster (also because JIT is time-constrained, unlike AOT-Compilation) ?

It seems that JIT-Compilation is a relatively old innovation, based off of Wikipedia's JIT-Compilation Article.

"The earliest published JIT compiler is generally attributed to work on LISP by McCarthy in 1960."

"Smalltalk (c. 1983) pioneered new aspects of JIT compilations. For example, translation to machine code was done on demand, and the result was cached for later use. When memory became scarce, the system would delete some of this code and regenerate it when it was needed again."

So why was Javascript  Interpreted to begin with?

I'm very confused, and I've done a lot of research on this, but I haven't found satisfactory answers.

So clear, concise answers would be appreciated. And if additional explanation about Interpreters, JIT-Compilers, etc. needs to be brought in, that's appreciated as well.


答:
If I understand you right, Feature B works unchanged, but because Feature A exists, the current behaviour of B isn't a good behaviour anymore. So it might be the case that the specification of feature B needs to change. </p>

<p>At one place where I worked they had no bugs, but "Change Requests". Precisely for that reason. </p>

Title: Is unwanted behavior, while work is in progress, declarable as a "bug"?

Body:
This might be only a question of definition, but maybe there's a consensus?

Given the situation, software Foobar Plus is under construction, we're not working on an update, but on the first release of it.

Now, a specific feature(A) was implemented;

Feature(A) caused a unwanted behavior in feature(B).

It has no influence on feature(A), but is caused by it.

Feature(B) isn't implemented yet, the behavior got noticed due interpreting debug logs.

The question now is; is this unexpected behavior called a bug, or just a change in feature(B)'s environment?

Edit:
This question isn't about blaming anyone but about finding the proper definition for this case.

Body:
If I understand you right, Feature B works unchanged, but because Feature A exists, the current behaviour of B isn't a good behaviour anymore. So it might be the case that the specification of feature B needs to change.

At one place where I worked they had no bugs, but "Change Requests". Precisely for that reason.


答:
Unwanted or unexpected behaviour almost always starts out life as a bug.

If the code that is in question is required for feature A, then that would necessitate a change request for compatibility with feature B. It then morphs itself into a feature request.

If the code in question is incorrect, poorly implemented or has untested side effects, then it is a bug in feature A. Then it remains a bug. Sure, it may not have originally or noticeably broken feature A - e.g. memory scribblers etc., but it is a bug.

Log the issue, triage, reclassify if needed, assign it, fix it, test it.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
I think there are evil things in programming, but I don't use the term pejoratively.

Evil is when code pretends to behave in one way, but in reality behaves in a very different fashion, and in a way that hurts a unenlightened rational programmer.  I often refer to this as a type of "Magic."  Magic is anything who's functionality is "hidden" from the programmer, and it comes in different styles.

Example: in Scheme the functions "car" and "cdr" could be implemented using functions only, however, they are not.  Instead they are implemented at a lower level imperatively because that runs faster on most computers.  I'd call this "white magic."  Its not evil, but its definitely magic.

By comparison the unique number NAN in Javascript is not equal to any other number... even itself.  This is "black magic." I don't want to get into a discussion of why you have NAN in Javascript (or why you have both Infinity and NaN), but you can see why a such a simple concept would be useful to a language with only floating point numbers.  However, having a constant number which cannot be tested for in the same way as other constant numbers is not something one would expect.  Fortunately Javascript provides isNAN to help solve this issue, but if you are unaware of NaN's unique property you might write the following code and get burned:

```<code>if(x == NaN)
</code>```

or if you're clever you might try the following with the same results

```<code>if(x === NaN)
</code>```

I joking refer to this as getting "mana burned" (it is magic afterall...).

I realize there are good reasons why you want things which are not numbers to be automatically equal to themselves, but you have to remember that for IEEE floating point numbers NaN has a specific bit sequence and it is similar to other numbers in this respect.  If you treat Javascript NaN the way you might treat an IEEE floating point NaN you are liable to get burned.  This is both deceptive and frustrating, the former being the reason I refer to this as Evil.

Then again, its possible people think otherwise...

Title: Is anything in programming truly evil?

Body:
I think there are evil things in programming, but I don't use the term pejoratively.

Evil is when code pretends to behave in one way, but in reality behaves in a very different fashion, and in a way that hurts a unenlightened rational programmer.  I often refer to this as a type of "Magic."  Magic is anything who's functionality is "hidden" from the programmer, and it comes in different styles.

Example: in Scheme the functions "car" and "cdr" could be implemented using functions only, however, they are not.  Instead they are implemented at a lower level imperatively because that runs faster on most computers.  I'd call this "white magic."  Its not evil, but its definitely magic.

By comparison the unique number NAN in Javascript is not equal to any other number... even itself.  This is "black magic." I don't want to get into a discussion of why you have NAN in Javascript (or why you have both Infinity and NaN), but you can see why a such a simple concept would be useful to a language with only floating point numbers.  However, having a constant number which cannot be tested for in the same way as other constant numbers is not something one would expect.  Fortunately Javascript provides isNAN to help solve this issue, but if you are unaware of NaN's unique property you might write the following code and get burned:

if(x == NaN)

or if you're clever you might try the following with the same results

if(x === NaN)

I joking refer to this as getting "mana burned" (it is magic afterall...).

I realize there are good reasons why you want things which are not numbers to be automatically equal to themselves, but you have to remember that for IEEE floating point numbers NaN has a specific bit sequence and it is similar to other numbers in this respect.  If you treat Javascript NaN the way you might treat an IEEE floating point NaN you are liable to get burned.  This is both deceptive and frustrating, the former being the reason I refer to this as Evil.

Then again, its possible people think otherwise...


问:
Help me design this use case
I have following entities:

Data:

User_id

Categories: Interests, Disinterests, Categories A, B C...

Each categories have sub categories: Interests=Gaming, Physics, Programming etc..

Now each user could belong to multiple sub categories.

So there is M:N relation ship between categories and users.

Scale:

1 Billion Users

100 Categories each could have subcategories ranging form 100 - 10,000

Operations Needed

Batch Read and Write: Selection and Projection given user_id. E.g. Get all the Interests of user A.

Real Time Read and Write: I need to get all the users for a given field like Interest:Games.

Current Design

I used separate files for each sub categories containing list of users. Redis server has keys-value pairs like

```<code><userId_InterestId:games,programming>
</code>```

However this design has many limitations, like slow access times due to disk operations to get all users for a given category. Huge number of keys in Redis i.e. number of (users * number of sub_categories).

I need a change of design

Current plan is to use MongoDb to maintain hierarchical data for  user <-> categories mapping.

```<code><User_id, Interests, A, B, C>.
</code>```

Each categories will have children fields. Since MongoDB is in-memory DB access using user_id should be faster right? But how about reverse query where I specify Interest::Programming as key? Is there any better way I could design it?

答:
There are essentially 3 basic aspects of the model:

A List of users (identified and indexable using user-id)

A Tree structure for the Categories and Subcategories

The M x N relationship between users and categories/subcategories.

Had there been a simpler structures of categories as linear list there would hardly be a question of how to do it. All you needed was to have a map of user-id:cat-id.

Now, since the category listing is a tree and not a linear map, it isn't all that bad! what you should do ideally is to create a hash-map which can linearize the completely hierarchical representation for till each leaf node

for a simple example -

HASH_VAL1 := GAMING

HASH_VAL2 := PROGRAMMING

HASH_VAL3 := PROGRAMMING->C++

Now it is easy to see that MxN relationship can be set up as
user_id - HASH_VALX list.

There are several simple advantages this system has:

The look up from Interest to User is just as fast as the other way. The reverse maping doesn't require any special indexing.

You can edit and manipulate the interest categories or have other information around it which evolve without having to modify user-interest_hash_value relationship.

You can convert the leaf into node and all still works. For example,
another HASH_VALUE_X can start representing PROGRAMMING->C++->Borland-C++ that wouldn't affect the existing relationship which are at USER:PROGRAMMING->C++ level.

You can interestingly add indirect relation ship for example, if USER_X:HASH_VALUE_3=PROGRAMMING->C++ implies USER_X:HASH-PROGRAMMING you can maintain that by just having another USER_X:HASH_VALUE_2 without affecting other data relations.

Last but not least, adding data - filtering records can be pretty linear and hence can be optimized in multiple different ways (Caching, indexing etc.) depending on how system works.

Title: Help me design this use case


问:
When should I instantiate a variable rather than grabbing it through a method?
This may be tedious, but I would love to know which is a more efficient way of programming. The result may only be slightly better or slightly worse, but I am still interested in which is 'better'.

Say I want to create an array of String objects based on the amount of columns I received from an SQL query and then go ahead and fill this String[] object with values through the use of a for loop. i.e.

```<code>if(rs.next()) {
    String[] topLine = new String[metadata.getColumnCount()];

    for (int i = 0; i < metadata.getColumnCount(); i++) {
        topLine[i] = getColumnValue(rs, metadata.getColumnType(i + 1), i + 1);
    }
    writeNext(topLine);
}
</code>```

See the use of metadata.getColumnCount() to fetch the amount of columns, only twice. Would it be more appropriate (and faster) to bring this value into it's own variable such that:

int columnCount = metadata.getColumnCount();

and make use of it only twice? Or should I leave the method to call twice?
What n times do I have to call metadata.getColumnCount() before it becomes more efficient to use a local variable. Is there even any change?

Edit: By the way, this isn't my code, I picked it up as an example.

答:
When should I instantiate a variable rather than grabbing it through a method?

When the value returned in the method has meaning or will be use past the name of the method, then get the value and assign it to variable with the appropriate name.

If metadata.getColumnCount() is constant during the loop, then you can get it and cache it in a local before the loop.

Either way I wouldn't be concerned about the performance of the get unless you have been able to measure the degradation and it would make a difference to the application. Focus on the clarity and the intent of the code, optimise based on performance measurements. Modern compilers and VM are very good at what they do.


答:
I think it depends on how rigorous you want to be with your intro courses, Khan Academy has a programming section that uses Javascript to teach programming concepts and it works pretty well because you hand wave quite a few things to start doing 'cool things' (that are generally handled by external frameworks or HTML5 APIs) and learn the basics of variables, functions, parameters, loops, etc.

If you want to talk about inheritence, data strutures, and scoping though Javascript may get in the way instead of making things easier... You'll also have to defer diving into types and generics because you just won't have them.

I'm surprised no-one has mentioned Java as an alternative yet -- the CS program at the school where I went started with Java, then moved to C with some assembly before branching out into other languages.

I don't really like Java, but I thought it was a useful starting point for learning because:

it uses C style syntax (unlike Python)

it lets you start out thinking in an object oriented mindset (unlike C or Javascript)

it's type system is pretty standard and easy to understand

it doesn't require manual memory management (like C or even C++)

it generally avoids a lot language specific paradigms or problem areas, examples include: list comprehensions and tuple assignment in Python, prototypal inheritance and scoping oddities in JavaScript, extension methods and delegates in C#

C# and Java are both fairly similar, but cross platform support for the CLR was not very mature when I started taking classes -- though this has been improved recently.

I also took the Udacity intro to programming course in Python and thought it was really quite good as well... and Python is usually just fun to write small programs with.


问:
What exactly is copyrighted, the text of the code itself, or the design?
I am both the sole developer for a relatively small company and someone who enjoys programming as a hobby. Recently, for one of my personal projects, I started making a framework for a RESTful API and NoSQL integration that I enjoyed programming at home. Near the same time, my work assigned me to begin a project for integrating the disjointed pieces of our backend into something more easily extensible -- using a RESTful API. As I have begun to code both of these projects, I have found that they are, understandably, shaping up in a similar way (similar class hierarchy, interfaces, etc.) However, I have been programming both of them separately, without copying code from one project to another, and only doing work on work time and personal projects in my personal time.

Now, since I have no agreement stating otherwise with my work, I know (or assume) that all code I write there is copyrighted under my workplace, and not under me. And, as I said, I have not taken any code from work and used it in other projects. Also, while some aspects of both projects are similar, others are quite different (the work one does not use NoSQL because too many processes depend on SQL, for example). The similarities seem unavoidable to me, since I am writing both and I have a specific idea of how HTTP requests should be handled, data should be returned, etc.

However, I still worry about the legal implications of all this. While the code itself has not been copied between projects, the solutions have similar points, and I was wondering if only the text of code is copyrightable, or the overall solution. Could these two projects that handle the same problem in similar ways be considered derivative of one another? I.e., could my home project be considered an infringement of work?

If that answer would be yes, the similar solution would be grounds for infringement, it would cause me additional worry, as I believe if I made a RESTful API 10 years from now, it would still look similar, as it is the way I would handle this kind of problem.

Also, I know this is not a site of legal experts and any advice I get is subjective, so I suppose I'm also looking for insight into what is the Right Thing™.

答:
Ideas can not be copyrighted. Only specific implementations of an idea fall under copyright.

But ideas can be patented. Patents on software are not valid in all jurisdictions, so when the idea happens to be patented you might still be able to distribute your software in some parts of the world but not others.


问:
What is a good way to organize service layer classes?
I had a Service layer in my app and, for a while, there's just one class for API calls

Current Scenario

MyAPI Class

authenticateApp()

authenticateUser()

Looking in the future, that class will be so huge that will be difficult to maintain it. Even if I group calls by the same module (user authenticate, user profile, etc.) it will be overpopulated.

Future Scenario

MyAPI Class

authenticateApp()

authenticateUser()

...

getSomeDataFromSomeModule()

To avoid that, how can I should create modules over several files in a way that is not visible to the other layers?

Will some patterns like the Factory Method or Decorator pattern help me? Is there some other pattern that I missed that would solve this?

答:
Looking in the future, that class will be so huge that will be
  difficult to maintain it. Even if I group calls by the same module
  (user authenticate, user profile, etc.) it will be overpopulated.

Maybe it's time to refactor into multiple classes having these 2 principles in mind:

Maximum 5 public methods by class (rule of thumb)

A class should do only one thing, but doing it well (single responsibility principle)

If there is an important number of method call to do in order to achieve a scenario, consider regrouping them in a Facade.


答:
Not a good Idea.

Since you dont have the type system in JavaScript.

Your students will never know why there are 3 different levels of int float and double


答:
Even if you did not copy code between the two projects - at least not intentionally - if your employer gets to know about the issue, he might impute this to you.

And can you be 100% sure you did not copy anything unintentionally? Given someone runs a compare tool on both source codes, can you be sure he will not find parts for which it might be debatable if they are really "newly written", or might be copied? You wrote you got have "similar class hierarchy, interfaces" - for me this sounds more than just  following the same ideas, "class hierarchy and interfaces" are things expressed in code. If the worst case happens and your employer is going to sue you, are you sure he will not find a judge with a similar opinion?

So if I were in your shoes, I would be very careful and avoid to publish your personal project openly.

Title: What exactly is copyrighted, the text of the code itself, or the design?

Body:
I am both the sole developer for a relatively small company and someone who enjoys programming as a hobby. Recently, for one of my personal projects, I started making a framework for a RESTful API and NoSQL integration that I enjoyed programming at home. Near the same time, my work assigned me to begin a project for integrating the disjointed pieces of our backend into something more easily extensible -- using a RESTful API. As I have begun to code both of these projects, I have found that they are, understandably, shaping up in a similar way (similar class hierarchy, interfaces, etc.) However, I have been programming both of them separately, without copying code from one project to another, and only doing work on work time and personal projects in my personal time.

Now, since I have no agreement stating otherwise with my work, I know (or assume) that all code I write there is copyrighted under my workplace, and not under me. And, as I said, I have not taken any code from work and used it in other projects. Also, while some aspects of both projects are similar, others are quite different (the work one does not use NoSQL because too many processes depend on SQL, for example). The similarities seem unavoidable to me, since I am writing both and I have a specific idea of how HTTP requests should be handled, data should be returned, etc.

However, I still worry about the legal implications of all this. While the code itself has not been copied between projects, the solutions have similar points, and I was wondering if only the text of code is copyrightable, or the overall solution. Could these two projects that handle the same problem in similar ways be considered derivative of one another? I.e., could my home project be considered an infringement of work?

If that answer would be yes, the similar solution would be grounds for infringement, it would cause me additional worry, as I believe if I made a RESTful API 10 years from now, it would still look similar, as it is the way I would handle this kind of problem.

Also, I know this is not a site of legal experts and any advice I get is subjective, so I suppose I'm also looking for insight into what is the Right Thing™.


问:
Is this a valid situation for returning rather than throwing an exception?
This is not something I would ever normally do, but I have a situation where some existing legacy code is being reused in a new application. The code is shared and needs to be used by both the legacy and new application. The legacy application is a reporting application and errors are reported as messages no differently to informational messages in the UI. The new application actually executes actions based on these calculations: so errors are now critical to program execution.

We have hundreds of business logic methods that sort a person into a series of buckets, where the buckets are contained in a dictionary (key is bucket number, value is true if they are in that bucket according to the calculation):

```<code>public Dictionary<int, bool> Calculation(IPerson person, out string message)
{
    try
    {
        var buckets = new Dictionary<int, bool>();

        // Do logic to determine what buckets the person is in
        // message is used by the legacy application UI...can be set to anything
    }
    catch(Exception)
    {
        message = "Some non-consistent error message";
    }

    return buckets;
}
</code>```

In each method there is an all encompassing exception block that swallows the exception (yes...I know).

For the purposes of these calculations an exception failure does not mean that the whole calculation should be discarded: if there is an exception and the person doesn't end up in all the buckets they should we don't care. The message is used to communicate back to the UI that for this person, the whole calculation may not have completed and that is considered enough. Message may also contain non error information...its not specifically an error message and when there is an error there is no consistent text to look for.

With the new application, we potentially want to take a different execution path if there was an exception: at the very least we want to consistently detect and display errors to the UI in an obvious and distinct fashion, not just as whatever text was assigned to the message variable. Also we would like to log the exception details in this new application.

I am not allowed to make a change that will alter the behaviour of the legacy application, but I can refactor the method signatures. I am proposing that the exception be caught as it is now, but to return it is an out parameter:

```<code>public Dictionary<int, bool> Calculation(IPerson person, out string message, out Exception exception)
{
    try
    {
        var buckets = new Dictionary<int, bool>();

        // Do logic to determine what buckets the person is in
        // message is used by the legacy application UI...can be set to anything
    }
    catch(Exception ex)
    {
        message = "Some non-consistent error message";
        exception = ex;
    }

    return buckets;
}
</code>```

I know this is totally non-standard and absolutely not the way exceptions are intended to be used, but in a situation where we want to report that an exception occurred that was handled...why not pass back the exception itself? keep in mind also I can't change the behaviour of the legacy application.

Thoughts? Is this still a terrible idea? Is there a better way of doing this given the constraints?

答:
I think that the requirement not to change the behavior of the legacy application is pretty restrictive. Further, I completely agree with you that the right thing to do is just throw the Exception and catch it where it needs to be caught, by the UI.

That said, given the requirement not to change the behavior, I think your solution is a tolerable compromise, given the situation. It does what you need it to do for the reasons you've stated. The only change I would make is to throw both message and Exception into it's own class, e.g.

```<code>public Dictionary<int, bool> Calculation(IPerson person, out ErrorResult result) {
    try {
    // snip
    } catch (Exception ex) {
        result.message = "Some non-consistent error message";
        result.exception = ex;
    }
}
</code>```

Mostly because of the principle of "related objects ought to be bound together in the same class".

You may even want to consider wrapping both the Dictionary and the ErrorResult class into one, larger class to remove the out parameter. In fact, I would probably do something like:

```<code>public class Result {
    Dictionary<int, bool> result;
    List<ErrorResult> errors;
}
</code>```

This way you can keep track of all the possible thrown exceptions and their messages. Your method signature would then become:

```<code>public Result Calculation(IPerson person) {
</code>```

Body:
I think that the requirement not to change the behavior of the legacy application is pretty restrictive. Further, I completely agree with you that the right thing to do is just throw the Exception and catch it where it needs to be caught, by the UI.

That said, given the requirement not to change the behavior, I think your solution is a tolerable compromise, given the situation. It does what you need it to do for the reasons you've stated. The only change I would make is to throw both message and Exception into it's own class, e.g.

public Dictionary<int, bool> Calculation(IPerson person, out ErrorResult result) {
    try {
    // snip
    } catch (Exception ex) {
        result.message = "Some non-consistent error message";
        result.exception = ex;
    }
}

Mostly because of the principle of "related objects ought to be bound together in the same class".

You may even want to consider wrapping both the Dictionary and the ErrorResult class into one, larger class to remove the out parameter. In fact, I would probably do something like:

public class Result {
    Dictionary<int, bool> result;
    List<ErrorResult> errors;
}

This way you can keep track of all the possible thrown exceptions and their messages. Your method signature would then become:

public Result Calculation(IPerson person) {


答:
You have already mentioned the modules, if the code is already making sense to be logically grouped in that manner, continue with that.

It may be unavoidable to have a gatekeeper object that grants access to the modules, but every module would control access and functionality tied to it. Going back to basics and keep it DRY and keep it SOLID help delineate those high level modules.

In terms of patterns, the structural patterns are a good place to start exploring possibilities. The creational patterns should also offer guidance on getting access to the modules from the gatekeeper.

Title: What is a good way to organize service layer classes?

Body:
I had a Service layer in my app and, for a while, there's just one class for API calls

Current Scenario

MyAPI Class

authenticateApp()

authenticateUser()

Looking in the future, that class will be so huge that will be difficult to maintain it. Even if I group calls by the same module (user authenticate, user profile, etc.) it will be overpopulated.

Future Scenario

MyAPI Class

authenticateApp()

authenticateUser()

...

getSomeDataFromSomeModule()

To avoid that, how can I should create modules over several files in a way that is not visible to the other layers?

Will some patterns like the Factory Method or Decorator pattern help me? Is there some other pattern that I missed that would solve this?


答:
JavaScript is a horribly poorly designed language, with a whole bunch of weird gotchas. I would avoid it as a first teaching language. I'd also avoid C. I think it's complexity and opacity hides the concepts you're going to want to concentrate.

I'd prefer Python. It's high level enough to make it easy to focus on core concepts, has some high quality accessible tools that mean you can introduce the debugger early on, and the immediate mode means that it's easy to "play" in it which helps a lot with learning.

However, since these students are intended to go on to C# why would you not start with that? It's a pretty good language to write in, the tools are excellent and you can start by building really usable things early on.


问:
A secondary "type system" for references?
I'm designing a language and was wondering how to incorporate C++-like references with regards to their place in the type system. I think they're useful for operations like indexing and dereferencing (v[i] returns a reference that can be assigned to, *pointer_type returns a reference to an a that behaves like an a).

Nominally in C++, a reference type like int& and its original type int are two distinct types. However, I believe that this is inconsistent with the rest of the type system: an int& can be substituted for int and they sometimes behave as they were the same type, and sometimes they don't, without explicit conversions (which is one of the reasons why references are used in the first place).

My solution would be for bindings and function arguments to essentially have a "secondary type", or rather another qualification with special rules, determining whether they are references or not. There would be two types in this secondary type system: ref and non-ref (default), and these labels would be written in places where other similar labels like const (or mut) would be -- mainly when introducing new bindings or in function types.

Thus, along with classical type mismatch errors, the compiler would report something like mismatched binding mechanism as well. For example this would happen if the programmer attempted to place a function which accepts a single integer by-reference into a list of functions which accept it by-copy (ref a -> b vs. a -> b). Although the functions would have the same type: a -> b, the binding mechanisms are incompatible (because if passed lvalues that are later assigned to, unexpected incompatible behaviour could occur).

Does this solution make sense or is it better to just wrap it in the type system and suffer inconsistencies? Are there some negative side-effects that I'm not anticipating?

To clarify: the touching points between these two type systems would have special rules. For example, there would be implicit conversions from ref to non-ref while keeping the type invariant.

答:
C++ treats int, const int, int&, and const int& as separate types with ways to convert to/from each type (except to const int or to const int&).  If you know what types you have and what types are expected, then given a list of converters, you know if you can make each passed parameter pass as an argument parameter.

Since there may also be custom converters (overloading operator =), you can simply add this to the list of converters and apply the same rules.  The biggest advantage of this approach is simplicity.

If you decide that int, const int, int&, and const int& are all the same, then const and & then become modifiers of that type.  It might be a very smart idea to come up with a way of creating custom type modifiers which declares how that type can convert to the normal type, and then using this method to create predefined type modifiers like & and const.

The compiler would then attempt to convert from one modifier to "normal" type and from normal type to the modifier present in the method argument.  If it is missing the proper conversion, then it is not the method being called (and if no such methods found, then compiler would throw an error).

For instance to call a method void doSomething(int& val) by passing to it a const int valToPass, your compiler would attempt to first convert const int valToPass to int valToPass, but no conversion would exist, and so you wouldn't call that method.  However calling doSomething(const int val) with int& valToPass would be called because there would exist a converter from int& valToPass to int valToPass, and from int valToPass to const int valToPass.

A const int& type would simply be connected to the existing int & which behaves in a similar fashion, except that from the normal type int, it must first be convertible to int & before it can convert to const int&.

In all these examples I'm using int, but these declarations would hold for all types.  The point is that the programmer using your language could create custom extensions using their keywords (so long as it doesn't conflict with existing type modifiers or keywords).

I would stay away from a secondary type, because that implies that there will necessarily be exactly two, and there is already const and & to consider, but I think that you're moving in the right direction.

I hope that helps!


问:
What is the most obscure sorting algorithm you know?
I just read about cyclesort via a sortvis.org blog post.
This is probably the most obscure one I have heard of so far, since it uses maths that I am not familiar with (detecting cycles in permutations of integer sets).

What is the most obscure one you know?

答:
I once did an in vector registers bubble sort in CRAY assembler. The machine
had a double shift instruction, which allowed you to shift the contents of a
vector register up/down by one word. Put the every other point in two vector registers, then you could do a full bubble sort without ever having to make another memory reference until you are done. Except for the N**2 nature of bubble sort it was efficient.

I also once needed to do a floating point sort of a length 4 vector as fast as possible for a single sort. Did it by table lookup (the sign bit of A2-A1 is one bit, sign of A3-A1 forms another bit ..., then you look up the permutation vector in a table. It was actually the fastest solution I could come up with. Doesn't work well on modern architectures though, the floating and integer units are too separated.


问:
Why is it so bad to read data from a database "owned" by a different microservice
I have recently read this excellent article on the microservice architecture: http://www.infoq.com/articles/microservices-intro

It states that when you load a web page on Amazon, then 100+ microservices cooperate to serve that page.

That article describes that all communication between microservices can only go through an API. My question is why it is so bad to say that all database writes can only go through an API, but you are free to read directly from the databases of the various micro services. One could for example say that only a few database views are accessible outside the micro service so that the team maintaining the micro service know that as long as they keep these views intact then they can change the database structure of their micro service as much as they want.

Am I missing something here? Is there some other reason why data should only be read via an API?

Needless to say, my company is significantly smaller than Amazon (and always will be) and the maximum number of users we can ever have is about 5 million.

答: State management (potentially a database) can be deployed in the Microservice's container and exposed via an API. The a Microservice's database is not visible to other systems outside the container - only the API. Alternatively you could have another service (e.g. a cache) manage state via an API.  Having all the Microservice's dependencies (other than API calls to other services) within a single deployable container is a key distinction in the architecture. If one does not get that go back and study the architecture. </p>