问:
Nested Try Catch Error Handling with Log Files?
Best practice question for error handling in C#?

In our system we will be writing out files, and with each file they will have a corresponding error file. The error file will get written every time even if there are not any errors.

I'm looking at the best way to handle the errors for this. Assuming when we go to write the main CSV file, we would get a number of errors. From permissions on the folder, to a parsing exception when turning a Datatable to a CSV.

If we get a permission error the error log file will fail as well. Would this be done in the exception? in another try catch (which would be bad.. I think).

We would also want to get the exception to place in the error file.

Some pseudo code below (without the try catch in the exception)
or should this be broken down more and using methods, that contain their own Try / Catch that could bubble up the messages to log and write to files.

```<code>    Message.log("begin writing file");
        try {
           try {
              // get data from DB
              // write to CSV file
              // all good, write Empty Error Log file and main file
           }
           catch(Exception ex) {
              // Write Error File with ex.toCSV
              // write log message.
              Message.log("error : " + ex.ToString());
           }

        } catch (Exception ex) {
             var e = new Exception(string.Format("An unexpected error occurred for file.\r\n{0}", ex.Message));
             Message.log(e);
             throw e.
        }
       Message.log("all files written");
</code>```

答:
You only need one catch, provided you can make the message you are logging have a single format.  You can also simply rethrow the caught exception, rather than creating a new one.

The following code is semantically equivalent to your existing code:

```<code>Message.log("begin writing file");
try
{
  // get data from DB
  // write to CSV file
  // all good, write Empty Error Log file and main file
}
catch (Exception ex)
{
     Message.log(e);
     throw;
}
Message.log("all files written");
</code>```

Body:
You only need one catch, provided you can make the message you are logging have a single format.  You can also simply rethrow the caught exception, rather than creating a new one.

The following code is semantically equivalent to your existing code:

Message.log("begin writing file");
try
{
  // get data from DB
  // write to CSV file
  // all good, write Empty Error Log file and main file
}
catch (Exception ex)
{
     Message.log(e);
     throw;
}
Message.log("all files written");


问:
Is it a bad practice to modify code strictly for testing purposes
I have a debate with a programmer colleague about whether it is a good or bad practice to modify a working piece of code only to make it testable (via unit tests for example).

My opinion is that it is OK, within the limits of maintaining good object oriented and software engineering practices of course (not "making everything public", etc).

My colleague's opinion is that modifying code (which works) only for testing purposes is wrong.

Just a simple example, think of this piece of code that is used by some component (written in C#):

```<code>public void DoSomethingOnAllTypes()
{
    var types = Assembly.GetExecutingAssembly().GetTypes();

    foreach (var currentType in types)
    {
        // do something with this type (e.g: read it's attributes, process, etc).
    }
}
</code>```

I have suggested that this code can be modified to call out another method that will do the actual work:

```<code>public void DoSomething(Assembly asm)
{
    // not relying on Assembly.GetExecutingAssembly() anymore...
}
</code>```

This method takes in an Assembly object to work on, making it possible to pass your own Assembly to do the testing on. My colleague didn't think this is a good practice.

What is considered a good and common practice ?

答:
Looks like you're talking about dependency injection. It's really common, and IMO, pretty necessary for testability.

To address the broader question of whether it's a good idea to modify code just to make it testable, think of it this way: code has multiple responsibilities, including a) to be executed, b) to be read by humans, and c) to be tested. All three are important, and if your code doesn't fulfill all three responsibilities, then I'd say it's not very good code. So modify away!

ContentLicense: CC BY-SA 3.0


答:
Modifying code to make it more testable has benefits beyond testability.  In general, code that is more testable

Is easier to maintain,

Is easier to reason about,

Is more loosely coupled, and

Has a better overall design, architecturally.

Title: Is it a bad practice to modify code strictly for testing purposes

Body:
I have a debate with a programmer colleague about whether it is a good or bad practice to modify a working piece of code only to make it testable (via unit tests for example).

My opinion is that it is OK, within the limits of maintaining good object oriented and software engineering practices of course (not "making everything public", etc).

My colleague's opinion is that modifying code (which works) only for testing purposes is wrong.

Just a simple example, think of this piece of code that is used by some component (written in C#):

```<code>public void DoSomethingOnAllTypes()
{
    var types = Assembly.GetExecutingAssembly().GetTypes();

    foreach (var currentType in types)
    {
        // do something with this type (e.g: read it's attributes, process, etc).
    }
}
</code>```

I have suggested that this code can be modified to call out another method that will do the actual work:

```<code>public void DoSomething(Assembly asm)
{
    // not relying on Assembly.GetExecutingAssembly() anymore...
}
</code>```

This method takes in an Assembly object to work on, making it possible to pass your own Assembly to do the testing on. My colleague didn't think this is a good practice.

What is considered a good and common practice ?


问:
What factors should be evaluated when determining a desktop software price?
What factors should be evaluated when determining a desktop software price?</p>

答:
Here are a few things to consider based on the information given:

Price of a desktop computer. Never charge more than the price of a PC except for the Enterprise Edition. You don't want there to be sticker-shock.

Cost of the Box. Nothing says, "Our company has been around a long time." than selling your software in a cardboard box. This should be no more than 10% of total cost.

Number of programmers.  This doesn't have to be the actual number of programmers who worked on your app, but the number you can make the customer "think" worked on your app. The more you have the higher the cost. Anywhere from 50 - 100 US Dollars per dev.

Time to Boot Your App - The more software there is the longer it takes to boot-up is a software axiom for years to come. More software means more money. You will get back some of the losses due to extra hardware (See #1).

I realize these are just some general guidelines, so you may just want to consider $85.50 plus shipping and handling. What the heck, if you buy one now, you'll get another one free. Just pay the shipping and handling.


问:
Conditional construct for a kleenean data type
I was thinking of an hypothetical programming language with a kleenean data type which would implement Kleene's three-valued logic. To sum up, it's an extension of the boolean data type with the three constants true, false and unknown where unknown means that the value is either true or false, but we don't know which.

The truth tables for a kleenean type are well-known and the logic is quite easy to understand. However, I was wondering how one would design a conditional construct to take in account this unknown value.

A basic if-then-else conditional construct is almost always as follows:

```<code>if (boolean condition) then
    condition is true, do something
else
    condition is false, do some other thing
end
</code>```

However, I have troubles seeing what a kleenean if construct would look like. How could we interpret the unknown constant? Technically speaking, it could satisfy the true condition as well as the false condition since it is one of these two. However, we can't have it match any of those since it could be the other, it is not really true nor false.

Is there a well-known way to implement such a construct?

EDIT: To specify a little bit, I would prefere something different than the way boost::tribool works, or from a simple switch as if was an enum. Answers about quantum superposition and semantics are welcome.

答:
However, I have troubles seeing what a kleenean if construct would look like.

It looks exactly like an ordinary if. However, the semantics are slightly different. Instead of saying “if the condition is true, then this otherwise that”, it actually goes something like “if the condition is known to be true, then this otherwise that” (or perhaps “proven” instead of “known”, depending on which modality you prefer to use your kleenean logic to represent). This then means that you may want to have an operator for testing “is unknown/unproven” so that you can check for the third state, though that is not strictly necessary:

```<code>let boolvar = boolean condition
if (boolvar) then
    # The true case...
elseif (not boolvar) then
    # The false case...
else
    # The unproven case...
fi
</code>```

(Assuming that not unknown is unknown, of course.)

Body:
However, I have troubles seeing what a kleenean if construct would look like.

It looks exactly like an ordinary if. However, the semantics are slightly different. Instead of saying “if the condition is true, then this otherwise that”, it actually goes something like “if the condition is known to be true, then this otherwise that” (or perhaps “proven” instead of “known”, depending on which modality you prefer to use your kleenean logic to represent). This then means that you may want to have an operator for testing “is unknown/unproven” so that you can check for the third state, though that is not strictly necessary:

let boolvar = boolean condition
if (boolvar) then
    # The true case...
elseif (not boolvar) then
    # The false case...
else
    # The unproven case...
fi

(Assuming that not unknown is unknown, of course.)


问:
Ship Early, Ship Never
This started as a "Note to Self," so please excuse me if the frustration is all too evident and the writing is less than stellar...

Three major subjects I've had at the forefront of my mind lately:

Motivation

Learning (Curiosity)

Doing (Making)

I've been studying motivation and incentives for months now. It seems there are an infinite number of different motivations that people might have for doing things (I realize that sounds trite but bear with me). I've been really drawn to it because I'm desperate to find out why I do the things I do and why I don't do the things that I want to do but don't do.

I'm in the midst of reading Paul Graham's excellent Hackers and Painters book. In it, he makes the case that hackers and painters are very similar because they are both "makers." Painters make paintings. Hackers make software. Painters don't necessarily need to understand the chemical composition of paint to make beautiful paintings. And hackers don't necessarily need to know 1's and 0's to make beautiful software.

Graham then draws the distinction between disparate computer science fields:

some people seem to be studying mathematics

some people seem to be studying the computers themselves

the hackers are making software.

The difference is incredibly important. It seems the motivation for some is to make beautiful things. And the motivation for the others is to learn out of curiosity. Certain motivations seem obvious to me, but curiosity seems a bit less obvious. I would certainly consider myself as a curious person with a seemingly unquenchable thirst to learn just about everything I can. But this is exactly where the problem comes up.

The thing that scares me so much is that I desperately want to make things. I desperately want to do things. I want to write a book. I want to paint a painting. I want to compose a song. I want to do things like travel. But the strangeness is that I also want to learn things. I want to learn to play guitar. I want to learn about art history. I want to learn more about philosophy and literature.

The key seems to be the balance between learning and doing... between studying and making.

While I'm not sure how much one should learn about a given thing before doing it, I know for certain that I find myself constantly on one side rather than the other. As it stands now (and as far as I can tell I've always been this way), I am a learner and not a doer. I've read great books. I've practiced guitar for years. I've spent countless hours studying programming.

But I've written 0 books. I've composed 0 songs. I've coded 0 beautiful programs. I've painted 0 beautiful paintings. I've started 0 viable businesses.

The scary part of all this is that there are probably countless unfinished works of art in the world. Is this my misanthropic revenge against society and culture to never produce or finish any of the works of art that I start? Perhaps the worst part (aside from this being my natural inclination), is the fact that I f***ing know better. I just finished books like "Getting Things Done" and "Making Ideas Happen." I've aggregated and synthesized countless words of wisdom on how to do things and how to make things.

Imagine the horror of going through life without being able to do the things you want to do. If this is something you've struggled with (and hopefully overcome), please share. If not... perhaps some delicious pity would make me feel better.

[UPDATE: Just wanted to send a quick thanks to everyone that shared their thoughts. I deliberately left the question somewhat open-ended in hopes of encouraging discussion and having others refashion the central problem around their similar experience, and I think it worked out great... there's a lot of amazing insight here to work with and it was really helpful. Thanks again.]

答:
I can't say why you do that. But I can tell you how I deal with that.

Think of it like training a dog. Dogs do things that they have been rewarded to do, and avoid things they associate with discomfort. To teach a dog something complex, you have to break it down into little steps and reward each step until it's a habit.

I am inspired by big projects. But because they are big, they scare me. So I break down the big thing into a lot of little things, pick the very first little thing, ignore all the rest, and do it. That success pleases me, so I pick the next little thing and do it. I set aside my fears and my false pride and just do one little thing at a time.

I intentionally do not compare my little thing with the grand vision. E.g., when I, a lazy blob, took up running, it was with the goal of doing a local 12k race. But the first day, I did not try to run 12k. I did something pretty small: 15 30-second bursts of jogging mixed in a 30-minute walk. (That's from Hal Higdon's 30/30 plan.) That was plenty of challenge for me the first day, because the hard part was actually getting out there and doing it.

In the spring I'll run that 12k race for the fifth time. I now feel that going out and running a few miles in the morning is fun and rewarding, something unthinkable when I started. I got there through a thousand tiny increments, each one of which was rewarding enough to make up for the discomfort of the work and the pain of the occasional failure. You can do this too; you just have to do it relentlessly, with patience and humility.

ContentLicense: CC BY-SA 2.5

Title: Ship Early, Ship Never


问:
A programming language that allows you to define new limits for simple types
Many languages like C++, C#, and Java allow you to create objects that represent simple types like integer or float. Using a class interface you can override operators and perform logic like checking if a value exceeds a business rule of 100.

I'm wondering if it's possible in some languages to define these rules as annotations or attributes of a variable/property.

For example, in C# you might write:

```<code>[Range(0,100)]
public int Price { get; set; }
</code>```

Or maybe in C++ you could write:

```<code>int(0,100) x = 0;
</code>```

I've never seen something like this done, but given how dependent we have become on data validation before storage. It's strange that this feature hasn't been added to languages.

Can you give example of languages where this is possible?

答:
It's strange that this feature hasn't been added to languages.

Special features for range-limited types are not needed in C++ and other languages with powerful type systems.

In C++, your goals can be met relatively simply with user-defined types.  And in applications where range-limited types are desirable, they are hardly sufficient.  For example, one would also want the compiler to verify that physical unit computations were written correctly, so that velocity / time produces an acceleration, and taking the square root of acceleration / time produces a velocity.  Doing this conveniently requires the ability to define a system of types, without explicitly naming every type that could ever appear in a formula.  This can be done in C++.


问:
How to get different resources in a single endpoint in RESTful?
I have a REST webservice that have a couple of resources, like Company and User. But now I need to make a modification to the API to return a special list combining company, user and maybe other type of resource. Like a list of recommendations with various type of resources.

Which is the best approach to solve this?

I need to make a new endpoint (resource), something like: /recommendations? I already have the /company endpoint, and the /user endpoint returning the corresponding objects. This is fine. But now I need some way to return an array with a combination of users and companies.

Also I'm thinking that the json will look like an array of objects, but how the client can know which type of object is parsing if every object in the array is a different resource?

EDIT

I want that my client could show a recomendations screen in the app. The problem is that this list can combine multiple types of data (users, companies). It doesn't matter if this resources have a relationship or not.
The client shoud recive a json like that:

```<code>"recomendations": [
    {
        "id_user": 1
        "name": "Jean"
        ...
    },
    {
        "id_company": 2
        "name": "Starbucks"
        ...
    },
    ...
]
</code>```

答:
Without making assumptions about relationships between Company and User, I think you just want a nice way to return composition of different type of objects. There's a proposed standard that pretty well defines how to do this, Hypertext Application Language. Here is an example:

```<code>GET /recommendations HTTP/1.1
Host: example.org
Accept: application/hal+json

HTTP/1.1 200 OK
Content-Type: application/hal+json

{
    "_links": {
    "self": { "href": "/recommendations" },
    "next": { "href": "/recommendations?page=2" },
    "find": { "href": "/recommendations{?id}", "templated": true }
},
"_embedded": {
    "recommendations": [{
        "_links": {
            "self": { "href": "/recommendations/123" },
            "users": { "href": "/users/98712" },
            "companies": { "href": "/companies/7809" }
       },
     },{
         "_links": {
             "self": { "href": "/recommendations/124" },
             "users": { "href": "/users/97213" },
             "companies": { "href": "/companies/12369" }
         },
    }]
},
}
</code>```

Copied from ExampleDocument

Body:
Without making assumptions about relationships between Company and User, I think you just want a nice way to return composition of different type of objects. There's a proposed standard that pretty well defines how to do this, Hypertext Application Language. Here is an example:

GET /recommendations HTTP/1.1
Host: example.org
Accept: application/hal+json

HTTP/1.1 200 OK
Content-Type: application/hal+json

{
    "_links": {
    "self": { "href": "/recommendations" },
    "next": { "href": "/recommendations?page=2" },
    "find": { "href": "/recommendations{?id}", "templated": true }
},
"_embedded": {
    "recommendations": [{
        "_links": {
            "self": { "href": "/recommendations/123" },
            "users": { "href": "/users/98712" },
            "companies": { "href": "/companies/7809" }
       },
     },{
         "_links": {
             "self": { "href": "/recommendations/124" },
             "users": { "href": "/users/97213" },
             "companies": { "href": "/companies/12369" }
         },
    }]
},
}

Copied from ExampleDocument


问:
"Open-source" licenses that explicitly prohibit military applications
I am a researcher, and in my research I do a lot of programming. I am a big fan of the open-source concept - especially in research, where transparency and reproducibility is already a big part of the culture. I gladly contribute as much as I can to the community, and releasing my code for anyone to use is part of that.

However, in research there is always a certain measure of uncertainty about what the stuff you produce will be used for. I fully understand that I can't copyright any results or conclusions - but I can protect how others use my code, and I would like to make sure that there is no (legal) way to incorporate software I produce in military applications.

I've read through a few of the shorter ones of the common OSS licenses, and summaries of some more, but they all seem to focus solely on the questions "do you earn money on my code?" and "do you make my code available with your program?" - nothing about what the program actually does with the code.

Are there any good open-source licenses that explicitly prohibit all kinds of military applications?

Update:

After reading up some more on how OSS works, I've realized that a license that meets my needs by definition will not be open-source, since open-source licenses cannot discriminate against fields. Thus, I'm rather looking for a license that is like an open-source license, except that it prohibits military use. I want this license to be already existing, authored or at least reviewed by someone who actually knows licensing, since I don't.

Also, in response to a couple of remarks that this will be difficult to enforce: yes, I realize that. But this is more for myself than for the legal implications; if I use a license like this, and a military organization uses my code anyway, they are breaking the law and they are doing it despite my explicit instructions not to. Thus, the potentially gruesome things that they do with applications that include software I've written are no longer "on my conciousness", since they stole the software from me. (And somewhere I have a naïve hope that if they need something I've done, and my license prohibits them from using it legally, they'll get someone elses program that does the same thing and allows them to use it. Not that governments always do, but they always should abide by the law...)

It's a moral safeguard, so to speak, rather than something I actually expect to bring up in court (if my mediocre code is ever used by CIA...)

答:
Here's a starting point.  It is Canadian Mind Products policy on "no military use" of their software.  Canadian Mind Products is Roedy Green's company.  Roedy has done some absolutely brilliant work, that has not gotten nearly enough mainstream attention.

Full Disclosure:  1.  Roedy is an old friend, although we've never met in person.  2.  I don't agree with him on this.

You might also look at Ben Kuipers "Why Don't I Take Military Funding?".


问:
npm packages.json: devDependencies vs global installation
I'm new Node.js development and I have a question about best practices when writing package.json files.

From my understanding, you have to list all devependences that you need to execute your app under "dependencies" in the package.json file. All your extra dependences that are required to run your test (or your build process) have to be listed in "devDependencies".

But what about tools that you additionally use, but which are not necessarily required by every developer. Take the node-inspector package as an example, which I installed globally on my machine but did not add to the package.json file.

Is that a good practice, or would you recommend to also file those packages as "devDependencies"?

答:
devDependencies are packages you need in order to work on your project. Testing frameworks used in the project, mock APIs, CSS preprocessors (if you don't ship a compiled version) fit here.

node-inspector is not needed for you to run tests and make changes to parts of your code, so  it should not be included in the package. Other users might use different debuggers.


问:
New C++11 analogous to python 2 ->3?

I'm a Python2 developer and I just ordered The C++ programming language, 4th edition, from Bjarne Stroustrup's, to learn C++11. But right after I ordered it, I started to wonder if I made a mistake. Are the changes made to C++ in C++11 analogous to how Python moved from 2 to 3 insofar as code significantly breaking and not being backwards compatible? Or is learning C++11 safe to do?

If I coded C++11 in XCode, the latest version being whatever it is, would it work on say a Windows machine? Or does that depend more on what will compile the code, fairly certain that XCode uses LLVM.

答:
C++11 is both more and less disruptive than Python 3000.

It is less disruptive since it contains fewer breaking changes and those breaking changes are rarely encountered.

It is more disruptive in that it will pretty significantly change the way code is written and systems are designed in C++. Programs in Python 3 are mostly written the same way they were in Python 2. The breaking changes are mostly cleanup, like getting rid of old-style classes. C++11 OTOH contains some features that can quite drastically change the way you write code: for example, the combination of a memory model, standard library concurrency primitives, lambda literals and type inference allow for syntactically and conceptually lightweight high-level concurrency in the style of Clojure or Haskell.

Title: New C++11 analogous to python 2 ->3?


答:
It's a bit of a chicken and egg problem.

One of the biggest reasons why it's good to have good test coverage of your code is that it allows you to refactor fearlessly. But you're in a situation where you need to refactor the code in order to get good test coverage! And your colleague is fearful.

I see your colleague's point of view. You have code which (presumably) works, and if you go and refactor it - for whatever reason - there's a risk that you'll break it.

But if this is code which is expected to have ongoing maintenance and modification, you're going to be running that risk every time you do any work on it. And refactoring now and getting some test coverage now will allow you take that risk, under controlled conditions, and get the code into better shape for future modification.

So I would say, unless this particular codebase is fairly static and not expected to have significant work done in the future, that what you want to do is good technical practice.

Of course, whether it's good business practice is a whole 'nother can of worms..


答:
I've implemented this approach in the language I develop (then I removed this feature and switched to the boolean logic, as considered three-state logic not really useful).

A three-state logical could be converted to boolean transparently with the following rule:

The boolean value of the logical is true only when the logical value is true.

The unknown and false logical values correspond to the false boolean.

To be able to work with three-state logicals, a set of unary operators could be used:

++ (is) - convert a logical operand to boolean value.
Just in a more verbose way than implicit conversion.

-- (not) - result is true only when operand is false.

+- (known) - result is true only when operand is either true or false.

-+ (unknown) - result is true only when operand is unknown.

This way conditionals could be implemented to work with boolean conditions, as they use to. A logical could be used as boolean condition either transparently or explicitly. Different combinations of logical operators could be used to achieve the same goal, whatever suits best:

```<code>if (condition) {
  // condition is true
} else if (--condition) {
  // condition is false
} else {
  // condition is unknown
}

if (-+condition) {
  // condition is unknown
} else if (condition) {
  // condition is true
} else {
  // condition is false
}
</code>```

Title: Conditional construct for a kleenean data type

Body:
I was thinking of an hypothetical programming language with a kleenean data type which would implement Kleene's three-valued logic. To sum up, it's an extension of the boolean data type with the three constants true, false and unknown where unknown means that the value is either true or false, but we don't know which.

The truth tables for a kleenean type are well-known and the logic is quite easy to understand. However, I was wondering how one would design a conditional construct to take in account this unknown value.

A basic if-then-else conditional construct is almost always as follows:

```<code>if (boolean condition) then
    condition is true, do something
else
    condition is false, do some other thing
end
</code>```

However, I have troubles seeing what a kleenean if construct would look like. How could we interpret the unknown constant? Technically speaking, it could satisfy the true condition as well as the false condition since it is one of these two. However, we can't have it match any of those since it could be the other, it is not really true nor false.

Is there a well-known way to implement such a construct?

EDIT: To specify a little bit, I would prefere something different than the way boost::tribool works, or from a simple switch as if was an enum. Answers about quantum superposition and semantics are welcome.

Body:
I've implemented this approach in the language I develop (then I removed this feature and switched to the boolean logic, as considered three-state logic not really useful).

A three-state logical could be converted to boolean transparently with the following rule:

The boolean value of the logical is true only when the logical value is true.

The unknown and false logical values correspond to the false boolean.

To be able to work with three-state logicals, a set of unary operators could be used:

++ (is) - convert a logical operand to boolean value.
Just in a more verbose way than implicit conversion.

-- (not) - result is true only when operand is false.

+- (known) - result is true only when operand is either true or false.

-+ (unknown) - result is true only when operand is unknown.

This way conditionals could be implemented to work with boolean conditions, as they use to. A logical could be used as boolean condition either transparently or explicitly. Different combinations of logical operators could be used to achieve the same goal, whatever suits best:

if (condition) {
  // condition is true
} else if (--condition) {
  // condition is false
} else {
  // condition is unknown
}

if (-+condition) {
  // condition is unknown
} else if (condition) {
  // condition is true
} else {
  // condition is false
}


问:
IPv4 to IPv6. where is IPv5?
As all of us know that after IPv4 it came IPv6. How this transition happened?

I just want to know was there any IPv5 also? or there is any other logic in naming this version of IP as IPv6?

答: IPv5 was used to define an experimental real-time streaming protocol. To avoid any confusion, it was decided to not use IPv5 and name the new IP protocol IPv6. Another thing is that IPv6 has a high span of IP adresses that is up to 340 trillion trillion trillions.</p>

Title: IPv4 to IPv6. where is IPv5?


答:
There are (seemingly) opposing forces in play.

On the one hand, you want to enforce encapsulation

On the other hand, you want to be able to test the software

Proponents of keeping all 'implementation details' private are usually motivated by the desire to maintain encapsulation. However, keeping everything locked down and unavailable is a misunderstood approach to encapsulation. If keeping everything unavailable was the ultimate goal, the only true encapsulated code would be this:

```<code>static void Main(string[] args)
</code>```

Is your colleague proposing to make this the only access point in your code? Should all other code be inaccessible by external callers?

Hardly. Then what makes it okay to make some methods public? Isn't it, in the end, a subjective design decision?

Not quite. What tends to guide programmers, even on an unconscious level, is, again, the concept of encapsulation. You feel safe exposing a public method when it properly protects its invariants.

I wouldn't want to expose a private method that doesn't protect its invariants, but often you can modify it so that it does protect its invariants, and then expose it to the public (of course, with TDD, you do it the other way around).

Opening up an API for testability is a good thing, because what you're really doing is applying the Open/Closed Principle.

If you only have a single caller of your API, you don't know how flexible your API really is. Chances are, it's quite inflexible. Tests act as a second client, giving you valuable feedback on the flexibility of your API.

Thus, if tests suggest that you should open up your API, then do it; but maintain encapsulation, not by hiding complexity, but by exposing complexity in a fail-safe manner.

Body:
There are (seemingly) opposing forces in play.

On the one hand, you want to enforce encapsulation

On the other hand, you want to be able to test the software

Proponents of keeping all 'implementation details' private are usually motivated by the desire to maintain encapsulation. However, keeping everything locked down and unavailable is a misunderstood approach to encapsulation. If keeping everything unavailable was the ultimate goal, the only true encapsulated code would be this:

static void Main(string[] args)

Is your colleague proposing to make this the only access point in your code? Should all other code be inaccessible by external callers?

Hardly. Then what makes it okay to make some methods public? Isn't it, in the end, a subjective design decision?

Not quite. What tends to guide programmers, even on an unconscious level, is, again, the concept of encapsulation. You feel safe exposing a public method when it properly protects its invariants.

I wouldn't want to expose a private method that doesn't protect its invariants, but often you can modify it so that it does protect its invariants, and then expose it to the public (of course, with TDD, you do it the other way around).

Opening up an API for testability is a good thing, because what you're really doing is applying the Open/Closed Principle.

If you only have a single caller of your API, you don't know how flexible your API really is. Chances are, it's quite inflexible. Tests act as a second client, giving you valuable feedback on the flexibility of your API.

Thus, if tests suggest that you should open up your API, then do it; but maintain encapsulation, not by hiding complexity, but by exposing complexity in a fail-safe manner.


问:
Should I parse an email template before or after placing it in the queue?
I have a web application that sends out transactional (triggered) emails to users. We've setup a message queue for the web application to write to when it needs to send out an email (best practices reasons etc.).

The question I'm struggling with is when to have the email template parsed into text:

Parse the template and place the entire email body into the queue

Pro: can keep the business logic and template close by

Con: more data over the wire to the queue (email body vs email type/ids etc.)

Parse the template as part of the queue processing (before it's sent to the transactional email service)

Pro: less data over the wire to the queue, less processing on the messaging logic

Con: queue processor needs to have business logic

I like option #1 because I don't see data over wire ever getting too big and keeping the email logic in a central location makes more logical sense from a development standpoint.

Is there a best practice in this situation?

答:
I agree with your reasons to choose option #1. If the e-mails you send won't clog up your Internet connection, why should they clog up the network connection between your web application and your queue processor?

There is always a trade-off between code maintainability and performance. However, since you state yourself that performance problems with option #1 are possible but unlikely, I would not sacrifice code maintainability for an unlikely performance problem.


答:
A good and common practice is to use Unit testing and debug logs. Unit tests ensures that if you make any further changes in program, your old functionality is not breaking. Debug logs can help you trace the program at run time.

Sometimes it happens that even beyond that we need to have something only for testing purpose. It is not unusual to change the code for this. But the care should be taken such that the production code is not affected because of this. In C++ and C this is achieved using the MACRO, which is compile time entity. Then the testing code do not come into picture at all in production environment. Don't know if such provision is there in C#.

Also when you add testing code in your program, it should be clearly visible  that this portion of code is added for some testing purpose. Or else the developer trying to understand the code is simply going to sweat over that part of code.


答: The problem is your logger. The logger should not throw errors. If there is any error in logger try to resolve it best in logger code, by changing the log location or by disabling the logging, or in extreme by stopping application. Logging is frequent operation, if once it fails it is going to fail again and again. It will be expensive putting try catch around the logging operation every time. </p>

Title: Nested Try Catch Error Handling with Log Files?

Body:
Best practice question for error handling in C#?

In our system we will be writing out files, and with each file they will have a corresponding error file. The error file will get written every time even if there are not any errors.

I'm looking at the best way to handle the errors for this. Assuming when we go to write the main CSV file, we would get a number of errors. From permissions on the folder, to a parsing exception when turning a Datatable to a CSV.

If we get a permission error the error log file will fail as well. Would this be done in the exception? in another try catch (which would be bad.. I think).

We would also want to get the exception to place in the error file.

Some pseudo code below (without the try catch in the exception)
or should this be broken down more and using methods, that contain their own Try / Catch that could bubble up the messages to log and write to files.

```<code>    Message.log("begin writing file");
        try {
           try {
              // get data from DB
              // write to CSV file
              // all good, write Empty Error Log file and main file
           }
           catch(Exception ex) {
              // Write Error File with ex.toCSV
              // write log message.
              Message.log("error : " + ex.ToString());
           }

        } catch (Exception ex) {
             var e = new Exception(string.Format("An unexpected error occurred for file.\r\n{0}", ex.Message));
             Message.log(e);
             throw e.
        }
       Message.log("all files written");
</code>```


问:
Increasing User Changes/Requirements in Agile Methodology
My question is quite simple. How to handle a situation where the team is applying agile methodology in software projects and there so many iterations and change in requirements, that the schedule is highly affected? Plus you have your manager who is always wanting things to get done within schedule and it is something you cannot control?</p>

答:
It sounds like your manager does not really buy into Agile, but rather tries to put an Agile peg into a 'fixed date' mould.

You can run an Agile project with a fixed end-date, but then all parties should understand that you will just deliver whatever features you have completed up to the end date. You can not agree to both a date and a feature set beforehand and then allow the customer to make changes at will without consequences to the final delivery.

One way you could combine an Agile development team with a fixed-date project is to have a strong, in-house, product owner who carefully protects the project scope and keeps the change-request negotiations with the real customer away from the development team. The product owner is then the responsible for avoiding missing the deadline due to scope creep.
This assumes that the original schedule was realistic in the first place.


问:
Should the design take longer than code development?
I once heard that if you spend 90% of your time developing the design of your program the coding part will only take a trivial 10% of the time.  I have found a lot more success in spending about 30% of my time designing the architecture than when I used to spend 0% in design.  As a result my programs seem to avoid unnecessary coupling and are now more flexible to change before any re-factoring takes place.

I usually finish the design phase once I have a clear idea of what all the objects should be named (I am really picky about naming objects) and what single responsibility each will have.  Once I feel confident in my design and feel ready to start constructing the software, would there be any benefit to taking more time to keep re-thinking the design? To me it might seems like it might be overkill.

What's an effective design to code development time ratio and should the design time be greater than the code development time?

答:
First, it depends on the kind of project. Is it similar to something you have already done, repeatedly? Then your coding part can be extremely short. On the other hand, if it is completely new, with a lot of new functionality, then you probably need to code a lot of functionality. (Well, or use an existing library. Which needs to be tested. Is testing of a new library considered a part of development?)

Second, what exactly is your definition of "design" and "development"? For example, one person draws classes in UML, and at the end compiles them to code. Another person creates classes in IDE and refactors them, but does not write method bodies yet. The former one's work would probably be classified as "design" and the latter one's as "development", yet they are doing the same thing, just using different tools. (A more philosophical person could perhaps argue that all coding is design.)

Third, it probably depends on the programming language, methodology used, etc. Shortly -- if you made a mistake in the design phase, would it be easy or difficult to notice? Because if you don't notice it in the design phase, you will have to find it and fix it during the time officially spent developing.

OwnerDisplayName: Korey Hinton


问:
Programming style in Perl
I work in Java so basically I use OOP paradigm during coding.
I am about to start working in Perl and I was wondering what is the paradigm that Perl developers follow.
In wiki it mentions that it supports many paradigms but I am not sure I understand this since it is a scripting language.

So my question is:
Are the object oriented patterns I'm familiar with in Java idiomatic in Perl, or will I need significant change to my design style to write effective Perl?

Note: This is not a question to critique Perl. I actually have to work in Perl and would like to understand how the current way I program will change.

答:
I am in the same situation, I have been using Java for a looong time,

Having moved to Perl was a shock and a relief but, I used a book called 'Perl Best Practices' It helps a lot and if you understand the basic concepts of programming languages it's all easy to just flow with it.

Just remember with perl there is more then one way to do it, I have spend countless hours looking at certain code and modifying it, but in the end it gets the job done with a simple syntax error.

Title: Programming style in Perl


问:
Should I obtain a licence from Oracle before developing Java software?
Should I obtain a licence from Oracle before developing Java software? I'm in the preliminary planning stages of developing a server on top of the the Hadoop/Java platforms.

I'm not much at all worried about the Hadoop side, but the "process" for developing on top of the Java VM is somewhat ambiguous. I was in the process of setting up the JVM on FreeBSD, when I saw that we are only licensed to use it for "personal use".

So I thought hmm, what's the situation over in Linux Land? It was even more ambiguous there, and I wasted about an hour on Usenet looking for the answer.

Let me clarify my question. I don't care about OpenJDK and much less so interested in fighting Oracle in court (no relation), I'm interested more in Oracle's policy towards "Indie" Java developers and by "Indie" I mean a small house of developers under a sole-proprietorship/llc. with no legal team.

To be even extra clear, I want to stay on Oracle's good side so if/when my product becomes a success that I don't have to give up the majority of my revenue, or worse, incorporate for quick cash or worse, file bankruptcy and throw away 10 years of work/maintenance.

I'm sorry but their legal license is full of double-talk and ambiguous "legal" terms that could mean pretty much anything. I apologize again if this is common knowledge, I come from a C/C++ background and have only been considering Java recently now that the it's becoming the definitive language for distributed computing.

答:
From what I know and checked it with links below, development of software for Java and installing JVM, using and distributing don't need any special license. There is some list of commercial features, but I don't think you need those.

If you would like to change something in JVM or classes of JDK then it would be different matter but I do not consider it "java software development" but JVM or runtime development, you don't want to build competing virtual machine? Don't change binary code of JVM, don't change sun, oracle, java packages in JDK and you should be OK.

Licensing and Distribution FAQs at www.java.com

This page provides answers to some frequently asked questions about Java software distribution and Java software license...

Java SE Products page at oracle.com

Download:

Oracle Binary Code License Agreement for the JAVA SE Platform Products (PDF)...

BCL for Java SE page at oracle.com

Oracle Binary Code License Agreement for the Java SE Platform Products and JavaFX...


答:
I don't think that you have to use some "90%" as golden rule, just use what is best for YOU. I would think of it as guide line to spend more time on thinking how to do it, instead of trying  by permutation.

Just say loud NO to "golden rules", use them as indicators yes, enforce them never.

Title: Should the design take longer than code development?

Body:
I once heard that if you spend 90% of your time developing the design of your program the coding part will only take a trivial 10% of the time.  I have found a lot more success in spending about 30% of my time designing the architecture than when I used to spend 0% in design.  As a result my programs seem to avoid unnecessary coupling and are now more flexible to change before any re-factoring takes place.

I usually finish the design phase once I have a clear idea of what all the objects should be named (I am really picky about naming objects) and what single responsibility each will have.  Once I feel confident in my design and feel ready to start constructing the software, would there be any benefit to taking more time to keep re-thinking the design? To me it might seems like it might be overkill.

What's an effective design to code development time ratio and should the design time be greater than the code development time?


答:
When making traditional estimations, my experience is that the effort distribution is roughly 30% design, 40% implementation, 30% test and usually the design is considered complete when you have identified the relevant classes, their responsibilities and optionally the major methods.

One of the risks that you run when doing a very complete and comprehensive design is that you can run Analysis Paralysis, which means that you never get anything done, because you keep 'improving' your design without a clear benefit for the current situation.

So, there definitely is an optimum in the amount of design to do, and that optimum lies around the point where you feel comfortable that your design addresses the relevant requirements and is detailed enough to act as a guide during the implementation.


答:
I tend to plan more in projects, which are similar to those I already did. Because I know what worked last time and what didn't, so I can get more into details in the planning about the architecture.

When I do something new, I have a vague idea about what I have to do. But start coding right away and throw the bad ideas out early has proven to be a better idea than planning a bunch of stuff AND implementing it later, just to see that the plans were flawed it the first place.

So the more I know about the software I'm going to implement, the more I dedicate to planning.


问:
How to decide between using an existing eCommerce solution and building your own?
There are a number of both open and close source off the shelf solutions.  For example Magento has an impressive list of sites that use them for eCommerce.  There are also stories such as this (only link to last section) where an eCommerce site is developed from scratch with great success.

I'm wondering if there's an objective way to approach the build vs customize decision?

答:
Break it down

Do we have the time and/or money?

This is a simple one. Can you afford to spend months in development? In some cases it may appear easier to build when your shop utilizes technology X whereas most of the decent e-commerce systems out there are using technology Y. But in most cases it may actually be easier to take on the burden of learning technology Y. Consider the complexity involved in e-Commerce systems and ask yourself these questions, "Do I understand technology X enough to produce a secure, compliant, and functional solution?" , and "Can I deliver a scalable solution that will stand the test of time?"

What problems need to be solved?

Arguably the most important item in this list. What does your business need out of an e-Commerce solution? I worked at a company not that long ago that needed a solution that would allow for an insane amount of nested categories and product filtering that must adhere to very specific rules based on school district boundaries in the United States. Every business will have some sort of specific problems that will need to be solved and it is wise to sit down ahead of time and sort all of those out. Compare those needs to the capabilities of the top 10/15 pre-built e-Commerce solutions out there, and you will start to piece together a plan of action much more efficiently.

Capabilities?

Is you/your team of developers capable enough to build an entire e-Commerce solution. Commerce on the web is a complex topic, and will require well-rounded web application developers in order to develop a compliant, scalable, and working solution. You will require some form of Payment Gateway in order to safeley, and cheaply accept card data. Also understand that your business must adhere to standards set by the major card companies, and becoming PCIe compliant can be a hassle if you plan on building, and running the solution in-house. However if you have a capable group of developers and an appropriate amount of time, you will be able to build for your businesses needs, create a unique e-Commerce experience for you customers, and tackle problems much faster.


问:
How is determined an impact of a requirement change on the existing code?
How companies working on large projects evaluate an impact of a single modification on an existing code?

Since my question is probably not very clear, here's an example:

Let's take a sample business application which deals with tasks. In the database, each task has a state, 0 being "Pending", ... 5 - "Finished".

A new requirement adds a new state, between 2nd and 3rd one.

It means that:

A constraint on the values 1 - 5 in the database must be changed,

Business layer and code contracts must be changed to add a new state,

Data access layer must be changed to take in account that, for example the state StateReady is now 6 instead of 5, etc.

The application must implement a new state visually, add new controls for it, new localized strings for tool-tips, etc.

When an application is written recently by one developer, it's more or less easy to predict every change to do. On the other hand, when an application was written for years by many people, no single person can anticipate every change immediately, without any investigation.

So since this situation (such changes in requirements) is very frequent, I imagine there are already some clever techniques and ways to predict the impact. Is there any? Do you know any books which deal about this subject?

Note: my question is not related to How do you deal with changing requirements? question. In fact, I'm not interested in evaluating the cost of a change, but rather the way to predict the parts of an application which will be concerned by the change. What will be those changes and how difficult they are really doesn't matter in my question.

答:
I don't think you can ever tell just how much a change will affect code.

That being said though, if one know the framework of the application well, he can generally predict about how long it will take and what needs to be done. It comes from experience, not metrics. I'm sure you've thought of cases that a user thought a change would be simple ('He's just adding one menu option! how hard can that be?!) but in reality was quite complex.

I have two possible solutions.

The first I think is critical: Documentation. Being able to read about the general layout of an application will help someone greatly in determining where changes will need to be made. Lower level docs about specific areas will help in actually making the changes.

The second would be to have a senior developer look at each request as he probably can tell quickly what it will entail. He then can give an estimate of how long it will take and what needs to happen before it is assigned to a person or team for development. This may not always be practical, so documentation is still extremely critical.


问:
Is this a valid example of a dangling pointer?
The book "Data Structures in C" (Horowitz and Sahni) suggests that in the following code the pointer pf is behaving as a dangling reference:

```<code>float f,*pf;
pf=(float*) malloc(sizeof(float));
*pf=2.6;
pf=(float*) malloc(sizeof(float));
</code>```

The reasoning they give is that after the last line there is no way
to retrieve the storage in which 2.6 was stored.

However, wikipedia defines a dangling pointer as

```<code>Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type
</code>```

In the code above pf does not satisfy that definition - it points to a valid object of appropriate type.

Is pf a dangling pointer, or something else?

答:
No I wouldn't describe that as a dangling pointer, but it is a memory leak because you do not free the first malloc before the second malloc. A dangling pointer would typically be a pointer which points to something which e.g. has already been freed

```<code>float f,*pf;
pf = malloc(sizeof(float));
*pf = 2.6;
free(pf);
f = *pf; /*uhoh pf no longer points to valid memory */
</code>```

Looking at the rest of code sample, f doesn't appear to be used, which is odd, and the cast to (float*) is unnecessary unless you need your code to also compile as C++ (something which was common when C++ was a newish language but not anymore, I suspect this may date your book?). While I can't find the exact book you reference, similar C and C++ books by the authors seem to have fairly poor reviews, you may want to consider a different textbook!

Body:
No I wouldn't describe that as a dangling pointer, but it is a memory leak because you do not free the first malloc before the second malloc. A dangling pointer would typically be a pointer which points to something which e.g. has already been freed

float f,*pf;
pf = malloc(sizeof(float));
*pf = 2.6;
free(pf);
f = *pf; /*uhoh pf no longer points to valid memory */

Looking at the rest of code sample, f doesn't appear to be used, which is odd, and the cast to (float*) is unnecessary unless you need your code to also compile as C++ (something which was common when C++ was a newish language but not anymore, I suspect this may date your book?). While I can't find the exact book you reference, similar C and C++ books by the authors seem to have fairly poor reviews, you may want to consider a different textbook!


问:
Is it a bad practice to modify code strictly for testing purposes
I have a debate with a programmer colleague about whether it is a good or bad practice to modify a working piece of code only to make it testable (via unit tests for example).

My opinion is that it is OK, within the limits of maintaining good object oriented and software engineering practices of course (not "making everything public", etc).

My colleague's opinion is that modifying code (which works) only for testing purposes is wrong.

Just a simple example, think of this piece of code that is used by some component (written in C#):

```<code>public void DoSomethingOnAllTypes()
{
    var types = Assembly.GetExecutingAssembly().GetTypes();

    foreach (var currentType in types)
    {
        // do something with this type (e.g: read it's attributes, process, etc).
    }
}
</code>```

I have suggested that this code can be modified to call out another method that will do the actual work:

```<code>public void DoSomething(Assembly asm)
{
    // not relying on Assembly.GetExecutingAssembly() anymore...
}
</code>```

This method takes in an Assembly object to work on, making it possible to pass your own Assembly to do the testing on. My colleague didn't think this is a good practice.

What is considered a good and common practice ?

答:
This may just be a difference in emphasis from the other answers, but I'd say that the code should not be refactored strictly to improve the testability. Testability is highly important for maintenance, but testability is not an end in itself. As such, I would defer any such refactoring until you can predict that this code will need maintenance to further some business end.

At the point that you determine that this code will require some maintenance, that would be a good time to refactor for testability. Depending on your business case, it may be a valid assumption that all code will eventually require some maintenance, in which case the distinction I draw with the other answers here (e.g. Jason Swett's answer) disappears.

To sum up: testability alone is not (IMO) a sufficient reason to refactor a code base. Testability has a valuable role in allowing maintenance on a code base, but it is a business requirement to modify your code's function that should drive your refactoring. If there is no such business requirement, it'd probably be better to work on something your customers will care about.

(New code, of course, is being actively maintained, so it should be written to be testable.)


答:
Unfortunately, the situation you find yourself in is probably one of the most common. Agile is gaining adoption in many markets due to buzz, and not because of understanding.  The same old problems still exist:  desire for fixed scope, fixed date, and fixed cost.  If the iron triangle is fixed, no development process is going to save you.

When you encounter the iron triangle, a compromise will need to be made with the client.  In your case, your client might be your manager.  The client needs to choose from the following (or a balance of all of them):

Scope adjustment. Drop some features to allow for room for changes.  Some changes to already-delivered features are indeed more important to make then building new features that might still be in your backlog.  Your Product Owner (or whomever is helping determine priority) can work this out with the client so they don't ask for a change and lose a feature they actually wanted more, or vice versa.

Schedule adjustment.  Allow for a later delivery date, or allow for multiple delivery dates where an initial set of features is delivered on time and then the team delivers a second release with the new scope at a later date.  Is it okay to deliver on date and have that change 2 weeks later?  This is iterative development, so things should be able to be continuously delivered in many scenarios.

Budget adjustment. This is probably the hardest to do, as most clients have fixed budgets for projects.  If the date is really important (go-to-market plans are in place and missing the date is not an option) and the scope cannot be reduced to fit into the timeline, you can use a request for additional budget to increase the size of your team to allow you to do more within a given iteration.

The most important piece is that the client needs to understand the impact of what they are asking for.  When they ask for a change, they are either losing a feature, missing the date, or increasing the cost of the project.   Making sure the client understands the impact of their request is paramount, and one of the reasons that you really need somebody playing the role of Product Owner with the client in order to keep the expectations set.

In your case, your team needs a team lead that interfaces with your manager and is having these discussions with them about the impact.  Your manager doesn't want you to fail either, but sometimes it is just a lack of understanding somewhere along the chain.  It's possible your manager might have somebody coming down on them about the schedule, so giving your manager ammunition to go back up the chain and fight for more time, budget, or scope reductions will help them and you.

Title: Increasing User Changes/Requirements in Agile Methodology

Body: My question is quite simple. How to handle a situation where the team is applying agile methodology in software projects and there so many iterations and change in requirements, that the schedule is highly affected? Plus you have your manager who is always wanting things to get done within schedule and it is something you cannot control?</p>


问:
What is the way to go to extract data from websites?
I've been thinking about a side project that envolves web data scraping.

Ok, I read the Getting data from a webpage in a stable and efficient way question and the discussion gave me some insights.

In the discussion Joachim Sauer stated that you can contact the owners of the sites and architect some way to provide the data that I want. The problem I see is that the websites are generally badly created and apparently seldom have changes in HTML (I don't think they will help me), but the data is relevant. I have suffered a lot using those sites so I would like to aggregate and show them in a better way.

So, going with scraping, specifically Scrapy (for python), is a problematic approach? I read that parse.ly uses scraping (Python and Scrapy), but in another context.

Given my context, there's a better approach than going with scraping? If going with scraping, how to deal with website structure's changes?

答:
Downloading the contents of a website can cause a wide range of problems for the website owners.

Bottleneck the server by using all available resources to feed your script requests.

Make a mistake and perform requests that would appear like an attack.

Get stuck in what is called a robot trap and keep downloading the same page because the URL constantly changes.

You might ignore the robotos.txt file and access parts of the website the owners don't want you too.

It's best practice to use a proper web crawling tool. Using the right tool for the job will ensure that you respect the performance, security and usage of the web server. These simple Python/PHP scripts for scraping websites do nothing but harm to the servers they ambush with thousands of web requests in an uncontrolled manner.

You should use a web crawler like Heritrix to download the website to an archive file. Once the archive file is created you can process it using Python/PHP all you want. Since it's stored locally on your harddrive there is no harm in how many times you read it.

The ethics and legal issues of using content from another website is a completely different issue. I'm not going to even go there, because that's between you and the website owner. What I don't want to see are people hammering websites needlessly as they try to download the content. Be respectful and web crawl with the same rules that companies like Google, Bing and Yahoo follow.


问:
How do I distinguish between things belonging to the standard library, specific gems, and those that are user-generated in Ruby?
I'm a beginning programmer, that for various reasons is using an existing Ruby codebase to learn to program. My goal is to be able to understand and eventually extend this codebase. However, I find it hard to understand what is a standard library function, a gem function, or a user-created function. Distinguishing between functions may not be the only thing that I need to do, there might be other "thingies" moving around too. The reason for the question is that I want to be able to read the code, and as I go through identify what documentation I need to read in order to understand the code.

Hence, my question is: in Ruby code, how do I distinguish between things belonging to the standard library, specific gems, and those that are user-generated, so that I may look in the right place to understand what identified functions (and other things) does?

答:
Pry is extremely useful for identifying where methods come from.

```<code>    [4] pry(#<ProductsController>)> show-doc respond_to

    From: /usr/local/var/rbenv/versions/2.0.0-p195/lib/ruby/gems/2.0.0/gems/actionpack-3.2.13/lib/action_controller/metal/mi
    Owner: ActionController::MimeResponds
    Visibility: public
    Signature: respond_to(*mimes, &block)
    Number of lines: 126

    Without web-service support, an action which collects the data for displaying a list of people
    might look something like this:

      def index
        @people = Person.all
      end
    ...
</code>```

It will also show you the source code for a method (and even let you edit it!):

```<code>    [5] pry(#<ProductsController>)> show-method respond_to

    From: /usr/local/var/rbenv/versions/2.0.0-p195/lib/ruby/gems/2.0.0/gems/actionpack-3.2.13/lib/action_controller/metal/mime_responds.rb @ line 191:
    Owner: ActionController::MimeResponds
    Visibility: public
    Number of lines: 8

    def respond_to(*mimes, &block)
      raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?

      if collector = retrieve_collector_from_mimes(mimes, &block)
        response = collector.response
        response ? response.call : default_render({})
      end
    end
</code>```

Body:
Pry is extremely useful for identifying where methods come from.

    [4] pry(#<ProductsController>)> show-doc respond_to

    From: /usr/local/var/rbenv/versions/2.0.0-p195/lib/ruby/gems/2.0.0/gems/actionpack-3.2.13/lib/action_controller/metal/mi
    Owner: ActionController::MimeResponds
    Visibility: public
    Signature: respond_to(*mimes, &block)
    Number of lines: 126

    Without web-service support, an action which collects the data for displaying a list of people
    might look something like this:

      def index
        @people = Person.all
      end
    ...

It will also show you the source code for a method (and even let you edit it!):

    [5] pry(#<ProductsController>)> show-method respond_to

    From: /usr/local/var/rbenv/versions/2.0.0-p195/lib/ruby/gems/2.0.0/gems/actionpack-3.2.13/lib/action_controller/metal/mime_responds.rb @ line 191:
    Owner: ActionController::MimeResponds
    Visibility: public
    Number of lines: 8

    def respond_to(*mimes, &block)
      raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given?

      if collector = retrieve_collector_from_mimes(mimes, &block)
        response = collector.response
        response ? response.call : default_render({})
      end
    end


问:
Should I write compact code or code with lots of spaces?
I have two friends that have completely different schools of thought on how to lay out their code.

The first says that code should be well-indented and use lots of spaces and to name variables judiciously in order to organize things in a way so that you can immediately understand the hierarchy and semantics of the code.

Here's a sample of what his code looks like:

```<code>var Stack = function () {

    var pair = function ( first ) {
        return function ( second ) {
            return function ( dispatcher ) {
                return dispatcher ( first ) ( second );
            };
        };
    };

    var getFirst = function ( pair ) {
        return pair ( function ( x ) {
            return function ( y ) {
                return x;
            };
        } );
    };

    var getSecond = function ( pair ) {
        return pair ( function ( x ) {
            return function ( y ) {
                return y;
            };
        } );
    };

    var emptyStack = function () {
        return function () {
            return null;
        }
    };

    var stack = emptyStack ();

    var self = {
        push: function ( item ) {
            stack = pair ( item ) ( stack );
            return self;
        },
        pop: function () {
            var top = getFirst ( stack );
            stack = getSecond ( stack ) || emptyStack ();
            return top;
        },
        top: function () {
            return getFirst ( stack );
        }
    };

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

The second says that it's better to have your code written in a more compact way so that you can see a bigger part of the picture at once and be able to recognize more immediately how one part of the program will affect another.

Here's the same program written in his style:

```<code>var Stack=function(){
var pair=function(x){return function(y){return function(f){return f(x)(y)}}};
var fst=function(p){return p(function(x){return function(y){return x}})};
var snd=function(p){return p(function(x){return function(y){return y}})};
var empt=function(){return function(){return null}};var stk=empt();
var slf={push:function(val){stk=pair(val)(stk);return slf},
pop:function(){var top=fst(stk);stk=snd(stk)||empt();return top},
top:function(){return fst(stk)}};return slf}
</code>```

I personally prefer writing code the first way, but I haven't really tried the second way much, so maybe I'm just not used to it.

I have noticed that when I look at the Javascript code of most professional websites, they usually use the second style, so there might be something to it.

Other than just subjective stylistics preferences, is there a reason to prefer one over the other?

答:
Most IDE-s will allow to collapse the first sample into 8 (or even 1) small lines, so that you can see the big picture. The second sample on the contrary can't be made to look like the first one easily.

The first sample is easier to understand, especially for newbies. It reveals the hierarchy and  the sequence of the actions performed. Besides IMO newbies would rather have difficulties in grasping the second sample at once, because it look rather "scary" and complicated.

So if you work in an environment of more or less experienced professionals, I'd prefer the second sample _ if you're used to that style, you can grasp the whole idea in a glance. But because in reality very few (if any) development environments consisting of experienced developers only, the first sample is better.

P.S. if you don't like to write all those spaces and new lines manually, you could have an automated tool for that.


答:
If you truly have a fixed schedule for completing a project, you need to use a process that is less agile.

If your timeline is fixed, the requirements (aka features, user stories) also need to be fixed, or at least fixed in size. To meet a fixed schedule, you need to lean more towards "following a plan" rather than "responding to change".

You need to have change management: if someone requests more features, the managers need to decide how to accommodate the request without lengthening the schedule. Jay's answer lays out the scope/schedule/budget trade-offs of traditional project management.

My experience is that there are often not good options for paying money to get more features within a limited timeframe. In that case, the choices come down to

Reject the new feature

Cancel another less important feature to make room for the new feature

Accept a cheaper implementation of certain features. (example: The quarterly sales figures are displayed as text, but not in an interactive 3d barchart)


答:
The problem is that software development is done and managed by people and people (especially management people) don't like to say no to the client because saying no is hard. Oddly clients tend to accept it better than people think they will. In their hearts, they know that new features will take time and cost money, but they have been trained to think they can ask for the moon by people who will work 90 hours a week to accommodate requests that should have been put off until later.

Whether you are doing agile or waterfall is irrelevant, the problem is the person who is communicating with the client doesn't have the guts to tell him the truth. If you ask for new features, they will cost $X more and take X more hours to do and the deadline will move.

The best you can do is push back when it happens with a new cost estimate, a new estimate of the hours to do the work and a new deadline or a suggestion that the new feature be included in the next iteration or a suggestion of what will be dropped to make room for the new feature. This needs to happen in writing and it needs to happen every single time that scope creep happens.

As a developer, when you are asked to add a new feature, you point out the features in this iteration that are not yet started or mostly incomplete (You don't want him to eliminate a completed one or one that is almost ready) and then ask which one he wants you to eliminate to accommodate the new feature or what the new deadline is. Never accept more work without either a change in deadline or other unfinished work being moved to a future iteration. However, this will only work if you get eveyone on board with it. One person accepting this type if scope creep will undermine the rest of you. One time of accepting that simple-to-make change will undermine your chances of pushing a complex change further down the road. You and your co-workers need to be disciplined about this.


答:
I generally write indented code, similar to #1, but with fewer blank lines. Indents allow for the detecting issues with brackets easily. This, combined with each assignment on it's own line, keeps things easier to read.
Tab completion allows the use of longer variable names without typing too much extra.

Yes, it is longer, but there is nothing wrong with writing long code. Just as I am using paragraphs in this answer to make reading easier, why not do the same in your code? Since the interpreter doesn't know the difference*, the only person benefiting is you.

Emacs has a VHDL plugin that I use on a daily basis which auto-beautifies code via  a keyboard shortcut. This allows for more focus on coding instead of spending time on formatting.

*language dependant. Some languages, like python, use indents as part of the syntax, in which case the interpreter does know the difference.

Title: Should I write compact code or code with lots of spaces?

Body:
I have two friends that have completely different schools of thought on how to lay out their code.

The first says that code should be well-indented and use lots of spaces and to name variables judiciously in order to organize things in a way so that you can immediately understand the hierarchy and semantics of the code.

Here's a sample of what his code looks like:

```<code>var Stack = function () {

    var pair = function ( first ) {
        return function ( second ) {
            return function ( dispatcher ) {
                return dispatcher ( first ) ( second );
            };
        };
    };

    var getFirst = function ( pair ) {
        return pair ( function ( x ) {
            return function ( y ) {
                return x;
            };
        } );
    };

    var getSecond = function ( pair ) {
        return pair ( function ( x ) {
            return function ( y ) {
                return y;
            };
        } );
    };

    var emptyStack = function () {
        return function () {
            return null;
        }
    };

    var stack = emptyStack ();

    var self = {
        push: function ( item ) {
            stack = pair ( item ) ( stack );
            return self;
        },
        pop: function () {
            var top = getFirst ( stack );
            stack = getSecond ( stack ) || emptyStack ();
            return top;
        },
        top: function () {
            return getFirst ( stack );
        }
    };

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

The second says that it's better to have your code written in a more compact way so that you can see a bigger part of the picture at once and be able to recognize more immediately how one part of the program will affect another.

Here's the same program written in his style:

```<code>var Stack=function(){
var pair=function(x){return function(y){return function(f){return f(x)(y)}}};
var fst=function(p){return p(function(x){return function(y){return x}})};
var snd=function(p){return p(function(x){return function(y){return y}})};
var empt=function(){return function(){return null}};var stk=empt();
var slf={push:function(val){stk=pair(val)(stk);return slf},
pop:function(){var top=fst(stk);stk=snd(stk)||empt();return top},
top:function(){return fst(stk)}};return slf}
</code>```

I personally prefer writing code the first way, but I haven't really tried the second way much, so maybe I'm just not used to it.

I have noticed that when I look at the Javascript code of most professional websites, they usually use the second style, so there might be something to it.

Other than just subjective stylistics preferences, is there a reason to prefer one over the other?


答:
Don't do either extreme! I would rather write

```<code>var Stack=function(){
    var pair=function(x){return function(y){return function(f){return f(x)(y)}}};
    var fst=function(p){return p(function(x){return function(y){return x}})};
    var snd=function(p){return p(function(x){return function(y){return y}})};
    var empt=function(){return function(){return null}};
    var stk=empt();
    var r={
        push:function(val){stk=pair(val)(stk); return r},
        pop:function(){var top=fst(stk); stk=snd(stk)||empt(); return top},
        top:function(){return fst(stk)}
        };
    return r}
</code>```

It's compact and readable.

Body:
Don't do either extreme! I would rather write

var Stack=function(){
    var pair=function(x){return function(y){return function(f){return f(x)(y)}}};
    var fst=function(p){return p(function(x){return function(y){return x}})};
    var snd=function(p){return p(function(x){return function(y){return y}})};
    var empt=function(){return function(){return null}};
    var stk=empt();
    var r={
        push:function(val){stk=pair(val)(stk); return r},
        pop:function(){var top=fst(stk); stk=snd(stk)||empt(); return top},
        top:function(){return fst(stk)}
        };
    return r}

It's compact and readable.


问:
Ship Early, Ship Never
This started as a "Note to Self," so please excuse me if the frustration is all too evident and the writing is less than stellar...

Three major subjects I've had at the forefront of my mind lately:

Motivation

Learning (Curiosity)

Doing (Making)

I've been studying motivation and incentives for months now. It seems there are an infinite number of different motivations that people might have for doing things (I realize that sounds trite but bear with me). I've been really drawn to it because I'm desperate to find out why I do the things I do and why I don't do the things that I want to do but don't do.

I'm in the midst of reading Paul Graham's excellent Hackers and Painters book. In it, he makes the case that hackers and painters are very similar because they are both "makers." Painters make paintings. Hackers make software. Painters don't necessarily need to understand the chemical composition of paint to make beautiful paintings. And hackers don't necessarily need to know 1's and 0's to make beautiful software.

Graham then draws the distinction between disparate computer science fields:

some people seem to be studying mathematics

some people seem to be studying the computers themselves

the hackers are making software.

The difference is incredibly important. It seems the motivation for some is to make beautiful things. And the motivation for the others is to learn out of curiosity. Certain motivations seem obvious to me, but curiosity seems a bit less obvious. I would certainly consider myself as a curious person with a seemingly unquenchable thirst to learn just about everything I can. But this is exactly where the problem comes up.

The thing that scares me so much is that I desperately want to make things. I desperately want to do things. I want to write a book. I want to paint a painting. I want to compose a song. I want to do things like travel. But the strangeness is that I also want to learn things. I want to learn to play guitar. I want to learn about art history. I want to learn more about philosophy and literature.

The key seems to be the balance between learning and doing... between studying and making.

While I'm not sure how much one should learn about a given thing before doing it, I know for certain that I find myself constantly on one side rather than the other. As it stands now (and as far as I can tell I've always been this way), I am a learner and not a doer. I've read great books. I've practiced guitar for years. I've spent countless hours studying programming.

But I've written 0 books. I've composed 0 songs. I've coded 0 beautiful programs. I've painted 0 beautiful paintings. I've started 0 viable businesses.

The scary part of all this is that there are probably countless unfinished works of art in the world. Is this my misanthropic revenge against society and culture to never produce or finish any of the works of art that I start? Perhaps the worst part (aside from this being my natural inclination), is the fact that I f***ing know better. I just finished books like "Getting Things Done" and "Making Ideas Happen." I've aggregated and synthesized countless words of wisdom on how to do things and how to make things.

Imagine the horror of going through life without being able to do the things you want to do. If this is something you've struggled with (and hopefully overcome), please share. If not... perhaps some delicious pity would make me feel better.

[UPDATE: Just wanted to send a quick thanks to everyone that shared their thoughts. I deliberately left the question somewhat open-ended in hopes of encouraging discussion and having others refashion the central problem around their similar experience, and I think it worked out great... there's a lot of amazing insight here to work with and it was really helpful. Thanks again.]

答:
Here's a motto for you:

Anything worth doing is worth doing badly.

You speak of painting beautiful paintings and coding beautiful programs.  I suspect you also want to write good novels and compose good songs.  You don't get to do those things, by and large, without working for a long time first and making bad things.

So, go out there and do cruddy work.  Write ugly programs, and try to see why they're ugly and what you could do better.  Find other people to tell you what you did wrong.  Try to learn about what you're doing, and remember that lots of learning materials make more sense with a little more experience under your belt  Do that with everything you want to do.

If you want to be a maker, make something.  Then make another thing.  Don't sweat the quality.  Then do it again.  Be reasonably proud of having made things, good or bad.  Most people don't even write bad programs or books, or paint something badly.

Title: Ship Early, Ship Never


答:
I agree with what superM said. My two cents:

I prefer the first one (not in that extreme) because that way I can maintain the code much more easily. Even if I have to change my own code from 6 months ago, I won't understand the second style as fast as the first.

What you see in JavaScript was probably written in a more human way, and even with comments, but some semi-compiler made some mechanical changes (like reducing the name of a variable from usersFacebookID to a and deleting all comments). This reduces the amount of data sent to a user, and this is the main bottle-neck of web apps, so the site seems to load faster. (And the end user anyway doesn't care about the codes style).


答:
You should use the first approach because it scales to larger programs.

The mentality of "I need to see how everything affects everything" is harmful to software development. You want functions/objects decoupled, so that you can change one thing without breaking another distant/unrelated function.

Even if you use a compact coding style, you will eventually have more code than can fit on the screen at once.

A better solution (from Clean Code by Robert Martin) is to list public "high level" functions first, and have each function stay at one level of detail.


问:
Third party libraries in an open-source C# project
I'm going to start an open source project from scratch, using git (via github) to manage the source. The project will be written in C# and will depend on at least two external libraries (more are likely to come). I wonder how I should reference the libraries, and the following ideas came to my mind:

A folder within the project that contains all external libraries as dll

This would mean I have the dll files in my repo, which I think is bad, because it isn't source. Also, I don't know how Visual Studio (or other IDEs) store the path the libraries, if they use absolute paths, that would be impossible.

Get the external libraries via nuget

This would be a clean and nice way to have the libraries organized, but what what if a library I need doesn't have a nuget-package? I can't just create one, can I?

Storing the source of the external library as part of my repo

Sounds like a stupid idea, it would make updating the libraries a pain.

Reference the repositories of the other projects via git somehow.

Sounds good, I could make my own fork of it to keep a state or just point to a commit. But is that even possible? Is that a good way?

tl;dr: How should I handle external libraries in an open-source C# project?

答:
If nuget is not available, the cleanest way may be to provide an export script which pulls the source code of the needed library from their external repository (of the library vendor) into your working directory. This will work even if the SCC system of the external libs is different from Git (as long as it has a command-line interface). EDIT: this will work also when the source code is not available in an SCC system at all, just as ftp or http download, for example.

You can integrate that script into your build process, of course. When using Visual Studio, as you mentioned it, you can write either a classic Makefile (using NMake), or use MSBuild to call that script when the external lib is not in your working dir. Perhaps the most simple approach is to add that script to a prebuild event, the details depend much on how the rest of your build process is organized.


答:
If your IDE doesn't support parsing and folding for your language, then maybe a more concise form would be in order, but overall it will be harder to pick up errors. The information density is so high you'd easily step over some error.
Besides that, the length of the lines would become quite long in cases where you have to make multiple calls in one function, which would necessitate scrolling to the side. (much more annoying then scrolling down, which is what most of our IDEs are designed to do)
If you're using s scripting language that will be interpreted instead of compiled, then you'd want to use a minifier before you ship it. The use of a minifier is a common practice in web development firms when using JS for bandwidth reasons. In interpreted languages white space is noise. Compilers usually remove any excessive whitespace when they tokenize the source code, leaving only usefull information after processing. (either to byte code or machine language) Compilers only have to deal with the noise once. Interpreters have to deal with the noise every time. (although most have some kind of caching to alleviate the problem these days.)

In the end it depends on the platform you use to edit your source and the language/environment you intend to use your code in, but I'd vote for option 1.


问:
Why does a contenteditable div not behave like an input element?
The motivation for the content editable div would be to allow user input inside a normal div element. Why does it then behave so differently to input element? Mainly I am referring to the addition of a div or a br on line break.

Additionally it does not have a placeholder item. So my question is what is the point of content-editable div? Why would I want to use it at all?

答:
what is the point of content-editable div?

The purpose of a contenteditable element is to provide WYSIWYG capabilities for editing the content and structure of elements within a Web page.

Why does it then behave so differently to input element?

A contenteditable element still has to render like a normal DOM element. To address your particular concern about line breaks, there is no way to express rendered line breaks in HTML without using an element like
 or
 (since normal source-code HTML line breaks aren't rendered in the visual page).

You might ask, "Why, then, did the WHATWG (or Microsoft) not simply make contenteditable elements play by different rules from 'normal' elements?" The answer is that a contenteditable element might stop being contenteditable at any time -- the status is toggleable. There is no obvious sensible way to make an element render its internal DOM differently depending on whether it is currently contenteditable or not.

Suppose non-
 visible line breaks were allowed when the element was in a contenteditable state. When the element switches out of contenteditable mode, should the non-
 line breaks then vanish? You might conceivably say, "Yes, that's fine!" to such a suggestion, but that flies in the face of the purpose of contenteditable I stated in my first sentence. Having the element change appearance based on its contenteditable state would spoil its usefulness as a WYSIWYG.

Body:
what is the point of content-editable div?

The purpose of a contenteditable element is to provide WYSIWYG capabilities for editing the content and structure of elements within a Web page.

Why does it then behave so differently to input element?

A contenteditable element still has to render like a normal DOM element. To address your particular concern about line breaks, there is no way to express rendered line breaks in HTML without using an element like <br> or <div> (since normal source-code HTML line breaks aren't rendered in the visual page).

You might ask, "Why, then, did the WHATWG (or Microsoft) not simply make contenteditable elements play by different rules from 'normal' elements?" The answer is that a contenteditable element might stop being contenteditable at any time -- the status is toggleable. There is no obvious sensible way to make an element render its internal DOM differently depending on whether it is currently contenteditable or not.

Suppose non-<br> visible line breaks were allowed when the element was in a contenteditable state. When the element switches out of contenteditable mode, should the non-<br> line breaks then vanish? You might conceivably say, "Yes, that's fine!" to such a suggestion, but that flies in the face of the purpose of contenteditable I stated in my first sentence. Having the element change appearance based on its contenteditable state would spoil its usefulness as a WYSIWYG.


问:
How is one expected to use open sockets with [delimited] continuations?
I'm trying to figure out how an open socket or file handle should interact with continuations. Searching has revealed that dynamic-wind is probably part of the solution, but I'm more interested in the methodology rather than the implementation, and all I could find is how to implement it under various conditions.

Do programmers even use sockets within continuations in such a way that it is necessary for dynamic-wind to close them? Or is it typically just a way to implement a "finally" block if the continuation exits past where the socket is handled?

What should happen if a continuation is re-entered after a hypothetical dynamic-wind closes the socket?

答:
It is common to automatically close files, sockets, and other resources when the program uses a continuation (or exception, which is often implemented using continuations) to exit a context. There are often library procedures that help do this automatically; for example, see Racket's call-with-input-file*, call-with-semaphore, etc. They all use dynamic-wind in their implementation.

It's often difficult to write code that uses or manages resources correctly in the presence of continuations. For example, if a file gets closed when control jumps out, should it be re-opened when control jumps back in? If so, maybe it needs to be opened in a different mode the second time, eg append instead of truncate. But now it may be difficult to ensure that the output is well-formed; continuation jumps may mean that parts get written multiple times, out of order, etc. And so on. So it's often useful to simply prohibit continuation jumps back into a context once it's been exited. Racket provides call-with-continuation-barrier for this purpose, but it can also be done with dynamic-wind and a mutable variable.

(One difference between using call-with-continuation-barrier and dynamic-wind is that you use call-with-continuation-barrier around your call to unknown code, whereas dynamic-wind would need to be around the beginning of the code that you want to protect from reentry, which may be harder to determine. There's a mailing-list post with more detailed discussion.)

The story is about the same for delimited continuations. For example, shift jumps out across boundaries, and applying the procedure it gives you jumps in across the captured context boundaries.

ContentLicense: CC BY-SA 4.0


问:
When to build(code) vs buy(download plugin)
Recently I have been working with a large set of talented programmers that lead to a discussion on when should we start building our own components (web js/css) vs downloading and modifying existing components that don't quite fit the needs of a project. Does anyone know or could suggest best practices for this type of conundrum?</p>

答:
There are a few different considerations that come into play when we consider it for our company, as listed below:

Cost - Is the time cost for modifying it going to be greater than the time cost for developing outright? Not all components will be easily modifiable, and if it would take 8 hours of development time to custom build versus 10 hours to modify, that is a factor.

Control - The component must be available with source code and modifiable.

Licensing - If there is any cost, is there a one time cost? Or is it ongoing? If it is free, is that only for private or single use? Or is there a fee if it is for a commercial application?

Branding - Depending on the component/programmer, they may specify that their accreditation either stay commented in the code, or be displayed on the website/application. You have to determine if that is acceptable.

Coding standard/documentation - The code may work, but if it is incomprehensible and/or poorly documented, it may cost more time to rework that portion than it is worth.

Those are the primary things that we consider when looking at developing, versus outsourcing or downloading available components.


问:
svndumpfilter Multiple Versions
I have a few questions about the Subversion open source project. I know that there are multiple versions of svndumpfilter (2,3). What are the tradeoffs and benefits of each version? In other words, what problems does each version seek to address?

There are known bugs in the original svndumpfilter that have not been resolved for years. Out of curiosity, why is this the case? Is it because svndumpfilter is of lower priority than the other working components of svn?

答:
Well, there's multiple versions of Subversion itself, so technically you should just go look at the changelog for the releases.

I think you'll find the differences are related to the times when the svn repository format changes, svn itself will happily (and silently) upgrade your working copy, and you can easily upgrade your server repo if you start using a new version of svn, the dumpfilter that you get with the server would just have been modified to work with the new formats.

Bugs, svndumpfilter is a tool that has certain limited uses, as a result it doesn't get modified much as people don;t tend to use it very often. Its also open source, so if someone really had a need to fix a particular bug in it, they would have (or paid someone else to do so). I don't know if that means "lower priority" or not, maybe "less resourced" would be a better term.

Title: svndumpfilter Multiple Versions