问:
Should I hold an Id and the Item
Let's say I have a Customer which contains an Address class like:

```<code>public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    // Constructor and other code
}
</code>```

Should I now also have a property for the reference Id to ask another class to give me the Address?

```<code>    public int RefAddressId { get; private set; }

    public Initialize()
    {
        Address = someInterface.GetAdressById(RefAddressId );
    }
</code>```

or should i ask another class to give me the Address based on my CustomerId

```<code>    public Initialize()
    {
        Address = someInterface.GetAdressByCostumerId(Id);
    }
</code>```

Is there a rule why and when I should prefer one over the other?

Or maybe there is even a other more common way to do this.

答: You can follow a suitable practice based on the requirement. In this case, a customer is unique and will have a unique address associated with it. If the address has the possibility of being used by many other customers, then using a separate interface for address seems like a good idea to me. In that case, the object can retrieve the address(possibly a large string) lazily when required, by integrating with the interface. However, if the address is very rarely used by other customers, storing a reference to the Address entity itself works well.</p>

Title: Should I hold an Id and the Item


问:
Using super keyword to access super class members
I have following questions about the super keyword in java:

I have a code below with classes:

A Extends no class contains integer variable i

B Extends class A contains integer variable i

C Extends class B contains integer variable i

```<code> class A {
    int i = 20;

    A() {
        System.out.println("I am in constructor of the parent class");
    }
}
</code>```

```<code>class B extends A {
    int i = 30;

    B() {
        System.out.println("I am in constructor of the subclass");
    }
}
</code>```

```<code>class C extends B {
    int i = 40;

    C() {
        System.out.println("I am in constructor of the main class");
    }

    void display() {
        System.out.println(i);
        System.out.println(super.i);
        /*
         * My first thoughts to access the third variable 'i'
         * inherited indirectly to this class by 'class A'.
         * I thought that it would print 20 :(.
           System.out.println(super.super.i);
         */
    }

    public static void main(String[] argue) {
        C obj2 = new C();
        obj2.display();
    }
}
</code>```

Now as class B inherits class A so it must have two integer variables i. Class C inherits class B so it will have two integer variables from B and one defined in itself.

Now I can print the inherited super class variable i in class C through the display method and of course the variable i defined in class C itself. The question is how to print the third i which has the value "20".

I know I can define a method in the class B that returns super.i; and call it through its object in class A that will print the third variable i and I also known that I can create an object of class A, but is there any other way by using super or any other thing to directly access the third variable in the class C.

Also the output is:

```<code>      I am in constructor of the parent class
      I am in constructor of the subclass
      I am in constructor of the main class
      40
      30
</code>```

why like the this keyword the super keyword cannot be used inside     static methods?

why is the super class constructor called to initialize the inherited variables of a subclass? This doesn't make any sense because if a class extends another class the variables and methods will be like they were locally declared in the class in other words its own members. So why can't the constructor of the subclass initialize those inherited members and has to call the super class constructor to initialize them.

答:
Your code is incomplete - here's what Java added for you:

```<code>class A extends Object { /* <-- Added */
    int i = 20;
    A() {
        super(); /* <-- Added */
        System.out.println("I am in constructor of the parent class");
    }
}
</code>```

And your other classes do just the same.

All classes extend some other class, even if it's "just" Object.

"super" refers to the super-class of the current instance but Static methods have no instance; they're just lumps of code that are "attached" to a class, but make no reference to any data held within the instance itself.  If this were a .Net question, I'd point you to the Split() and Join() methods on the String class; the [instance] Split method breaks up the current value held inside the String object but the [static] Join method takes both delimiter and [array] value as arguments and puts them together.

Constructors are inherently private in their action.  Their job is to ready the object itself to go to work, without any reference to its super class or any subclass (about which it should know nothing at all).
Instantiation runs all the way up the super-class "chain", all the way to Object, and executes the constructor on each class on the way "back down".

ContentLicense: CC BY-SA 3.0

Body:
Your code is incomplete - here's what Java added for you:

class A extends Object { /* <-- Added */
    int i = 20;
    A() {
        super(); /* <-- Added */
        System.out.println("I am in constructor of the parent class");
    }
}

And your other classes do just the same.

All classes extend some other class, even if it's "just" Object.

"super" refers to the super-class of the current instance but Static methods have no instance; they're just lumps of code that are "attached" to a class, but make no reference to any data held within the instance itself.  If this were a .Net question, I'd point you to the Split() and Join() methods on the String class; the [instance] Split method breaks up the current value held inside the String object but the [static] Join method takes both delimiter and [array] value as arguments and puts them together.

Constructors are inherently private in their action.  Their job is to ready the object itself to go to work, without any reference to its super class or any subclass (about which it should know nothing at all).
Instantiation runs all the way up the super-class "chain", all the way to Object, and executes the constructor on each class on the way "back down".


问:
Putting a password in a REST API call
Suppose I have a REST API that is also used to set/reset passwords. Let's also suppose that this works over a HTTPS connections. Is there any good reason not to put that password in the call path, let's also say I will encode it in BASE64?

An example would be to reset a password like this:

```<code>http://www.example.com/user/joe/resetpassword/OLDPASSWD/NEWPASSWD
</code>```

I understand BASE64 is no encryption, but I only want to protect the password to shoulder surfing in this case.

答:
The problem is to avoid plain text passwords in your requests.
There are two options to fulfill the restful webservice requirements.

1. Client side hashing

I'll guess you are storing your passwords like e. g. hash(password+salt)

You can hash the new password with a salt on the client side

That means: Create a new salt on the client side, create a hash e. g. hash(newPassword+newSalt)

Send the new created hash plus the salt to your restful webservice

Send the old password also as hash(oldPassword+oldSalt)

2. Encryption

Create a "one time key" (otk) resource for a user like /otk/john

This resource returns an secure random unique one time key, e. g. kbDlJbmNmQ0Y0SmRHZC9GaWtRMW0ycVJpYzhMcVNZTWlMUXN6ZWxLdTZESFRs and a unique ID e. g. 95648915125

Your restful webservice has to store this random otk for the next secure communication with the ID 95648915125

Encrypt your new and old password with the otk e. g. AES (for security reasons you should use two separate otks for the old and new password)

Send the encrypted passwords to your change password resource with the ID 95648915125

One otk and ID combination is allowed to work once only, so you have to deleted that combination after chaning the password

Possible better option: Send the current/old password by Basic-Auth.

Note: HTTPS is required for both options!

Title: Putting a password in a REST API call


问:
How to deal with a bug which seems to have fixed itself?
I'm a web application developer for an internal system. A user reports that there's a bug.

The bug was that some words could not be displayed. The report contains a screen capture which clearly show the bug. But the report is almost a month old and the bug can no longer be reproduced in our production environment.

How should I reply to the client and the user?

答:
Revert your dev environment to the version that the bug was noticed in and verify that the bug is there.

If it is there then you can investigate the bug and make sure that the current version doesn't have it. Then close the bug report with the comment that an unrelated change fixed it. Add a regression test if needed.

If you can't reproduce the bug in that version then the strategies laid out in many other questions here will be of use (Thanks Thomas for the initial list):

Turn away a bug if no reproducible test case exists?

How do I isolate difficult to reproduce bugs?

How to most effectively debug code?

Un-Explainable Bugs?

What to do with bugs that do not repro?

OwnerDisplayName: Ben Cheng


问:
How do you stay focused at work?
Sometimes, the things I have to do for my job are interesting and engaging.  Sometimes, they aren't.  Occasionally, they really aren't.

Do you have any particular strategies or tricks for dealing with those dull stretches when your brain would rather be doing anything other than what you're supposed to be doing, particularly when the Internet and its boundless opportunities for interesting Slack beckon?

答:
Some things I do:

Leave less windows open

Organise my desktop (using fences http://www.stardock.com/products/fences/ )

Try to do 1 thing at a time, multi tasking always ends in tears

Shut off the world (email, web, phone) for dedicated blocks when trying to get something important done

Keep my email inbox empty

ContentLicense: CC BY-SA 2.5

Title: How do you stay focused at work?


问:
Most useful features of VIM that aren't standard in a IDE
I'm considering whether I should start using VIM again instead of an IDE. What are the most useful features of VIM that aren't standard in an IDE?</p>

答: 'Insertion mode keyword completion'. Ctrl-P and Ctrl-N in insert mode to search through the text to try and complete whatever variable name you are typing. I've never seen this in any other IDE and I really miss it. Code completion in IDE's just isn't the same.</p>


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答:
Code snippets, experience and never ceasing enthusiasm. Always read stuff: programmer blogs, books, literature, other peoples' bad code. You'll get faster if you get a wider view on stuff. If you can imagine all kinds of complex background processes involved, and you really know the whole complexity of the target system.

The Pragmatic Programmer's Handbook is kind of awesome: it's about best practices and major pitfalls of many different aspects of software development. Rubber ducking and stuff sounds blatantly nerdy and stupid. However the nature of most programming problems is that we tend to think much too complex. I'm a great fan of simple and easy solutions: no great tricks, no super-elegant hacks: just using the simplest solutions.

If your team is good you can try to work collaboratively: Bespin and some other frameworks nowadays allow editing one file together. That's awesome if you're really into it and see your coworker doing the magic ;).

OwnerDisplayName: Nick Gotch

Title: How to become a "faster" programmer?

OwnerDisplayName: wishi


问:
What's the difference between a stream and a queue?
What's the difference between a stream and a queue?  They both have the concept of an ordered set of elements, but tend to have different implementations and a different vocabulary of 'insert'/'extract' (streams) vs. 'enqueue'/'dequeue' (queue).  Are these interchangable?  Do they suggest different concepts or patterns?  If so, what are the differences?</p>

答:
In functional programming languages (e.g. Scala), and maybe other languages as well, streams are really more like functional lists and they are queues. I should note, however, queues can actually be implemented using a pair of lists. In Scala and probably elsewhere, a Stream is just a lazy List - more specifically, the tail of the list is a lazy val.

Functional streams can share some similarity with queues, as opposed to, lists, in that you can use them in a way that you don't keep a reference to the head of the stream - but you have to be careful: https://stackoverflow.com/a/5159356/3096687. This is somewhat analogous to a dequeue call to a queue (although in the case of a stream, you do so implicitly: http://daily-scala.blogspot.com/2010/01/streams-2-stream-construction.html).


答:
In addition to all the above, consider the following scenario:

You start out with these two classes.

```<code> class A {
    int i = 20;

    A() {
        System.out.println("I am in constructor of the parent class");
    }
}
</code>```

```<code>class B extends A {
    int i = 30;

    B() {
        System.out.println("I am in constructor of the subclass");
    }
}
</code>```

You compile both classes, it creates two class files: A.class and B.class

Now you change your mind and rewrite A:

```<code> class A {
    int i = 10;

    A() {
        System.out.println("I am in constructor of the parent class");
    }
}
</code>```

You recompile A, so you get a new A.class, which you replace the old A.class with

Now the question is: how would B know that As initialisation code has changed? You haven't recompiled B, nor should you be required to do so. After all, B may already be packaged up in a different jar, maybe even in a different product you have no control over.*

The only reasonable way to support this case is for Bs constructor to start with calling As constructor and let A initialise itself.

*This may sound far-fetched at first, but this is exactly what happens when internal implementation details of JDK classes are changed. All the previously compiled Java applications in the world should run seamlessly with the new JDK.

Title: Using super keyword to access super class members

Body:
I have following questions about the super keyword in java:

I have a code below with classes:

A Extends no class contains integer variable i

B Extends class A contains integer variable i

C Extends class B contains integer variable i

```<code> class A {
    int i = 20;

    A() {
        System.out.println("I am in constructor of the parent class");
    }
}
</code>```

```<code>class B extends A {
    int i = 30;

    B() {
        System.out.println("I am in constructor of the subclass");
    }
}
</code>```

```<code>class C extends B {
    int i = 40;

    C() {
        System.out.println("I am in constructor of the main class");
    }

    void display() {
        System.out.println(i);
        System.out.println(super.i);
        /*
         * My first thoughts to access the third variable 'i'
         * inherited indirectly to this class by 'class A'.
         * I thought that it would print 20 :(.
           System.out.println(super.super.i);
         */
    }

    public static void main(String[] argue) {
        C obj2 = new C();
        obj2.display();
    }
}
</code>```

Now as class B inherits class A so it must have two integer variables i. Class C inherits class B so it will have two integer variables from B and one defined in itself.

Now I can print the inherited super class variable i in class C through the display method and of course the variable i defined in class C itself. The question is how to print the third i which has the value "20".

I know I can define a method in the class B that returns super.i; and call it through its object in class A that will print the third variable i and I also known that I can create an object of class A, but is there any other way by using super or any other thing to directly access the third variable in the class C.

Also the output is:

```<code>      I am in constructor of the parent class
      I am in constructor of the subclass
      I am in constructor of the main class
      40
      30
</code>```

why like the this keyword the super keyword cannot be used inside     static methods?

why is the super class constructor called to initialize the inherited variables of a subclass? This doesn't make any sense because if a class extends another class the variables and methods will be like they were locally declared in the class in other words its own members. So why can't the constructor of the subclass initialize those inherited members and has to call the super class constructor to initialize them.

Body:
In addition to all the above, consider the following scenario:

You start out with these two classes.

 class A {
    int i = 20;

    A() {
        System.out.println("I am in constructor of the parent class");
    }
}

class B extends A {
    int i = 30;

    B() {
        System.out.println("I am in constructor of the subclass");
    }
}

You compile both classes, it creates two class files: A.class and B.class

Now you change your mind and rewrite A:

 class A {
    int i = 10;

    A() {
        System.out.println("I am in constructor of the parent class");
    }
}

You recompile A, so you get a new A.class, which you replace the old A.class with

Now the question is: how would B know that As initialisation code has changed? You haven't recompiled B, nor should you be required to do so. After all, B may already be packaged up in a different jar, maybe even in a different product you have no control over.*

The only reasonable way to support this case is for Bs constructor to start with calling As constructor and let A initialise itself.

*This may sound far-fetched at first, but this is exactly what happens when internal implementation details of JDK classes are changed. All the previously compiled Java applications in the world should run seamlessly with the new JDK.


答:
I am going to assume that you have genuinely done everything you could to reproduce the bug but can't.

In a case like this it is often best to add some code around the area of the application that failed to log the work being done, so that hopefully you will have more data to work form if it happens again. Think through what information you need to have that you currently don't have available. For instance, maybe it only occurs when a particular set of input parameters are sent and so you record those every time the process runs. Check with your boss however before you do this, depending on the importance of the bug and the frequency of which it occurred, he may not want to spend the time to do this.

Then you go the the person who reported the bug (you can do this in the bug tracking application if you have one, you don't have to go in person) and say that you were unable to reproduce the bug but have added some additional logging to get more detail of what the process is doing in case the bug reoccurs. Then close the bug.

If you can't do additional logging. simply report that the bug was not reproducible and that if they run into it again, this is the information you will need to reproduce it and tell them what you need. We often ask them to tell us exactly what input parameters they were putting in when they got the error. Just having a screen shot of the error helps but knowing exactly what steps they were taking and what information they tried to use at the time the error occurred is more helpful. So basically you are putting the onus back on them to give you more information when they report the error if it occurs again.

In your bug tracker, be sure to explain what steps you tried, so that if the bug occurs again, the person handling it will have some background in what was done before.

Title: How to deal with a bug which seems to have fixed itself?

Body:
I'm a web application developer for an internal system. A user reports that there's a bug.

The bug was that some words could not be displayed. The report contains a screen capture which clearly show the bug. But the report is almost a month old and the bug can no longer be reproduced in our production environment.

How should I reply to the client and the user?


答:
Non-reproducible bags are the worst! It may have been fixed in the meantime, or it may still be there but is sporadic or the steps-to-reproduce is insufficiently specified. You have to make a judgement call on how high-risk the bug is, and how much you will expand on investigating it. Are you making an online recipe-manager, or steering control software for nuclear missiles?

If it is a low-impact bug, and you know changes have been made which could have resulted in the bug being unwittingly fixed, it may be acceptable to close the bug with the note that it is not reproducible and you assume it have been fixed.

If you are more concerned, you could make some theories about what caused the bug in the first place, and look through change log and source history to see if you can spot where it was fixes.

For a more serious bug, you will have to roll back the source to the point of last release, and then try to reproduce. If you reproduce successfully, you can write tests to ensure it is fixed in later commits.


问:
How to avoid circular patterns in Node?
I'm new to Node and JavaScript (well, asynchronous programming in general) and I noticed when I was working on a project that the following code is a circular pattern and that these are bad practice for the obvious reason that the module might not have loaded yet (and the example code is throwing errors because of that).

Here's my code:

Main module

```<code>var module2 = require('./module2');

var data = 'data';

module2.fetchStuff(data);
</code>```

Module2

```<code>var module3 = require('./module3');

var cleanDataArray = [];

function fetchStuff(data){
    // Fetches stuff based on data
    module3.cleanStuff(data);
}

function takeStuffBack(data){
    cleanData.push(data);
}

module.exports = {
    fetchStuff: fetchStuff,
    takeStuffBack: takeStuffBack,
    cleanData: cleanDataArray
};
</code>```

Module3

```<code>var module2 = require('./module2');

function cleanStuff(data){
    // Clean data from needless stuff
    module2.takeStuffBack(data); // I get a TypeError here because `module2` is yet to fully load.
}

module.exports = {
    cleanStuff: cleanStuff
};
</code>```

The XY

What this structure is supposed to do is for the start module to call a fetching function in module2, the fetching function needs to "wash" the data in the 3rd module before taking it back and providing it for whatever wants to export it. So I suppose the XY is that I need to do is to get data from a 3rd party API and then "clean" the data from the things it contains but I don't want, and then I need to make that "clean" version available to the rest of the application.

What other ways are there to do this in a better manner, without a circular pattern such as this which is broken because module2 won't load before module3 tries to call it?

答:
Using callbacks is the easier concept to implement from scratch for small scenarios. For long-term projects, usually Promises are implemented.

Bluebird is one library that gives them to you. They've also been added to the JavaScript specification, so maybe now they're accessible in Node? (Sorry; my main proficiency is clientside JS). To start with, see if your actual asynchronous library can return promises. If not, it shouldn't be difficult to wrap it with one. They generally look something like this.

```<code>function PromiseWrapFunction() {
  return new Promise(success, fail) {
    libMethod.doThing({
      onSuccess: success,
      error: fail
    });
  });
}
</code>```

Then, most of your functions will look like this. Assuming that you don't expect the "onReturn" logic to be reusable, you can simply use an anonymous internal function rather than naming it.

```<code>function myAsyncFunction() {
  return myLibWrapper.PromiseWrapFunction().then(function(data) {
    var slightlyTransformedVersionOfData = {
      myVar: data.oldVar + 2
    };
    return slightlyTransformedVersionOfData;
  });
}
</code>```

The basic idea here is that you can't return the final data yet, but you can return an object that represents the final data, and easily lets any accessor register callbacks (using .then(). The return value of that .then will be another such representative object, but its .then will return the modified data from your callback. Promises are a broad concept and this is a very quick summary, so try finding tutorials on them; they're usually a great way of avoiding circular patterns like these.

Title: How to avoid circular patterns in Node?

Body:
Using callbacks is the easier concept to implement from scratch for small scenarios. For long-term projects, usually Promises are implemented.

Bluebird is one library that gives them to you. They've also been added to the JavaScript specification, so maybe now they're accessible in Node? (Sorry; my main proficiency is clientside JS). To start with, see if your actual asynchronous library can return promises. If not, it shouldn't be difficult to wrap it with one. They generally look something like this.

function PromiseWrapFunction() {
  return new Promise(success, fail) {
    libMethod.doThing({
      onSuccess: success,
      error: fail
    });
  });
}

Then, most of your functions will look like this. Assuming that you don't expect the "onReturn" logic to be reusable, you can simply use an anonymous internal function rather than naming it.

function myAsyncFunction() {
  return myLibWrapper.PromiseWrapFunction().then(function(data) {
    var slightlyTransformedVersionOfData = {
      myVar: data.oldVar + 2
    };
    return slightlyTransformedVersionOfData;
  });
}

The basic idea here is that you can't return the final data yet, but you can return an object that represents the final data, and easily lets any accessor register callbacks (using .then(). The return value of that .then will be another such representative object, but its .then will return the modified data from your callback. Promises are a broad concept and this is a very quick summary, so try finding tutorials on them; they're usually a great way of avoiding circular patterns like these.


答:
Before you start developing:

Log out of your mailbox

Turn off any IM clients

Politely ask peers to give you time to concentrate

Of course, stop surfing the Internet

Every time you're interrupted, you'll slow down as it takes your mind time to get back on track with its thoughts. I've heard figures that for each interruption, it takes the human mind 5-10 minutes to reset back to the thought process it had before the interruption. With that much time per interruption, it doesn't take much to waste the whole day.

People in our company have actually taken to blocking off time in their calendars and then moving to an empty conference room for a couple of hours each day.

Title: How to become a "faster" programmer?

Body:
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

OwnerDisplayName: Dan


问:
Is it reasonable to insist on reproducing every defect before diagnosing and fixing it?
I work for a software product company. We have large enterprise customers who implement our product and we provide support to them. For example, if there is a defect, we provide patches, etc. In other words, It is a fairly typical setup.

Recently, a ticket was issued and assigned to me regarding an exception found by a customer in a log file that has to do with concurrent database access in a clustered implementation of our product. So this customer's specific configuration may well be critical in the occurrence of this bug. All we got from the customer was their log file.

The approach I proposed to my team was to attempt to reproduce the bug in a configuration setup similar to that of the customer and get a comparable log. However, they disagree with my approach saying that I don't need to reproduce the bug as it's overly time-consuming and will require simulating a server cluster on VMs. My team suggests I simply "follow the code" to see where the thread- and/or transaction-unsafe code is and put in the change working off of a simple local development, which is not a cluster implementation like the environment from which the occurrence of the bug originates.

To me, working out of an abstract blueprint (program code) rather than a tangible, visible manifestation (runtime reproduction) seems difficult, so I wanted to ask a general question:

Is it reasonable to insist on reproducing every defect and debug it before diagnosing and fixing it?

Or:

If I am a senior developer, should I be able to read multithreaded code and create a mental picture of what it does in all use case scenarios rather than require to run the application, test different use case scenarios hands-on, and step through the code line by line? Or am I a poor developer for demanding that kind of work environment?

Is debugging for sissies?

In my opinion, any fix submitted in response to an incident ticket should be tested in an environment simulated to be as close to the original environment as possible. How else can you know that it will really remedy the issue? It is like releasing a new model of a vehicle without crash testing it with a dummy to demonstrate that the air bags indeed work.

Last but not least, if you agree with me:

How should I talk with my team to convince them that my approach is reasonable, conservative and more bulletproof?

答:
Is it reasonable to insist on reproducing every defect and debug it before diagnosing and fixing it?

Since nobody said it in clear terms yet: Absolutely not!

Like everything else in software development, bugfixing means keeping in mind time, risk, and cost. Finding a balance between these is half of the job description of a developer.

Some bugs are not important enough to spend 2 days on, but important enough to spend 10 minutes on fixing them. Other bugs are non-deterministic and you already know a test environment can't prove they've been fixed. If setting up the test environment takes 2 days, you don't do it for these bugs. Instead you spend the time on smarter things, such as finding ways to set up a test environment in 5 minutes instead of 2 days.

And of course there are bugs where if you get them wrong a client will lose $100'000+. And bugs where the client will lose $100'000+ for every hour the bug isn't fixed. You need to look at the bug and make a decision. Blanket statements to treat all bugs the same don't work.


答:
If we think more visually about how the words are commonly used, we can avoid the clutter of specific uses by particular languages and implementations, so that these terms can actually mean something:

A queue of people waits in line and are served one by one. More people join the queue at the tail. Everyone waits as service proceeds and the service time is expected to vary. You can speak of how many people are served in total.

A stream of people, for example leaving a building through a door, are not served one by one, they just pass the exit point at a more-or-less steady rate. Delays are not expected and not well tolerated. You can speak of a rate of people: one per second.

That is the intention of these terms. They are metaphors. (like everything else) (Shhh! you'll ruin the story!)

Body: What's the difference between a stream and a queue?  They both have the concept of an ordered set of elements, but tend to have different implementations and a different vocabulary of 'insert'/'extract' (streams) vs. 'enqueue'/'dequeue' (queue).  Are these interchangable?  Do they suggest different concepts or patterns?  If so, what are the differences?</p>


问:
If the size of a set exceeds the period of a PRNG, is it true that some combinations may be unable to be generated?
Given that the size of some sets (example, 52! (about 2226 or 8*1067), the number of ways to shuffle a regular deck of cards) exceeds the period of most Pseudorandom Number Generators (PRNG), is it true that some combinations may be unable to be generated by the PRNG?

Does it matter if tries to permutate the array, vs. whether it picks items one by one? What if you re-seeded the generator periodically?

EDIT: Not a duplicate. I do not see how the proposed duplicate answers the question.: Is it true that some sequences cannot be generated, no matter how you use the RNG (including re-seeding)?

答:
Well... yes. If the cycle length of a periodic output of a process is smaller than the number of possible values in the data type, then some of the values of the data type will never be generated. In fact, combinatorial numbers are huge, they are much larger than most data types, so most possible results will never be generated.

But that is not what we use RNGs for. We're not interested in a process that merely permutes the set of all possible values. We want one that mimics a natural, unpredictable process, in which we (or an adversary who works against us) cannot discern any pattern to exploit. For many tasks, periodic RNGs deliver exactly that. The fact that they skip some (or most) values is irrelevant as long as you can't easily predict which of them they skip.


答:
To have a chance at generating all sequences you need to use at least log2(n) bits of entropy. For 52! that is 226 bits of entropy.

This means you need to reseed the PRNG so that all 226 bits get used. And even then you can't be fully sure there isn't a potential collision that robbed you of a possible output.

Though in most card games the entire deck is not used so you save a few bits that way.

In most cases the bigger challenge is getting those random bits.

Title: If the size of a set exceeds the period of a PRNG, is it true that some combinations may be unable to be generated?

Body:
Given that the size of some sets (example, 52! (about 2226 or 8*1067), the number of ways to shuffle a regular deck of cards) exceeds the period of most Pseudorandom Number Generators (PRNG), is it true that some combinations may be unable to be generated by the PRNG?

Does it matter if tries to permutate the array, vs. whether it picks items one by one? What if you re-seeded the generator periodically?

EDIT: Not a duplicate. I do not see how the proposed duplicate answers the question.: Is it true that some sequences cannot be generated, no matter how you use the RNG (including re-seeding)?


答:
Keep your personal life in order.  Get lots of sleep, eat healthy, and take vitamins - especially if you have an iron deficiency.  Stay away from "the drink" - if you know what I mean.  And remember, "Both Wine and Women can lead a wise man astray."

Also, create templates of your code and a "code generator" that works using regular expression patterns.  IF you find yourself copying and pasting, then searching and replacing similar classes, automate this process.  I did this for my PHP projects, in which I can create a CRUD application, complete with all the basic MVC components, based off my data tables - the data models all look the same except for the data tables they represent, so these are setup in templates and used to generate my initial code.  Saves hours of typing.

Finally, tell all people involved with the project that the code is going to take 1/4 to 1/2 times longer than YOU think.  Negotiate more breathing room for yourself, early on.  "Late" is a relative term.  When changes occur in the project, mid-stream, let everyone know up front that 8 more hours of work has been added.  A tracking system, such as one offered in "FogBugz" might be helpful to yourself and managers to anticipate how long its going to take to get something done, based on previous experiences.  I try to take the tact, "It wasn't late - I used the proper amount of time it takes to complete this function - it merely took longer than we expected."

Another programmer may say, "Well I could have done it faster..."  Maybe, maybe not, that's not a point worth debating or beating yourself up about - there's always going to be some "smart" guy trying to push that button.  He'll slow you down if you think about it!  Its always a bad situation when its your boss, though.  At that point, I'd consider looking for another job, cause that sort of boss is an arrogant JERK, in my book.

Title: How to become a "faster" programmer?

OwnerDisplayName: JasonMichael


问:
How does "repeat x = x:repeat x" return a list in Haskell?
This is supposed to return an infinite list of x's. However a list is created using an element, then the operator ':' and then a list.

The recursive definition of repeat' x = x:repeat' x seems to never get to the point where an actual list is created as it seams to continuously add singular elements (where?), doing something like x:x:x:x:...

答:
It creates an infinite list.

Since Haskell is lazy, the next invocation of repeat is not executed until it is needed for other computation. If you only need the first element of x:xs, x will be computed but xs will not be.

This way you can get as much of your infinite list as you need, beginning from the first element. E.g. take 5 $ repeat 'A' will give you "AAAAA" without computing the infinite rest of As.


答:
Probably your confusion comes from the fact that you are used to eager evaluation, whereas Haskell uses lazy evaluation.

For example, if you were to use the definition

```<code>repeat' x = x : repeat' x
</code>```

to evaluate the expression repeat' 10 eagerly, then you would get

```<code>repeat' 10                ==>
10 : repeat' 10           ==>
10 : 10 : repeat' 10      ==>
10 : 10 : 10 : repeat' 10 ==>
...
</code>```

and this would loop forever.

With lazy evaluation it is different. If you have the expression repeat' 10 in a certain context, this is not evaluated until the result of repeat' 10 is required.

As soon as you take values from the list, the above steps are executed, but only as many of them get executed as requested.

So, in Haskell applying your function to some value does not create an infinite data structure that is completely loaded in memory at some point in time: this is impossible because there is only a finite amount of memory and a computation that terminates can only take a finite amount of time. It rather creates a program from which you can pull any finite number of elements, i.e. any finite prefix of the infinite list.

Note that the finite prefix is not represented as a plain list

```<code>10 : 10 : 10 : []
</code>```

but as a term like

```<code>10 : 10 : 10 : repeat' 10
</code>```

So, suppose you want to compute with a finite list, e.g. take 2 [1, 2, 3]:

```<code>take 2 (1 : 2 : 3 : []) ==>
1 : take 1 (2 : 3 : []) ==>
1 : 2 : take 0 (3 : []) ==>
1 : 2 : []
</code>```

Now, the same but with your infinite list:

```<code>take 2 (repeat' 10)           ==> -- repeat' x = x : repeat' x
take 2 (10 : repeat' 10)      ==> -- take n (x : xs) = x : take (n - 1) xs
10 : take 1 (repeat' 10)      ==> -- repeat' x = x : repeat' x
10 : take 1 (10 : repeat' 10) ==> -- take n (x : xs) = x : take (n - 1) xs
10 : 10 : take 0 (repeat' 10) ==> -- take 0 _        = []
10 : 10 : []
</code>```

Title: How does "repeat x = x:repeat x" return a list in Haskell?

Body:
This is supposed to return an infinite list of x's. However a list is created using an element, then the operator ':' and then a list.

The recursive definition of repeat' x = x:repeat' x seems to never get to the point where an actual list is created as it seams to continuously add singular elements (where?), doing something like x:x:x:x:...

Body:
Probably your confusion comes from the fact that you are used to eager evaluation, whereas Haskell uses lazy evaluation.

For example, if you were to use the definition

repeat' x = x : repeat' x

to evaluate the expression repeat' 10 eagerly, then you would get

repeat' 10                ==>
10 : repeat' 10           ==>
10 : 10 : repeat' 10      ==>
10 : 10 : 10 : repeat' 10 ==>
...

and this would loop forever.

With lazy evaluation it is different. If you have the expression repeat' 10 in a certain context, this is not evaluated until the result of repeat' 10 is required.

As soon as you take values from the list, the above steps are executed, but only as many of them get executed as requested.

So, in Haskell applying your function to some value does not create an infinite data structure that is completely loaded in memory at some point in time: this is impossible because there is only a finite amount of memory and a computation that terminates can only take a finite amount of time. It rather creates a program from which you can pull any finite number of elements, i.e. any finite prefix of the infinite list.

Note that the finite prefix is not represented as a plain list

10 : 10 : 10 : []

but as a term like

10 : 10 : 10 : repeat' 10

So, suppose you want to compute with a finite list, e.g. take 2 [1, 2, 3]:

take 2 (1 : 2 : 3 : []) ==>
1 : take 1 (2 : 3 : []) ==>
1 : 2 : take 0 (3 : []) ==>
1 : 2 : []

Now, the same but with your infinite list:

take 2 (repeat' 10)           ==> -- repeat' x = x : repeat' x
take 2 (10 : repeat' 10)      ==> -- take n (x : xs) = x : take (n - 1) xs
10 : take 1 (repeat' 10)      ==> -- repeat' x = x : repeat' x
10 : take 1 (10 : repeat' 10) ==> -- take n (x : xs) = x : take (n - 1) xs
10 : 10 : take 0 (repeat' 10) ==> -- take 0 _        = []
10 : 10 : []


问:
Why ever use exception throw (in C#) except for Class Library development?
Why would I ever throw exceptions in code? (except for one specific scenario where I am developing a class library which the consumers of it, will not want / be able to change).

To be more specific, is there any reason to do this:

class EmailSender
{
   public void SendEmail(string recipient, string subject, string content)
   {
       if (string.IsNullOrEmpty(recipient))
       {
           throw new ArgumentNullException("exception text...");
       }

       // Send the email
   }

}
```

<p>Instead of this:</p>

<pre class="lang-cs prettyprint-override"><code>class EmailSender
{
   public bool SendEmail(string recipient, string subject, string content)
   {
       bool result = false;

       try
       {
           if (string.IsNullOrEmpty(recipient))
           {
              logger.Error("Error text...");
           }
           else
           {
              // Send the email
              result = true;
           }
       }
       catch (Exception ex)
       {
           logger.Error(ex);
       }

       return result;
   }
}
</code>```

Take into account that this class is in-house code and not something I am going to ship as a DLL or an open source project.

答:
Are you asking why not always handle the error inside the same method the error is detected?

It is rarely the case that you can handle an error at the same level as where the problem is detected, it is only possible because you example is contrived. For example, what if the "send the mail" logic contains multiple method calls:

```<code>VerifyAdresses(recipient);
ConnectToSmtpServer();
PostMessage();
</code>```

What if an error is detected in VerifyAdresses or ConnectToSmtpServer? If the method just logs the error and continues happily (as in your example), the PostMessage will be execute in any case, probably with a much more severe error as result.

You need to handle errors at the level where it is possible to gracefully recover. For example you can handle error in the mailing logic by not sending the mail. But you cannot gracefully handle an error locally inside VerifyAdresses() if that error prevents the whole operation of sending an mail. You need to be able to drop back up the call stack (possibly multiple steps) to the level where the error can sensibly be handled.

Edit: OK, you are really asking why not use C-style success/error result codes instead of exceptions. This discussion have been beaten to death, but suffice to say that the framework have made the choice for you. Result codes consistently used may in theory be as good as exceptions (if much more tedious and error prone), but since the framework already uses exceptions, it would be incredibly confusing and a waste of resources to use both exceptions and result codes in the same code base.

Body:
Are you asking why not always handle the error inside the same method the error is detected?

It is rarely the case that you can handle an error at the same level as where the problem is detected, it is only possible because you example is contrived. For example, what if the "send the mail" logic contains multiple method calls:

VerifyAdresses(recipient);
ConnectToSmtpServer();
PostMessage();

What if an error is detected in VerifyAdresses or ConnectToSmtpServer? If the method just logs the error and continues happily (as in your example), the PostMessage will be execute in any case, probably with a much more severe error as result.

You need to handle errors at the level where it is possible to gracefully recover. For example you can handle error in the mailing logic by not sending the mail. But you cannot gracefully handle an error locally inside VerifyAdresses() if that error prevents the whole operation of sending an mail. You need to be able to drop back up the call stack (possibly multiple steps) to the level where the error can sensibly be handled.

Edit: OK, you are really asking why not use C-style success/error result codes instead of exceptions. This discussion have been beaten to death, but suffice to say that the framework have made the choice for you. Result codes consistently used may in theory be as good as exceptions (if much more tedious and error prone), but since the framework already uses exceptions, it would be incredibly confusing and a waste of resources to use both exceptions and result codes in the same code base.


答:
Software generally consists of layers of functionality.  (i.e. the application layer, the persistence layer, the network layer, the database layer, etc.)

A "library" is a layer of functionality which has been distanced from your code by having been moved into a separate binary file, but this is just a technicality, the point is that it is just another layer of functionality.

A layer of functionality generally communicates errors to the layer above by throwing exceptions.

So, if all of the software that you are writing lives in a single layer as thin as a crispy pizza dough, then yes, I suppose there may be no need for you to ever throw an exception.

But if you ever do anything non-trivial in your career, then you will of course work simultaneously at different layers, and therefore you will have a need to throw an exception in one layer, to be caught (or not) by a layer above.

Title: Why ever use exception throw (in C#) except for Class Library development?

Body:
Why would I ever throw exceptions in code? (except for one specific scenario where I am developing a class library which the consumers of it, will not want / be able to change).

To be more specific, is there any reason to do this:

class EmailSender
{
   public void SendEmail(string recipient, string subject, string content)
   {
       if (string.IsNullOrEmpty(recipient))
       {
           throw new ArgumentNullException("exception text...");
       }

       // Send the email
   }

}
```

<p>Instead of this:</p>

<pre class="lang-cs prettyprint-override"><code>class EmailSender
{
   public bool SendEmail(string recipient, string subject, string content)
   {
       bool result = false;

       try
       {
           if (string.IsNullOrEmpty(recipient))
           {
              logger.Error("Error text...");
           }
           else
           {
              // Send the email
              result = true;
           }
       }
       catch (Exception ex)
       {
           logger.Error(ex);
       }

       return result;
   }
}
</code>```

Take into account that this class is in-house code and not something I am going to ship as a DLL or an open source project.


问:
Redistributing Nuget References w/ Licenses
I have a basic gap in my knowledge when it comes to open source licensing.

I realize that the answers to this question aren't legally binding :).

With that being said, let's say I am writing a custom application for a client.  It will run on their infrastructure.

Assume that:

I add a library to the project via NuGet.

That library is using the Apache 2.0 license.

I am not modifying the library at all - I am using it as is.

Do I need to provide a copy of the license in the source code?

Do I need to provide a copy of the license with the application binaries?

答:
The Apache 2.0 license lists under section 4. Redistribution:

You may reproduce and distribute copies of the Work or Derivative Works […] in Source or Object form,
  provided that You meet the following conditions:

1. You must give any other recipients of the Work or Derivative Works a copy of this License

[…]

3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work […]

4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file […]

So yes, you must provide a copy of the license with the source code and with compiled binaries. You also mustn't delete existing attribution notices from the source code. Also, you must forward a NOTICE file if it exists. If you fulfil these conditions, you can copy the library and distribute it to your client.

The patent stuff in the license is irrelevant for you if you don't own any patents regarding this software, but is important so that you and your client can use this software without inadvertently infringing on any author's patents. Event though, you do have to copy the license!


问:
How to design a meta model for configuration?
In our software we have a client/server architecture where the server is actually running on an embedded system with various hardware components (sensors, etc.). The different sensors as well as other features of the system itself can be configured by the client. The client does not know in advance which features and components can exist on the server. Client and Server are communicating over a network. The client should be user friendly. Technological and political constraints forbid us to use HTML/JS as a client (we use .NET).

Long story short, we want to provide a general meta-model for configuration that described configuration entities, their properties, relationships between the properties, validation rules, etc.

However we are realizing this is actually quite a complex task and I would like to hear opinions, helpfull tips and hopefully existing frameworks or models that can be used. We are currently looking at RDF as a possible language to dynamically create an ontology describing all the relationships described above, but RDF seems very complex for this.

Any ideas or suggestions?

答:
Use a Dictionary or Key/Value list to encode sensor attributes.  You can serialize it to send over the wire, and you don't need to know anything about your data model (i.e. your sensors) in advance to make it work.  Include a "Type" field in your object containing the dictionary, so that you know what kind of sensor it is.</p>

```<code>public class Sensor
{
    public SensorType SensorType { get; set; }
    public string Description { get; set; }

    // Properties common to all sensors go here
   ...

   // Properties specific to sensor type go into the dictionary.
    public Dictionary<string, string> SensorAttributes { get; set; }
}
</code>```

Body:
Use a Dictionary or Key/Value list to encode sensor attributes.  You can serialize it to send over the wire, and you don't need to know anything about your data model (i.e. your sensors) in advance to make it work.  Include a "Type" field in your object containing the dictionary, so that you know what kind of sensor it is.

public class Sensor
{
    public SensorType SensorType { get; set; }
    public string Description { get; set; }

    // Properties common to all sensors go here
   ...

   // Properties specific to sensor type go into the dictionary.
    public Dictionary<string, string> SensorAttributes { get; set; }
}


答:
I think they key word here is "timeliness". They didn't say you were too slow, rather that you were not timely.

In project management, it is important for the manager to be able to estimate when your work items will be complete with accuracy. I suspect that the main reason why your efforts were not deemed to be timely is that you frequently had items that were not delivered on schedule, and were delivered much later than scheduled.

To improve your timeliness, you might want to spend more time understanding how long it will take you to complete a particular work item given your skills, experience, and the domain. This will allow you to give better estimates to your project manager. The key here is "better" ... you could deliver on time more frequently by padding everything with a fudge factor, but what you really want to strive for is a more accurate estimate.

I would discuss this with your manager to see if this is actually the issue. Otherwise, you might end up programming twice as fast, promising things in half the time you used to, and still getting criticized for your timeliness because your estimates will still have the same error factor.

Title: How to become a "faster" programmer?

OwnerDisplayName: Larry Watanabe


问:
Is there particular circumstance that throwing root superclass exceptions is a good practice?
I've been taught that exceptions should be have concise meanings and should contain a message that explains to the client what the exceptional situation is. I am wondering, since I found a piece of code that contains a couple of lines into a try catch block and in the end catches a generic exception with the message: An error occurred performing the task

This is written in a library and somehow I trigger this exception. How am I supposed to fix what is broken if I do not know what is broken? Generally I know that this is not a good practice. Are there any situations that throwing/catching generic exceptions is a good practice?

答:
Using catch-all exception handlers is important in a couple of cases:

Your software needs to log all exceptions. Therefore, you will catch all exceptions at the outermost layer, log them, and rethrow them.

Your software is a long-running daemon or server that must not go down when some task cannot be completed. When you spawn a task, you will capture any exceptions thrown by that task and carry on regardless of failure of that task. E.g. a HTTP web server should not go down if any request leads to an exception. Instead, it responds with a 500 internal server error and continues to serve the other requests. Details of the original error are available in a log, and not passed on.

Your software is a library or layer. When an exception occurs, wrapping any exception in a domain-specific exception can provide more information than a naked stack trace. E.g. an FileNotFoundException("ad83jfw8.rsa could not be opened") is irrelevant to an external user when compared with a

```<code>IllegalConfigurationValue(
  key="crypto.secretKey",
  value="ad83jfw8.rsa",
  file="myApp.cfg",
  line=13,
  message="file could not be opened",
  cause=FileNotFoundException(…),
)
</code>```

The important point when substituting errors with custom exceptions is that the original problem is not swallowed but wrapped! The original exception should be passed along as a field, and probably be printed out in addition to a stack trace. E.g. in Java, the standard exception classes can take a Throwable cause in addition to a message. This design absolutely should be copied in custom exception classes!

In other cases, there is no excuse for swallowing an error. At the very minimum, the error must be wrapped or logged.

Body:
Using catch-all exception handlers is important in a couple of cases:

Your software needs to log all exceptions. Therefore, you will catch all exceptions at the outermost layer, log them, and rethrow them.

Your software is a long-running daemon or server that must not go down when some task cannot be completed. When you spawn a task, you will capture any exceptions thrown by that task and carry on regardless of failure of that task. E.g. a HTTP web server should not go down if any request leads to an exception. Instead, it responds with a 500 internal server error and continues to serve the other requests. Details of the original error are available in a log, and not passed on.

Your software is a library or layer. When an exception occurs, wrapping any exception in a domain-specific exception can provide more information than a naked stack trace. E.g. an FileNotFoundException("ad83jfw8.rsa could not be opened") is irrelevant to an external user when compared with a

IllegalConfigurationValue(
  key="crypto.secretKey",
  value="ad83jfw8.rsa",
  file="myApp.cfg",
  line=13,
  message="file could not be opened",
  cause=FileNotFoundException(…),
)

The important point when substituting errors with custom exceptions is that the original problem is not swallowed but wrapped! The original exception should be passed along as a field, and probably be printed out in addition to a stack trace. E.g. in Java, the standard exception classes can take a Throwable cause in addition to a message. This design absolutely should be copied in custom exception classes!

In other cases, there is no excuse for swallowing an error. At the very minimum, the error must be wrapped or logged.


答:
An exception should be descriptive. This is a combination of three things:

The identity (type) of the exception.

The message contained in the exception.

Other metadata contained in the exception such as a chained exception or error code.

Please note that different languages and runtimes have slightly different exception semantics, but these three ideas are fairly universal. At the very least, an exception has a type and usually has a message, but additional data is not always relevant. Also note that some languages such as C++ do not have a "root" exception type: while C++ does have std::exception, one may throw anything including primitives.

Picking on Java, there are four core types that form the backbone of the exception hierarchy: Throwable, Error, Exception, and RuntimeException. While none are abstract, none are intended to be thrown directly: one should use a more specific type. That being said, the fact that none are abstract means it is possible to instantiate and throw them directly.

Back to your original point: generally, one should throw specific exception subtypes because it makes it easier for specific exceptions to bubble up the call stack to be caught at the appropriate level. Consider the following Java example:

public void doSomething() throws Exception {
  doOneThing(); // Throws Exception
  doAnotherThing(); // Throws IOException
}
```

<p>If <code>doSomething()</code> is not an appropriate place to handle the exception, the method calling it must know what exceptions to catch. The order of the <code>catch</code> clauses is also important: they must go from specific to general. Catching <code>Exception</code> first will swallow <em>all</em> exceptions, including <code>IOException</code>, in the same block. This becomes a little tougher to figure out what to catch and what to do with the exception once caught. Consider this code instead:</p>

<pre class="lang-java prettyprint-override"><code>public void doSomething() throws SQLException, IOException {
  doOneThing(); // Throws SQLException
  doAnotherThing(); // Throws IOException
}
</code>```

It is now far less ambiguous what the possible errors are, and there is no coupling in terms of the order in which they are caught. Instead of this:

try {
  doSomething();
}
// Order matters!
catch (IOException e) {
  // Obviously some sort of file or socket I/O error.
}
catch (Exception e) {
  // What are we dealing with here?
}
```

<p>We have this:</p>

<pre class="lang-java prettyprint-override"><code>try {
  doSomething();
}
catch (IOException e) {
  // Obviously some sort of file or socket I/O error.
}
catch (SQLException e) {
  // Now we can get the error code and do something meaningful.
}
</code>```

You can also allow some exceptions to pass through up the call stack, and others to be handled in that try/catch block. For example, the first example would make it difficult to allow SQLException to pass up the call stack while handling IOException, because it is not declared properly. While possible, it would require casting, type checking, and would be brittle and unclean code.

The second example is more clear in terms of intent and allows more useful operations to be performed using the exception object.

Note that the above examples make the point that you might want to let some exceptions pass through, or you might want to handle different exceptions differently (e.g. show an error message for one, retry the operation for another). Some languages allow catching multiple types of exceptions without catching all exceptions. That can be a good compromise between a catch-all block and a very verbose "catch this, then this, then ..." block.

For example, consider the following block:

try {
  // open a file, read some XML, and instantiate
  // some classes referenced therein using reflection.
  initializeModule();
}
catch (IOException e) {
  // Do something
}
catch (ReflectiveOperationException e) {
  // Do something
}
catch (XMLStreamException e) {
  // Do something
}
```

<p>Java 8 allows the following instead:</p>

<pre class="lang-java prettyprint-override"><code>try {
  // open a file, read some XML, and instantiate
  // some classes referenced therein using reflection.
  initializeModule();
}
catch (IOException | ReflectiveOperationException | XMLStreamException e) {
  // Do something
}
</code>```

This can be a good compromise because it catches specific exceptions in a single block without catching too much which might not be a clean design or the right place to catch other exceptions. For example, the code above lets RuntimeException classes (e.g. null pointers) pass up the call stack. This can be annoying to do in Java because RuntimeException inherits from Exception. Catching Exception will also catch RuntimeExceptions, which is not always what one wants to do.

The only time where I find catching all exceptions to be good practice is as a last resort before dying:

public static void main(String[] args) {
  try {
    // Invoke program logic here.
  }
  catch (Throwable t) {
    // Last-ditch logging before letting the program die.
  }
}
```

Title: Is there particular circumstance that throwing root superclass exceptions is a good practice?

Body:
I've been taught that exceptions should be have concise meanings and should contain a message that explains to the client what the exceptional situation is. I am wondering, since I found a piece of code that contains a couple of lines into a try catch block and in the end catches a generic exception with the message: An error occurred performing the task

This is written in a library and somehow I trigger this exception. How am I supposed to fix what is broken if I do not know what is broken? Generally I know that this is not a good practice. Are there any situations that throwing/catching generic exceptions is a good practice?

Body:
An exception should be descriptive. This is a combination of three things:

The identity (type) of the exception.

The message contained in the exception.

Other metadata contained in the exception such as a chained exception or error code.

Please note that different languages and runtimes have slightly different exception semantics, but these three ideas are fairly universal. At the very least, an exception has a type and usually has a message, but additional data is not always relevant. Also note that some languages such as C++ do not have a "root" exception type: while C++ does have std::exception, one may throw anything including primitives.

Picking on Java, there are four core types that form the backbone of the exception hierarchy: Throwable, Error, Exception, and RuntimeException. While none are abstract, none are intended to be thrown directly: one should use a more specific type. That being said, the fact that none are abstract means it is possible to instantiate and throw them directly.

Back to your original point: generally, one should throw specific exception subtypes because it makes it easier for specific exceptions to bubble up the call stack to be caught at the appropriate level. Consider the following Java example:

public void doSomething() throws Exception {
  doOneThing(); // Throws Exception
  doAnotherThing(); // Throws IOException
}

If doSomething() is not an appropriate place to handle the exception, the method calling it must know what exceptions to catch. The order of the catch clauses is also important: they must go from specific to general. Catching Exception first will swallow all exceptions, including IOException, in the same block. This becomes a little tougher to figure out what to catch and what to do with the exception once caught. Consider this code instead:

public void doSomething() throws SQLException, IOException {
  doOneThing(); // Throws SQLException
  doAnotherThing(); // Throws IOException
}

It is now far less ambiguous what the possible errors are, and there is no coupling in terms of the order in which they are caught. Instead of this:

try {
  doSomething();
}
// Order matters!
catch (IOException e) {
  // Obviously some sort of file or socket I/O error.
}
catch (Exception e) {
  // What are we dealing with here?
}

We have this:

try {
  doSomething();
}
catch (IOException e) {
  // Obviously some sort of file or socket I/O error.
}
catch (SQLException e) {
  // Now we can get the error code and do something meaningful.
}

You can also allow some exceptions to pass through up the call stack, and others to be handled in that try/catch block. For example, the first example would make it difficult to allow SQLException to pass up the call stack while handling IOException, because it is not declared properly. While possible, it would require casting, type checking, and would be brittle and unclean code.

The second example is more clear in terms of intent and allows more useful operations to be performed using the exception object.

Note that the above examples make the point that you might want to let some exceptions pass through, or you might want to handle different exceptions differently (e.g. show an error message for one, retry the operation for another). Some languages allow catching multiple types of exceptions without catching all exceptions. That can be a good compromise between a catch-all block and a very verbose "catch this, then this, then ..." block.

For example, consider the following block:

try {
  // open a file, read some XML, and instantiate
  // some classes referenced therein using reflection.
  initializeModule();
}
catch (IOException e) {
  // Do something
}
catch (ReflectiveOperationException e) {
  // Do something
}
catch (XMLStreamException e) {
  // Do something
}

Java 8 allows the following instead:

try {
  // open a file, read some XML, and instantiate
  // some classes referenced therein using reflection.
  initializeModule();
}
catch (IOException | ReflectiveOperationException | XMLStreamException e) {
  // Do something
}

This can be a good compromise because it catches specific exceptions in a single block without catching too much which might not be a clean design or the right place to catch other exceptions. For example, the code above lets RuntimeException classes (e.g. null pointers) pass up the call stack. This can be annoying to do in Java because RuntimeException inherits from Exception. Catching Exception will also catch RuntimeExceptions, which is not always what one wants to do.

The only time where I find catching all exceptions to be good practice is as a last resort before dying:

public static void main(String[] args) {
  try {
    // Invoke program logic here.
  }
  catch (Throwable t) {
    // Last-ditch logging before letting the program die.
  }
}


答:
You seem to have two confusions here: first, how does Haskell ever complete a recursive definition such as repeat x = x:repeat x, and second, how does it know that this does, in fact, define a list.

The first is answered, as the other responses have done, by saying "laziness".  Writing repeat x = x:repeat x is actually a description of the value repeat x, to be consulted whenever individual entries in that value are needed.

The second is called "type inference" and goes like this.  Haskell knows that the operator : has the following type:

```<code>(:) :: a -> [a] -> [a]
</code>```

and therefore, in an expression x:y, y must be a list whose elements have the same type as x, and the expression itself is this kind of list as well.  So in x:repeat x, we must have repeat x be a list of values with the same type as x, and then the result of this is also such a list.  So it works out, at least for types, to declare that this list should equal repeat x itself.

Body:
You seem to have two confusions here: first, how does Haskell ever complete a recursive definition such as repeat x = x:repeat x, and second, how does it know that this does, in fact, define a list.

The first is answered, as the other responses have done, by saying "laziness".  Writing repeat x = x:repeat x is actually a description of the value repeat x, to be consulted whenever individual entries in that value are needed.

The second is called "type inference" and goes like this.  Haskell knows that the operator : has the following type:

(:) :: a -> [a] -> [a]

and therefore, in an expression x:y, y must be a list whose elements have the same type as x, and the expression itself is this kind of list as well.  So in x:repeat x, we must have repeat x be a list of values with the same type as x, and then the result of this is also such a list.  So it works out, at least for types, to declare that this list should equal repeat x itself.


问:
Is it ok to use service locator for ubiquitously used dependencies?
We strictly adhere to inversion of control in our codebase, but that creates hellish constructors (yes, I know that means our classes aren't cohesive enough, this is a work in progress).
The thing is, that sometimes those dependencies are quite silly like a DateTime wrapper to enable date mocking, or the logger, or a TaskFactory wrapper which are not directly related to the business of the class and I do not think they require explicit introduction.

Could we ease the load on our ctors by using a service locator for those items which are passed all over the system? What would be the disadvantages?

答:
What would happen if you decide that Class A needs a different logger (for example) than Class B? Or even harder, if instance 1 of Class A needs a different logger than instance 2 of Class A?

You might not have this requirement now, but in the feature you might have it. Maybe you want specific classes or instances to log into different files or to use completely different logging libraries.

These concerns might also be valid for the other dependencies that you want to obtain from the service locator.

You cannot solve this issue if you are using the Service Locator because the Service Locator limits composability. On the other hand, if you inject your dependencies, you have full power to compose your objects in anyway that you want.


答:
The one thing that I have noticed affecting my speed the most is motivation and having fun. This may seem Fuzzy, but when I'm motivated and doing something that I find fun I can be extremely effective. On the other hand when I'm neither it really feels like I have to push every single line of code out of me.

Find your sweet spots, what really motivates you and what kind of tasks do you really enjoy doing? And can you affect your planning so that you can do this? For me it's when I get to solve problems and design issues, and when I feel that I have a part of the project.

A few months ago we had a small project that our small team was assigned to do and it was a really important and very unrealistic deadline to it. However we were all very motivated and had great fun doing it and got it done in time, with a happy customer. The reason for my motivation was that we were very involved in the project and had to come up with creative ideas for it. I also got to do the parts that I really enjoy.

However recently I have been involved in a project where I'm basically being a code monkey, just doing mind numbing and frustrating tasks, or just having quick-fixing stuff the fastest way possible which I know will come back and bite me hard sometime in a near future, and it has been painfully slow.

So what is your sweet spots?

Title: How to become a "faster" programmer?

OwnerDisplayName: Runeborg


问:
A programming language that does not allow IO. Haskell is not a pure language
Are there any 100% pure languages (as I describe in the Stack Overflow post) out there already and if so, could they feasibly be used to actually do stuff? i.e. do they have an implementation? I'm not looking for raw maths on paper/Pure lambda calculus. However Pure lambda calculus with a compiler or a runtime system attached is something I'd be interested in hearing about.</p>

答:
"Purely functional language" is a quite confusing term.  Taken literally, the term means something like "a language that is only functional and nothing else".  So it encompasses Haskell, ML, Clean, etc.; Scheme comes close but doesn't quite make it; and the "impure" functional languages are strictly Perl, Scala, JavaScript, etc. --- "multi-paradigm" languages with good support for functional programming.  That's clearly not what people mean by "purely functional", though.

The key is to understand that people who say "purely functional language" really mean to say "pure functional language" --- a language based on pure functions --- and "purely functional" is a slip of the tongue that's become conventional.  The motto is "it's the functions that are pure, not the language".

Now, obviously you can't do I/O with pure functions1.  This makes purely functional languages different from impure languages, where a function like (made-up semantics)

```<code>promptForName = do { print "What is your name"; getLine }
</code>```

could be attributed the type String -> String.  But a functional language will generally have lots of other types beside just functions!  ("Purely functional" does not mean "everything is a function" in the same way that "pure OO" means "everything is an object".)  You can use any of those types to do I/O, if that's what you want that type for.

So the IO monad in Haskell is just a data type.  A value of that type represents a list of I/O actions for the program to perform (basically).  At runtime, the computer alternates between evaluating that list a little further and executing the actions described.  But the evaluation does no I/O!  That happens after the value's already been obtained.

1 Without defining additional semantics.  You could say "a program is a function of type String -> String; running it reads the contents of STDIN as a (lazy) string, applies the function to that string, and writes the resulting (lazy) string to STDOUT; but the entry point is the only function of type String -> String in the program that has those semantics, so it's not really the function type doing the I/O here.

Body:
"Purely functional language" is a quite confusing term.  Taken literally, the term means something like "a language that is only functional and nothing else".  So it encompasses Haskell, ML, Clean, etc.; Scheme comes close but doesn't quite make it; and the "impure" functional languages are strictly Perl, Scala, JavaScript, etc. --- "multi-paradigm" languages with good support for functional programming.  That's clearly not what people mean by "purely functional", though.

The key is to understand that people who say "purely functional language" really mean to say "pure functional language" --- a language based on pure functions --- and "purely functional" is a slip of the tongue that's become conventional.  The motto is "it's the functions that are pure, not the language".

Now, obviously you can't do I/O with pure functions1.  This makes purely functional languages different from impure languages, where a function like (made-up semantics)

promptForName = do { print "What is your name"; getLine }

could be attributed the type String -> String.  But a functional language will generally have lots of other types beside just functions!  ("Purely functional" does not mean "everything is a function" in the same way that "pure OO" means "everything is an object".)  You can use any of those types to do I/O, if that's what you want that type for.

So the IO monad in Haskell is just a data type.  A value of that type represents a list of I/O actions for the program to perform (basically).  At runtime, the computer alternates between evaluating that list a little further and executing the actions described.  But the evaluation does no I/O!  That happens after the value's already been obtained.

1 Without defining additional semantics.  You could say "a program is a function of type String -> String; running it reads the contents of STDIN as a (lazy) string, applies the function to that string, and writes the resulting (lazy) string to STDOUT; but the entry point is the only function of type String -> String in the program that has those semantics, so it's not really the function type doing the I/O here.


答:
I presume that when you say a "DateTime wrapper" what you really mean is a "Clock" interface which can be queried for the DateTime value which humans occasionally perceive as "now".

I too have encountered the problem of having to pass dependencies around a lot, and I have solved it with a universal lightweight adaptation of Domain Driven Design which I call Subject Oriented Programming.

I don't use service locators because:

A service locator is a mandatory global dependency. That's a bad thing to have. Trust me, you will sooner or later regret having it.

A service locator may, as JDT pointed out, defer a compile-time error to a run-time error. And since these errors occur when a system is being wired together, while tests are usually wired differently, these errors cannot be detected with unit testing or integration testing, you have to do end-to-end testing in order to discover them.

I also don't use dependency injection frameworks because:

They work by magic, and I don't like magic.

They embrace silent failure, while I mandate hard failure.

They don't have an API that you can call, so you cannot use code completion, you have to know stuff by heart.

The idea behind Subject Oriented Programming is this:

Every object ideally belongs to a domain. In this case, it is called a subject of that domain.

A domain is the exclusive factory of its subjects. Nobody else may instantiate a subject.  This in turn means that all subject constructors are hidden to the outside world.  (Package-private in java.)

Ideally, subjects are visible to outside code (code outside the namespace or package of their domain) via interfaces, not as concrete classes. (But this is irrelevant to this discussion.)

Every subject receives a reference to the domain to which it belongs as its first constructor parameter. (This is analogous to how every method of an object receives the this pointer as its first (hidden) parameter. In other words, the domain is to a subject what the object is to a method.)

Every subject that needs to use some service obtains it from its own domain via a property of the domain. (Regular getXYZ(), no map lookup.)

The domain may offer a service directly, as in myDomain.getGradientSaturator(), or indirectly, as in myDomain.getSplineDomain().getReticulator().

Domains receive their dependencies as constructor parameters.

So:

Nobody needs to query any repository for services, no huge lists of dependencies are passed either to constructors or to factory methods, (except perhaps to constructors of domains, which are rare,) and the availability of all services is guaranteed (so to speak*) by the compiler.

Still, at various places where domain hierarchies are constructed, all necessary services are supplied, so any one of them can be replaced with a mock.

In lack of any better term, I am calling this Subject-Oriented Programming for the time being.

(*) so to speak, unless you do something silly, like pass null to a constructor which expected a GradientSaturator.

Title: Is it ok to use service locator for ubiquitously used dependencies?

Body:
We strictly adhere to inversion of control in our codebase, but that creates hellish constructors (yes, I know that means our classes aren't cohesive enough, this is a work in progress).
The thing is, that sometimes those dependencies are quite silly like a DateTime wrapper to enable date mocking, or the logger, or a TaskFactory wrapper which are not directly related to the business of the class and I do not think they require explicit introduction.

Could we ease the load on our ctors by using a service locator for those items which are passed all over the system? What would be the disadvantages?

ContentLicense: CC BY-SA 4.0


问:
For what reasons would you use a separate class extension for each delegate in Swift?
I was working through a Ray Wenderlich tutorial and noticed that the author uses class extensions to hold delegate callbacks rather than having them be handled in the class itself i.e.:

delegate callbacks inside class extension:

```<code>extension LogsViewController : UIPopoverPresentationControllerDelegate {
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        ...
    }
}
</code>```

as opposed to having it be contained within the class:

delegate callbacks inside class:

```<code>class LogsViewController : UITableViewController, UIPopoverPresentationControllerDelegate {
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        ...
    }
}
</code>```

I found this strange and interesting at the same time. He has a file dedicated just to extensions on the LogsViewController class named "LogsViewControllerExtension.swift" and has a different extension for each delegate protocol: UITableViewDataSource, UISplitViewDelegate, etc i.e.:

multiple class extensions each w/ delegate callbacks inside its own file:

```<code>extension LogsViewController: UISplitViewControllerDelegate {
    ... callbacks
}

extension LogsViewController : UIPopoverPresentationControllerDelegate {
    ... callbacks
}
</code>```

Why?

What advantages are there to doing this? I can see where it might be a little more readable to separate this out but at the same time it is a level of indirection. Are there OO principles that are supportive of or against doing this?

答:
I don't know why you said it adds a level of indirection. Maybe you mean something different by that than the traditional meaning, because there is no extra indirection created by doing this. But why do it?

I do it because it is more modular. All the code that is required by the interface is grouped in a single place (except the actual properties.) If I later choose to make a separate class to implement that protocol (and thus introduce an actual level of indirection,) all I need to do is change the extension into a class of it's own (passing the needed properties in through an init function,) and create a property on the ViewController to instantiate the object into.

I also put any private functions which are only used by the functions of that protocol into the extension. I haven't gone so far as to create a completely separate file for the extension, but doing so makes it clear that those private functions are only for that protocol.

And at any rate, people often complain about fat view controllers and breaking a view controller up this way helps keep it better organized, even if it doesn't actually make the view controller thinner.


问:
Is it better to check `c >= '0'` or `c >= 48`?
After a discussion with some my colleagues, I've a 'philosophical' question about how treat the char data type in Java, following the best practices.

Suppose a simple scenario (obviously this is only a very simple example in order to give a practice meaning to my question) where, given a String 's' as input, you have to count the number of numeric characters present in it.

These are the 2 possible solutions:

1)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= 48 && s.charAt(i) <= 57) {
            n++;
        }
    }
</code>```

2)

```<code>    for(int i=0; i<s.length(); i++) {
        if(s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
            n++;
        }
    }
</code>```

Which of the two is more 'clean' and compliant with the Java best practices?

答: It's always better to use c >= '0' because for c >= 48 you need to convert c in ascii code.


答: When actually writing code, CodeRush helps quite a bit especially when you've mastered its shortcuts. Plus it's free :D</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: GaiusSensei


问:
creating platform for multiple webapps
I have already built a nodejs webapp that I want to make available as a service, but I don't know the next steps to automate the whole thing given the following steps :

people come to my website and create an account for a free trial by providing what could possibly be the domain name for their version of my app ( what will become a subdomain on my server)

an image of the app is automatically set up and launched on provideddomain.mywebsite.com

they log to their account to start configuring their version of my app

if they like the app they can purchase or transfert a domain so that their version of the app can be accessible from provideddomain.mywebsite.com to newdomain.com

Basically, I wish to offer a platform where my customers can use an image of my app ( behind the fomain namr of their choosing domain).

I think I can use containers and kubernetes to have something like a paas, but I don't know if they are the right tools for achieving what I'm looking for.

I already know how to deploy an app on openshift (containers) and I figured there must be a way to automate the whole process. Much like what WordPress does when you create an account and have a subdomain and everything, ready for you to use.

Can anyone point me to the right resources ?

any other tips, hints on some steps I didnt mention will also be greatly appreciated.

答:
A container per client is great if there's ever a chance they'll download it and run it elsewhere. Otherwise, consider a multi-tenant architecture and save the containers, VMs, etc for adding resources to your platform.

To start, you'll need a master client data store. You'd need this anyway, so it's no big change. Use this data store to track your clients, their service level/billing, and which application node/cluster is serving them.

When a prospect signs up, add them to the client data store and assign them to an appropriate app cluster. (An app cluster is some combination of web servers, service endpoints, and data stores.) If your architecture is truly multi-tenant, there's no need spin up a new database or container on the cluster. It'll already be ready for application data. The client can immediately start experimenting -- their data is logically partitioned (could be physically partitioned as well, but that's another topic).

Application configuration is likely stored on the app cluster, though you'll want billable features tracked in the master data store as well.

If the client wants their own domain, it's a simple matter to add the host to your web servers and route requests as appropriate. If you want to get fancy, you could register domains on their behalf. Again, that's probably another topic.

This setup doesn't change the need to add resources as you grow. It just makes the need for a new container, data store, or VM a choice about your growth and not something you have to do each time a client signs up.

Other resources:

Degrees of multi-tenancy from ComputerWorld

Multi-tenant architectures from DevX

Why you should care from ZDNet

Title: creating platform for multiple webapps


问:
What design pattern is used in this delegating scenario?
I am currently having to bend some framework API to fit my usecase.
The framework provides generic interfaces such as

```<code>public interface Processor<T> {
    T process(T t);
}
</code>```

with various implementations. These are used by some classes such as

```<code>public SomeClass<T> {
    public SomeClass(Processor<T> p, [...]) {}
}
</code>```

To fit my usecase, I need SomeClass to behave differently without affecting the existing Processors.
To do so, SomeClass has to operate on wrapped Ts. Hence:

```<code>SomeClass<Container<T>>
</code>```

As said, this should not affect the Processors which still shall operate on T. To be able to do this I wrote delegators which unwrap T from the container and then delegate the processing of T:

```<code>public class BoxDelegatingProcessor<T> implements Processor<Container<T>> {
    private Processor<T> delegatee;

    public Container<T> process(Container<T> wrapped) {
        return wrap(delegatee.process(unwrap(wrapped));
    }
    [...]
}
</code>```

What design pattern (according to GoF) is this?
I don't think it's Decorator, because there es no actual "functionality" involved? It's more of a type adapter.

答: This is the adaptor pattern. You are adapting a Processor<T> so it can be used where a Processor<Container<T>> is expected.


答:
Why not use .NET custom configuration? It has a lot to recommend it:

Define configuration with any level of complexity, nesting, etc.

Relationships are easily defined in the config XML and easy to handle via .NET code.

Includes validation.

If defined in a separate assembly, that configuration assembly can be used across any number of projects.

Uses .NET convention!

Depending on the audience, reading XML can be very user-friendly. Grok at a glance.

Add a ProtectedConfigurationProvider to store configuration in alternative locations or formats. (It's not just for encryption.)

Title: How to design a meta model for configuration?

Body:
In our software we have a client/server architecture where the server is actually running on an embedded system with various hardware components (sensors, etc.). The different sensors as well as other features of the system itself can be configured by the client. The client does not know in advance which features and components can exist on the server. Client and Server are communicating over a network. The client should be user friendly. Technological and political constraints forbid us to use HTML/JS as a client (we use .NET).

Long story short, we want to provide a general meta-model for configuration that described configuration entities, their properties, relationships between the properties, validation rules, etc.

However we are realizing this is actually quite a complex task and I would like to hear opinions, helpfull tips and hopefully existing frameworks or models that can be used. We are currently looking at RDF as a possible language to dynamically create an ontology describing all the relationships described above, but RDF seems very complex for this.

Any ideas or suggestions?


问:
Best way to control serialisation of posted form data
I'm working on an ASP.NET MVC project. I have a form that is strongly typed. Is it considered good practice to add serialisation attributes to the same view model to control how the data is serialized once it is posted to the server. For example, I have many properties that are strictly used to show/hide UI components. Can I add [XmlIgnoreAttribute] to each of these properties in the view model so they won't be serialised or is it better to create a completely difficult class for serialization. </p>

答:
Conceptually, consider viewing and updating. They're very different things. Using a distinct ViewModel and UpdateModel is sensible. The ViewModel contains everything the view needs to do its job (that it doesn't already have). As such, it might contain select options, background colors, image paths... who knows? When you update the data from the ViewModel, it doesn't make much sense to pass those properties along.

As you mention, one option is to fuss with bindings so you don't get the unneeded data. That leaves me cold, however. I'd much rather see an action parameter that does exactly what it means. An explicit UpdateModel does the trick. Sometimes, you can simply recycle a domain model. If the data coming back from the UI is a little trickier (maybe it maps to more than one domain model), a separate UpdateModel serves you well.

Keep in mind, this isn't necessarily a common practice from what I see in the field. Using that same criteria, however, I'd note that brushing your teeth after meals also appears to be an uncommon practice and I'm not giving that up any time soon.