答:
Are there any arguments in for or against including the extraneous parentheses? Does practical experience suggest that it is worth including them for readability? Or is it a sign that a developer needs to really sit down and become confident in the basics of their language?

If no one else ever would have to look at my code again, I do not think I would care.

But, from my experience:

I look at my code again occasionally (sometimes years after writing it)

Others sometimes look at my code

Or even have to expand/fix it!

Neither myself or the other remembers exactly what I was thinking when writing it

Writing cryptic "minize the character count" code hurts readability

I almost always do this because I trust my ability to quickly read and not make little mistakes a lot more with parens than nothing else.

In your case, I would almost assuredly do something like:

```<code>if (a AND b) then ab = true
if (c AND d) then cd = true
If (ab OR cd) Then ...
</code>```

Yes, it's more code. Yes, I can do fancy bool operators instead. No, I don't like the chance when skimming code 1+ years in the future I misread fancy bool operators. What if I was writing code in a language which had different AND/OR precedence and had to jump back to fix this? Am I going to go, "aha! I remember this clever little thing which I did! I didn't have to include parens when I wrote this last year, good thing I remember now!" if that happens (or worse, someone else who wasn't aware of this cleverness or was thrown into a "fix asap" type situation)?

Separating with () makes it so much more straightforward to quickly skim and understand later...

Body:
Are there any arguments in for or against including the extraneous parentheses? Does practical experience suggest that it is worth including them for readability? Or is it a sign that a developer needs to really sit down and become confident in the basics of their language?

If no one else ever would have to look at my code again, I do not think I would care.

But, from my experience:

I look at my code again occasionally (sometimes years after writing it)

Others sometimes look at my code

Or even have to expand/fix it!

Neither myself or the other remembers exactly what I was thinking when writing it

Writing cryptic "minize the character count" code hurts readability

I almost always do this because I trust my ability to quickly read and not make little mistakes a lot more with parens than nothing else.

In your case, I would almost assuredly do something like:

if (a AND b) then ab = true
if (c AND d) then cd = true
If (ab OR cd) Then ...

Yes, it's more code. Yes, I can do fancy bool operators instead. No, I don't like the chance when skimming code 1+ years in the future I misread fancy bool operators. What if I was writing code in a language which had different AND/OR precedence and had to jump back to fix this? Am I going to go, "aha! I remember this clever little thing which I did! I didn't have to include parens when I wrote this last year, good thing I remember now!" if that happens (or worse, someone else who wasn't aware of this cleverness or was thrown into a "fix asap" type situation)?

Separating with () makes it so much more straightforward to quickly skim and understand later...


问:
What's the best way to manage error logging for exceptions?
Introduction

If an error occurs on a website or system, it is of course useful to log it, and show the user a polite message with a reference code for the error.

And if you have lots of systems, you don't want this information dotted around - it is good to have a single centralised place for it.

At the simplest level, all that's needed is an incrementing id and a serialized dump of the error details. (And possibly the "centralised place" being an email inbox.)

At the other end of the spectrum is perhaps a fully normalised database that also allows you to press a button and see a graph of errors per day, or identifying what the most common type of error on system X is, whether server A has more database connection errors than server B, and so on.

What I'm referring to here is logging code-level errors/exceptions by a remote system - not "human-based" issue tracking, such as done with Jira,Trac,etc.

Questions

I'm looking for thoughts from developers who have used this type of system, specifically with regards to:

What are essential features you couldn't do without?

What are good to have features that really save you time?

What features might seem a good idea, but aren't actually that useful?

For example, I'd say a "show duplicates" function that identifies multiple occurrence of an error (without worrying about 'unimportant' details that might differ) is pretty essential.

A button to "create an issue in [Jira/etc] for this error" sounds like a good time-saver.

Just to re-iterate, what I'm after is practical experiences from people that have used such systems, preferably backed-up with why a feature is awesome/terrible.

(If you're going to theorise anyway, at the very least mark your answer as such.)

答:
Sometimes, the log information is just too voluminous to be stored on disk.  One approach I have seen is to write your logging entries to a firehose (in, say, perl) something like this:

```<code># Create socket.
my $sock = IO::Socket::INET->new(
    Proto       => 'udp',
    PeerAddr    => $bcastaddr,
    Broadcast   => 1,
) or die "Can't create socket ($bcastaddr): $!";

while (<>) {
    chomp;
    unless (/File\ does\ not\ exist:/) {
        $sock->send("$eventtype:$_") or warn "Can't send: $!";
    }
}
</code>```

then an analyst can grep out what s/he wants to look at.

ContentLicense: CC BY-SA 2.5

Body:
Sometimes, the log information is just too voluminous to be stored on disk.  One approach I have seen is to write your logging entries to a firehose (in, say, perl) something like this:

# Create socket.
my $sock = IO::Socket::INET->new(
    Proto       => 'udp',
    PeerAddr    => $bcastaddr,
    Broadcast   => 1,
) or die "Can't create socket ($bcastaddr): $!";

while (<>) {
    chomp;
    unless (/File\ does\ not\ exist:/) {
        $sock->send("$eventtype:$_") or warn "Can't send: $!";
    }
}

then an analyst can grep out what s/he wants to look at.


问:
How can I increase my programming skills?
I program in C and I believe I know the language well. I understand all the concepts and my problems never come from misuse of the language.

I have problems because I always forget or oversee things. Setting a variable to zero, or generating a particular test case. I keep finding bugs in my code due to conditions I could not foresee or forgot.

Any idea how to fix this?

答:
Self discipline.

The only way to attain it is to learn from your mistakes and take steps to not make them. It's unfortunate that you haven't learned this after a few years. Turn on all compiler warnings, treat warnings as compiler errors and see what that turns up.

Static analysis can also be of help here in showing you flawed code paths.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


答:
Use a strongly-typed language with some ceremony, like C#.  C# will force you to write your code in a more structured, object-oriented way, but it still looks like C.  The strong typing will ferret out some of the errors you described, at compile time.

Alternatively, you can learn C the hard way.

Title: How can I increase my programming skills?

Body:
I program in C and I believe I know the language well. I understand all the concepts and my problems never come from misuse of the language.

I have problems because I always forget or oversee things. Setting a variable to zero, or generating a particular test case. I keep finding bugs in my code due to conditions I could not foresee or forgot.

Any idea how to fix this?


问:
What are the downsides of mixing tabs and spaces?
The advantage of using tabs for indentation is that people can configure their editor to use the tab width they are comfortable with. The only argument against this seems to be that people don't want their code to look differently based on editor settings. However, since code is ultimately being written to be easy to read later, it seems much more beneficial to allow the reader to set the width to their preferred value.

On the other hand, because tabs have a different width in different environments, you will get aligning issues when you use it to format multi-line statements and other things.

An example of this is:

```<code>print(name + " is now " + age +
      "years old!")
</code>```

But in this case the spacing in front of the second line has a very different purpose than that used to indent blocks. Since the purpose here is to align the second line with the print( characters, the best solution here is to use spaces, since they're guaranteed to be as wide as each character in the line above.

To summarize, what is wrong with

...using tabs for indentation where everyone can set their own preferred width

...using spaces for aligning multi-line code where the width does matter

Since most of these questions are typically just tabs vs spaces, I hope to gain some more insight here about the advantages/disadvantages of using each for their own separate use cases.

答:
what is wrong with

...using tabs for indentation where everyone can set their own preferred width
  ...using spaces for aligning multi-line code where the width does matter

Nothing's wrong with that; in fact, it's the best solution to the "tabs vs. spaces" war, because, as you've already discovered, it allows for variable depth of block indentation for the people who want it (via tab width setting), while maintaining consistent formatting within the block (as is increasingly mandated or at least strongly recommended by language style guides, for example PEP8 for Python).

There's really only one right answer here, and that's that if you're a programmer you need to be using a proper IDE or an editor meant to be used by programmers to edit code.  People using Notepad or Nano and indenting by hand are an edge case.  Eclipse, Emacs, Vim, and XCode all can be set up to indent code automatically via the "tabs for blocks, spaces for multiline statement alignment" method.  This works for practically all languages except for Python, where PEP8 says that "all spaces and no tabs" is preferred (thus no need to debate there either).

I favor Emacs, but I wouldn't force it on other developers who already have a tool that they are comfortable with, as long as that tool can the job.  People who turn the tabs vs. spaces "debate" into an editor holy war are missing the point.  If you are indenting by hand, you're Doing It Wrong.  Period.  If other people can't open up your code in their editor without the formatting being ruined, you're also Doing It Wrong.  This should be simple stuff, and it is if you use the right tools for the job.  We're programmers, after all--configuring an editor should be a piece of cake compared to some of the mental hoops we have to jump through every day on the job.


问:
Best practice refactor n-tier into vertical slices architecture
What work path do there exist to identify reasonable vertical slices of a classic n-tier platform code base and infrastructure (enterprise size)? Regardles of refactor or a new solution I think there will be the same approach (more or less?) So i'm primary interested in steps and definitioning of modules, functions, then "test" them into a function-unit or if it's appproved as a vertical.

To extend my thoughs..

I understand that a vertical should be a actor, a kind of business value. But is a communication system a actor, or a functional unit in a vertical slice? Probably yes And no (depends on enterprise), but how to decide? Is shipment a part of Order, or are both Order and Shipment different verticals?

What should a vertical slice consist of, to be a true vertical? In terms of Levels of functions, like "an own data store, an own client configuration tool, an own business intelligence calculation" and so on. Btw: It's a requirement that the verticals should be deployed and operatable independently of each other.

Maybe there is a kind of "yes/no" schema to use? "Is this X used for Y?" Yes - then it's a vertical. "Is this X used with Z?" - Yes, then it's anti-pattern for vertical. "Is X depend on the funtion YY?" If yes, then..

And so on. Links to success stories when define verticals is also of interest.

答:
Tackling a significant refactor requires you to have a solid understanding as to why you're performing that refactor.

I'll rule out the hobby level justifications such as "make the code more pure" or "improve stylistic expression" or similar.  Those aren't bad justifications, but a commercial project will almost never see or use that level of justification for a major undertaking.

In contrast, commercial level refactoring justification always involves pain.

"Maintenance has become impossible."

"The code base can't be extended."

"Code changes generate obscure errors in unanticipated areas of the code."

Pain justifies the expense and risk involved.  And pain leads you to your answer.  You refactor in order to minimize future pain.  Refactor in order to encapsulate the change.

You mentioned a couple of aspects such as communication systems, orders, and shipments.  And you correctly called out that there isn't a one-size-fits-all approach to identify what belongs where.  Every system is different based upon its domain and business need.

For your system, identify what is changing.  Push that into its own vertical that conforms to a contract or an API with the rest of the system.  Whenever that section changes, you can verify it still meets its contract and control the amount of damage from the code change.


答:
I have been in a project where with logged client errors using Microsoft Enterprise library.
All exception where send to our mail box.  In the mail subject we added hash code of serialized error for avoiding duplicated messages. One could of course store serialized messages in database and so on.

I recommend you to check out Microsoft Enterprise library and Log4Net.

Some Features of Log4Net

Support for multiple frameworks

Output to multiple logging targets

Hierarchical logging architecture

XML Configuration

Dynamic Configuration

Logging Context

Proven architecture

Modular and extensible design
•   High performance with flexibility

Title: What's the best way to manage error logging for exceptions?

Body:
Introduction

If an error occurs on a website or system, it is of course useful to log it, and show the user a polite message with a reference code for the error.

And if you have lots of systems, you don't want this information dotted around - it is good to have a single centralised place for it.

At the simplest level, all that's needed is an incrementing id and a serialized dump of the error details. (And possibly the "centralised place" being an email inbox.)

At the other end of the spectrum is perhaps a fully normalised database that also allows you to press a button and see a graph of errors per day, or identifying what the most common type of error on system X is, whether server A has more database connection errors than server B, and so on.

What I'm referring to here is logging code-level errors/exceptions by a remote system - not "human-based" issue tracking, such as done with Jira,Trac,etc.

Questions

I'm looking for thoughts from developers who have used this type of system, specifically with regards to:

What are essential features you couldn't do without?

What are good to have features that really save you time?

What features might seem a good idea, but aren't actually that useful?

For example, I'd say a "show duplicates" function that identifies multiple occurrence of an error (without worrying about 'unimportant' details that might differ) is pretty essential.

A button to "create an issue in [Jira/etc] for this error" sounds like a good time-saver.

Just to re-iterate, what I'm after is practical experiences from people that have used such systems, preferably backed-up with why a feature is awesome/terrible.

(If you're going to theorise anyway, at the very least mark your answer as such.)


问:
JS Framework for server-heavy and/or client-light pages
I've been reading articles such as this one that indicates web development has evolved to use JS frameworks.  Where I work, we have a massive website with many existing web applications that are already established and are server side heavy.

One article I read said that the DOM manipulation/jQuery method leads to unmaintanable spaghetti code, and that you should strive to use a JS MV* framework.  However, sometimes I just have a fairly simple list of items generated from the server; something like:

```<code><div class=shower data-id=1>show</div>
<ul><li class=hider data-id=1>one</li></ul>
//js
$(".shower").on("click", function () {
    $(".hider[data-id=" + $(this).data("id") + "]").show();
});
</code>```

...and that would pretty much be the extend of the JS on that page.  According to the MV* framework disciples, the need to reference specific classes or attributes in the JS is a problem and models should be used instead.  However, it seems like overkill to include a massive library for creating rich applications to handle some fairly trivial DOM manipulation and animations.

Is there a JS framework in existence that bridges the gap between complete front-end stack frameworks and tightly coupled HTML/JS?  If not, how could I write such code to avoid this coupling?

Additionally is there any reason to push strongly for making the switch to such a framework for established server-heavy applications (especially in cases where we have to support JavaScript being turned off)?

答:
The author of the article you linked seems to have forgotten about server-side HTML generation completely.  You don't need all that JS ceremony to create a data-driven web page; the JS is there to augment the page, not generate it.

That said, none of these JS frameworks is all that large.  "Massive library" is a mischaracterization.  I suspect that if you make the attempt to write such code to avoid tight coupling, you'll be reinventing Backbone/Ember/Angular anyway.

If you're genuinely worried about the library size, use Resig's Micro-Templating, which weighs in at about thirty lines of javascript.  Alternatively, you can get a custom-tailored recommendation for a JS framework at one of the links below.

See Also

http://microjs.com/#

http://garann.github.io/template-chooser/


答:
I've been a dev and done a good deal of developer support for years and I'd like to share three good pieces of advice that have helped me in my time.

1. Write code to fail first

Stop writing code with the intention of making it work - doing that is for amateurs and students.  Code that only works is in many respects a single use case with failure always an option.  Instead write code with the expectation that any actions that can fail will at some point.  Only when every possible failure condition has been exhausted can you be reasonably sure your code will work.  What if that memory isn't allocated, file isn't available, data is corrupted or that stack under/overflows?

2. Accept that as a programmer you are not as good as you think you are

...and you never will be.  When we programmers accept that we will all make mistakes then will we apply ourselves to be thorough.  Each mistake is a learning opportunity and each bug is not a bug, it is a class of bugs - if you don't validate input in one place and your code barfs, fix it and then consider where else that might be the case in your code.

3. Use the resources available to you

There are so many resources open to devs now, fix compiler warnings if you can.  Code quality tools available, some for free - in C# I like to take code and throw Pex at it and see what failure points it found that I had missed...  an exercise like that is a real eye opener!  Refactor some old code as a mental exercise, set yourself a time limit so as not to spend all day on it.  There are people around you who can do peer reviews use them.  Learn a different language - not because you specifically intend to use it, but because it will exercise your thought paths and ways of thinking about things in your chosen language.


答:
I learned EMACS in 1983 and freely intermixed tabs and spaces until LAST YEAR, when a young programmer explained to me the errors of my ways. We had a group meeting and changed our policy to eliminate tabs in our source code.

Here's why:

Yes, you can freely intermix tabs and spaces, and high-quality editors like EMACS handle it perfectly. EMACS properly has a hacking-backspace which kills a tab and turns it into 7 spaces. EMACS indent mode understands that it is appropriate to use 4 spaces to indent a little, then a tab, then a tab and 4 spaces, then 2 tabs, etc.

However, there were a large number of WINDOWS programmers who didn't have the benefit of EMACS in the 1990s. Their only tool with Visual Studio and it indented with TABS. Indenting C with 8 spaces is stupid, so they changed their tabstop to 4. This works, but when you bring the code into a tab-aware editor, it looks horrible.

Even though spaces are uniformly 1 space, the above discusion makes it clear that you can't depend upon the other programmer's system to be properly set up.

So we went through all of our code and UNTABIFIED it. Oh, the horror. Oh the shame.

Now we have this little line at the top of each of our C files:

```<code>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
</code>```

Title: What are the downsides of mixing tabs and spaces?

Body:
The advantage of using tabs for indentation is that people can configure their editor to use the tab width they are comfortable with. The only argument against this seems to be that people don't want their code to look differently based on editor settings. However, since code is ultimately being written to be easy to read later, it seems much more beneficial to allow the reader to set the width to their preferred value.

On the other hand, because tabs have a different width in different environments, you will get aligning issues when you use it to format multi-line statements and other things.

An example of this is:

```<code>print(name + " is now " + age +
      "years old!")
</code>```

But in this case the spacing in front of the second line has a very different purpose than that used to indent blocks. Since the purpose here is to align the second line with the print( characters, the best solution here is to use spaces, since they're guaranteed to be as wide as each character in the line above.

To summarize, what is wrong with

...using tabs for indentation where everyone can set their own preferred width

...using spaces for aligning multi-line code where the width does matter

Since most of these questions are typically just tabs vs spaces, I hope to gain some more insight here about the advantages/disadvantages of using each for their own separate use cases.

Body:
I learned EMACS in 1983 and freely intermixed tabs and spaces until LAST YEAR, when a young programmer explained to me the errors of my ways. We had a group meeting and changed our policy to eliminate tabs in our source code.

Here's why:

Yes, you can freely intermix tabs and spaces, and high-quality editors like EMACS handle it perfectly. EMACS properly has a hacking-backspace which kills a tab and turns it into 7 spaces. EMACS indent mode understands that it is appropriate to use 4 spaces to indent a little, then a tab, then a tab and 4 spaces, then 2 tabs, etc.

However, there were a large number of WINDOWS programmers who didn't have the benefit of EMACS in the 1990s. Their only tool with Visual Studio and it indented with TABS. Indenting C with 8 spaces is stupid, so they changed their tabstop to 4. This works, but when you bring the code into a tab-aware editor, it looks horrible.

Even though spaces are uniformly 1 space, the above discusion makes it clear that you can't depend upon the other programmer's system to be properly set up.

So we went through all of our code and UNTABIFIED it. Oh, the horror. Oh the shame.

Now we have this little line at the top of each of our C files:

/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */


答:
The Devil is in the Details

You're not incompetent. You just lack a bit of attention to details and aren't demanding enough.

Let the Compiler be your Guide

You say you're a C programmer. Let the compiler be demanding of you, and compile (for gcc) with at least: -Wall -Werror -ansi -pendantic -Wstrict-prototypes.

... and Invite its Helpers to the Party!

Make sure to run some code quality tools on your code on top of that. Use the plethora of linters, static code analyzers and others that you have at hand to try to detect possible bugs. Use Valgrind.

Add Constraints to the Mix

Force yourself to write code that targets different operating systems and architectures. Some are way less forgiving than others when it comes to screwing up your memory allocations, and you'll see various results in the way they handle their threading models. As you'll work through these differences, you'll learn to iron out problematic points.

Develop a Keen Eye for Testing

That's not everything though, and they cannot guess what you are trying to do. So get into the habit of thinking of edge cases and good tests for you code. Ultimately, these things will come naturally to you, and writing more robust code becomes a habit. You just don't have the habit yet.

Fail Early, and Fail Hard

Write code that really fails. Meaning that when someone's wrong, it should really fail hard and crash, so the issue is notable and needs to be addressed, instead of weaseling your way out by trying to handle errors and staying alive for as long as you can.

There are different schools of thought, and both have advantages. Defensive Programming is great to write software that is somewhat fault-tolerant and doesn't crash by compromising security of the platform. However sometimes you want to use a design-by-contract approach and enforce these contracts (and the developers know when things would go wrong early on in the dev cycle).

Practice, Practice, Practice

Of course, all of the above is already about that. But maybe what you lack is an incentive to do it and do something great. You mention having issues as soon as things get complex. Then get out of your comfort zone and build something complex. What do you miss in your virtual life, on a regular basis? If you can think of something, can you build it? Start simple, and build something bigger and bigger as you go. See it through, and improve its overall design as you go. Then maybe throw it out and do a full rewrite: now that you have a better insight, you should be able to rebuild this complex system faster, and with a better design not suffering from its initial flaws.

Train yourself.


问:
High-Load Java Server for Multiplayer
I am making a multiplayer game. Now I am trying to choose the technology to connect the android devices to the server. The clients run on Android, and the game is MMORPG. I would like to write the server in java. Right now I have only 3 ideas for it:

1) creating multithreading environment with plain java and sockets. In this way it will be easier to perform full-duplex connection between the game client and the server. But I have the following concerns:

1.1) The game is MMORPG with a large number of objects, and I am not sure how such solutions are scaled if there are for example 5000 people playing at the same time. How many threads will I be able to run on java Machine? How can I approximately calculate that? In case 1 thread is reading for each socket and 1 thread is writing to the socket (so 2 threads for 1 player).

1.2) When the number of players grows, how will I be able to scale my self-written jar-archive to distribute over several servers? Maybe there is some special trick to do that?

1.3) A lot of programming overhead - sockets API is quite low level.

2) Creating a Servlet-interface for serving HTTP requests.

2.1) Easy to control sessions (and authorization) as long as each player has his/her own session.

2.2) can connect to java EE EJB or whatever - a lot of complications with system-level programming are taken away. So I can concentrate on writing business logic.

2.3) Can serve all types of clients with HTTP - mobile devices + browsers.

2.4) High-speed - even 1 servlet container can serve a few thousand requests per second so it will be really fast.

2.4) But this approach cant provide a full-duplex communication. I will have to send requests every 1 second to check for updates. 1 second delay does not make a lot of difference for the game as it is turn-based, but still it generates a lot of traffic. Is it feasible when there are many players playing? I heard about some COMET technology, but it seems like if the server has to push many messages in row, I will still have to send requests every time + this technology is not well established yet.

3) Creating sockets and connecting them through JMS to the java EE server.

3.1) Cool because allows for full duplex communication between clients and server + provides all cool features of java EE. Later can be extended to browser through servlet interface.

3.2) It seems like some kind of overengineering. Is it really how people would do that? I mean is it even the correct way? Would any sane developer do it like that?

I would like you to help me out with the choice please. I dont have much experience with doing some work like that. And would like to stick to the best practices.

答:
Why Rewrite What you can Get Off the Shelf?

Why not use RedDwarf Server (formerly Project DarkStar)?

RedDwarf Server is an open source middleware solution for developing the server-side of massively multiplayer online games. It is the official community fork of Project Darkstar, an open source project supported and managed by Sun Microsystems. - from RedDwarf's Wikipedia article

RedDwarf's domain seems down today (2013-06-12), but there's still a wiki, and they are migrating to a GitHub repo.

RedDward presents its philosophy and goals as:

Make server-side game code reliable, scalable, persistent, and fault-tolerant in a manner that is transparent to the game developer.

Present a simple single-threaded event-driven programming model to the developer. The developer should never have his or her code fail due to interactions between code handling different events.
  (from the RedDwarf Tutorial)

Not that this doesn't mean that server-code is single-threaded, but that it is abstracted from the game developer's perspective. The RedDwarf Tutorial provides a lot more information on what RedDwarf can do and clarifies many of its design decisions.

One point of concern for you, though, was that the multi-node capability wasn't fully implemented last time I check (ca. 2011).

From Scratch

That shouldn't stop you from attempting to do most of these things from scratch, if you value the learning experience. However, this is a major effort and will be rather time-consuming, and as, you noted in your question, some of these issues are rather low-level in the tech stack to deal with and will greatly increase the complexity of the code you'll have to maintain.

But anyways, regarding your 3 options, your first one seems the best to me, if you were to go for a home-made implementation. Option 2 (using HTTP servlets) seems only adapted for some games, though I guess it could be a relatively decent alternative to implement something yourself while still delegating to the a middleware, and you could benefit from many web server additions for handling the load (cache modules, etc...). Option 3 (using JMS + JEE) indeed seems overengineered, but it's hard to know for sure without knowing what you have in mind.

And if you're here to try to learn, then obviously Option 1 will cover a lot of ground. But it's going to be a rather uphill battle.

Title: High-Load Java Server for Multiplayer


问:
Should a software company have a dedicated team for research and/or utility libraries?
I work in a company that does web applications for various banks and some smaller e-shops
We employ about 20 developers and have 4-5 projects in development at any one time.
Our development teams don't interact much and a lot of the same problems are done in varied ways(good to bad).

I was wondering if it would be a good idea for a company to have a team of programmers that do research on current frameworks and continually improve a common library of functions and a common framework to build current and future projects much faster and more efficiently.

How large should a team like this be?

Also should it have permanent members that train others or should it rotate people?

Update: I was thinking about a common project that people can work on for fun that might spark some interest. It seems that when people have job pressures the solutions they come up with are not the best.

答:
I think that's NOT A GOOD IDEA, because for libraries to be useful they have to help you solve real project problems, and you only get to know them by, well... working in real projects.

Otherwise you can end with a "theoretically" very good library!


问:
When should I use or not BooleanUtils.isTrue(...) and BooleanUtils.isFalse(...)?
About this function: org.apache.commons.lang3.BooleanUtils.isFalse(Boolean bool) and the similar isTrue, my co-work (less experienced) use it for every boolean in the code. I am trying to convince him that it is not a good practice because make the code confusing. In my POV, it should be used ONLY if the boolean to be tested is a type of non-primitive Boolean and it can be null. Actually, even this I think it is unnecessary, because the implementation of this function is simply Boolean.TRUE.equals(bool) or Boolean.FALSE.equals(bool). Anyway, I think it is totally crazy do something like:

```<code>boolean isReady = true;

if (BooleanUtils.isTrue(isReady)) {
   // ...
}
</code>```

when you cold simply do

```<code>if (isReady) {
   // ...
}
</code>```

or (!isReady) for the opposite.

His only argument to use this is "it is easy to read". I just can't accept this argument. Am I wrong? What arguments can I use to convince him that no useless code is better than useless code in this case?

Thank you guys.

答:
1) Bugs come from code. The more code you have, the more bugs. Always try to write less code, even if that's just a few words here and there.

2) Easy isn't Easiest. Which is easiest to read?

Try compromising with if(isReady == True), if he really wants that explicit comparison.


问:
Why use test runners?
I'm currently designing an automated testing framework for doing embedded systems testing on an embedded Linux system. There exists an old system, but it is particularly hard to use, mainly because it wasn't designed as a framework and was originally designed to test one product only. What this means is that the framework changes with each new product to test, which would take a lot of time spent simply understanding where to modify the system and how.

Now, I've been given the opportunity to create a new system from the ground up, with the goals of making it much more easy to use and a lot more intuitive. One of the things that I noticed in both the old system and other test systems I used was the idea of setting up all the tests and verification conditions, and then running the test so that the set up and test running were two different paths that occurred sequentially. One of the downsides to this is that any print statements would occur outside the flow path of the actual tester, so printing out failed variables needs to be added into the tester somehow.

Now that it falls on me to redesign the system. I'm wondering what added benefits are presented by going with a test-runner style architecture over simply setting things up, with checking variables and reporting back all at the same time.

答:
I suggest taking a glance at the book XUnit Test Patterns. It covers a lot of different ways to define a test framework, and it discusses some of the pros and cons of many different approaches.

I think the best benefit of using a test runner vs. the approach that you mentioned, is that it becomes easier to run a subset of the tests (which could be just one of them).

Title: Why use test runners?


问:
Will git whine if I create my projects in multiple directories?
I'm new to git (and github). I work in Java and Python. Right now, I manage my projects in only one directory - let's call it Code and the folder is on my Desktop.

I want to group my projects by the language I code in. So, I want:

```<code>/Code/
++ /Java/
++ /Python/
</code>```

I do not know if Git would be happy with this or not. If it would be, what should I set my home directory to be?

And how should I manage it with my github account? For example, I create a new repo on GH for a new-project in Python (but I already have files on my local machine in /Code/Python/new-project), how should I about committing the files to GH making sure any other directories are not messed up with?

EDIT:

Just to be clear, I have unrelated projects in /Code/project_1, /Code/project_2, /Code/project_3 etc. But I want to arrange them as /Code/Java/project_1, /Code/Java/project_1, /Code/Python/project_1 etc.

答: I don't know if it's considered good practice or not, but I'm fairly sure git allows creating a new local repository in any arbitrary directory, which then can be added to github via the standard "git remote add" command or the relevant menus in the GUI application.</p>


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
A qualified "yes".

After reading other answers, I'll try for something more practical than somewhat "ideal" answers

You need to separate professional and hobby.

As much as learning half a dozen languages and ways of thinking makes you a better individual, you aren't paid to learn, say, Haskell if you're employed to pimp a corporate intranet site in an MS shop

Part of that bargain would be that the employer facilitates you in training in your speciality as well as in general development skills: next .net version, general OO techniques, become a Scrum Master, go to SQL Pass etc.

Feel free to learn Python, Perl, OpenGL, whatever on your own time for your own enjoyment and satisfactions. I know several folk that do this.

Summary: Yes you can, but don't give up on "outside interests"


问:
Testing MVC models when using SQL referential constraints
I have an MVC web app that's wired against PostgreSQL. The DB uses the full gamut of various referential constraints to ensure referential integrity, as opposed to say the Rails approach, where you try to do most of the checks in the model logic. Also, by choice, I'm not using an ORM, I'm writing the SQL statements by hand for each model.

Now, I want to write unit tests and functional tests for it. The problem is that if I write these tests against the database (as opposed to mocking), I will have to create an entire long hierarchical chain of references for each model I'm testing, or the system won't let me generate them in a vacuum. E.g. I cannot create a model without a foreign key, and the foreign key does have to point to an existing record, etc. all the way up the chain.

The thing to remember is that, unlike with an ORM, I cannot trust my data access layer (DAL) to work as expected. I might have fat fingered a statement somewhere, or maybe just got the logic wrong. I must test my data access layer to do what it's supposed to.

One way to solve this problem is to use something like Rails' Factory Girl, which, when properly configured, will generate the chain of records you need to instantiate any model in your system. This way I test both the DAL and the model logic. This is obviously not ideal because test cases would waste a ton of time hitting the DB and add extra boilerplate that I simply don't need. My suite will go up in run time real fast, which is bad.

The solution I'm thinking of is to:

have a test suite just for the DAL. This test suite would make sure of creating all of the right references and would only test that the SQL statements are working as expected. References won't really be explicitly tested (seems a bit of an overkill, but it can be done if desired), but at the very least it will make sure that a chain of relations can be built in the "happy path" scenario. This suite is ultimately going to be comparatively short and thus not consume too many cycles.

mock both model and controller tests, so that things can be tested in isolation without DB reference constaints getting in the way. This is where the vast majority of testing will happen, so mocking the DB makes complete sense as far as saving time goes. This way I'm also not testing the SQL access layer twice, no need to.

My question is, is the proposed solution above how most people solve their SQL with constraints and model/controller tests problem, or am I missing an option here?

答: The approach that I've taken in the past is to have something that generates the SQL statements for me, and then I make sure that my domain models are calling that correctly. This ends up looking like a specialized query generator for the queries that are being built in my application. I then mock that when I'm unit testing my models. And I either write unit tests against the query generation, which makes sure the correct string is generated, or I just write an integration test that actually involves a database.</p>


问:
Method to test/reproduce Heisenbug possibly relating to Multimedia Class Scheduler Service?

The Problem

I am hunting down a bug in a web application related to multi-uploads using a Flash movie/applet. Sometimes, the progress bar that is used in the Flash applet to indicate file upload progress will read over 100% for a progress and causes the entire upload system to halt.

Aside from the logic errors associated with the rest of that code, attempting to reproduce this bug to trace execution and debug is a feat in itself. It's a Heisenbug, and I have seen it just once in about two days of trying. Other developers' machines can reproduce it with more regularity.

The only time I reproduced it was rebooting after changing my registry key for SystemResponsiveness, as my machine uses Windows Server 2008 R2. That registry key controls CPU priority for multimedia applications. Windows Server 2008 R2 sets this key to 100 (giving multimedia applications very low priority), whereas I set mine to 20 as it is what a desktop Windows 7 install sets it to. All other developer machines that can reproduce this issue have SystemResponsiveness set to a default 100.

When I set my SystemResponsiveness back to 100, I immediately saw this issue. However, reproducing the issue is  still spotty.

My Theory

So I am going on the assumption that this bug, as it involves Flash, is related to the SystemResponsiveness registry key as described in Microsoft's documentation for Multimedia Class Scheduler Service, which is the multimedia subsystem of Windows 7 and Windows 2008 R2.

By setting the responsiveness to 100, multimedia like Flash 'movies' (which this uploader is) may encounter problems, and this becomes a timing/interruption issue for the uploader, which then causes other bugs to manifest themselves.

How to test?

Now I'm trying to come up with a way to test this theory. I think I need to have a background process peg the CPU usage at 100% (across 4 cores), and then attempt to use the uploader. The background/non-multimedia services should cause stuff like Flash to perform worse and I should run into problems.

edit

I decided to run a CPU stress test to peg my system's CPU utilization at 100% - other than make my machine slow to a crawl, the bug did not manifest itself. This Heisenbug is really eluding reproduction.

My Inquiry

However, I'm not sure if that is the correct approach to test my theory, so I'm wondering if anyone has any insight into tracking down MMCSS-related issues?

答:
This definitely sounds like a race condition, and those are really hard to force to happen consistently. It may be very difficult to find a scenario that consistently reproduces the issue, because there are some many variables involved.

Maxing out the CPU was a good first shot. The next thing I would try would be to put some load on the disk. Since this is a file uploader, it may be an I/O issue instead of a pure CPU issue.

If that doesn't work, then I'd become really good friends with someone that can make this happen often, if not consistently. Measure the probability that it'll happen on that person's system before making any changes. Then see if your changes have any affect on the probability.

Might be best to take the time to write a script to walk through this for you. You're likely going to be repeating those steps a lot.


问:
How to write unit tests without mocking data
My design doesn't allow me to mock the data so I am using sqlite as test database that has minimum data to run the unit tests. Below is the pseudo code

```<code>//Method to be tested
public IList<Funds> GetFunds()
{
  List<Funds> objFundsList = //gets two records from sqlite db;
  return objFundsList;
}

//Test Method
public void Check_If_Get_Funds_Returns_List_of_Funds()
{
      FundsService obj = new FundsService();
      var lstFunds =   obj.GetFunds();
      Assert.AreEqual(2,lstFunds.Count());
      //Do I need to get first item here to check if bindings for fund is successful
      var fund = obj.GetFunds().First();
      Assert.AreEqual("test",fund.Name);
}
</code>```

Since I am not using in-memory mock objects, I can't do sequenceequal. In this scenario, which other tests I can include.

答:
If the order of the result set is undefined by the implementation, then you'll need to write an assertion that's not dependent on the order of the results. CollectionAssert.AreEquivalent is one such method. Here's an example:</p>

```<code>// I'm assuming that you've written a helper method to get each fund's name
var actualNames = GetFundNamesFrom(obj);
var expectedNames = ["test1", "test2"];
CollectionAssert.AreEquivalent(expectedNames, actualNames);
</code>```

Body:
If the order of the result set is undefined by the implementation, then you'll need to write an assertion that's not dependent on the order of the results. CollectionAssert.AreEquivalent is one such method. Here's an example:

// I'm assuming that you've written a helper method to get each fund's name
var actualNames = GetFundNamesFrom(obj);
var expectedNames = ["test1", "test2"];
CollectionAssert.AreEquivalent(expectedNames, actualNames);


问:
What's the next logical TDD move in this learning example?
I'm inching my way up the TDD ladder and I've got to a point where I'd like to get advice on the "next move". I realize there might not be a single answer here, so any logical suggestion would be great.

The thing I think I'm stuck on is knowing weather I should force duplication or proceed with primary functionality implemented by minimal (and temporary due to not being general) code.

I'm trying to go in a strict green/red/re-factor cycle.  Also, this example is so simple it doesn't require any mocked objects, but I think it's still a valid example (please correct me if I'm wrong or I've gone into some kind of trivial case that's not worth working with).

UPDATE: I continued with this almost to the conclusion so I suppose I'll leave it up and see if anyone has any comments and if not I will delete..

Tests:

```<code>using NSpec;

namespace TicTacToe
{
    public class new_game : nspec
    {
        protected TicTacToeGame game;

        private void before_each()
        {
            game = new TicTacToeGame();
        }

        private void when_game_starts()
        {
            it["board should be clear"] = () => game.BoardState.should_be("---,---,---");
            it["it's x's turn"] = () => game.PlayerUp.should_be('x');
            it["no winner yet"] = () => game.Winner.should_be('-');
        }
    }

    public class specify_game : new_game
    {
        private void first_move()
        {
            context["is x in the center"] = () =>
                {
                    act = () => game.Move('x', 2, 2);

                    it["board should have x in the center"] = () => game.BoardState.should_be("---,-x-,---");
                    it["it's y's turn"] = () => game.PlayerUp.should_be('y');

                    context["then y in the center"] =
                        () =>
                            {
                                it["should throw OtherPlayerOccupiesSpaceException"] =
                                    expect<OtherPlayerOccupiesSpaceException>(() => game.Move('y', 2, 2));
                                it["no winner yet"] = () => game.Winner.should_be('-');
                            };

                    context["then y in the upper left"] = () =>
                        {
                            act = () => game.Move('y', 1, 1);
                            const string expectedBoardState = "y--,-x-,---";
                            it["correct board state is " + expectedBoardState] = () => game.BoardState.should_be(expectedBoardState);
                            it["it's x's turn"] = () => game.PlayerUp.should_be('x');
                            it["no winner yet"] = () => game.Winner.should_be('-');

                            context["then x in the middle top"] = () =>
                                {
                                    act = () => game.Move('x', 1, 2);
                                    const string expectedBoardState2 = "yx-,-x-,---";
                                    it["correct board state is " + expectedBoardState2] = () => game.BoardState.should_be(expectedBoardState2);
                                    it["no winner yet"] = () => game.Winner.should_be('-');

                                    context["then y in the right top"] = () =>
                                    {
                                        act = () => game.Move('y', 1, 3);
                                        const string expectedBoardState3 = "yxy,-x-,---";
                                        it["correct board state is " + expectedBoardState3] = () => game.BoardState.should_be(expectedBoardState3);
                                        it["no winner yet"] = () => game.Winner.should_be('-');

                                        context["then x in the middle bottom"] = () =>
                                            {
                                                act = () => game.Move('x', 3, 2);
                                                const string expectedBoardState4 = "yxy,-x-,-x-";
                                                it["correct board state is " + expectedBoardState4] = () => game.BoardState.should_be(expectedBoardState4);
                                                it["x wins"] = () => game.Winner.should_be('x');
                                            };
                                    };
                                };
                        };
                };
            context["is y int the center"] =
                () =>
                    {
                        it["should throw NotYourTurnException"] =
                            expect<NotYourTurnException>(() => game.Move('y', 2, 2));
                    };
        }
    }
}
</code>```

Implementation:

```<code>using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TicTacToe
{
    public class TicTacToeGame
    {
        private readonly char[,] grid = new char[3,3];

        private bool xsTurn = true;

        public TicTacToeGame()
        {
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    grid[i, j] = '-';
                }
            }
        }

        public string BoardState
        {
            get
            {
                var sb = new StringBuilder();
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        sb.Append(grid[i, j]);
                    }
                    if (i < 2)
                        sb.Append(',');
                }
                return sb.ToString();
            }
        }

        public char PlayerUp
        {
            get { return xsTurn ? 'x' : 'y'; }
        }

        public void Move(char player, int down, int over)
        {
            over -= 1;
            down -= 1;
            if (player != PlayerUp)
                throw new NotYourTurnException();
            if (grid[down, over] != '-')
                throw new OtherPlayerOccupiesSpaceException();
            this.grid[down, over] = player;
            xsTurn = !xsTurn;
        }

        public char Winner
        {
            get
            {
                string boardState = BoardState;

                var xWins = new[]
                    {
                        "xxx,...,...",
                        "...,xxx,...",
                        "...,...,xxx",
                        "x..,x..,x..",
                        ".x.,.x.,.x.",
                        "x..,x..,x..",
                        "..x,..x,..x",
                        "x..,.x.,..x",
                        "..x,.x.,x..",
                    };

                    var yWins = new[]
                    {
                        "yyy,...,...",
                        "...,yyy,...",
                        "...,...,yyy",
                        "y..,y..,y..",
                        ".y.,.y.,.y.",
                        "y..,y..,y..",
                        "..y,..y,..y",
                        "y..,.y.,..y",
                        "..y,.y.,y..",
                    };

                if (xWins.Any(win => Regex.IsMatch(boardState, win)))
                    return 'x';

                if (yWins.Any(win => Regex.IsMatch(boardState, win)))
                    return 'y';

                return '-';
            }
        }
    }
}
</code>```

Output:

```<code>PM> NSpecRunner.exe .\TicTacToe\bin\Debug\TicTacToe.dll

new game
  when game starts
    board should be clear
    it's x's turn
    no winner yet
  specify game
    first move
      is x in the center
        board should have x in the center
        it's y's turn
        then y in the center
          should throw OtherPlayerOccupiesSpaceException
          no winner yet
        then y in the upper left
          correct board state is y--,-x-,---
          it's x's turn
          no winner yet
          then x in the middle top
            correct board state is yx-,-x-,---
            no winner yet
            then y in the right top
              correct board state is yxy,-x-,---
              no winner yet
              then x in the middle bottom
                correct board state is yxy,-x-,-x-
                x wins
      is y int the center
        should throw NotYourTurnException

17 Examples, 0 Failed, 0 Pending
</code>```

答:
To respond to the comments that you received, I think this was a useful experiment.

To answer your question, the approach that I take is to do the easiest thing to make the test pass. This can have one of two outcomes.

The first outcome is that another test is needed. This happens when the code you've written can't possibly be good enough. The example I always use to demonstrate this is a method that adds two numbers.

Test:

```<code>expect(plus(2, 2)).to eq(4)
</code>```

Implementation:

```<code>def plus(x, y)
  return 4
end
</code>```

That's the simplest way to make the test pass, but it's obviously not good enough. So we need to add another test so that in order for both tests to pass, the implementation must be correct.

Test:

```<code>expect(plus(2, 2)).to eq(4)
expect(plus(2, 3)).to eq(5)
</code>```

Implementation:

```<code>def plus(x, y)
  return x + y
end
</code>```

The second outcome is that I end up copying and pasting, because that's the easiest way to get a green bar. But that leaves me with duplication that I don't want. So I refactor in small chunks to remove any duplication and the keep the green bar as I go. I can't really think of a good small example to demonstrate that, which is something that I should work on.

Body:
To respond to the comments that you received, I think this was a useful experiment.

To answer your question, the approach that I take is to do the easiest thing to make the test pass. This can have one of two outcomes.

The first outcome is that another test is needed. This happens when the code you've written can't possibly be good enough. The example I always use to demonstrate this is a method that adds two numbers.

Test:

expect(plus(2, 2)).to eq(4)

Implementation:

def plus(x, y)
  return 4
end

That's the simplest way to make the test pass, but it's obviously not good enough. So we need to add another test so that in order for both tests to pass, the implementation must be correct.

Test:

expect(plus(2, 2)).to eq(4)
expect(plus(2, 3)).to eq(5)

Implementation:

def plus(x, y)
  return x + y
end

The second outcome is that I end up copying and pasting, because that's the easiest way to get a green bar. But that leaves me with duplication that I don't want. So I refactor in small chunks to remove any duplication and the keep the green bar as I go. I can't really think of a good small example to demonstrate that, which is something that I should work on.


答:
Git, for all that, cares not one whit about what your directory structure looks like. It can be infinitely nested, one flat broad file space in a single directory, or whatever. It doesn't care if you have symlinks pointing at files between directories, it doesn't even particularly care if you have symlinks pointing outside the project tree.

It also doesn't care at all what language the files are written in, or whether they are programs, data, images, etc.

GIT DON'T CARE. Git is a honey badger in that regard.

The only caveat here, if a directory is empty, Git won't pick it up to add to the repo. This is why you see so many bare directories except for a .gitkeep file. The name of this file matters not to Git, it's just a convention adopted by us Gits. :)

So, organize your project however makes sense to you. The only major conventions that seem to go across the board are having a readme and license file in the project root. Your project's particular environment may require more, but then we're getting into more specifics.

Again, GIT DON'T CARE.

Now, to address your specific question: Just make a repo for each project; Git, nor Github, care:

```<code>YOUR MACHINE:
  /Code
    /Python
      /pycoolstuff
        /.git/
        /.gitignore
      /pymorecoolstuff
        /.git/
        /.gitignore
    /Java
      /enterpriseTiddlyWinks
        /.git/
        /.gitignore
    /Ruby
      /Rails
        /RecipeApp
          /.git/
          /.gitignore
      /Sinatra
        /comicservice
          /.git/
          /.gitignore
</code>```

Meanwhile, over on github, you just have these projects as individual repo depots:

```<code>github.com/imacoder/comicservice
github.com/imacoder/pycoolstuff
github.com/imacoder/pymorecoolstuff
github.com/imacoder/enterpriseTiddlyWinks
github.com/imacoder/RecipeApp
</code>```

The instructions for dealing with existing local repo after you make your Github repo are right there on the post-creation page you get from Github:

On local machine:

```<code>$ cd /Code/Python/new_project
$ git add --all -v # assuming you do know you want everything checked in
$ git commit -m 'some message'
$ git remote add origin git@github.com:imacoder/new_project
</code>```

(If you had Github create the README and/or .gitignore (I never do this))

```<code>$ git pull origin master
</code>```

(Fix any merge conflicts)

```<code>$ git push origin master
</code>```

Boom-de-yada! Everything is up on Github.

Title: Will git whine if I create my projects in multiple directories?

Body:
I'm new to git (and github). I work in Java and Python. Right now, I manage my projects in only one directory - let's call it Code and the folder is on my Desktop.

I want to group my projects by the language I code in. So, I want:

```<code>/Code/
++ /Java/
++ /Python/
</code>```

I do not know if Git would be happy with this or not. If it would be, what should I set my home directory to be?

And how should I manage it with my github account? For example, I create a new repo on GH for a new-project in Python (but I already have files on my local machine in /Code/Python/new-project), how should I about committing the files to GH making sure any other directories are not messed up with?

EDIT:

Just to be clear, I have unrelated projects in /Code/project_1, /Code/project_2, /Code/project_3 etc. But I want to arrange them as /Code/Java/project_1, /Code/Java/project_1, /Code/Python/project_1 etc.

Body:
Git, for all that, cares not one whit about what your directory structure looks like. It can be infinitely nested, one flat broad file space in a single directory, or whatever. It doesn't care if you have symlinks pointing at files between directories, it doesn't even particularly care if you have symlinks pointing outside the project tree.

It also doesn't care at all what language the files are written in, or whether they are programs, data, images, etc.

GIT DON'T CARE. Git is a honey badger in that regard.

The only caveat here, if a directory is empty, Git won't pick it up to add to the repo. This is why you see so many bare directories except for a .gitkeep file. The name of this file matters not to Git, it's just a convention adopted by us Gits. :)

So, organize your project however makes sense to you. The only major conventions that seem to go across the board are having a readme and license file in the project root. Your project's particular environment may require more, but then we're getting into more specifics.

Again, GIT DON'T CARE.

Now, to address your specific question: Just make a repo for each project; Git, nor Github, care:

YOUR MACHINE:
  /Code
    /Python
      /pycoolstuff
        /.git/
        /.gitignore
      /pymorecoolstuff
        /.git/
        /.gitignore
    /Java
      /enterpriseTiddlyWinks
        /.git/
        /.gitignore
    /Ruby
      /Rails
        /RecipeApp
          /.git/
          /.gitignore
      /Sinatra
        /comicservice
          /.git/
          /.gitignore

Meanwhile, over on github, you just have these projects as individual repo depots:

github.com/imacoder/comicservice
github.com/imacoder/pycoolstuff
github.com/imacoder/pymorecoolstuff
github.com/imacoder/enterpriseTiddlyWinks
github.com/imacoder/RecipeApp

The instructions for dealing with existing local repo after you make your Github repo are right there on the post-creation page you get from Github:

On local machine:

$ cd /Code/Python/new_project
$ git add --all -v # assuming you do know you want everything checked in
$ git commit -m 'some message'
$ git remote add origin git@github.com:imacoder/new_project

(If you had Github create the README and/or .gitignore (I never do this))

$ git pull origin master

(Fix any merge conflicts)

$ git push origin master

Boom-de-yada! Everything is up on Github.


答: I think the goal should be to have descriptive boolean variable names, as you have shown in your example.</p>

Title: When should I use or not BooleanUtils.isTrue(...) and BooleanUtils.isFalse(...)?

Body:
About this function: org.apache.commons.lang3.BooleanUtils.isFalse(Boolean bool) and the similar isTrue, my co-work (less experienced) use it for every boolean in the code. I am trying to convince him that it is not a good practice because make the code confusing. In my POV, it should be used ONLY if the boolean to be tested is a type of non-primitive Boolean and it can be null. Actually, even this I think it is unnecessary, because the implementation of this function is simply Boolean.TRUE.equals(bool) or Boolean.FALSE.equals(bool). Anyway, I think it is totally crazy do something like:

```<code>boolean isReady = true;

if (BooleanUtils.isTrue(isReady)) {
   // ...
}
</code>```

when you cold simply do

```<code>if (isReady) {
   // ...
}
</code>```

or (!isReady) for the opposite.

His only argument to use this is "it is easy to read". I just can't accept this argument. Am I wrong? What arguments can I use to convince him that no useless code is better than useless code in this case?

Thank you guys.


答: It's absurd to use BooleanUtils.isTrue(isReady) when isReady is a boolean, not a Boolean.  Your colleague seems like one of those guys who thinks that the more code he writes, the more productive he is.  Maybe he should go find a job programming in Ada.


问:
Should I fully parenthesize expressions or rely on precedence rules?
Let's say I have a boolean condition a AND b OR c AND d and I'm using a language where AND has a higher order of operation precedence than OR. I could write this line of code:

```<code>If (a AND b) OR (c AND d) Then ...
</code>```

But really, that's equivalent to:

```<code>If a AND b OR c AND d Then ...
</code>```

Are there compelling arguments in favor or against including the extraneous parentheses?

Does practical experience suggest that including them significantly improves readability?

Or is wanting them a sign that a developer really needs to sit down and become conversant in the  basics of their language?

答: As everyone said, use parentheses everytime it makes the expression more readable. However if the expression is complicated I'd advise to introduce new functions for the subexpressions.


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答:
Isn't the answer to this question a resounding "NO" independent of whomever you ask?

Ask your graphic artists if they should be given a slower machine.

Ask your writers if they would choose a slower machine over a faster one.

Ask your administrative assistants whether they would prefer a slower or faster machine.

All of them will say they'll be more productive with a faster machine.


问:
Variable type object
Is there a language with something like the following construct?

```<code>var_type(TYPE_1, TYPE_2,..., TYPE_N) obj;
</code>```

and now its possible to:

```<code>TYPE_17 staticTypeVariable17;
obj = staticTypeVariable17;

TYPE_3 staticTypeVariable3;
obj = staticTypeVariable3;
</code>```

without obj being a pointer of some base class and with no need for casting if the types used are from the predefined set.
So basically an object that can switch it's type amongst a predefined set of types.

答:
The construct you are referring to is called a discriminated union and is part of quite a few languages and can be created in more.

Among the languages that support discriminated unions are C++, Visual Basic, ML and Haskell and those are just the languages that popped up in the wikipedia article.

Title: Variable type object


问:
Is the usage of internal scope blocks within a function bad style?
There are some (quite rare) cases where there is a risk of:

reusing a variable which is not intended to be reused (see example 1),

or using a variable instead of another, semantically close (see example 2).

Example 1:

```<code>var data = this.InitializeData();
if (this.IsConsistent(data, this.state))
{
    this.ETL.Process(data); // Alters original data in a way it couldn't be used any longer.
}

// ...

foreach (var flow in data.Flows)
{
    // This shouldn't happen: given that ETL possibly altered the contents of `data`, it is
    // not longer reliable to use `data.Flows`.
}
</code>```

Example 2:

```<code>var userSettingsFile = SettingsFiles.LoadForUser();
var appSettingsFile = SettingsFiles.LoadForApp();

if (someCondition)
{
    userSettingsFile.Destroy();
}

userSettingsFile.ParseAndApply(); // There is a mistake here: `userSettingsFile` was maybe
                                  // destroyed. It's `appSettingsFile` which should have
                                  // been used instead.
</code>```

This risk can be mitigated by introducing a scope:

Example 1:

```<code>// There is no `foreach`, `if` or anything like this before `{`.

{
    var data = this.InitializeData();
    if (this.IsConsistent(data, this.state))
    {
        this.ETL.Process(data);
    }
}

// ...

// A few lines later, we can't use `data.Flows`, because it doesn't exist in this scope.
</code>```

Example 2:

```<code>{
    var userSettingsFile = SettingsFiles.LoadForUser();

    if (someCondition)
    {
        userSettingsFile.Destroy();
    }
}

{
    var appSettingsFile = SettingsFiles.LoadForApp();

    // `userSettingsFile` is out of scope. There is no risk to use it instead of
    // `appSettingsFile`.
}
</code>```

Does it look wrong? Would you avoid such syntax? Is it difficult to understand by beginners?

答:
I agree that reusing variable is more often than not a code smell. Probably such code should be refactored in smaller, self-contained, blocks.

There is one particular scenario, OTOH, in C#, when they tend to popup - that is when using switch-case constructs. Situation is very nicely explained in: C# Switch statement with/without curly brackets… what's the difference?


问:
Are Ruby on Rails / Grails the fastest frameworks for getting sites up quickly?
I'm considering using Grails for a new website, but am open to other/new programming languages and frameworks.  I have done development using J2EE/JSF2, ASP.NET, and PHP.  Is Grails or Ruby on Rails pretty much the best way to get functionality up and running quickly?

Some initial thoughts:

DJango looks similar to RoR/Grails and I'd consider it

GWT is an interesting concept but it doesn't seem like turnaround time is quite as fast

Thanks,
-Jon

答:
I haven't used everything, but Rails is pretty darn fast. I expect Grails is too as it embodies the DRY philosophy pretty well. I don't know enough about other dynamic language frameworks to say.

Even with good code generation strategies my ASP.NET (webforms) don't seem as efficient.


问:
If the model is validating the data, shouldn't it throw exceptions on bad input?
Reading this SO question it seems that throwing exceptions for validating user input is frowned upon.

But who should validate this data? In my applications, all validations are done in the business layer, because only the class itself really knows which values are valid for each one of its properties. If I were to copy the rules for validating a property to the controller, it is possible that the validation rules change and now there are two places where the modification should be made.

Is my premise that validation should be done on the business layer wrong?

What I do

So my code usually ends up like this:

```<code><?php
class Person
{
  private $name;
  private $age;

  public function setName($n) {
    $n = trim($n);
    if (mb_strlen($n) == 0) {
      throw new ValidationException("Name cannot be empty");
    }
    $this->name = $n;
  }

  public function setAge($a) {
    if (!is_int($a)) {
      if (!ctype_digit(trim($a))) {
        throw new ValidationException("Age $a is not valid");
      }
      $a = (int)$a;
    }
    if ($a < 0 || $a > 150) {
      throw new ValidationException("Age $a is out of bounds");
    }
    $this->age = $a;
  }

  // other getters, setters and methods
}
</code>```

In the controller, I just pass the input data to the model, and catch thrown exceptions to show the error(s) to the user:

```<code><?php
$person = new Person();
$errors = array();

// global try for all exceptions other than ValidationException
try {

  // validation and process (if everything ok)
  try {
    $person->setAge($_POST['age']);
  } catch (ValidationException $e) {
    $errors['age'] = $e->getMessage();
  }

  try {
    $person->setName($_POST['name']);
  } catch (ValidationException $e) {
    $errors['name'] = $e->getMessage();
  }

  ...
} catch (Exception $e) {
  // log the error, send 500 internal server error to the client
  // and finish the request
}

if (count($errors) == 0) {
  // process
} else {
  showErrorsToUser($errors);
}
</code>```

Is this a bad methodology?

Alternate method

Should maybe I create methods for isValidAge($a) that return true/false and then call them from the controller?

```<code><?php
class Person
{
  private $name;
  private $age;

  public function setName($n) {
    $n = trim($n);
    if ($this->isValidName($n)) {
      $this->name = $n;
    } else {
      throw new Exception("Invalid name");
    }
  }

  public function setAge($a) {
    if ($this->isValidAge($a)) {
      $this->age = $a;
    } else {
      throw new Exception("Invalid age");
    }
  }

  public function isValidName($n) {
    $n = trim($n);
    if (mb_strlen($n) == 0) {
      return false;
    }
    return true;
  }

  public function isValidAge($a) {
    if (!is_int($a)) {
      if (!ctype_digit(trim($a))) {
        return false;
      }
      $a = (int)$a;
    }
    if ($a < 0 || $a > 150) {
      return false;
    }
    return true;
  }

  // other getters, setters and methods
}
</code>```

And the controller will be basically the same, just instead of try/catch there are now if/else:

```<code><?php
$person = new Person();
$errors = array();
if ($person->isValidAge($age)) {
  $person->setAge($age);
} catch (Exception $e) {
  $errors['age'] = "Invalid age";
}

if ($person->isValidName($name)) {
  $person->setName($name);
} catch (Exception $e) {
  $errors['name'] = "Invalid name";
}

...

if (count($errors) == 0) {
  // process
} else {
  showErrorsToUser($errors);
}
</code>```

So, what should I do?

I'm pretty happy with my original method, and my colleagues to whom I have showed it in general have liked it. Despite this, should I change to the alternate method? Or am I doing this terribly wrong and I should look for another way?

答:
I'm pretty happy with my original method, and my colleagues to whom I have showed it in general have liked it. Despite this, should I change to the alternate method? Or am I doing this terribly wrong and I should look for another way?

If you and your colleagues are happy with it, I see no pressing need to change.

The only thing that is questionable from a pragmatic perspective is that you are throwing Exception rather than something more specific.  The problem is that if you catch Exception, you may end up catching exceptions that have nothing to do with validation of user input.

Now there are many people who say things like "exceptions should only be used for exceptional things, and X Y Z is not exceptional".   (For example, @dann1111's Answer ... where he labels user errors as "perfectly normal".)

My response to that is that there is no objective criterion for deciding whether something ("X Y Z") is exceptional or not.  It is a subjective measure.  (The fact that any program needs to check for errors in user input does not make the occurrence errors "normal".  In fact, "normal" is largely meaningless from an objective standpoint.)

There is a grain of truth in that mantra.  In some languages (or more accurately, some language implementations) exception creation, throwing and/or catching is significantly more expensive than simple conditionals.  But if you look at it from that perspective, you need to compare the cost of create/throw/catch against the cost of the extra tests that you might need to perform if you avoided using exceptions.  And the "equation" has to take into account the probability that the exception needs to be thrown.

The other argument against exceptions is that they can make code harder to understand.  But the flip-side is that when they are used appropriately, they can make code easier to understand.

In short - the decision to use or not use exceptions should be made after weighing up the merits ... and NOT on the basis of some simplistic dogma.


答:
In my opinion, it is useful to distinguish between application errors and user errors, and only use exceptions for the former.

Exceptions are intended to cover things that prevent your program from executing properly.

They are unexpected occurrences that prevent you from continuing, and their design reflects this: they break normal execution and jump to a place that allows error handling.

User errors like invalid input are perfectly normal (from your program's perspective) and should not be treated as unexpected by your application.

If the user enters the wrong value and you display an error message, did your program "fail" or have an error in any way?  No.  Your application was successful--given a certain kind of input, it produced the correct output in that situation.

Handling user errors, because it is part of normal execution, should be part of your normal program flow, rather than handled by jumping out with an exception.

Of course it is possible to use exceptions for other than their intended purpose, but doing so confuses the paradigm and risks incorrect behavior when those errors occur.

Your original code is problematic:

The caller of the setAge() method must know way too much about the method's internal error handling: the caller needs to know that an exception is thrown when the age is invalid, and that no other exceptions could be thrown within the method. This assumption could be broken later if you added additional functionality within setAge().

If the caller does not catch exceptions, the invalid age exception would later be handled in some other, most likely opaque, way.  Or even cause an unhandled exception crash.  Not good behavior for invalid data being entered.

The alternative code also has problems:

An extra, possibly unnecessary method isValidAge() has been introduced.

Now the setAge() method has to assume that the caller already checked isValidAge() (a terrible assumption) or validate the age again. If it validates the age again, setAge() still has to provide some sort of error handling, and you are back to square one again.

Suggested design

Make setAge() return true on success and false on failure.

Check the return value of setAge() and if it failed, inform the user that the age was invalid, not with an exception, but with a normal function that displays an error to the user.

Title: If the model is validating the data, shouldn't it throw exceptions on bad input?

Body:
Reading this SO question it seems that throwing exceptions for validating user input is frowned upon.

But who should validate this data? In my applications, all validations are done in the business layer, because only the class itself really knows which values are valid for each one of its properties. If I were to copy the rules for validating a property to the controller, it is possible that the validation rules change and now there are two places where the modification should be made.

Is my premise that validation should be done on the business layer wrong?

What I do

So my code usually ends up like this:

```<code><?php
class Person
{
  private $name;
  private $age;

  public function setName($n) {
    $n = trim($n);
    if (mb_strlen($n) == 0) {
      throw new ValidationException("Name cannot be empty");
    }
    $this->name = $n;
  }

  public function setAge($a) {
    if (!is_int($a)) {
      if (!ctype_digit(trim($a))) {
        throw new ValidationException("Age $a is not valid");
      }
      $a = (int)$a;
    }
    if ($a < 0 || $a > 150) {
      throw new ValidationException("Age $a is out of bounds");
    }
    $this->age = $a;
  }

  // other getters, setters and methods
}
</code>```

In the controller, I just pass the input data to the model, and catch thrown exceptions to show the error(s) to the user:

```<code><?php
$person = new Person();
$errors = array();

// global try for all exceptions other than ValidationException
try {

  // validation and process (if everything ok)
  try {
    $person->setAge($_POST['age']);
  } catch (ValidationException $e) {
    $errors['age'] = $e->getMessage();
  }

  try {
    $person->setName($_POST['name']);
  } catch (ValidationException $e) {
    $errors['name'] = $e->getMessage();
  }

  ...
} catch (Exception $e) {
  // log the error, send 500 internal server error to the client
  // and finish the request
}

if (count($errors) == 0) {
  // process
} else {
  showErrorsToUser($errors);
}
</code>```

Is this a bad methodology?

Alternate method

Should maybe I create methods for isValidAge($a) that return true/false and then call them from the controller?

```<code><?php
class Person
{
  private $name;
  private $age;

  public function setName($n) {
    $n = trim($n);
    if ($this->isValidName($n)) {
      $this->name = $n;
    } else {
      throw new Exception("Invalid name");
    }
  }

  public function setAge($a) {
    if ($this->isValidAge($a)) {
      $this->age = $a;
    } else {
      throw new Exception("Invalid age");
    }
  }

  public function isValidName($n) {
    $n = trim($n);
    if (mb_strlen($n) == 0) {
      return false;
    }
    return true;
  }

  public function isValidAge($a) {
    if (!is_int($a)) {
      if (!ctype_digit(trim($a))) {
        return false;
      }
      $a = (int)$a;
    }
    if ($a < 0 || $a > 150) {
      return false;
    }
    return true;
  }

  // other getters, setters and methods
}
</code>```

And the controller will be basically the same, just instead of try/catch there are now if/else:

```<code><?php
$person = new Person();
$errors = array();
if ($person->isValidAge($age)) {
  $person->setAge($age);
} catch (Exception $e) {
  $errors['age'] = "Invalid age";
}

if ($person->isValidName($name)) {
  $person->setName($name);
} catch (Exception $e) {
  $errors['name'] = "Invalid name";
}

...

if (count($errors) == 0) {
  // process
} else {
  showErrorsToUser($errors);
}
</code>```

So, what should I do?

I'm pretty happy with my original method, and my colleagues to whom I have showed it in general have liked it. Despite this, should I change to the alternate method? Or am I doing this terribly wrong and I should look for another way?


答:
The approach I've used in the past is to put all validation logic dedicated Validation classes.

You can then inject these Validation classes into your Presentation Layer for early input validation.  And, nothing prevents your Model classes from using the very same classes to enforce Data Integrity.

Following this approach you can then treat Validation Errors differently depending on which layer they happen in:

If Data Integrity Validation fails in the Model, then throw an Exception.

If User Input Validation fails in the Presentation Layer, then display a helpful tip and delay pushing the value to your Model.


问:
How do I improve my memory and recall?
How do I go about improving my memory and recall as it relates to Programming?

I have a tendency to cache API information short term and then immediately put it out of my head as I move on to something else.

This sometimes makes me look bad as I can't recall API information on code I should be really familiar with. It also can be a big time sink, as I often know that I can do something with an API, but I have to look up the specifics on how to actually do it.

Are there any tools or methods I could use to make up for my memory short comings?

答:
Never memorize something that you can look up
  -- Albert Einstein.

every time he was asked something, he'd say he didn't know and needed to look it up! He must have been a right thicko....

Title: How do I improve my memory and recall?


问:
Why is it rare to collect analytics/usage data in open source software?
So, I've been developing some analytic software at my work and also have started to take more notice to analytics in general. For instance, I recently installed Google Analytics on my blog(which is custom and open source).

I mostly make open source software outside of work, so I think it might be cool to be capable of gathering some form of usage data and such on how my tools are used, opt-in only of course. However, this seems to almost never be done. Why? What's with the taboo of analytics in open source software?

答:
Some people do - see the recent spat between LibreOffice and OpenOffice over who had more users (based on downloads).

But the problem is such stats are only vague indicators - I have downloaded lots of software that I never use, or only use once. Then there;'s the privacy aspect, many people will turn off usage reports (even products like Office ask you).

Ohloh has some stats on FOSS products, some of them might be of interest to you.


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答: Whichever one you need to solve your current problem.</p>


答:
From my point of view (I'm a Java guy) it is totally valid how you implemented it the first way.

It is valid that an object throws an Exception when some preconditions are not met (e.g. empty-string).
In Java the concept of checked exceptions is inteded to such a purpose - exceptions that must be declared in the signature to be propably thrown, and the caller explicitly needs to catch those. In contrast, unchecked exceptions (aka RuntimeExceptions), may happen any time without the need to define a catch-clause in code. While the first are used for recoverable cases (e.g. wrong user input, filename does not exist), the latter are used for cases the user/programmer can't do anything about (e.g. Out-Of-Memory).

You should though, as already mentioned by @Stephen C, define your own exceptions and catch specifically those to not catch others unintentionally.

Another way, however, would be to use Data Transfer Objects which are simply data-containers without any logic. You then handover such a DTO to a validator or the Model-Object itself for validation, and only if successfull, make the updates in the Model-Object.
This approach is often used when presentation logic and application logic are seperated tiers (presentation is a webpage, appplication a webservice). This way they are physically separated, but if you have both on one tier (as in your example), you must ensure that there will be no workaround to set a value without validation.


问:
I'm a manager. How can I improve work relationships and communication with programmers?
A little background first. I'm a project manager at medium-sized company. I started as a CS major and had a little exposure to programming, but after a few months I knew it's not my path, so I switched over to management. That proved to be a good decision, and after graduating I've worked in software management at various companies (for 5 years now).

Recently, we had a very painful project. It was the worst of the worst, with many mistakes both on our side and on the customers side and just barely ending it without losses. It has led to many frustrating situations, one of which escalated to the point where one of our senior developers left company after a vocal argument with us (the management). This was a red flag for me: I did something terribly wrong. (for the record, the argument was about several mistaken time estimates)

I searched many places for answers and a friend pointed me to this site. There are many questions here about frustrations with management. I can understand that the general bad experiences lead to a general reluctance against "those guys in the suits".

I'm that guy in the suit. It may not look like it, but all I want is a successful project, and with limited resources it takes painful decisions. That's my job. One of the things the aforementioned senior developer complained about was work equipment. Frankly, I had no idea that the computers we had were not suited for working. After this, I asked many programmers and the general consensus was that we need better machines. I fixed that since then, but there was obviously a huge communication gap between me and the programmers. Some of the most brilliant developers are the most shy and silent people. I know that, and it was never a problem during an interview. People are different, and have strengths at different areas.

The case of the underpowered PCs is just one of the many that led me to thinking that there is a communication issue. How can I improve communication with programmers without being intimidating and repetitive?

What I'm hoping is that people don't complain about good things. If you love your workplace and love (or at least like :)) your manager, please tell me about them. What are they doing right? Similarly, if you hate it, please describe in detail why. I'm looking for answers about improving communication because I think that is my problem, but I might be wrong.

答:
I have done various roles over many many years - developer, senior developer, technical lead etc.

From your question - it's quite obvious that your developers don't tell you stuff because they don't think you can help.

This may be because of 2 reasons.

They don't think you have the power to fix things. However, I think this is unlikely because then you probably would know it & also the developers would have whined about it to you.

You are the kind of person who when a developer comes to you with a problem, does one or more of the following things

When they come to you with problems, you tell them - I like solutions not problems.

You listen to them nicely & then task them with fixing the problem. You give them pep talk about what an honour it is for them be given the responsibility to fix the problem. Over time your guys understand that when they go to you with a problem, they will end up with extra work, so they don't come to you with problems.

You deny it's a problem. You give convincing reasons for this. But as this keeps happening, over time your guys learn that there is no point approaching you with a problem.

You say "Yes, I understand". You say this kind of stuff happens occasionally & there is nothing one can do. If this is a pattern, then again your guys understand it.

If it's any or all of the above, then you need to rectify it.


问:
How is multi-threading different in a Java based Web Application vs Stand-alone Java Application
I am fairly new to Java and my experience is limited to Web Based Applications running on a Web Container (Jboss in my case).

Am I correct in saying that for Web Applications the web container takes care of multi-threading? If so, can I introduce new treads in a Web Based applications? Is there any advantage in doing so and in what scenario one would need to do that?

答:
Am I correct in saying that for Web Applications the web container takes care of multi-threading?

Most webservers (Java and otherwise, including JBoss) follow a "one thread per request" model, i.e. each HTTP request is fully processed by exactly one thread. This thread will often spend most of the time waiting for things like DB requests. The web container will create new threads as necessary.

Some servers (in the Java ecosystem primarily Netty) do asynchronous request handling, either with a "one thread does everything" model, or something more complex. The basic idea there is that having lots of waiting threads wastes resources, so working asynchronously can be more efficient.

If so, can I introduce new treads in a Web Based applications?

It's possible, but should be done very carefully, since errors (like memory leaks or missing synchronization) can cause bugs that are very hard to reproduce, or bring down the whole server.

Is there any advantage in doing so and in what scenario one would need to do that?

Well, the advantage is that you can do stuff in parallel. Using threads to improve pure computational speed is something you should not do on a webserver, as it would slow down the handling of other requests. That kind of thing should be done on a separate server, probably using some sort of job queue.

A legitimate scenario for multithreading in the context of handling an HTTP request might be if you need to access other network resources, e.g. call several different web services. If you do it in a single thrad, you have to wait for each call to finish in turn. But if you use multiple threads, the total waiting time is only the delay of the single slowest call.


问:
Why the current enthusiasm for Functional Programming?
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?

答: Definitely because of F#, though sometimes it is hard to tell which one is the cause and which one is the effect.</p>


问:
function exit condition on parameter consistency check
When checking for parameter consistency a the top of a function body, what is the best strategy?

This one:

```<code>protected void function(Object parameter)
    if (parameter == null)
        return;

    //... do things
}
</code>```

...or this one:

```<code>protected void function(Object parameter)
    if (parameter != null) {
        //... do things
    }
}
</code>```

答:
I think there is not change in terms of performance because in both cases the main code of the function is not evaluated if the parameter is deemed inconsistent.

From this point of view, as superM says in his comment, there rest is pretty much up to you and should be as consistent as possible across your project.


答:
It is a matter of preference which style you choose, but I would go for your first option, for the following reasons. In my opinion....

It is cleaner and easier to read if you return early from the function when the function cannot be executed because of some condition.

Checking for equality is generally less prone to simple error than checking for inequality. For example, it is certainly easier to miss if you had written the inequality as if (!parameter)

The second example means you need to indent your code an additional level.

Title: function exit condition on parameter consistency check

Body:
When checking for parameter consistency a the top of a function body, what is the best strategy?

This one:

```<code>protected void function(Object parameter)
    if (parameter == null)
        return;

    //... do things
}
</code>```

...or this one:

```<code>protected void function(Object parameter)
    if (parameter != null) {
        //... do things
    }
}
</code>```


答:
I would recommend doing the first one because it is clearer but there is a school of thought that you should only have one exit point from a function.  This is perhaps a good opportunity to use Exceptions if your language supports them usually via the throw command.  Such as...

```<code>protected void function(Object parameter)
    if (parameter == null)
        throw new ArgumentNullException("parameter must not be null.");

    //... do things
}
</code>```

This will tell the code calling the function that the problem occurred rather than allowing the application to continue under the assumption the function has completed correctly.

Body:
I would recommend doing the first one because it is clearer but there is a school of thought that you should only have one exit point from a function.  This is perhaps a good opportunity to use Exceptions if your language supports them usually via the throw command.  Such as...

protected void function(Object parameter)
    if (parameter == null)
        throw new ArgumentNullException("parameter must not be null.");

    //... do things
}

This will tell the code calling the function that the problem occurred rather than allowing the application to continue under the assumption the function has completed correctly.


问:
Creating a site just for URL redirecting (.NET MVC) due to changing domains and URLs
I'd just like to hear about any experience creating a (simple) site for redirecting requests.

Basically we have multiple domains, but as we add more domains and change URLs, there is a huge problem of maintaining old links.

When discussing this we are considering using one constant site to determine where the present url is located.

The idea would be pretty simple, just e.g. links.url.com and then a parameter to find a database row which would contain e.g. domain, parameters, and any other necessary fields to redirect successfully.

for example: links.url.com/id=12345 would read the new domain e.g. url2.com and the parameters id=324324324&id2=34234 so the controller would just redirect to url2.com/id=324324324&id2=34234.

Is this a good way to handle changing URLs as the domains and URLs change? Are there downfalls to this approach, or better ways to go about URL change?

答: The best way is to issue HttpResponse.RedirectPermanent with the new location and you can do so from your 404 page code-behind to see if the location they're trying to reach is the old one so you don't need a new site.</p>