答:
After having a similar query about Time complexity, which was cleared by JanHudec (Why does this algorithm work in O(n m)?), I now have an answer to my problem.

The time complexity should be seen from the iterations of the innermost loop. k gets incremented at most m times in every iteration of the while loop.
Hence, there is an O(n m) complexity.

Title: Why does this implementation of Dijkstra's algorithm work in O(n^2)?

Body:
Here is the code I use for implementing Dijkstra's algorithm. Consider a graph with n vertices and m edges. Shouldn't it run in O(n^2 m) ? Someone may say that there are n vertices and each edge gets processed once, therefore it is O(n m). But the while loop can run at most n times, the 1st for loop at most n times and the second for loop at most m times. Therefore, this should be an O(n^2 m) implementation.

Here X is a vector, head[] and shortest[] are arrays.

```<code>X.push_back(1);
head[1] = true;

while(X.size()!=MAX) {
    min = INT_MAX;

    for(j=0;j<X.size();j++) {
        node = X[j];

        for(k=0;k<graph[node].size();k++) {
            v = graph[node][k];

            if(head[v]==true)
                continue;

            if(min>(weight[node][k]+shortest[node])) {
                pos = v;
                min = weight[node][k]+shortest[node];
            }
       }
  }

  shortest[pos] = min;
  head[pos] = true;

  X.push_back(pos);
}
</code>```


问:
Which languages are used today for low-level programming?
When I hear low-level programming, such as for drivers, embedded systems, operating systems, etc., I immediately think about C and perhaps C++. But mainly C.

But what other languages are also used for these kind of tasks? Today, I mean, not what has been used.

答:
Normally low level programming such as driver programming is a mixture of an assembly language and C.

The assembly language is used to talk to the hardware and C is used to talk to the kernel.

ContentLicense: CC BY-SA 2.5


问:
Is this a good pattern: replacing a long function with a series of lambdas?
I recently run into the following situation.

```<code>class A{
public:
    void calculate(T inputs);
}
</code>```

Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up. Now, calculate() turns out to be quite a long and complicated function. I perceive three possible structures for it:

write it as a wall of text - advantages - all the information is in one place

write private utility functions in the class and use them in calculate's body - disadvantages - the rest of the class doesn't know/care/understand about those methods

write calculate the following way:

```<code>void A::calculate(T inputs){
    auto lambda1 = () [] {};
    auto lambda2 = () [] {};
    auto lambda3 = () [] {};

    lambda1(inputs.first_logical_chunk);
    lambda2(inputs.second_logical_chunk);
    lambda3(inputs.third_logical_chunk);
}
</code>```

Can this be considered a good or bad practice? Does this approach reveal any problems? All in all, should I consider this as a good approach when I am again faced with the same situation?

EDIT:

```<code>class A{
    ...
public:
    // Reconfiguration of the algorithm.
    void set_colour(double colour);
    void set_density(double density);
    void set_predelay(unsigned long microseconds);
    void set_reverb_time(double reverb_time, double room_size);
    void set_drywet(double left, double right);
    void set_room_size(double value);;

private:
    // Sub-model objects.
    ...
}
</code>```

All those methods:

get a value

compute some other values, without using state

call some of the "sub-model objects" to change their state.

It turns out that, excepting set_room_size(), those methods simply pass the requested value to sub-objects. set_room_size(), on the other hand, does a couple of screens of obscure formulas and then (2)does half a screen of calling sub-objects setters to apply the various obtained results. Therefore, I have separated the function into two lambdas and call them at the end of the function. Had I been able to split it into more logical chunks, I would have isolated more lambdas.

Regardless, the goal of the current question is to determine if that way of thinking should persist, or is it at best not adding value (readability, maintainability, debug-ability etc.).

答:
I think you made a bad assumption:

Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up.

I disagree with this. For example, if I had a class that represents a car, I would definitely want to split it up, because I surely want a smaller class to  represent the tires.

You should split this function up into smaller private functions. If it really seems separated from the other part of the class, then that may be a sign that the class should be separated. Of course it is hard to tell without an explicit example.

I don't really see the advantage of using lambda functions in this case, because it does not really make the code cleaner. They were created to aid functional style programming, but this is not that.

What you wrote resembles a little bit to Javascript style nested function objects. Which is again a sign that they belong tightly together. Are you sure, that you shouldn't make a separate class for them?

To summarize, I do not think that this is a good pattern.

UPDATE

If you don't see any way to encapsulate this functionality in a meaningful class, then you can create file scoped helper functions, that are not members of your class. This is C++ after all, OO design is not a must.

ContentLicense: CC BY-SA 3.0


问:
Is using data generated using AGPL-v3 licensed code considered distribution?
I'm considering using parts of a GNU Affero General Public License v3 (GNU AGPL v3) licensed library in a commercial context, but we obviously can't afford to release our whole code-base.

We would only need the library for a crawler-like step in the backend. If we use the library in the crawler to generate data and push it into a database, and have our web-app hosted by another program/process entirely that reads from the database, are we legally required to release any of our source code? The web-facing ("distributed") code would not call the AGPL-v3 licensed code, only use it's generated output.

Any insight is greatly appreciated!

答:
The AGPL is the Affero General Public License, and offers some protection for users from proprietary lock-in when they use a web service powered by free code.

There are a couple of recent versions from different authors (Affero, Inc, and the Free Software Foundation respectively):

Affero General Public License v2 http://www.affero.org/agpl2.html

GNU Affero General Public License v3 http://www.gnu.org/licenses/agpl-3.0.html

Know which one you are subject to.

Your lawyer needs not only to decide whether you meet the definition of 'distribution' in your jurisdiction, but also whether your entire code base meets the definition of 'linking'. Because you only need to publish the source code that links to the library.  In general terms, code that only reads a database populated by AGPL code is unlikely to be considered 'linked' to that code so you won't have to publish the source for that, though I don't know of precedent or opinion for that.

Update There is guidance from the FSF (authors of the GNU AGPL) that says:

However, in many cases you can distribute the GPL-covered software alongside your proprietary system. To do this validly, you must make sure that the free and non-free programs communicate at arms length, that they are not combined in a way that would make them effectively a single program.

The difference between this and “incorporating” the GPL-covered software is partly a matter of substance and partly form. The substantive part is this: if the two programs are combined so that they become effectively two parts of one program, then you can't treat them as two separate programs. So the GPL has to cover the whole thing.

If the two programs remain well separated, like the compiler and the kernel, or like an editor and a shell, then you can treat them as two separate programs—but you have to do it properly. The issue is simply one of form: how you describe what you are doing. Why do we care about this? Because we want to make sure the users clearly understand the free status of the GPL-covered software in the collection.

*(Emphasis mine) From the GPL FAQ which would also apply to the GNU AGPL http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystem *

An alternative is to purchase a commercial license from the author(s) of your library with terms that suit your business better, update or otherwise negotiate with the author(s) to ensure they intended to permit your planned use.

More general information at AGPL - what you can do and what you can't

This is not legal advice but background information, and I am not a lawyer.


问:
Is the 'finally' portion of a 'try ... catch ... finally' construct even necessary?
Some languages (such as C++ and early versions of PHP) don't support the finally part of a try ... catch ... finally construct. Is finally ever necessary? Because the code in it always runs, why wouldn't/shouldn't I just place that code after a try ... catch block without a finally clause? Why use one? (I'm looking for a reason/motivation for using/not using finally, not a reason to do away with 'catch' or why it's legal to do so.)

答:
Like so many other unusual things about the C++ language, the lack of a try/finally construct is a design flaw, if you can even call it that in a language that frequently appears to not have had any actual design work done at all.

RAII (the use of scope-based deterministic destructor invocation on stack-based objects for cleanup) has two serious flaws.  The first is that it requires the use of stack based objects, which are an abomination that violate the Liskov Substitution Principle.  There are plenty of good reasons why no other OO language before or since C++ has used them--within epsilon; D doesn't count as it's based heavily on C++ and has no market share anyway--and explaining the problems they cause is beyond the scope of this answer.

Second, what finally can do is a superset of object destruction.  Much of what is done with RAII in C++ would be described in the Delphi language, which does not have garbage collection, with the following pattern:

```<code>myObject := MyClass.Create(arguments);
try
   doSomething(myObject);
finally
   myObject.Free();
end;
</code>```

This is the RAII pattern made explicit; if you were to create a C++ routine that contains only the equivalent to the first and third lines above, what the compiler would generate would end up looking like what I wrote in its basic structure.  And because it's the only access to the try/finally construct that C++ provides, C++ developers end up with a rather myopic view of try/finally: when all you have is a hammer, everything starts to look like a destructor, so to speak.

But there are other things that an experienced developer can do with a finally construct.  It's not about deterministic destruction, even in the face of an exception being raised; it's about deterministic code execution, even in the face of an exception being raised.

Here's another thing you might commonly see in Delphi code:  A dataset object with user controls bound to it.  The dataset holds data from an external source, and the controls reflect the state of the data.  If you're about to load a bunch of data into your dataset, you will want to temporarily disable the data binding so that it doesn't do strange things to your UI, trying to update it over and over with every new record that's entered, so you would code it like this:

```<code>dataset.DisableControls();
try
   LoadData(dataset);
finally
   dataset.EnableControls();
end;
</code>```

Clearly, there is no object being destroyed here, and no need for one.  The code is simple, concise, explicit, and efficient.

How would this be done in C++?  Well, first you would have to code up an entire class.  It would probably be called DatasetEnabler or somesuch thing.  Its entire existence would be as a RAII helper.  Then you would need to do something like this:

```<code>dataset.DisableControls();
{
   raiiGuard = DatasetEnabler(dataset);
   LoadData(dataset);
}
</code>```

Yes, those apparently-superfluous curly braces are necessary to manage the proper scoping and ensure that the dataset gets re-enabled immediately and not at the end of the method.  So what you end up with does not take less lines of code (unless you use Egyptian braces).  It requires a superfluous object to be created, which has overhead. (Isn't C++ code is supposed to be fast?)  It is not explicit, but instead relies upon compiler magic.  The code that gets executed is described nowhere in this method, but instead resides in an entirely different class, possibly in an entirely different file.  In short, it is in no way a better solution than being able to write the try/finally block yourself.

This kind of problem is common enough in language design that there's a name for it: abstraction inversion.  It occurs when a high-level construct is built on top of a low-level construct, and then the low-level construct is not directly supported in the language, requiring those who wish to use it to re-implement it in terms of the high-level construct, often at steep penalties to both code readability and efficiency.

Body:
Like so many other unusual things about the C++ language, the lack of a try/finally construct is a design flaw, if you can even call it that in a language that frequently appears to not have had any actual design work done at all.

RAII (the use of scope-based deterministic destructor invocation on stack-based objects for cleanup) has two serious flaws.  The first is that it requires the use of stack based objects, which are an abomination that violate the Liskov Substitution Principle.  There are plenty of good reasons why no other OO language before or since C++ has used them--within epsilon; D doesn't count as it's based heavily on C++ and has no market share anyway--and explaining the problems they cause is beyond the scope of this answer.

Second, what finally can do is a superset of object destruction.  Much of what is done with RAII in C++ would be described in the Delphi language, which does not have garbage collection, with the following pattern:

myObject := MyClass.Create(arguments);
try
   doSomething(myObject);
finally
   myObject.Free();
end;

This is the RAII pattern made explicit; if you were to create a C++ routine that contains only the equivalent to the first and third lines above, what the compiler would generate would end up looking like what I wrote in its basic structure.  And because it's the only access to the try/finally construct that C++ provides, C++ developers end up with a rather myopic view of try/finally: when all you have is a hammer, everything starts to look like a destructor, so to speak.

But there are other things that an experienced developer can do with a finally construct.  It's not about deterministic destruction, even in the face of an exception being raised; it's about deterministic code execution, even in the face of an exception being raised.

Here's another thing you might commonly see in Delphi code:  A dataset object with user controls bound to it.  The dataset holds data from an external source, and the controls reflect the state of the data.  If you're about to load a bunch of data into your dataset, you will want to temporarily disable the data binding so that it doesn't do strange things to your UI, trying to update it over and over with every new record that's entered, so you would code it like this:

dataset.DisableControls();
try
   LoadData(dataset);
finally
   dataset.EnableControls();
end;

Clearly, there is no object being destroyed here, and no need for one.  The code is simple, concise, explicit, and efficient.

How would this be done in C++?  Well, first you would have to code up an entire class.  It would probably be called DatasetEnabler or somesuch thing.  Its entire existence would be as a RAII helper.  Then you would need to do something like this:

dataset.DisableControls();
{
   raiiGuard = DatasetEnabler(dataset);
   LoadData(dataset);
}

Yes, those apparently-superfluous curly braces are necessary to manage the proper scoping and ensure that the dataset gets re-enabled immediately and not at the end of the method.  So what you end up with does not take less lines of code (unless you use Egyptian braces).  It requires a superfluous object to be created, which has overhead. (Isn't C++ code is supposed to be fast?)  It is not explicit, but instead relies upon compiler magic.  The code that gets executed is described nowhere in this method, but instead resides in an entirely different class, possibly in an entirely different file.  In short, it is in no way a better solution than being able to write the try/finally block yourself.

This kind of problem is common enough in language design that there's a name for it: abstraction inversion.  It occurs when a high-level construct is built on top of a low-level construct, and then the low-level construct is not directly supported in the language, requiring those who wish to use it to re-implement it in terms of the high-level construct, often at steep penalties to both code readability and efficiency.


答:
Can't believe nobody else has raised this (no pun intended) - you don't need a catch clause!

This is perfectly reasonable:

```<code>try
{
   AcquireManyResources();
   DoSomethingThatMightFail();
}
finally
{
   CleanUpThoseResources();
}
</code>```

No catch clause anywhere is sight, because this method can't do anything useful with those exceptions; they are left to propagate back up the call stack to a handler that can.  Catching and re-throwing exceptions in every method is a Bad Idea, especially if you're just re-throwing the same exception.  It completely goes against how Structured Exception Handling is supposed to work (and is pretty close to returning an "error code" from every method, just in the "shape" of an Exception).

What this method does have to do, though, it to clean up after itself, so that the "Outside World" never needs to know anything about the mess that it got itself into.  The finally clause does just that - no matter how the called methods behave, the finally clause will be executed "on the way out" of the method (and the same is true for every finally clause between the point at which the Exception is thrown and the eventual catch clause that handles it); each one is run as the call stack "unwinds".

Title: Is the 'finally' portion of a 'try ... catch ... finally' construct even necessary?

Body: Some languages (such as C++ and early versions of PHP) don't support the finally part of a try ... catch ... finally construct. Is finally ever necessary? Because the code in it always runs, why wouldn't/shouldn't I just place that code after a try ... catch block without a finally clause? Why use one? (I'm looking for a reason/motivation for using/not using finally, not a reason to do away with 'catch' or why it's legal to do so.)

Body:
Can't believe nobody else has raised this (no pun intended) - you don't need a catch clause!

This is perfectly reasonable:

try
{
   AcquireManyResources();
   DoSomethingThatMightFail();
}
finally
{
   CleanUpThoseResources();
}

No catch clause anywhere is sight, because this method can't do anything useful with those exceptions; they are left to propagate back up the call stack to a handler that can.  Catching and re-throwing exceptions in every method is a Bad Idea, especially if you're just re-throwing the same exception.  It completely goes against how Structured Exception Handling is supposed to work (and is pretty close to returning an "error code" from every method, just in the "shape" of an Exception).

What this method does have to do, though, it to clean up after itself, so that the "Outside World" never needs to know anything about the mess that it got itself into.  The finally clause does just that - no matter how the called methods behave, the finally clause will be executed "on the way out" of the method (and the same is true for every finally clause between the point at which the Exception is thrown and the eventual catch clause that handles it); each one is run as the call stack "unwinds".


答: I did some research for 8-bit programming a little while ago (hobby related; I wanted to try building some basic electronics). Other than C and Assembly, the only languages I found mentioned favorably for these tasks were Scheme and Forth.</p>

Title: Which languages are used today for low-level programming?

Body:
When I hear low-level programming, such as for drivers, embedded systems, operating systems, etc., I immediately think about C and perhaps C++. But mainly C.

But what other languages are also used for these kind of tasks? Today, I mean, not what has been used.


问:
How shall I handle event loop exceptions?
What is the best practice for handling exceptions thrown from event handlers/listeners in a event loop? For example:

```<code>class EventLoop
{
  public:
  void start(); //create a thread which calls run();
  void run()
  {
    while(true)
    {
      listener.waitEvent();  //blocks until an event occured
      try
      {
        listener.processEvent(); //calls given handler
      }
      catch(const Exception& excp)
      {
        //The exception is thrown from another class
        //What shall I do?
      }
    }
  }
  //other code..
}
//Sample event loop usage:
EventLoop el;
SampleListener sampleListener;
el.setListener(sampleListener);
el.start();
//other work..
</code>```

In this example, when processEvent() throws an exception, the event loop thread should be able to continue to run. Also, the error should be handled. One possible solution may be add an errorOccured() method to listener. In catch block the method could be invoked.
But it increases complexity of the program seriously.

Your suggestions?
Thanks..

答:
What I do is that I just log the exception class name, the exception message, and the full exception stack trace.  I do not think that there is anything else that can be done, nor anything else that needs to be done.

I consider this an integral part of the notifier pattern: the fact that an observer may fail should not affect the notifier in any way whatsoever, nor should it prevent any other observers from observing the notification.

Some people believe that once an exception has been thrown, the application should terminate, but I think that this is terribly short-sighted.


问:
Proper way to refactor multiple if based conditions
I took over a large legacy code base. It has a code like this:

```<code>if ($route == 'login' || $route == 'logout' || $route == 'forgot-password') {
    return;
}

if ($loggedInUser == false && $currentRoute !== 'login') {
    redirectTo('login', 'You need login');
    return;
}

if ($loggedInUser) {
    if ($loggedInUser['passwordChanged'] == false && $currentRoute !== 'change-password') {
        redirectTo('change-password', 'You need change your password');
        return;
    }

    if ($loggedInUser['profileUpdated'] == false && $currentRoute !== 'update-profile') {
        redirectTo('update-profile');
        return;
    }

    if ($loggedInUser['role'] !== 'admin') {
        redirectTo('logout');
        return;
    }
}
</code>```

I think i can make each condition a closure function. Put all of them in an array and loop over array and run each function.

I'm wondering if there is a more elegant way to do this controls.

答:
Karnaugh Maps are a great way to reduce logic complexity. Karnaugh Maps notwithstanding you want to clearly define the various states and their basic transition logic. Regardless of how much you can reduce the number and complexity of logic expressions you must carefully analyze states (for example "UpdatingProfile") and make methods accordingly.

The closure idea may be fine if your overall design is more functional than object oriented. However it may just be a pointless exercise in sweeping dirt under the rug; Do not make code maintenance worse.


问:
which is a better practice one method that does everything or a series of different methods?
I'm working with asp.net and c#

Lets say I have a bunch of drop-downs and I want to bind data from a database, is it better to make a master-bind method that loops each one and gets the parameters to bind them all or make a method for each one of the drop-downs?

Right now the program has the masterbind method that binds all the dropdowns, it does its work, but since I got asked to rebuild that whole form, I wanted to know which one is optimal. I've searched the web... some people say that one method is better others say that individual methods are better.

答: I think that is not good technique. Method should adhere single responsibility principle. Which means each method should have single responsibility. So it's better if you go with different method to bind each drop down. That's really help lot in future.</p>


问:
How useful are IT headhunters/recruiters when looking for a new job?
Since they exist for several fields with varying degrees of usefulness, I'm curious as to the reputation of headhunters/recruiters that focus solely on IT professionals (e.g. programmers, software engineers, CIOs, etc) when it comes to finding a new job.

Are they actually useful or is it fairly hit or miss? Does the old adage of only working with a limited number apply or can you safely give you resume/CV to several of them?

答:
I'd say it is hit and miss.  Some recruiters have been good but just as many if not more have been lousy for me.  Course this was just in Seattle and Calgary, but in each case a limited supply is better as some agencies will be applying on the same position and getting applied twice or more will get you disqualified generally.  Thus, I'd be careful about having too many and not being aware of where your resume is going as sometimes recruiters may just try to apply you everywhere under the sun to get their commission, but this problem exists in every field where there are the a-holes that ruin it for everyone else.

Don't forget to maintain contact with recruiters and headhunters as sometimes they may forward new positions to people they would see as preferred in some regards and some recruiters may change companies and thus the person you may have used before is now somewhere else.


答: It depends on the complexity of the binding operation. If it's just one line to populate the dropdown, encapsulating that in a method is unnecessary. If it's a dozen lines of database queries and looping over the result and whatever else, having a populateDropdownA method makes sense.</p>

Title: which is a better practice one method that does everything or a series of different methods?

Body:
I'm working with asp.net and c#

Lets say I have a bunch of drop-downs and I want to bind data from a database, is it better to make a master-bind method that loops each one and gets the parameters to bind them all or make a method for each one of the drop-downs?

Right now the program has the masterbind method that binds all the dropdowns, it does its work, but since I got asked to rebuild that whole form, I wanted to know which one is optimal. I've searched the web... some people say that one method is better others say that individual methods are better.


问:
Small code, big test
I have this code in a controller of an MVC implementation:

```<code>public void execute() {
        try {
            String path = userSelectsFile();
            if ( path == null ) return; //Just returns if the user press "Cancel"

            //Load the data
            Collection<Info> infos = Infos.fromJSON(getInputReader(path));
            //Show the data in the interface
            new ShowTransformationsInTree(win(), infos, win().getTree()).execute();
        } catch (Exception e) {
            new ComplainAction(win(), "Unable to...blah, blah", e).execute();
        }
    }
</code>```

To test this, I have to mock the user interface to show file dialog and make getInputReader method an abstract factory method.

Test code:

```<code>    /**
     * Mocks the LoadTransformationsAction so the factory method getReader returns a ByteInputStream
     */
    public class MockLoadTransformationsAction extends LoadTransformationsAction {
        //CONSTRUCTOR REMOVED FOR CLARITY.....

        @Override
        protected InputStreamReader getInputReader(String path) {
            assertEquals(FAKE_ABSOLUTE_PATH, path);
            return new InputStreamReader(
                    new ByteArrayInputStream(TestHelpers.createDataBytes());
        }
    }

    /**
     * Test the proper loading of the data.
     */
    @Test
    public void testLoadData(@Mocked final FileChooser anyChooser) {
        new Expectations() {{
            //Mocks the IntelliJ idea API
            FileChooser.chooseFile(null, null, null); result = new MyFakeVirtualFile(); //Returns a fixed path
        }};

        //Loads the data from the JSON file
        MainToolWin m = new FakeMainToolWin();
        LoadTransformationsAction action = new MockLoadTransformationsAction(
                m, new FakeProject(), new MockInputProgram());
        action.execute();

        //Test that the transformations are in the UI Tree
        DefaultTreeModel model = (DefaultTreeModel)m.getTree().getModel();
        assertEquals(2, model.getChildCount(model.getRoot()));
        assertEquals(3, model.getChildCount(model.getChild(model.getRoot(), 0)));
    }
</code>```

Questions:

Am I doing too much to test too little?

As you can see there are mock and fake objects all the way. Can so much mocking can make my test unreliable?

Is there a better design?

答:
Yes, too many or too complicated mock objects are a bad thing.  Yes, there is a better design, and I have been toying with the idea in my mind for years. Unfortunately, I cannot fully explain it here because the paper that I am writing about it is not complete yet.  But, in coarse terms, here is what is happening:

You are mixing business logic with GUI logic, and GUIs are generally very hard to test. You are already making some effort to separate the two, as evidenced by your use of a (presumably GUI-agnostic) tree model data structure, but you are not going all the way with this idea, since you are only making this tree available to your business logic via a "main tool window" which is a GUI concept.

The notion of presenting the user with the opportunity to select a file, which they may cancel, is part of your business logic.  The fact that you use a GUI to accomplish this is irrelevant: you could achieve the same thing with a command-line interface, asking the user to type the filename, and allowing for an empty filename to mean 'cancel'.

So, if you completely isolated all your business logic from the GUI-related code, then your business logic would be fully testable with no mock objects.  (Not just a few simple mock objects, but actually zero mock objects.)

Generally, the presence of a mock object in testing means that the design is not perfect.  Quite often an imperfect design which requires mock objects to test is a pragmatic compromise, but you seem to be asking what's best, so, that's what's best.

EDIT:

After discussing it a bit, it turns out that your main concern is the accessing of the data in the file. Here is what I have to say about this:

(And yes, now it seems like this question is more suitable for codereview.stackexchange.com.)

Currently, your business logic needs some "Infos" to work with, but it contains specific hard-coded knowledge of the fact that these "Infos" are coming from JSON; furthermore, it contains specific hard-coded knowledge of the fact that this JSON comes from a file.  (By virtue of the 'path' variable.) I think that's a bit problematic.  If your business logic needs some "Infos" to work with, it should not be concerned with how they can be obtained.  It should just be given those infos from the outside.  So, instead of having to mock the creation of a stream, your test code would just be constructing test instances of the "Infos" class to test your business logic with.

Then, you would need a separate set of tests to make sure that your Infos.fromJSON() method works correctly, and these tests would belong to the "Infos" class, not to your controller class.  (Maybe you already have them.)

Essentially, what you would be doing with such an approach is that you would be isolating your business logic from the file system, and from text-file-format-choice (JSON) considerations, which is just as crucial as isolating it from the GUI.

If you don't want to do all this, then you have to create precisely that mock object which you have created; this should not come as a surprise, and it is actually not an awful lot of work compared to what you need to accomplish.

Title: Small code, big test


问:
WCF Project Structure & Maintainability
We are working on a medium scale WCF project configured to use per call instancing and wondering weather it's a good practice to create classes per service method to hold the business logic since each service method deals with a single operation and business logic is quite complex ?

Do we need to worry about number of class files in a project considering maintainability (Approximately 100 classes holding service method implementations) ?

答:
Creating a separate class per service method is a bit of overkill, but it absolutely makes sense to have different classes for unrelated methods. So you can have the UserService class to add, update, delete, reset password, or whatever and a FooService to handle all the stuff related to Foo. Ideally you should have a separate class library project where all the classes that hold business logic are kept and a WCF project where all the business methods are called from and the logic to handle the services is kept.

As far as number of files goes, having that many in a project isn't really a problem, they should definitely be separated into multiple folders because its way easier to look at a list of 5-10 folders with 10-20 files than one big list of 100 files.

Title: WCF Project Structure & Maintainability


答:
For copyright, a program and the data that the program operates on (or the data that come out of the program) are considered to be completely separate works and the copyright license of the one does not affect how you can license the other.

The one exception is if the program copies (part of) its internals to the output. Then the output is considered to be a derived work of both the input and the program portions that were copied over and the licenses of both influence what you can do.

For example, it is perfectly possible to write a fully closed-source application using an editor that is distributed under a strong copyleft license (like GPL or AGPL). The license of the editor does not influence in any way how I can license my code.

An example of the exceptional case is when you use Bison to generate a parser. The output from Bison contains significant portions of code written by the Bison authors, so they have a say in how you can use that output. (Incidentally, the portions that Bison copies over are specifically exempted from the GPL requirements that the rest of Bison falls under).

Title: Is using data generated using AGPL-v3 licensed code considered distribution?

Body:
I'm considering using parts of a GNU Affero General Public License v3 (GNU AGPL v3) licensed library in a commercial context, but we obviously can't afford to release our whole code-base.

We would only need the library for a crawler-like step in the backend. If we use the library in the crawler to generate data and push it into a database, and have our web-app hosted by another program/process entirely that reads from the database, are we legally required to release any of our source code? The web-facing ("distributed") code would not call the AGPL-v3 licensed code, only use it's generated output.

Any insight is greatly appreciated!


答:
In this case, the difficult legal test is deciding whether your data-consuming application can legally be considered "combined with" your AGPL data-producing application. The FSF proposes that two programs must communicate "at arms length" to be considered separate works. (The tricky bit about this rule is that no one is entirely sure how long programs' arms are.)

First, we can rule out any AGPL requirements being transfered via data output, by consulting the GPL FAQ. There is a question that directly addresses this (from the other side -- trying and failing to make GPL rules apply to generated data):

Is there some way that I can GPL the output people get from use of my program? For example, if my program is used to develop hardware designs, can I require that these designs must be free?

In general this is legally impossible; copyright law does not give you any say in the use of the output people make from their data using your program. If the user uses your program to enter or convert his own data, the copyright on the output belongs to him, not you. More generally, when a program translates its input into some other form, the copyright status of the output inherits that of the input it was generated from.

So the only way you have a say in the use of the output is if substantial parts of the output are copied (more or less) from text in your program...

Thus, as long as the AGPL crawler doesn't include any GPL-licensed data in its output (and I see no reason whatsoever why a Web crawler would do so), then the generated data itself caries no burden of AGPL responsibility.

Still, it could be the case that the data-consuming code might be legally considered part of the same program as the AGPL data-producing code, in which case the AGPL would apply to the entire work. Without seeing your architecture (and possibly without the final ruling a judge), it's not possible for me to say whether the two components can be called one work, but the information you've presented strongly suggests the two components appear to be separate works, legally speaking. Again, from the FAQ:

Where's the line between two separate programs, and one program with two parts? This is a legal question, which ultimately judges will decide. We believe that a proper criterion depends both on the mechanism of communication (exec, pipes, rpc, function calls within a shared address space, etc.) and the semantics of the communication (what kinds of information are interchanged).

If the modules are included in the same executable file, they are definitely combined in one program. If modules are designed to run linked together in a shared address space, that almost surely means combining them into one program.

By contrast, pipes, sockets and command-line arguments are communication mechanisms normally used between two separate programs. So when they are used for communication, the modules normally are separate programs. But if the semantics of the communication are intimate enough, exchanging complex internal data structures, that too could be a basis to consider the two parts as combined into a larger program.

It seems that writing to and reading from a database falls in the same broad category as "pipes, sockets and command-line arguments." Your data-consuming code could run without the data-producing code running on the same computer at all: you could have one system generate a database, and then pass the database to another system that consumes it. From this point of view, it seems clear to me (through not a surefire legal certainty) that the programs are separate works, and a user who interacts with your data-consuming Web process is not also interacting with your data-producing AGPL code.


问:
Best way to work easily with a database in remote programs?
In Database 101 you learned never to distribute the sensitive database password along with your program, since all a person has to do is reverse engineer the program, find where you actually need the original password for authentication, then echo/print that line. However when you have multiple remote programs that need to talk to a central database, what do you do?

My hackish solutions used to involve PHP, tons of GET variables, and JSON. I would make a request to the server with a set mode and parameters, then parse the JSON output. It was buggy, not entirely secure (only slowed an attacker down) since I didn't have any registration mechanism, hard to scale, and made all existing ORM's useless. Besides, it was attempting to reinvent SSH or SSL, not something that's too terribly smart.

What's the alternative though? What other options are out there that can provide security for the database while making it easy on me?

答:
Wrapping the database in a services/API layer is the most common way to do this.

At the most basic level provide full ORM mapping, but generally you would provide endpoints that provide different  create / update / result features.

Like your hackish PHP solution, only good :)


问:
GPLv3 + commercial license on the same project?
I'm trying to find a solution to publish my source as open source just for personal and no-profit use, and sell licenses for commercial use.

I see Packery which uses GPLv3 for non commercial, and a custom license for commercial.

For what I know, everything under GPLv3 can be used everywhere without any limitation, so how can it works for Packery?

Can I do the same?

答:
Definitly. It is called Multy-Licencing, and it is quite common:

http://en.wikipedia.org/wiki/Multi-licensing

The point is that you as a copy right holder can publish your work under as many separate licence as you like.

UPDATE

Typical use cases are these:

You are developing a library. You create a GPL version for opensource projects to use, and a comercial licenced version for the closed sourced projects. The GPL licence prohibits incorporation in closed source software, so these projects must choose the comercial licence. Qt has a similar licencing scheme.

You are developing an end user software. You create a GPL version what everyone can use (you are not allowed to add any restrictions), and a comercial version with additional functionality. Those who need the additional functionality must choose the comercial licence.


问:
Is having a bi directional message queue a design smell?
I have an architecture with 1 backend server and multiple frontend servers.

The frontend servers are connected in a bi-directional (web sockets) connection to clients so they can send messages to clients.

The frontend and backend are connected through a message bus.
There is one queue for frontend to backend messages and another queue for backend to frontend messages.

For example, when a client requests an operation, the frontend sends the request to the backend and acknowledges the client the request was sent.

Sometimes, when the backend finishes handling a request, it sends a status message to the frontend who forwards it to the client that requested the operation.

I've never seen anything similar. Usually the communications only go one way - from frontend to backend.

I'm worried, am I doing something bizarre?

I came up with this architecture because of the bi-directional nature of web sockets. This way the server can notify clients as soon as a request is processed.

答:
Communications do not usually only go one way.  Parties usually communicate using request-response pairs, which are clearly not one way.  I presume that you already know this, so what you are probably thinking when you say "one-way" is not how information flows, but who initiates the requests.

So, yes, the way we usually do things is that only one of the parties initiates requests.  Which means that the other party always sends responses.

But there is an exception: the "callback", otherwise known as the "notifier-observer" pattern.  It is perfectly fine for one side to send a "register observer" request to which the other side will immediately respond with an "observer registered" response and then, in the future, with one or more "event observation" responses.

Your terminology with "front-end servers" and "back-end servers" and other unrelated entities you call "clients" only confuses things, and you should not have brought it into the discussion.  Things are very simple: Within the context of a communication session between two parties, the requesting party is always called a client, and the responding party is always called a server.  In your case, your server is what you call a "back-end server", and your client is what you call a "front-end server".

EDIT:

Of course, in order to accomplish two-way communication you need to employ two queues.  I have worked on one large-scale system which employed two queues per pair of modules that communicated, (one queue for each "way" in the "two-way",) so trust me, it is not something bizarre.


答:
No, this is not generally a good pattern

What you're doing is breaking up a function into smaller functions using lambda.  However, there is a much better tool for breaking up functions: functions.

Lambdas work, as you have seen, but they mean much much much much much more than simply breaking up a function into local bits.  Lambdas do:

Closures.  You can use variables in the outer scope inside the lambda.  This is very powerful and very complicated.

Reassignment.  While your example make it hard to do assignment, one always has to pay attention to the idea that code may swap functions at any time.

First-class functions.  You can pass a lambda function to another function, doing something known as "functional programming."

The instant you bring lambdas into the mix, the next developer to look at the code must immediately mentally load all of those rules in preparation for seeing how your code works.  They don't know that you're not going to use all that functionality.  This is very expensive, compared to the alternatives.

It's like using a back-hoe to do your gardening.  You know that you're only using it for digging little holes for this year's flowers, but the neighbors will get nervous.

Consider that all you are doing is grouping your source code visually.  The compiler doesn't actually care that you curried things with lambdas.  In fact, I'd expect the optimizer to immediately undo everything you just did when it compiles.  You are purely catering to the next reader (Thanks for doing that, even if we disagree on methodology!  Code is read far more often than it is written!).  All you are doing is grouping functionality.

Functions placed locally within the stream of source code would do just as well, without invoking lambda.  Again, all that matters is that the reader can read it.

Comments at the top of the function saying "we're dividing this function into three parts," followed by big long lines of // ------------------ between each part.

You can also put each part of the calculation into its own scope.  This has the bonus of immediately proving beyond all doubt that there is no variable sharing between parts.

EDIT: From seeing your edit with example code, I'm leaning towards the comment notation being the cleanest, with brackets to enforce the boundaries that the comments suggest.  However, if any of the functionality was reusable in other functions, I'd recommend using functions instead

```<code>void A::set_room_size(double value)
{
    {
        // Part 1: {description of part 1}
        ...
    }
    // ------------------------
    {
        // Part 2: {description of part 2}
        ...
    }
    // ------------------------
    {
        // Part 3: {description of part 3}
        ...
    }
}
</code>```

Title: Is this a good pattern: replacing a long function with a series of lambdas?

Body:
I recently run into the following situation.

```<code>class A{
public:
    void calculate(T inputs);
}
</code>```

Firstly, A represents an object in the physical world, which is a strong argument for not splitting the class up. Now, calculate() turns out to be quite a long and complicated function. I perceive three possible structures for it:

write it as a wall of text - advantages - all the information is in one place

write private utility functions in the class and use them in calculate's body - disadvantages - the rest of the class doesn't know/care/understand about those methods

write calculate the following way:

```<code>void A::calculate(T inputs){
    auto lambda1 = () [] {};
    auto lambda2 = () [] {};
    auto lambda3 = () [] {};

    lambda1(inputs.first_logical_chunk);
    lambda2(inputs.second_logical_chunk);
    lambda3(inputs.third_logical_chunk);
}
</code>```

Can this be considered a good or bad practice? Does this approach reveal any problems? All in all, should I consider this as a good approach when I am again faced with the same situation?

EDIT:

```<code>class A{
    ...
public:
    // Reconfiguration of the algorithm.
    void set_colour(double colour);
    void set_density(double density);
    void set_predelay(unsigned long microseconds);
    void set_reverb_time(double reverb_time, double room_size);
    void set_drywet(double left, double right);
    void set_room_size(double value);;

private:
    // Sub-model objects.
    ...
}
</code>```

All those methods:

get a value

compute some other values, without using state

call some of the "sub-model objects" to change their state.

It turns out that, excepting set_room_size(), those methods simply pass the requested value to sub-objects. set_room_size(), on the other hand, does a couple of screens of obscure formulas and then (2)does half a screen of calling sub-objects setters to apply the various obtained results. Therefore, I have separated the function into two lambdas and call them at the end of the function. Had I been able to split it into more logical chunks, I would have isolated more lambdas.

Regardless, the goal of the current question is to determine if that way of thinking should persist, or is it at best not adding value (readability, maintainability, debug-ability etc.).

Body:
No, this is not generally a good pattern

What you're doing is breaking up a function into smaller functions using lambda.  However, there is a much better tool for breaking up functions: functions.

Lambdas work, as you have seen, but they mean much much much much much more than simply breaking up a function into local bits.  Lambdas do:

Closures.  You can use variables in the outer scope inside the lambda.  This is very powerful and very complicated.

Reassignment.  While your example make it hard to do assignment, one always has to pay attention to the idea that code may swap functions at any time.

First-class functions.  You can pass a lambda function to another function, doing something known as "functional programming."

The instant you bring lambdas into the mix, the next developer to look at the code must immediately mentally load all of those rules in preparation for seeing how your code works.  They don't know that you're not going to use all that functionality.  This is very expensive, compared to the alternatives.

It's like using a back-hoe to do your gardening.  You know that you're only using it for digging little holes for this year's flowers, but the neighbors will get nervous.

Consider that all you are doing is grouping your source code visually.  The compiler doesn't actually care that you curried things with lambdas.  In fact, I'd expect the optimizer to immediately undo everything you just did when it compiles.  You are purely catering to the next reader (Thanks for doing that, even if we disagree on methodology!  Code is read far more often than it is written!).  All you are doing is grouping functionality.

Functions placed locally within the stream of source code would do just as well, without invoking lambda.  Again, all that matters is that the reader can read it.

Comments at the top of the function saying "we're dividing this function into three parts," followed by big long lines of // ------------------ between each part.

You can also put each part of the calculation into its own scope.  This has the bonus of immediately proving beyond all doubt that there is no variable sharing between parts.

EDIT: From seeing your edit with example code, I'm leaning towards the comment notation being the cleanest, with brackets to enforce the boundaries that the comments suggest.  However, if any of the functionality was reusable in other functions, I'd recommend using functions instead

void A::set_room_size(double value)
{
    {
        // Part 1: {description of part 1}
        ...
    }
    // ------------------------
    {
        // Part 2: {description of part 2}
        ...
    }
    // ------------------------
    {
        // Part 3: {description of part 3}
        ...
    }
}


问:
PHP MVC Display many records - model logic
I bet this question has been asked already but I can't form my thought as you can see from the title, so I couldn't find anything. I am working with MVC for quite some time now and I'm pretty happy to say that when things work out good they are nearly perfect ( in my eyes ), however I never feel like I'm doing a good job at this particular task.

Say I have my model for a user, with all of its properties and methods like,

```<code>namespace Models;

class User {

    private $id;
    private $name;

    public function __get($name){
        return $this->$name;
    }

    public function setName($name){
        $this->name = $name;
        return true;
    }

    public function save(){
        // Save user to database
    }

    public function getById($id){
        // fill properties from database with id $id
    }

}
</code>```

All fine all good, but then when I need to display a list of users for, say a search page or something, I always end up doing something like adding a static method getUsers or something that returns an array of \Models\User objects which just doesn't give me that "good code" feeling, hopefully you know what I mean. It gets even worse when I need to only get a couple of columns from the database, then the greater number of properties is empty and just feels like I'm messing up.

I want to ask you what is the correct way to do this?

答:
I don't know if this is what you're looking for but here goes.

Methods like save, get, getBy, getAll, etc, are generic and would ideally work across multiple models. For the most part, the only difference is going to be SPECIFICALLY where that data is. So why not make a super model of sorts for all your models to extend.

```<code>class Super_Model
{
    public $table; // this will be defined in the model

    public function getAll(){
        // returns all from $table
    }

    // etc
}

class User_Model extends Super_Model
{
    public function __construct()
    {
        $this->table = 'Users';
    }
}
</code>```

Now you can do the following without having to define getUsers:

```<code>$user_model = new User_Model();
$users = $user_model->getAll();
</code>```

Body:
I don't know if this is what you're looking for but here goes.

Methods like save, get, getBy, getAll, etc, are generic and would ideally work across multiple models. For the most part, the only difference is going to be SPECIFICALLY where that data is. So why not make a super model of sorts for all your models to extend.

class Super_Model
{
    public $table; // this will be defined in the model

    public function getAll(){
        // returns all from $table
    }

    // etc
}

class User_Model extends Super_Model
{
    public function __construct()
    {
        $this->table = 'Users';
    }
}

Now you can do the following without having to define getUsers:

$user_model = new User_Model();
$users = $user_model->getAll();


答:
Any licensor can issue multiple (different) licenses aimed at different user segments, specifically with different "abilities to pay."

In your example, Packery used an "open ended" license for non-commercial use, and a more restrictive one for commercial use.

That kind of practice is quite common.

Title: GPLv3 + commercial license on the same project?

Body:
I'm trying to find a solution to publish my source as open source just for personal and no-profit use, and sell licenses for commercial use.

I see Packery which uses GPLv3 for non commercial, and a custom license for commercial.

For what I know, everything under GPLv3 can be used everywhere without any limitation, so how can it works for Packery?

Can I do the same?


问:
Why is it (or was it) important to separate CSS from HTML?

Intro

I recently watched the slides from React: CSS in JS and I really like the idea of having CSS applied using JS (and with JSX, this would mean having all the HTML, JS and CSS in one file, which is just great for small, reusable components); however I'm worried about possible problems with semantic/performance/whatever, which lead me to...

The question

Why is it important to separate CSS from HTML?

Obvious reasons I can think of are avoiding duplication and keeping the HTML purely semantic while letting CSS handle the styling. I can do both in JS. Are there any other reasons I'm missing?

Edit: I missed a very important thing here - I'm designing architecture for a big web application, not some small blog thing. It will have its own build pipeline, with virtually any configuration possible.

Edit #2: I see a lot of arguments about separation of concerns, most of which are (in my understanding) based on assumption that it is more often to change just HTML or just CSS and once as opposed to editing HTML and CSS in parallel. While this might be the case for small websites, my commit history shows me the opposite - I usually edit both HTML and CSS together. So instead of separating all HTML from all CSS I would separate each component from each other.

I still don't see any serious drawback of doing this.

Caching? Each component file could be cached.

Semantics? I could still have semantic in HTML and styles in CSS, just in one file.

Re-use and maintainability? It will be even easier with separated components instead of a bunch of HTML and CSS files with unclear relationships.

MVC? I could have my mini MVC inside each component.

Edit #3: FYI all: @keithjgrant wrote a great folow-up article about this question: http://keithjgrant.com/posts/against-css-in-js.html

答:
The key point is separation of concerns:

Readability:

It's definitely easier to just open the file that contains css rules instead of your huge HTML file looking for the culprit. So, it is easier to maintain your website.

Cachability:

Since your HTML code will be different for all the pages of your site but your CSS won't, and it would be silly to reload them for every page. Separating css styles in separate files make the cachable. So, it affects the page load time too (also decrease the more page load times by minifying the css).

OwnerDisplayName: Bhojendra Nepal


答:
It is all about separation. Separating HTML, CSS and JS is necessary for readability and maintainability. While you COULD mesh them all together for a small site you definitely should not. When designing you should always try to make the site as maintainable and expandable as you can (within reason).

JS is also too heavy to be used for markup and styles on a regular basis. For larger sites this would drag down your performance greatly.

Title: Why is it (or was it) important to separate CSS from HTML?

Body:
Intro

I recently watched the slides from React: CSS in JS and I really like the idea of having CSS applied using JS (and with JSX, this would mean having all the HTML, JS and CSS in one file, which is just great for small, reusable components); however I'm worried about possible problems with semantic/performance/whatever, which lead me to...

The question

Why is it important to separate CSS from HTML?

Obvious reasons I can think of are avoiding duplication and keeping the HTML purely semantic while letting CSS handle the styling. I can do both in JS. Are there any other reasons I'm missing?

Edit: I missed a very important thing here - I'm designing architecture for a big web application, not some small blog thing. It will have its own build pipeline, with virtually any configuration possible.

Edit #2: I see a lot of arguments about separation of concerns, most of which are (in my understanding) based on assumption that it is more often to change just HTML or just CSS and once as opposed to editing HTML and CSS in parallel. While this might be the case for small websites, my commit history shows me the opposite - I usually edit both HTML and CSS together. So instead of separating all HTML from all CSS I would separate each component from each other.

I still don't see any serious drawback of doing this.

Caching? Each component file could be cached.

Semantics? I could still have semantic in HTML and styles in CSS, just in one file.

Re-use and maintainability? It will be even easier with separated components instead of a bunch of HTML and CSS files with unclear relationships.

MVC? I could have my mini MVC inside each component.

Edit #3: FYI all: @keithjgrant wrote a great folow-up article about this question: http://keithjgrant.com/posts/against-css-in-js.html

OwnerDisplayName: sareed


答:
One could say that the separation of html, css and js codewise conforms web development to the Model-View-Controller-Pattern.

Also html, css and js are often very much entangled, so looking at them in different windows, can be quite handy from time to time.

OwnerDisplayName: Yannic Welle


问:
How to design database tables for a Factory class?
How can I design database table structure for a class that varies in its core parameters, when it is created by a factory method?

I have a Factory like this:

```<code>class ProductFactory
{
    public function giveMeProduct()
    {
        switch ($this->productLine) {
            case "A": return new AProduct();
            case "B": return new BProduct();
            case "C": return new CProduct();
            case "D": return new DProduct();
            case "E": return new EProduct();
            case "F": return new FOptions();

            default: return new Product();
        }
    }
}

$product = (new ProductFactory("A"))->giveMeProduct();
</code>```

Each product has different parameters.  There are some shared, but not many.

So for example once created, each product contains the following variable options:

```<code>______stages___pipes___holder___orientation (flags)
| A  |   x   |        |       |            |
| B  |       |   x    |   x   |      x     |
| C  |       |        |       |      x     |
| D  |       |   x    |   x   |            |
| E  |       |   x    |       |            |
 etc
</code>```

So I can either design several tables, one for each product, but I think doing so will be quite wasteful in resources (extra tables, files, connecting tables) for just a few parameters in a small little product options class.  Or I can cobble all product options into a single table, which will be sparse, like one above.  It will be wasteful but in other ways (table space), although seeing that I don't have many options it may be okay.

In a word, I have 6 classes, each with different options, most of which are not shared among classes.

How do I design a table for this class to persistently store and recover data?  What patterns can I use?

答:
I would solve this with three tables: products, features, and product_features.</p>

```<code>Products
id     name       description
1223   A          abcdefg
1224   B          hijklmnop
1225   C          qrstuvwxyz

features
id   name            description
20   stages          such-and-such
21   pipes
22   holder
23   orientation

product_features
PRIMARY KEY(product_id,feature_id)
CONSTRAINT FK_product_id FOREIGN KEY (product_id) REFERENCES products(id)
CONSTRAINT FK_feature_id FOREIGN KEY (feature_id) REFERENCES features(id)

product_id   feature_id
1223         20
1224         21
1224         22
1224         23
</code>```

Body:
I would solve this with three tables: products, features, and product_features.

Products
id     name       description
1223   A          abcdefg
1224   B          hijklmnop
1225   C          qrstuvwxyz

features
id   name            description
20   stages          such-and-such
21   pipes
22   holder
23   orientation

product_features
PRIMARY KEY(product_id,feature_id)
CONSTRAINT FK_product_id FOREIGN KEY (product_id) REFERENCES products(id)
CONSTRAINT FK_feature_id FOREIGN KEY (feature_id) REFERENCES features(id)

product_id   feature_id
1223         20
1224         21
1224         22
1224         23


问:
What is "egoless programming"?
I first heard this term about fifteen years ago.

My understanding is similar to that described in the Wikipedia article and a TechRepublic article: you work with your colleagues in a "friendly, collegiate way in which personal feelings are put aside". It includes things like doing peer reviews with mutual respect and a desire to learn, and not feeling like you "own" code, so if somebody has a suggestion or says there's a bug or needs to change it, you don't get defensive about it.

I've also thought it was largely about having an attitude that makes for good relations with other programmers with the goal of improving the code. So I haven't seen it as being incompatible with taking pride in the quality of your work or feeling regret if something you did caused your customer a problem.

However, an answer to a recent question makes me think some other programmers have different understandings about "egoless programming". So what is the correct definition? And what are its implications?

答:
All of the above.

Egoless programming has mostly to do with how much respect you have for the programmer who comes after you, who is going to have to figure out what you did with your code so that they can maintain it, and quite possibly improve on what you did (I know, that seems inconceivable, since all the code I write is already perfect ;).

I also believe that egoless programmers don't take dogmatic positions about their work.  This makes them flexible enough to work in environments where their idealistic expectations may not always be so eagerly embraced or unconditionally accepted.

Title: What is "egoless programming"?


问:
Why Double.parseDouble("ABC") not returns Double.NaN?
This code:

```<code>Double.parseDouble("ABC")
</code>```

throws a NumberFormatException.

Why is it wrong to expect a Double.NaN (NaN is literally Not-A-Number).

A working example is this:

```<code>public static void main(String[] args) {
    System.out.println("Is ABC a number? " + Double.isNaN(Double.parseDouble("ABC"));
}
</code>```

I expect Is ABC not a number? true as output.

Why must this be an Exception?

答: This lets you easily detect the cases where the input is completely nonsensical. You can parse the string "NaN" and get NaN, so if the user wanted to give you NaN, he could type that. The fact that you received "ABC" means they weren't even trying to enter a double at all.


答:
In addition to the good answer by @Doval, throwing a NumberFormatException is more general: it works for similar methods like Integer.parseInt().  There is no NaN equivalent for ints, shorts, etc.

So, throwing a NumberFormatException is both more specific/informative than returning NaN, it is also more generalizable.

That's truly a win-win!

Title: Why Double.parseDouble("ABC") not returns Double.NaN?

Body:
This code:

```<code>Double.parseDouble("ABC")
</code>```

throws a NumberFormatException.

Why is it wrong to expect a Double.NaN (NaN is literally Not-A-Number).

A working example is this:

```<code>public static void main(String[] args) {
    System.out.println("Is ABC a number? " + Double.isNaN(Double.parseDouble("ABC"));
}
</code>```

I expect Is ABC not a number? true as output.

Why must this be an Exception?


问:
Software release question: do you refactor pre or post-release?
I work in finance and we have some calculators that I support. I can come up with programming solutions, but I don't have a lot of software design or release management experience.

I was recently asked to approve coworker's code. The enhancement was fairly simple, but during my review I realized they came up with their own method to process input files. We have generic methods that could already be confusing for newhires with only classroom programming experience, and I don't want to make onboarding any more difficult by propagating poor design in our code base.

I'm concerned that since we're not a software shop, my managers won't prioritize refactoring once the problem has a working solution. How hard should I push to keep our code clean for the release?

答:
You'll want to read up on the term "technical debt".

If time & resources permit, it is much better to do any code clean up immediately while the problem is fresh in your mind.

Leaving clean up as a to-do item for others can turn into a very bad habit.  These to-do items are rarely addressed, and after many years can lead to such a horrific mess that management dumps the entire system and fires people (I've seen it happen).


答:
NaN has a very specific meaning as the result of an undefined numerical operation such as division by zero or taking the square root of a negative number (within the realm of real numbers).  It's not an appropriate return value from code that parses a floating point number.

Code like that should signal an error when it comes across text that can't be parsed as a number.

Also, as others have mentioned, it's a consistency issue.  Only floating point values even have a NaN.  Integer and boolean types don't.  parseX() should behave the same way in all cases where possible.

This is called the principle of least surprise.  That is, design things in the most consistent way possible to avoid surprising others using your APIs.


答:
If any of this is applicable to your situation, you'll know what to do:

A correction is made to your generic methods, but the code that created their own is still broke.

You spend time teaching another new candidate that "all the code uses the generic method" but they have to fix the one that doesn't. Now you get to take more time to explain how to fix this. You were expected to be able to fix these types of problems sooner, but now there is a delay.

Because you don't enforce the rules, your team turns into a bunch of Cowboy Coders. The performance of the team drops.

Don't ask permission to take the time to do things right. Everyone assumes you already are and that's why everything in their mind seems to take longer then they think it should. If your boss has to clean up this mess, he's going to do it by replacing you.

Title: Software release question: do you refactor pre or post-release?

Body:
I work in finance and we have some calculators that I support. I can come up with programming solutions, but I don't have a lot of software design or release management experience.

I was recently asked to approve coworker's code. The enhancement was fairly simple, but during my review I realized they came up with their own method to process input files. We have generic methods that could already be confusing for newhires with only classroom programming experience, and I don't want to make onboarding any more difficult by propagating poor design in our code base.

I'm concerned that since we're not a software shop, my managers won't prioritize refactoring once the problem has a working solution. How hard should I push to keep our code clean for the release?


答:
There isn't one correct definition as the concept of "Ego" is subject to great interpretation.  Depending on your psychological and spiritual beliefs there are more than a few different answers about how one can try to remove ego from their life.

The implication as I understand the term is that there is a collective ownership, so that each person on the team is working for the benefit of everyone rather than just oneself.  "David Logan on tribal leadership" is a TED Talk where a level 4 tribe would be the one of egoless people in a sense.

Title: What is "egoless programming"?

Body:
I first heard this term about fifteen years ago.

My understanding is similar to that described in the Wikipedia article and a TechRepublic article: you work with your colleagues in a "friendly, collegiate way in which personal feelings are put aside". It includes things like doing peer reviews with mutual respect and a desire to learn, and not feeling like you "own" code, so if somebody has a suggestion or says there's a bug or needs to change it, you don't get defensive about it.

I've also thought it was largely about having an attitude that makes for good relations with other programmers with the goal of improving the code. So I haven't seen it as being incompatible with taking pride in the quality of your work or feeling regret if something you did caused your customer a problem.

However, an answer to a recent question makes me think some other programmers have different understandings about "egoless programming". So what is the correct definition? And what are its implications?


问:
Is it bad practice to register assemblies in the GAC?
I have moved a few assemblies to the Global Assembly Cache because they are used by multiple applications i.e. a VB.NET app and an ASP.NET app.

I remember a few years ago when I started in my current role I noticed that the previous developer registered COM DLLs in the System32 folder.  I asked about this and Hans Passant replied saying this was poor practice because System32 is for Operating System DLLs.  Is it bad practice to register assemblies in the GAC for similar reasons?

My understanding is: if a .NET DLL is accessed my 2 or more applications then put it in the GAC.

答:
I would say yes, using the GAC is a "bad practice"... Or better put, it's not a recommended practice for most situations. Case and point, the next version of ASP.NET doesn't even use the GAC (Link).

Some other reasons the GAC is a bad idea:

Deploying assemblies into the GAC can be difficult.

Versioning assemblies in GAC can be difficult.

Configuring permissions to assemblies can be difficult.

And, if anything, my personal experience with the GAC has lead me to avoid it at all costs... :)

ContentLicense: CC BY-SA 4.0


问:
Should an HTTP API always return a body?
Is there some sort of standard regarding HTTP API responses?

After reading this discourse thread I started to wonder.  We are developing our public HTTP JSON API at my work, and we do not return anything when it's not strictly needed (for example a PUT to /resource/{id} only returns 200 when OK or the corresponding 4XX or 5XX code, but no JSON body)

Should we return a generic {"success":true} like they discuss on that link above, or is it ok to return a "void" body and handle everything with http response codes?

答:
I would suggest returning only what is needed + a little clarification.

For example, depending on how your API is to be used, you could include a copy of the object, as is exists after being saved.

So a POST of {key: 123} might return {key: 123, foo: 'bar'}.

The basic idea is it is better to return the object then to have to query for it again.

That said, of your API consumers don't need the object there's no need to return it.

I usually return {success: true} or some such, when there is no object required on POST PUT and PATCH because it makes it easier for the receiving end. That said, it's better 99% of the time to return the saved representation of the object, it's rare that they won't need it anyway, and it's "cheaper" to send it all in one request then in two.

To be specific, in a lab it's perfectly find to handle everything with just status codes, in the real world, it's much better to return some data, even if redundant, so that API consumers can easily under stand what your trying to say.

Returning 200 {success: true} lets people write code both ways:

```<code>if response.code == 200
  do stuff
end
</code>```

and

```<code>if response.body.success
  do stuff
end
</code>```

in addition it's not that hard to do on your side.

Lastly, (sorry for the poos answer structure), by providing a public JSON api your giving up a lot of control on how it's going to be used. Some clients may react different to different bodies (or lack there of) or status codes.

Body:
I would suggest returning only what is needed + a little clarification.

For example, depending on how your API is to be used, you could include a copy of the object, as is exists after being saved.

So a POST of {key: 123} might return {key: 123, foo: 'bar'}.

The basic idea is it is better to return the object then to have to query for it again.

That said, of your API consumers don't need the object there's no need to return it.

I usually return {success: true} or some such, when there is no object required on POST PUT and PATCH because it makes it easier for the receiving end. That said, it's better 99% of the time to return the saved representation of the object, it's rare that they won't need it anyway, and it's "cheaper" to send it all in one request then in two.

To be specific, in a lab it's perfectly find to handle everything with just status codes, in the real world, it's much better to return some data, even if redundant, so that API consumers can easily under stand what your trying to say.

Returning 200 {success: true} lets people write code both ways:

if response.code == 200
  do stuff
end

and

if response.body.success
  do stuff
end

in addition it's not that hard to do on your side.

Lastly, (sorry for the poos answer structure), by providing a public JSON api your giving up a lot of control on how it's going to be used. Some clients may react different to different bodies (or lack there of) or status codes.


问:
RESTful way of referencing other resources in the request body
Let's assume that I have a resource called group with the following representation:

```<code>{
    "id": 1,
    "name": "Superheroes"
    "_links": {
        "self": {
            "href": "http://my.api.com/groups/1"
        }
    }
}
</code>```

Now let's say I want to create a new person instance by POSTing to /persons/1. Which of the following should I use for the request body:

Using ID

```<code>{
    "name": "Batman",
    "groupId": 1
}
</code>```

Using link

```<code>{
    "name": "Batman",
    "group": "http://my.api.com/groups/1"
}
</code>```

With the first method I access the id directly either to look up the related resource or eventually store the id in the database, when I persist the person instance. But with the other method, I either have to extract the id from the URI or, follow the link to load the related resource, and then find out its id. I really don't want to store the URI in the database.

With the latter option, seeing that the server controls the structure of the URI, is it fine for me to parse the id out of the link? Following the link back to the server itself seems odd, seeing that at this point we already have access to the information directly (we just need the id).

So to sum up, which of these options is best?

Use the id directly.

Use the link, but parse out the id.

Use the link, but access the link to get the resource instance, and then get the id.

答:
The "right" answer is dependent on your situation, but never link.

```<code>POST
{
    "name": "Batman",
    "groupId": 1
}
</code>```

is fine

```<code>POST
{
    "name": "Batman",
    "groupName": "my group"
}
</code>```

Could be nice for convenience.

Using a link is bad, because the link could change depending on tons of stuff (i.e. www.example.com/groups/1 or example.com/groups/1 or groups.example.com/groups/1-group-name-in-seo-friendly-format may all point at the same resource). You want to pass in something that  "never" changes. ID is a good choice, but it may be cost effective to allow a name to be passed in (to reduce overall number of calls).

I would normally say make the consumer GET /groups.json and POST /users with the group id.

Body:
The "right" answer is dependent on your situation, but never link.

POST
{
    "name": "Batman",
    "groupId": 1
}

is fine

POST
{
    "name": "Batman",
    "groupName": "my group"
}

Could be nice for convenience.

Using a link is bad, because the link could change depending on tons of stuff (i.e. www.example.com/groups/1 or example.com/groups/1 or groups.example.com/groups/1-group-name-in-seo-friendly-format may all point at the same resource). You want to pass in something that  "never" changes. ID is a good choice, but it may be cost effective to allow a name to be passed in (to reduce overall number of calls).

I would normally say make the consumer GET /groups.json and POST /users with the group id.


答:
I would recommend Staying away from the GAC as much as you can. Different assembly versions don't always play nice and debugging that can be a real PIA.

From a technical point if two apps use an assembly it is acceptable to place it in the GAC.

In real world usage, the few Kilobites of saved space is not worth the weeks/months of debugging a GAC dependency problem. It's much better (in real practice) to keep an app and it's dependencies as isolated as possible.

Title: Is it bad practice to register assemblies in the GAC?

Body:
I have moved a few assemblies to the Global Assembly Cache because they are used by multiple applications i.e. a VB.NET app and an ASP.NET app.

I remember a few years ago when I started in my current role I noticed that the previous developer registered COM DLLs in the System32 folder.  I asked about this and Hans Passant replied saying this was poor practice because System32 is for Operating System DLLs.  Is it bad practice to register assemblies in the GAC for similar reasons?

My understanding is: if a .NET DLL is accessed my 2 or more applications then put it in the GAC.


问:
Should Perl scripts really have no extension?
I just began reading O'Reilly's Learning Perl, 6th Edition and was surprised when I came across this excerpt.

```<code>#!/usr/bin/perl
print "Hello, world!\n";
</code>```

Let’s imagine that you’ve typed that into your text editor. (Don’t
  worry yet about what the parts mean and how they work. You’ll see
  about those in a moment.) You can generally save that program under
  any name you wish. Perl doesn’t require any special kind of filename
  or extension, and it’s better not to use an extension at all.

Why is it better to have no extension? Imagine that you’ve written a
  program to calculate bowling scores and you’ve told all of your
  friends that it’s called bowling.plx. One day you decide to rewrite it
  in C. Do you still call it by the same name, implying that it’s still
  written in Perl? Or do you tell everyone that it has a new name? (And
  don’t call it bowling.c, please!) The answer is that it’s none of
  their business what language it’s written in, if they’re merely using
  it. So it should have simply been called bowling in the first place.

This is the only source I've seen with this view, everything else I've read has supported the .pl extension. I'm no Perl programmer yet, and I wanted to know what the community's view on this was before I got into a habit.

答:
Doesn't matter

```<code>#!/usr/bin/perl
</code>```

tells the system what program to use to run the code.

if you changed that to

```<code>#!/usr/bin/bash
</code>```

or

```<code>#!/usr/bin/python
</code>```

you would use a different interpreter.

Having the extension is totally optional, and the point that the user doesn't need to know the language is 100% correct in most cases.

running add 2 3 and getting back 5 is all i care about (as a user).

The only time I add an extension to scripts is if I need the end user (some times my self) to know the language for some reason.

example.sh or example.pl to show to different ways to accomplish the same task.

All that said though, it is more common to not have an extension, but it's all taste.

Body:
Doesn't matter

#!/usr/bin/perl

tells the system what program to use to run the code.

if you changed that to

#!/usr/bin/bash

or

#!/usr/bin/python

you would use a different interpreter.

Having the extension is totally optional, and the point that the user doesn't need to know the language is 100% correct in most cases.

running add 2 3 and getting back 5 is all i care about (as a user).

The only time I add an extension to scripts is if I need the end user (some times my self) to know the language for some reason.

example.sh or example.pl to show to different ways to accomplish the same task.

All that said though, it is more common to not have an extension, but it's all taste.


答:
The phrase doesn't have an ISO standard meaning, so different people can legitimately mean different things by it.

I believe it was coined by Weinburg in The Psychology of Computer Programming.  He meant programming without tying any of one's ego to the code, so that it isn't "your code", it's just code.  This facilitates cooperation to improve the code, the ability to accept criticism of what you've written (because it isn't directed at you), and general teamwork.

Title: What is "egoless programming"?


答:
All the book is telling you is that on Unix, the file extension is nothing more than a convention.  In reality, many types of files fall in to this category.  Ruby files use the same convention so they don't need the .rb extension.  C compilers only need valid C code, so you can name them .watoozy if you wanted to.

While there is no technical restraint, there is the practical constraint of the principle of least surprise.  Basically, it would be very surprising to see ruby code in a .pl file, so people don't generally do that.

The one exception to the rule

In some server applications, the start up script is in an extension-less file to make it easier to start up the application as a service.  The file looks like just any other compiled command in that case.  As long as you have Perl installed, it will behave that way as well.

Title: Should Perl scripts really have no extension?

Body:
I just began reading O'Reilly's Learning Perl, 6th Edition and was surprised when I came across this excerpt.

```<code>#!/usr/bin/perl
print "Hello, world!\n";
</code>```

Let’s imagine that you’ve typed that into your text editor. (Don’t
  worry yet about what the parts mean and how they work. You’ll see
  about those in a moment.) You can generally save that program under
  any name you wish. Perl doesn’t require any special kind of filename
  or extension, and it’s better not to use an extension at all.

Why is it better to have no extension? Imagine that you’ve written a
  program to calculate bowling scores and you’ve told all of your
  friends that it’s called bowling.plx. One day you decide to rewrite it
  in C. Do you still call it by the same name, implying that it’s still
  written in Perl? Or do you tell everyone that it has a new name? (And
  don’t call it bowling.c, please!) The answer is that it’s none of
  their business what language it’s written in, if they’re merely using
  it. So it should have simply been called bowling in the first place.

This is the only source I've seen with this view, everything else I've read has supported the .pl extension. I'm no Perl programmer yet, and I wanted to know what the community's view on this was before I got into a habit.


问:
Should I generate reports client or server side?
I am thinking of a standard AJAX setup (JS<->PHP<->MySql).

I want to generate reports (charts, tables, etc) probably using at maximum a few dozen data points (certainly never over 1k).

I am unsure whether to download all data on initial page load and generate charts when the user changes a parameter - say start date for example - using JS totally on the client side or to send an AJAX request to the server & use PHP there to generate & return a chart.

What should I take into consideration?

Is there a standard approach, or does it "depend"?

Any considerations of performance with so little data? Security?

Might client side be better if I want to export the reports?

Does it just boil down to which ever free charting package looks good to me?

For smart 'phones, can they readily generate charts responsively, or would it be better to download them as an image file form the server?

I suppose that it also depends on whether I will allow the user to click the charts & perform operations, or drag things around, etc. I.e. if I want something dynamic, or if a static image will suffice

答:
You are in the land of "depends"

I tend to favor client side reporting. However if it takes longer to transfer the data points then your in sever land.

There is no standard answer. For smaller data sets client side is fine and common.

No real performance concerns with small data sets other then off loading chart generation to the client (browser) means your can handle more requests.

Exporting the report depends on your needs, There are better server side solutions then client side ones for exporting reports, but why do they need to be exported. Can't they just be re-run.

It does depend on charting package, but go beyond just looking at the free ones. $200 is not that much in the grand scheme.

Modern mobiles can generate carts just fine, depends on the charting package.

Your much better using "dynamic" from the start. I have never seen a report that didn't make the user want to "drill down" somewhere.


答:
Using the GAC isn't bad per se (in some situations it may even be required), but you should know what you're doing.

However, some quick tips;

Don't deploy to the GAC if the machine is not yours to command.

Don't deploy to the GAC if you don't use assembly versioning.

Don't deploy to the GAC if you can just use a local bin folder.

Don't deploy to the GAC if you want to use multiple distinct versions in different locations on the machine (unless they differ in major.minor version).

That said;

I wouldn't deploy to the GAC for an ASP.NET scenario. Just use the bin folder in the web application path. Note that ASP.NET looks into the local bin folder before looking in the GAC as well.


问:
Sell dual licensed software with 3rd party contributions
I host a project on GitHub.

Right now it has a custom license (shareware) but I'm going to move to a dual license AGPLv3 + commercial license.

I would like to have some information about the commercial part of my software:

Lot of users send Pull Requests to my repository to implement new features or fix bugs. Right now I own the copyright and all the rights of these PR. But when I'll move to AGPLv3 or later everything will be under this License.

Does it mean that when I sell my software I will be able to sell with the commercial license only the parts written by me and I will not have rights for the parts written by users?

答:
It is not uncommon in Open Source to have contributors agree to a contribution agreement which clarifies the copyright situation.

You can formulate it either in a way that the contributors keep their copyright, which means that a license change is practically impossible without the permission of every single contributor. Or you can formulate it in a way that they transfer their copyright to you, which allows you to publish it under a different license.

Templates for either kind of agreement can be generated on http://www.harmonyagreements.org/ (the agreement texts themselves are licensed under CC-BY 3.0)

Many open source contributors will not agree to waive their rights unless they get paid or have some other tangible advantage from the development of your project, because they will be fully aware that when they contribute for free to a project with dual-licensing, they are essentially free laborers working for someone else's profit.

You don't necessarily need such agreements when the license of your project is clear and you don't intend to change it, as it will be clear for everyone that these are the conditions under which your project works. You also don't need it when your project is under a non-copyleft FOSS license like BSD or MIT, because these allow relicensing under a proprietary license anyway.

But when you try to make a license change from a copyleft-license to a non-copyleft or a proprietary one without a contributor agreement from everyone, you are in legal limbo, as it is quite open to interpretation whether the contributors have transfered their copyright or not. A contributor might get the idea to sue for a share of the profits you make based on licensing their work under the new license. I am not a lawyer, so I can not estimate how likely it would be that they are successful. But no matter if they succeed or not, such a discourse will definitely not be positive for the reputation of your project.


问:
How do we sequence logs from different services in a system?
So, if I am designing a system as a set of different roles (client, app-server, backend services 1 to n). Each of these roles will have their own logging mechanism. I can aggregate all the logs at one location, but how can I sequence the logs from different sources, to show an interleaved log?

I can make my own strategy. Timestamps can help but will not be 100% accurate. What is normally done in the industry?

答:
Normally you view the logs independently. Too much log is a real problem. There is almost no reason to view an interleaved log. If you really need to log an "action" through all the services have them write to a central log

syslog is a great example

apache writes to one log mysql to another, and there's usually never a reason to interleave them. Your structure is not that different.

If you really want to interleave a log then your going to have to do so using "something central" i.e. syslog, one file, a database, etc, but you should treat the log as FIFO and not as ordered in any specific way.


答:
The advice in the book is perfectly valid -- at least for UNIX-like systems. The execution of the script is controlled by the #! line, not by the extension part of the file name. Using a special extension for Perl scripts exposes information that should not be important to anyone running the script.

Windows is a different matter. Windows does not support the #! mechanism; instead, the method used to open a file depends on the extension. For example, the Windows shell might be configured so that double-clicking on a .pl file (or executing it from a prompt) will pass it as an argument to the Perl interpreter. Installing a Perl system will probably set that up for you automatically.

For Perl scripts intended to be portable, the .pl suffix required by Windows might "leak" onto UNIX-like systems. It's probably best to have a system-specific installation method that chooses an appropriate name for the script as it's installed.

On UNIX-like systems, a .pl extension is mostly harmless, and if you find it useful as a reminder of what language is used by a particular script (perhaps you have a collection of .pl, .py, .sh, and .rb scripts), then you can do that. But there are drawbacks to that approach, as described in the book: if you reimplement a script in a different language, you'll have to change the name and update anything that calls it.

(Perl modules need to have a .pm extension so that Perl can find them. For example, this:

```<code>use Foo::Bar;
</code>```

will cause the interpreter to search for a file named Bar.pm in a a directory named Foo under one of the directories listed in the @INC array. But .pm files aren't meant to be executed directly.)

This is the only source I've seen with this view, everything else I've read has supported the .pl extension.

I find that surprising. Most of the advice I've seen says not to use the .pl extension for executable scripts.

Body:
The advice in the book is perfectly valid -- at least for UNIX-like systems. The execution of the script is controlled by the #! line, not by the extension part of the file name. Using a special extension for Perl scripts exposes information that should not be important to anyone running the script.

Windows is a different matter. Windows does not support the #! mechanism; instead, the method used to open a file depends on the extension. For example, the Windows shell might be configured so that double-clicking on a .pl file (or executing it from a prompt) will pass it as an argument to the Perl interpreter. Installing a Perl system will probably set that up for you automatically.

For Perl scripts intended to be portable, the .pl suffix required by Windows might "leak" onto UNIX-like systems. It's probably best to have a system-specific installation method that chooses an appropriate name for the script as it's installed.

On UNIX-like systems, a .pl extension is mostly harmless, and if you find it useful as a reminder of what language is used by a particular script (perhaps you have a collection of .pl, .py, .sh, and .rb scripts), then you can do that. But there are drawbacks to that approach, as described in the book: if you reimplement a script in a different language, you'll have to change the name and update anything that calls it.

(Perl modules need to have a .pm extension so that Perl can find them. For example, this:

use Foo::Bar;

will cause the interpreter to search for a file named Bar.pm in a a directory named Foo under one of the directories listed in the @INC array. But .pm files aren't meant to be executed directly.)

This is the only source I've seen with this view, everything else I've read has supported the .pl extension.

I find that surprising. Most of the advice I've seen says not to use the .pl extension for executable scripts.