答: Interesting.  I hardly ever use isset().  My PHP code is rarely in a state where I dont know if a variable has been set in the first place.  Every GET or POST variable used is accessed via a function that will provide it a default if it doesnt exist.  Default values in function calls are typically explicitly set to 0 or empty strings.</p>

Title: Why do many PHP Devs hate using isset() and/or any of PHP's similarly defensive functions like empty()?

Body:
Over on stackoverflow, I see this issue crop up all the time:

E_NOTICE ?== E_DEBUG, avoiding isset() and @ with more sophisticated error_handler

How to set PHP not to check undefind index for $_GET when E_NOTICE is on?

How to stop PHP from logging PHP Notice errors

How do I turn off such PHP 5.3 Notices ?

Even Pekka (who offers a lot of solid PHP advice) has bumped against the dreaded E_NOTICE monster and hoped for a better solution than using isset(): isset() and empty() make code ugly

Personally, I use isset() and empty() in many places to manage the flow of my applications.  For example:

```<code>public function do_something($optional_parameter = NULL) {
    if (!empty($optional_parameter)) {
        // do optional stuff with the contents of $optional_parameter
    }
    // do mandatory stuff
}
</code>```

Even a simple snippet like this:

```<code>if (!isset($_REQUEST['form_var'])) {
    // something's missing, do something about it.
}
</code>```

seems very logical to me.  It doesn't look like bloat, it looks like stable code.  But a lot of developers fire up their applications with E_NOTICE's enabled, discover a lot of frustrating "uninitialized array index" notices, and then grimace at the prospect of checking for defined variables and "littering" their code with isset().

I assume other languages handle things differently.  Speaking from experience, JavaScript isn't as polite as PHP.  An undefined variable will typically halt the execution of the script.  Also, (speaking from inexperience) I'm sure languages like C/C++ would simply refuse to compile.

So, are PHP devs just lazy?  (not talking about you, Pekka, I know you were refactoring an old application.)  Or do other languages handle undefined variables more gracefully than requiring the programmer to first check if they are defined?

(I know there are other E_NOTICE messages besides undefined variables, but those seem to be the ones that cause the most chagrin)

Addendum

From the answers so far, I'm not the only one who thinks isset() is not code bloat.  So, I'm wondering now, are there issues with programmers in other languages that echo this one?  Or is this solely a PHP culture issue?


问:
Do all programs run in a loop?
I was wondering whether all programs run in a Loop, checking for variable changes then acting upon said changes followed by another Loop. Or do they run in a While statement, waiting for a variable to change before they execute a routine? Or am I just completely wrong?</p>

答:
“While” is a form of loop.  For the scope of your question it would make no difference.

CLI programs usually don't run in a loop.  GUI programs usually do.  Some have parallel execution flows.  I suggest you read the Wikipedia article on event loop so that you grasp the different styles.

ContentLicense: CC BY-SA 3.0

Title: Do all programs run in a loop?


问:
How to reconstruct this application using design pattern
I am engaging in redesigning a linux c++ server application. The application acts as file relayer in the form of receiving file packets (incuding control packets and data packets) from client A, writing these packets into a local data file then create and update index file, finally start many threads to read the file data and forward these data packets to its receivers such as client B, client C, client D, etc. Flow chart is like: Client A -> Server -> Client B, Client C, Client D, ...

Currently the application is using Producer-Consumer pattern to pass data packets among modules, here are some modules we have: SocketModule(contains a thread for listening and reading incoming data of all sockets), SessionModule(for managing user tcp sessions), FileRelayModule(contains many threads for doing jobs like processing incoming packets and writing into local data file, reading local data files and updating index files and forwarding these data packets to receivers via TCP sockets).

The problem is that its performance is so bad, take an example,  it takes about 15 minutes for Client A to send a file of size 200M to Client B, but I did a p2p file sending and receiving between different machines it takes only 20 seconds.

We think the main cause of bad performance is that we store sockets information in a global std::map, then every thread who wants to send out data (to clients) needs to wait for the lock for std::map, thus the application acts like single-threaded application.

As the original design of this application doesn't follow principles of design pattern and this results in many issues, so we want redesign it using MVC pattern, adding roles of thread manager and file manager. The first item I think of is to use a ThreadPool, then dispatch every accepted socket into the thread who has the least clients(sockets number). Is this possible or reasonable for this application? What would you do if you were the designer of this project?

[update]

1. I will check the project and figure out which part is the real bottleneck of
   performance

2. No matter which part is the real bottleneck, we need to reconstruct the
   application for it to manage the resources such as threads and memory and
   be easy to maintain.

I am gonna do things like following:

1. Create many classes: CSessionManager for managing tcp session data (contains
   a thread), CFileManager for doing file relaying and managing all data files and index files (contains a ThreadPool with 32 threads of which contains a sockets map, and a listening socket), CFileServer(contains the CSessionManager and CFileManager). Here CFileServer acts as Controller, the CFileManager acts as Model.

2. The CFileManager will create a thread pool with 32 threads initialized at the startup. The CFileServer creates a listening socket and puts every accepted socket to CFileManager where the the new accepted socket is set to a thread in the threadpool by querying who has the least sockets.

[update2]

The threadpool will be designed as following(is it reasonable?):

```<code>               std::list<CThread*> workers;
               //each thread would be
               class CThread{
                   public:
                     PostMsg(CMessage*);
                     static void Run();

               private:
                     map<int, socketinfo*> sockets;
                     std::deque<CMessage*> messageQueue;
               };

               ...
               Other objects will call PostMsg to inform message
               to this CThread and in the run function:
               void CThread::Run(){
                     ....
                     while(1){
                         ....
                         //firstly process all messages
                         //these messages includes adding socket,
                         //deleting socket, or go offline
                         CMessage* msg = messageQueue.pop_front;
                         if (msg != NULL) {
                            process(msg);
                         }

                         //after processing the messages,
                         //now read/write the sockets data
                         //set readfd and writefd
                         ret = select(max, readfd, writefd, NULL, timeout);

                         //now process readfd and writefd
                         //read data from readfd, then write to local
                         //file read data from local file then write
                         //to wirtefd or post a message to controller
                        // to remove fd from array.
                         ......
                     }
               }
</code>```

答:
If I were the designer of this project, I would focus on the performance first, and then any design patterns.

Performance improvement starts with knowing where the bottlenecks are, not where you think they are. You could spend many hours (or days, weeks) optimizing a part of the program that does not influence the overall performance at all. There are tools for profiling concurrent programs, but I usually just let the threads write some log info about where they spend their time.

First of all, the benchmark time. The P2P situation with which you compare is not exactly equal to your own application. In the P2P case, the sending client already had the file, whereas in your application's case, that file needs to be uploaded first. From what I gather, this upload stage is a single-threaded process too, and it is worthwhile to check how long it takes. A comparable situation would be using FTP to upload the file, and then P2P to distribute it. Also, timings over a local network would be vastly different from timings over the internet.

With that out of the way, though, I'd say that a factor 15 improvement is a nice goal.

At first glance, I see the following potential bottlenecks:

The file is read in its entirety, and then further processed, before distribution starts. Perhaps this process can also be made concurrent, and perhaps sending file blocks to clients can start as soon as you have them, adding the extra information later. If need be, the client can do its own reconstruction of the complete file (just as with P2P).

Disk I/O. It looks like the file is written to disk, and each thread is performing disk I/O to read it. This may be sped up with caching or memory mapping. You may also want to check that your disk hardware can handle the I/O.

The std::map is a horrible data structure quite on its own, let alone when it is locked.
It is a balanced red-black tree, so each insert or remove may trigger a rebalance, and each search is O(lg n). On top of that, memory allocation may seriously impact performance. What you would like is to see each socket as a Task, and have unfinished tasks in a simple TaskQueue. A (double-)linked list (possibly with a memory pool) or a std::vector acting as stack is enough. That will reduce the wait time to O(1) with a very low constant.

Socket I/O. Your threads may be waiting a long time before the I/O call with the clients is finished. By setting it up as asynchronous calls, they can handle writing to a socket, put the socket on the TaskQueue, and let another thread handle the callback.

A ThreadPool is a good idea, but I wouldn't burden each thread with multiple clients. Let them read a simple task from the TaskQueue, perform it quickly, and then insert the updated task back into the TaskQueue. Each thread just does a different thing based on some "command" in the task.

Last but not least, is the file binary or compressed? Reducing the size of data to transfer is also a valid optimization.

I think that what you are looking for in MVC is the responsiveness and concurrency, the "feel" that it acts fast, as found in a lot of MVC applications. That is however due, in part, to the messaging system that MVC uses, and its implementation. (The other parts are that different Views and Controllers can behave concurrently, and that the Model is non-blocking.) MVC in itself guarantees no performance gain.

So I would focus on the underlying patterns, that may even be used by MVC itself: ThreadPools, TaskQueue, and simultaneously asynchronous I/O and caching.

With that in place, I don't see a real use for MVC. MVC is an abstraction for different Views and different Controllers, that show and act upon the Model in different ways. What you have, however, is a lot of the same. So instead of, say, the Model telling each thread or client that it has a file ready, it can just put so many tasks on the queue, and not care about which process handles what exactly. As long as the queue is empty at the end of the process, you're okay.

Anyway, as I said, before you do anything, make sure that you know what the actual bottlenecks are.


答:
You should learn something about computer science. It will show you that when a program runs, it is the CPU fetch instructions to run. So there is a possibility that cpu do nothing but wait for a intterrupt to wake it up.

The event driven is the best practice nowadays. It costs little and responsive quickly. Though there is not pure event driven os. Linux like OSes use kernel to reponse to interrupts and manage processes by loop-calling schedule method.

Title: Do all programs run in a loop?

Body: I was wondering whether all programs run in a Loop, checking for variable changes then acting upon said changes followed by another Loop. Or do they run in a While statement, waiting for a variable to change before they execute a routine? Or am I just completely wrong?</p>


问:
Pattern to use for different Stages in a software
I am developing a software for a laboratory to test some devices. To test each device there are multi subtests which should be done to reach to the final result.To perform a complete test, the software must pass Stage1 then automatically goes to Stage2 then Stage3 and so on until the whole test is finished. meanwhile the user can select to just have the Stage3 or Stage2 or any other Stages independently to be performed (which she selects that at runtime).
this is the thing I have done so far:

```<code>public class IronTestWorkFlow:ITestWorkFlow
    {
        private readonly List<ITestStages> _testStageses;

        public IronTestWorkFlow(List<ITestStages> testStageses )
        {
            if (testStageses == null)
            {
                throw new ArgumentNullException("testStageses");
            }
            _testStageses = testStageses;
        }
    }
</code>```

I am useing a DI container. But I don't know how to change the list of Stages in ITestWorkFlow at runtime.

Questions:

1- Am I designing this right?

2- If yes which pattern shall I follow to obey the principles and change the stages at runtime? and how can I do that?

答: You can use a Mediator pattern. You would have a master list of all available tests in the master workflow. A user won't talk to this workflow directly, but instead to the Mediator. The Mediator will keep track of which tasks are actually selected (in its own list), and expose those to the user.</p>

OwnerDisplayName: Mehrdad Kamelzadeh


答:
No, not all programs run in a loop. Interactive programs have a main (message) loop to respond to user input.

Programs also run in some sort of loop (while not Terminated do) when they stay around and wait for input other than user actions. For example HTTP servers that wait for requests to arrive, image processers that wait for files to arrive in a folder, etc.

Programs that take their input parameters, do their thing, report back and then finish, will not run in a loop. That doesn't mean they do not use any loops at all. The work they do may require plenty of loops, but they don't run a loop waiting for more input.

Title: Do all programs run in a loop?


问:
How to handle complex conditions?
We are working on project where we have to manage these conditions.
i.e.:

A User can save an order under these conditions:

User has permission "SaveOrder"

Order is in state "shipped"

Online Shop is opened.

This condition is for example - I would like to point out, that we have three conditions from different areas(role and permissions, inner state of object order and state of another domain object).

In a previous project we used this code:

```<code>public static bool CanSaveOrder(Order order)
{
   return
   CurrentPrincipal.HasPermission(Permissions.SaveOrder) &&
   order.State == States.Shipped &&
   OnlineShop.IsOpen();
}
</code>```

But I feel that there can be a more elegant/dynamic solution.

I have read something about a "business role engine". Is it a right way to manage this condition?

答:
If you're just asking whether the same code can be formulated in a better way, that is indeed a duplicate of the question pointed out above. Read the answers to that question (and to its duplicates).

However, a business rules engine is something quite different. It means that you specify the conditions in a separate repository from the code - maybe a data base, maybe configuration files, maybe a web service - and your program only contains code to read information about how to make the decision from that repository. It will then apply the rule and return true or false depending on what it evaluates to.

This has far-reaching consequences. You can then change business logic without rewriting your program, ideally without even redeploying or restarting it. The downside is, of course, that your system depends on another external component to function, that obtaining the information from the repository may take longer, and that the code to make the decision becomes less self-explanatory than before. It depends heavily on the concrete situation whether switching to a business rules engine makes sense or not. Whether or not this is considered "elegant" is subjective, and usually not the most useful criterion to make that decision.

Title: How to handle complex conditions?


问:
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.)

答:
Here's some things I've learned from error monitoring in our applications:

Being able to tail a rolling log file (I generally use log4net/log4j for logging in applications and BareTail to follow the log) is really useful for being able to check on the current health of a system

For seeing when problems were introduced and the rate at which problems occur it's nice to have them in a database with timestamps to that you can run reports.

The ability to send email/sms/voice alerts is super helpful in making sure systems stays up, but you have to have the ability to easily customize what types of errors that alert you. If you're getting 800 error emails a day your bound to miss the "Oh no the data center is on fire" one.

I've had great results for log4net because it makes it really easy to log to multiple places and make changes to the logging configuration easy as well.

ContentLicense: CC BY-SA 2.5


问:
Can >8bit per channel colours be seen as intended in the browser?
For, say, a subtle background gradient to a web page, what are the advantages and disadvantages of saving it as a 16bit/channel png?

Are the colours represented by >8bits displayed in the intended detail in all browsers?

答:
Advantages

Below 1/256th improvement in gradient display quality

Disadvantages

Not all browsers have implemented 48bpp PNG decoding

Most displays can't render the full 8bit/channel gamut as well as they claim to, let alone 16

Increased file size

You have to make a value judgement - is it warranted for a background element?  Probably not.


问:
How do the Application and Database Interface Layers interact at their boundary?
I was watching one of Uncle Bob's videos and he brought up the Database Interface Layer.  He had this diagram showing it:

These arrows show that the DB Interface Layer is aware of and calls the Application and Database layer, but not vice versa.

The DB Interface Layer has "data records" in it.  These are "classes" that have the name of the table and the fields of the columns.  These are what I usually call DTOs.  But these data records have all public fields and no/few methods.

The DB Interface layer is responsible for grabbing the data from the database, populating the "data records" and implementing an interface in the Application Layer like so:

I'm a little confused because I've never heard about this separation before.  Every project I've worked on uses the DTOs in the view which is apparently wrong (at least according to Uncle Bob's video).

Also, I've never worked on a project where the DB Interface Layer calls the Application Layer.  It's always the Application layer asking the DB Interface Layer for information.  For example, by using a DAO.

But this is starting to make sense.  Whenever I use hibernate I'm always pulling my hair out because I try to make the DTOs more OO and the library always fights me.

So, I guess what I'm trying to ask is, what does the code look like on/at the boundary between the Application and the Database Interface Layer?  For example, how does the Application get the implementation of the Order Gateway Implementation?  Is the Order Gateway Implementation a DAO?  I don't have a clear picture of how the POS can use the Order Gateway vs how/when the Order Gateway gets populated with data.

答:
I think your confusion comes from the term "Interface".

There is a DatabaseInterface-Interface and a DatabaseInterface-Implementation.

The Applicaton layer knows and uses the DatabaseInterface-Interface to get data from the database into dto-s or daimain-objects.

The DatabaseInterface-Implementation implements the DatabaseInterface-Interface and knows/uses dto-s.

Many developpers call this the Repository-Pattern

If the arrows in your picture means "uses or calls" then the arrow from "Interface" to "order" in the 2nd image has the wrong direction.


答:
```<code>  > "bussiness role engine". Is it a right way to manage these condition?
</code>```

It depends.

"bussiness  role engine" can make sense if

you have several instances with different definitions of "canSaveOrder" (i.e. different internetshops that use the same software)

the meaning of "canSaveOrder" often changes.

Otherwhise the "bussiness  role engine" may violate the principles YAGNI and KISS

Title: How to handle complex conditions?

Body:
We are working on project where we have to manage these conditions.
i.e.:

A User can save an order under these conditions:

User has permission "SaveOrder"

Order is in state "shipped"

Online Shop is opened.

This condition is for example - I would like to point out, that we have three conditions from different areas(role and permissions, inner state of object order and state of another domain object).

In a previous project we used this code:

```<code>public static bool CanSaveOrder(Order order)
{
   return
   CurrentPrincipal.HasPermission(Permissions.SaveOrder) &&
   order.State == States.Shipped &&
   OnlineShop.IsOpen();
}
</code>```

But I feel that there can be a more elegant/dynamic solution.

I have read something about a "business role engine". Is it a right way to manage this condition?

Body:
  > "bussiness role engine". Is it a right way to manage these condition?

It depends.

"bussiness  role engine" can make sense if

you have several instances with different definitions of "canSaveOrder" (i.e. different internetshops that use the same software)

the meaning of "canSaveOrder" often changes.

Otherwhise the "bussiness  role engine" may violate the principles YAGNI and KISS


问:
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?

答:
It's neaty and nifty and tickles your brain. That's fine.

It's also, IMHO, a classic bandwagon. A solution looking for a problem.

It's like all those startup companies founded by engineers dazzled with a favorite idea, that burn brightly for a while, but are quietly overtaken by companies founded on providing what is needed.

That's the new idea I would like to see take off, need-based programming, not nifty-idea-based programming. Maybe that sounds mundane, but I think it can in fact be pretty creative, and nifty.


问:
Use the word "Apple" and "Safari" in my application
I am developing an application and i want to use two words somewhere in my application.
First i want to use the word "Safari" in a menu option which labels "Open in Safari"(for a url).
The second is the word "Apple" in my Terms pages where i want to use it in the phrase "....as provided by Apple",referring to technologies and API's provided by Apple.

Can i use them and if yes with in which conditions?(adding "TM" or "Copyright" signs maybe?).

Thanks.

答:
On the page where you speak about Apple® and Safari®, you need to use the appropriate TM, SM, or ® symbol the first time the term apears, plus the following type of statement, usually in the footnotes (assumes distribution outside the US):

Apple and Safari are trademarks of Apple Inc., registered in the U.S.
  and other countries.

By googling "apple trademark" I was able to find a list of Apple Trademarks and from there, Guidlines for Using Apple Trademarks.  Just about every company has similar web pages.  You always need to look them up to see whether product names are trademarked or registered (or serial-marked).  Also there are guidelines about how and how not to use these words in sentences, how to use logos, and the relative size and typeface of Apple trademarks compared to the rest of the packaging of your product.

As @JamesSnell asked, why wouldn't you make your program launch the default browser of the current operating system?  Why limit yourself to Sarari and Chrome, presumably only on a Mac?

It is interesting to note that Trademarks (inc. serial marks and registered trademarks) are one of three groups of unrelated (in the US) legal protections colloquially referred to as "Intellectual Property."  The other two are Copyrights and Patents.

Disclaimer:  I am not a lawyer, nor a spokesperson for Apple.  These statements are not legal advice, but my personal "best guess" at how to use Apple trademarks.  Please read the linked documents and use your own best judgement about how to apply Apple's rules in this and other situations.  Better yet, hire a licensed lawyer to advise you.


问:
What does "extreme" in "extreme programming" (XP) refers to?
"Extreme" suggests that it has very different from normal, very aggressive, exceeding limits, but in my opinion regular releases, pair programming, unit testing, collaboration with customers are quite normal and acceptable. What does extreme mean?</p>

答:
Extreme programming programming came about when those practices weren't quite normal as you put it. For some people back then the practices were "extreme".

You could translate it to "pure" or "opinionated".


答:
Extreme Programming or 'XP' (nothing at all to do with windows in this case) meant a different approach to the traditional methods of 'requirements - coding - testing  - deployment' as separate phases that followed sequentially.

Extreme Programming meant using new Agile approaches that puts the customer at the heart of development.

The work itself emphasizes teamwork to avoid the more traditional 'silo-ing' of areas such as IT, Sales, Marketing, Customer Service, etc.

It uses 5 key areas - communication, simplicity, feedback, respect, and courage.

This was an extremely different approach when the Extreme Programming project was first introduced on March 6th 1996.

Today, nearly 20 years later, with the Agile movement in full-swing it's starting to become the norm in many industries and doing things the older, traditional way, might soon become extreme!

Title: What does "extreme" in "extreme programming" (XP) refers to?

Body: "Extreme" suggests that it has very different from normal, very aggressive, exceeding limits, but in my opinion regular releases, pair programming, unit testing, collaboration with customers are quite normal and acceptable. What does extreme mean?</p>


问:
Design question on best option to store data on remote computers
I'm making a windows forms application which I want to install on a few computers that are all connected together on a network. Each of these computers have access to a number of servers on which various tasks are carried out etc.

I want each instance of the application in use to be able to store and retrieve data regarding the separate remote servers (this data can be edited by everyone using the application on their computer). The application needs to be able to retrieve data from the servers when the user clicks an update button. The user can then edit and update that data if necessary.

I think the main options for storing the data are as follows:

Store data all in one place in a database

Have a folder on each of the servers and save XML files to it with the data

Which would be the best approach in this scenario and why? Are there any better alternatives?

Note: I would usually opt for the database approach but I want to store data in an alternative way because using a database would require selecting one of the servers to host the database, which doesn't make sense as to which one would have that stored on it and not the other servers, albeit only one database would be needed by the application.

答:
I would go for the database. Quick, easy and known.

As per your issues, I do not know why you mix application servers with database server. After all, you can have your database server in a machine with no application server at all. Having a "conceptually" separate database server allows your fellow SysAdmin to optimize that server for databases engines. Not to mention licencing issues if you plan to use Oracle or similar.

The "mixed data" has the side effect that when one of your server fails/has downtime, you do not know which of your other servers may fail. Ugly, ugly. If you need it for some reason (the only reason I can think of is spreading lots of files through your desktop almost unused HD), probably there is a service app for that in the internet (which should cover replication and encriptation).


问:
Forcing people to read and understand code instead of using comments, function summaries and debuggers?
I am a young programmer (finished computer science university but still under a year of working in the industry) and I recently got a job working on some C code for a decent size web service. Looking at the code the only places I saw comments were when people were stashing their old code. Function and variable names are similarly informative most of the time - futex_up(&ws->g->conv_lock[conv->id%SPIN]);. Confronting a senior programmer about the situation and explaining that adding comments and meaningful names would make the code more maintainable and readable in the future, I got this reply:

In general, I hate comments. Most of them time, like the case you
  mention with the return value, people use comments to get around
  reading the code. The comments don't say anything other than what the
  guy thought the code does at the time he put in the comment (which is
  often prior to his last edit). If you put in comments, people won't
  read the code as much. Then bugs don't get caught, and people don't
  understand the quirks, bottlenecks, etc. of the system. That's
  provided the comments are actually updated with code changes, which is
  of course totally unguaranteed.

I want to force people to read the code. I hate debuggers for a
  similar reason. They are too convenient and allow you to step through
  dirty code with watches and breakpoints and find the so-called
  problem, when the real problem was that there are bugs in the code
  because the code has not been simplified enough. If we didn't have the
  debugger, we would refuse to read ugly code and say, I have to clean
  this up just so I can see what it is doing. By the time you are done
  cleaning up, half the time the bug just goes away.

While what he wrote goes against a lot I have been taught in the university, it does make some sense. However, since experience in the studies sometimes doesn't work in real life, I would like to get an opinion of people more vetted in code.

Is the approach of avoiding commenting code to make people actually read the code and understand what is going on make sense in a medium-sized coding environment (one that can be reasonably read in whole by every person working on it within a month or two), or is it a recipe for a long-term disaster? What are the advantages and disadvantages of the approach?

答:
If you can only "read the code", you will not get an idea of what the function is intended to do. So, if someone fucks up (I know nobody does, this is a hypotetical case) and do something wrong, you have no way of checking it in the code. You have to wait for unit tests to detect it (if they check it).

Add to that, that not adding comments forces me to read functions A1, A2, A3... from beginning to end while I am only interested in understanding function A, which calls all of the above.

I would bet on your senior programmer being lazy (bad) or wanting people to notice how cleverly he codes (way worse).


答:
Well written code should be sufficiently self-documenting that you don't need any comments explaining what the code does, because it is obvious from reading the code itself.
This implies also that all functions and variables have descriptive names, although it might be needed to learn the lingo of the problem and solution domains.

This does not mean that well-written code should be completely without comments, because the important comments are those explaining why a particular, non-trivial, function/block/etc is implemented as it is and why not a different solution has been chosen.

The problem with comments describing the code itself is that they tend to get outdated, because the code gets changed to fix a bug, but the comments remain untouched. This is far less the case with comments describing the reasoning for coming to the current solution.

Title: Forcing people to read and understand code instead of using comments, function summaries and debuggers?

Body:
I am a young programmer (finished computer science university but still under a year of working in the industry) and I recently got a job working on some C code for a decent size web service. Looking at the code the only places I saw comments were when people were stashing their old code. Function and variable names are similarly informative most of the time - futex_up(&ws->g->conv_lock[conv->id%SPIN]);. Confronting a senior programmer about the situation and explaining that adding comments and meaningful names would make the code more maintainable and readable in the future, I got this reply:

In general, I hate comments. Most of them time, like the case you
  mention with the return value, people use comments to get around
  reading the code. The comments don't say anything other than what the
  guy thought the code does at the time he put in the comment (which is
  often prior to his last edit). If you put in comments, people won't
  read the code as much. Then bugs don't get caught, and people don't
  understand the quirks, bottlenecks, etc. of the system. That's
  provided the comments are actually updated with code changes, which is
  of course totally unguaranteed.

I want to force people to read the code. I hate debuggers for a
  similar reason. They are too convenient and allow you to step through
  dirty code with watches and breakpoints and find the so-called
  problem, when the real problem was that there are bugs in the code
  because the code has not been simplified enough. If we didn't have the
  debugger, we would refuse to read ugly code and say, I have to clean
  this up just so I can see what it is doing. By the time you are done
  cleaning up, half the time the bug just goes away.

While what he wrote goes against a lot I have been taught in the university, it does make some sense. However, since experience in the studies sometimes doesn't work in real life, I would like to get an opinion of people more vetted in code.

Is the approach of avoiding commenting code to make people actually read the code and understand what is going on make sense in a medium-sized coding environment (one that can be reasonably read in whole by every person working on it within a month or two), or is it a recipe for a long-term disaster? What are the advantages and disadvantages of the approach?


问:
btnBack vs backButtonField
For blackberry GUI developement.  I am using the name convention like backButtonField and some of my colleagues are using btnBack.

But sometimes I stuck with the names like loginVerticalFieldManager its a very long name.  At that time vfmLogin looks better

So for GUI components names what convention should I follow?

答: The reason I stll use this bastardized variation of Hungarian Notation in my GUI code is simply because Visual Studio has a convenient dropdown list of controls in the code page. They are listed alphabetically, and when looking to code an event handler for a Button, I can scroll to the "btn" section and find the one I want easily. Even if I don't remember it's exact name, I'll remember it when I see it. Otherwise, I'd have to hunt through the whole list tyring to remember the button's name, or go find it on the form.</p>

Title: btnBack vs backButtonField


答:
I want to force people to read the code. I hate debuggers for a
  similar reason. They are too convenient and allow you to step through
  dirty code with watches and breakpoints and find the so-called
  problem, when the real problem was that there are bugs in the code
  because the code has not been simplified enough.

Your senior programmer seems to have an understandable problem about coding style. He's wrong in how he tackles the problem, though.

Both comments and descriptive coding are essential: well-written code with descriptive names quickly tells you what code does; but the comments tell you what the code should do (and why not, why it does it one way and not another. Then you have unit tests to verify that the "contract" (what the code should have done) is actually fulfilled, and do it automatically, frequently and with no further effort on your part.

Without the comments, it would take a long time (or a unit test, which at this point I suspect your boss likes even less than comments, if he believes that "bugs get caught by people reading code) before finding the error:

```<code>// Multiply margin by a fixed amount.
page->margin += fixedMargin;
</code>```

and, yes, the comment might be wrong, but now you know that in one of those two lines there's an error. This, plus another useful resource, version control, enables you to find the discrepancy in less than 30 seconds. Verifying the output and even stepping with a debugger might not (a value of fixedMargin of about 1.01 could give you ambiguous results, for example).

If your mentor is after simplicity (I agree with him that it's a desirable trait), he ought to deploy some way of checking metrics such as cyclomatic complexity and establishing metric goals. That goes for comments too: I agree that it makes no sense to document every single line of code, but you should strive to cover modules, functions and any "WTF point" in the code.

```<code>// Useless comment: multiply a by four

// Useful comment (even if maybe it shouldn't be in this exact point of code):
// Zooming 2:1, four pixels get mapped into one, divisor needs multiplying by four
a *= 4;
</code>```

His method may give results - in the case he hates, you would have 20% coding and 80% documenting and testing. With his method you get 20% coding and 80% debugging and head-scratching.

The difference between the two cases are, I think, in people's morale and in overall productivity. If you properly document and mock functions and modules, a module can be implemented by someone who does not need to know the overall picture, does not have to study side-effects in a black box scenario, and for bottom line's sake, can be less experienced.

Your mentor is apparently comfortable running up a fearsome amount of technical debt. I'd check his stats on deadline slippage and/or ETAs; short of a miracle, any long-running project not kept up by a one-man-band or a tightly knit group of coding buddies is due to have its technical debt called in sooner or later.

Body:
I want to force people to read the code. I hate debuggers for a
  similar reason. They are too convenient and allow you to step through
  dirty code with watches and breakpoints and find the so-called
  problem, when the real problem was that there are bugs in the code
  because the code has not been simplified enough.

Your senior programmer seems to have an understandable problem about coding style. He's wrong in how he tackles the problem, though.

Both comments and descriptive coding are essential: well-written code with descriptive names quickly tells you what code does; but the comments tell you what the code should do (and why not, why it does it one way and not another. Then you have unit tests to verify that the "contract" (what the code should have done) is actually fulfilled, and do it automatically, frequently and with no further effort on your part.

Without the comments, it would take a long time (or a unit test, which at this point I suspect your boss likes even less than comments, if he believes that "bugs get caught by people reading code) before finding the error:

// Multiply margin by a fixed amount.
page->margin += fixedMargin;

and, yes, the comment might be wrong, but now you know that in one of those two lines there's an error. This, plus another useful resource, version control, enables you to find the discrepancy in less than 30 seconds. Verifying the output and even stepping with a debugger might not (a value of fixedMargin of about 1.01 could give you ambiguous results, for example).

If your mentor is after simplicity (I agree with him that it's a desirable trait), he ought to deploy some way of checking metrics such as cyclomatic complexity and establishing metric goals. That goes for comments too: I agree that it makes no sense to document every single line of code, but you should strive to cover modules, functions and any "WTF point" in the code.

// Useless comment: multiply a by four

// Useful comment (even if maybe it shouldn't be in this exact point of code):
// Zooming 2:1, four pixels get mapped into one, divisor needs multiplying by four
a *= 4;

His method may give results - in the case he hates, you would have 20% coding and 80% documenting and testing. With his method you get 20% coding and 80% debugging and head-scratching.

The difference between the two cases are, I think, in people's morale and in overall productivity. If you properly document and mock functions and modules, a module can be implemented by someone who does not need to know the overall picture, does not have to study side-effects in a black box scenario, and for bottom line's sake, can be less experienced.

Your mentor is apparently comfortable running up a fearsome amount of technical debt. I'd check his stats on deadline slippage and/or ETAs; short of a miracle, any long-running project not kept up by a one-man-band or a tightly knit group of coding buddies is due to have its technical debt called in sooner or later.


答:
From the C2 wiki:

The ExtremeProgrammingCorePractices constitute an ExtremeProgrammingProject.

Why "Extreme"?

"Extreme" means these practices get "turned up" to a much higher "volume" than on traditional projects. XP ignores any other practice (like BigDesignUpFront) that does not appear on the list. The result is stable, productive, and very rapid because the practices support each other the more they are used together without interference. An Extreme project is typically so stable and sedate it can lead to FortyHourWeeks without any schedule slips.


问:
How do you convince management to throw away a prototype?
I love prototyping as a fast effective way to put a UI in front of a user.

Many times though, management get their beaks in the way, and the prototype is dragged kicking and screaming into main stream development.

How do you manage management into not doing this?

答:
Sidestep the problem in the first place. DON'T FINISH IT. By that I mean don't make it look pretty or like it's a fit with existing styles on the site. The goal is simply to get the most crude working version of it possible so you can see that the very basic UI flow works. If you throw existing site style on it or overly polish it, they're going to assume you can just "plug it in." Management is like Pakleds from Star Trek. They just want you to "make it go." The more ready you make it seem, the more ready they're going to think it is.

If that doesn't solve your problem, get a job at at least one company with a well-known brand name for a year. Put your email and number on an online resume and you will be fighting recruiters back with a stick, which will enable you to say to them "absolutely not" with the confidence of a dev who knows what they are doing and can get a new job tomorrow where hopefully your expertise on the matter is taken more seriously.

I'm currently working on a codebase that has not two but a triple-stack-whammy of Rails, .NET and Java. The reason we got the Rails tacked on was because a prototype was done in Rails and the top dog at the company said "make it go." We need to say no sometimes. As long as we're not doing it all the time they should take us seriously.

But yeah, whatever you do with a prototype, make sure it starts out real ugly.


答:
Someone (attributed to Richard C. Haven, a Delphi programmer) once wrote:

Beginners comment nothing.

Journeymen comment the obvious.

```<code>myVar = myVar + 1; // add one to myVar

/* This method adjusts the page margin by the appropriate device offset */
</code>```

Masters comment the reason for not doing it another way

```<code>/*

I already tried obvious approaches A, B, and C to solve this problem.
They didn't work for the following reasons: ...

Therefore I wrote this less-than-obvious approach which works and
passes all unit tests.

*/
</code>```

Your "senior programmer" may be senior in terms of age / longevity, but it sounds to me like he has some professional growing up to do.

As for debugging, there's a lot to be said for clean code and liberal use of logging and/or print() statements.  However, using a good debugger I can usually find the problem in a tiny fraction of the time it would take without it.  It's a power tool.  Use it.

Body:
Someone (attributed to Richard C. Haven, a Delphi programmer) once wrote:

Beginners comment nothing.

Journeymen comment the obvious.

myVar = myVar + 1; // add one to myVar

/* This method adjusts the page margin by the appropriate device offset */

Masters comment the reason for not doing it another way

/*

I already tried obvious approaches A, B, and C to solve this problem.
They didn't work for the following reasons: ...

Therefore I wrote this less-than-obvious approach which works and
passes all unit tests.

*/

Your "senior programmer" may be senior in terms of age / longevity, but it sounds to me like he has some professional growing up to do.

As for debugging, there's a lot to be said for clean code and liberal use of logging and/or print() statements.  However, using a good debugger I can usually find the problem in a tiny fraction of the time it would take without it.  It's a power tool.  Use it.


答:
Never compromise the quality of your code.

Writing junk code is a false economy.

As other posters have suggested you can achieve this by using specific tools for mock ups.

However, there are different reasons to building prototypes. Sometimes you can show what you need to without writing code, but often this is not the case. A stakeholder might want you to demonstrate the technical feasibility of a feature.

Build the absolute leanest thing you can to demonstrate the feature/prove the concept. Leave out anything else.

For a UI feature, make sure you don't develop anything on the server - dont touch it at all. Develop again mocks/fakes built in.

If you need to put effort into making the UI conform to the style of the rest of the application dont bother. If it looks good enough without any effort then change the colours to make it stand out, or maybe even a watermark to show that it is a prototype.

I've found the most likely offenders of causing prototypes to turn into production code are sales people. They will sell your product to new customer - without this new feature, the client would not have signed. You can't blame them, they have targets. Be careful with them; make sure they don't make you take out the things that indicate that it is a prototype. You have to stand your ground - they probably should not be misleading customers anyway.

Your management may start to force you to do turn a prototype into production code piece by piece, if you followed my first piece of advice never to write crappy code, there you should be no problem. Gradually, you build up the software, without compromise.

Then if management start to force you to reduce quality you have to ask yourself why. Are they passive? weak? desperate? None of those things are good reasons to stick around at a company.

Title: How do you convince management to throw away a prototype?

Body:
I love prototyping as a fast effective way to put a UI in front of a user.

Many times though, management get their beaks in the way, and the prototype is dragged kicking and screaming into main stream development.

How do you manage management into not doing this?


答:
Comments should be used as a written record which explains something confusing. If you're writing something that is potentially confusing and cannot be simplified, such that you suspect that even you will have a hard time understanding it six months later, then write a comment.

If you comment liberally, everything and everywhere, then comments lose their effectiveness at flagging the difficulties. (Rememer the fable of the boy who cried "Wolf!")

Comments occupy "screen real estate", unless you have a good folding editor; you have to keep skipping past them when moving around in the code. And of course comments like /* increment i by one */ next to i++ are complete garbage.

If the code is so complicated that it requires a guide to the internals, then, by golly, write a guide to the internals.  Call it README-internals.txt (or perhaps HTML) and stash it in the same directory as the code, and put in a comment which says /* this is all explained in README-internals.txt */.

About debuggers: any tool which helps you find a bug is valuable. It is silly to dismiss tools. Breakpoint debuggers should not be used to verify that code is working. At least, not relied upon as a primary means. A debugger will cheerfully step over a statement like a[i] = i++ in C and confirm a bad intuition.

Debugging tools which actually catch some kind of run-time violation, however, can be relied upon as a test tool. If you have a debugger that catches misuses of dynamic memory, and the code passes numerous test cases under that debugger, that is a source of confidence that memory isn't being misused.

So, keep in mind that "debugger" refers to more than one kind of tool, not only a breakpoint/step debugger. Some debuggers only provide a view into the program, leaving you to do the reasoning about what is wrong, whereas other debuggers look for problems for you.

Code cannot always be simplified for the sake of not having a debugger or refusing to use one. What if you follow your boss' suggestion and simplify the code to the point that it cannot be simplified any further, and you still need a debugger?


答:
In a perfect world without deadlines his approach might work.

A user reported a bug in application X. We'll let the new guy spend two months to get a deep and thorough understanding of the code, and then maybe add a few weeks of refactoring. If the bug still occurs, he should be able to find it then and won't even need a debugger!

In the real world, this sounds like a reliable way to get out of business.


问:
Placing elements in graph with a streaming/online algorthm
We have a stream of points with about 1000 points per second. For each point, we have a complex vector (hundreds of dimensions). Our goal, for each point is to link it to the 5 closest points that we've already seen.

We determine "closest" by computing a distance (euclidian or other) between 2 points. Obviously, in a perfect world we would have enough money and time to compute the distance between a new point with each of the points we've already seen and it would keep the 5 closest. The world is not perfect and we're looking for a solution.

Has anyone worked with this before?

答:
To my knowledge, the best software for doing this sort of processing is Apache Mahout.  There are algorithms that are more efficient than a linear search, but generally only for lower dimensions.  Fortunately (although not for your pocketbook), it's highly parallelizable, so you can always throw more hardware at the problem.

To improve latency on a live stream, you might consider preprocessing some historical data to get a feel for a typical distance between closest nodes, then use that distance as a heuristic.  Instead of the absolute five closest, you can pick the first five that are within, say, 5x of the typical distance.  You can increase or decrease that margin as processing power permits.

Another potentially useful heuristic is that once you identify one relatively close point, its previously identified nearest neighbors are good candidates for your new point, and you can branch out from there, rather than picking candidates at random.

For example, if 95% of the nearest neighbors have a distance of 10 or less, first do a linear search to find any point within 50, then look at that point's nearest neighbors, then the closest of the neighbor's neighbors, and so on.


问:
Where does Objective-C fall in the language performance continuum?
There seems to be a lot of discussion of the various speed merits to C or C++ as compared to say Java or Python, but I rarely see Objective-C mentioned. Roughly where does it fall in terms of language performance?</p>

答: Objective-C is slower than C/C++. The reason being the runtime of Objective-C which dispatches methods lookups dynamically at runtime the same way as Smalltalk, from which it has taken over this execution model. Dispatches all methods at runtime is called "true message sends" as opposed to function call in C/C++ where the function address is determined at compile time (except for C++ virtual methods). But I can't say how much slower Objective-C is. ASAIK it is only used for application development because of the performance penalty.</p>


答:
Comments are very overrated and most frequently misused. Though I don't know about your current situation (since I don't find the quoted quote speaking for good code readability), in general you shouldn't spray comments all over your code (with perhaps the exception of highlevel comments, which are already close to documentation0.

It's for a reason that commenting is one of the code smells described in Martin Fowlers Refactoring book (for a summary, see: http://www.industriallogic.com/wp-content/uploads/2005/09/smellstorefactorings.pdf, the book is not freely available afaik).

However, you should substitute comments with meaningful method and variable names, and I don't think w and gs classify. However, personally I would press more on good naming, than on commenting.

Btw, if you search for 'clean code' and 'comments' or 'code smell' and 'comments' you find great reads about this, ie. http://franksworld.com/blog/archive/2010/07/01/12035.aspx (with a summary of why Uncle Bob Martin of Clean Code dislikes comments)


答:
What your senior developer is referring to is code entropy. I imagine he's referring to cases where code is badly designed, and the only way to understand it well and work with it are comments and debugger.

In other words, comments and debuggers can be used to work around underlying issues. However, they are both tools, and blaming the tool is not an effective way to go about anything.

For your example, if a codebase has a lot of broken code, then the solution is not to leave out comments and make everyone read as much code as possible. In fact, this is a waste of time and resources. Instead, set up processes like peer review and pair programming, where code written by one person is sure to have been reviewed by another. These processes not only achieve the same goal with better accuracy, they also avoid a waste of resources where dozens of developers have to understand one complex bit of code, just because it lacks comments and documentation.

Furthermore, efficient comments can actually reduce the amount of error in code. Reading them makes source code easier to understand, and often saves you from having to search through whole batches of source files, just to find out why a line of code is necessary. Sure, the comment may turn out to be wrong - But unless the overall quality of the project is downright horrible, you'll end up saving more time by trusting accurate comments, than you will lose to those that are outdated. And saved time on understanding, means more time for refactoring, which is a much better way to combat code entropy.


答:
If you put in comments, people won't read the code as much. Then bugs don't get caught, and people don't understand the quirks, bottlenecks, etc. of the system. That's provided the comments are actually updated with code changes, which is of course totally unguaranteed.

Nothing like an opinionated idiot.

Next time when you are shopping for a book to read. Besure to read it cover to cover before you buy it. Otherwise you'll never know exactly if it's what you were looking to buy. That's basically what he's telling you to do.

He has made a few assumptions that are foolish.

Reading the source code will provide you with the purist perspective of what it does.

Comments pertain to the scope of the source code they are associated with.

That is his narrow perspective about comments, and as such he sees no value in them. Here are the limitations of not having comments.

Source code is an instruction set for a computer. It does not expression concepts or ideas. Therefore, source code will never tell you what the programmers objectives were. Source code that compiles without errors and does not crash can still fail to meet the objectives. How will you know any different from the computer by reading the source code? The computer already does that, yet it could still fail to meet the objective.

Source code does not explain the programmer's intent. open window, prompt for deposit does not explain that the programmer intended to communicate a warning to the user.

Next time you have a conversation with this guy and he asks why you are adding comments to your source code. Reply with this statement.

"I write source code to tell the computer what to do, and I write comments to tell people what to do."


问:
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...

答:
Fast Fourier transform (FFT)

The FFT is an extremely important and widely-used method of extracting useful information from sampled signals.

A fast Fourier transform (FFT) is an efficient algorithm to compute the discrete Fourier transform (DFT) and its inverse.


答:
I find that code review is a fantastic process for answering this question in concrete ways. If I read someone's pull request (putting forth actual effort to read it, not just glancing at it with the attitude that everything must be immediately apparent) and can't understand what it does, I tell people to add a comment. Or you can do this by yourself with a rubber duck.

Most people inuititively know what ideas needs to be commented - It's whatever you would say to someone standing next to you if they asked you a question about the code. Often I'll ask someone to explain something in a review, they'll give a great answer, and my response is "Copy that explanation you just wrote into a comment in the code."

But for some reason that's rarely the content that people end up writing in their comments. Instead people write inane stuff like

```<code>/**
 * Gets the {@link List} of {@link Author}s for the given {@link Book}.
 *
 * @param book The {@link Book} for which you want the {@link Author}s.
 * @return All of the {@link Author}s for the given {@link Book}.
 */
List<Author> getAuthors(Book book) { ...
</code>```

and

```<code>// increment i by 1
i += 1
</code>```

and that's the kind of stuff that the experienced coworkers are reacting to. I myself tell people when I'm reviewing code to remove these sorts of low-level comments that add no more information than can be found in the immediately surrounding lines.

One prime example of a trivial thing that does need to be commented is descriptions of duck types in dynamic languages. If a function's argument or return value is a dict with a bunch of properties on it, you're in for some insanity later on if you don't comment exactly what those properties are.

No amount of commenting will raise any nontrivial code to the level that an 8-year-old could understand, so you shouldn't try. You have to make some assumptions that the reader knows how to read the code, because otherwise it's a completely futile effort.

Finally, comments are very often wrong. People often skip over them when reading, and don't update them when things change. You can't write a unit test for your comments, so only the way to defend your code against the rot that occurs when your careless coworkers start monkeying with it is to comment only the ideas are are essential. Comments that don't add value add negative value when they become erroneous.

Document design, ideas, architecture, history, rationale - not lines of code.

Body:
I find that code review is a fantastic process for answering this question in concrete ways. If I read someone's pull request (putting forth actual effort to read it, not just glancing at it with the attitude that everything must be immediately apparent) and can't understand what it does, I tell people to add a comment. Or you can do this by yourself with a rubber duck.

Most people inuititively know what ideas needs to be commented - It's whatever you would say to someone standing next to you if they asked you a question about the code. Often I'll ask someone to explain something in a review, they'll give a great answer, and my response is "Copy that explanation you just wrote into a comment in the code."

But for some reason that's rarely the content that people end up writing in their comments. Instead people write inane stuff like

/**
 * Gets the {@link List} of {@link Author}s for the given {@link Book}.
 *
 * @param book The {@link Book} for which you want the {@link Author}s.
 * @return All of the {@link Author}s for the given {@link Book}.
 */
List<Author> getAuthors(Book book) { ...

and

// increment i by 1
i += 1

and that's the kind of stuff that the experienced coworkers are reacting to. I myself tell people when I'm reviewing code to remove these sorts of low-level comments that add no more information than can be found in the immediately surrounding lines.

One prime example of a trivial thing that does need to be commented is descriptions of duck types in dynamic languages. If a function's argument or return value is a dict with a bunch of properties on it, you're in for some insanity later on if you don't comment exactly what those properties are.

No amount of commenting will raise any nontrivial code to the level that an 8-year-old could understand, so you shouldn't try. You have to make some assumptions that the reader knows how to read the code, because otherwise it's a completely futile effort.

Finally, comments are very often wrong. People often skip over them when reading, and don't update them when things change. You can't write a unit test for your comments, so only the way to defend your code against the rot that occurs when your careless coworkers start monkeying with it is to comment only the ideas are are essential. Comments that don't add value add negative value when they become erroneous.

Document design, ideas, architecture, history, rationale - not lines of code.


答:
Any time you write code, you should be thinking about the next programmer who will inherit what you wrote. If you write comments because you were taught to do so as a best practice or just out of habit, you should probably stop writing comments all the time because anybody reading your stuff will start to ignore them as useless.

If you only comment when naming conventions and structure can't explain some weird element of what you're doing (usually because of something else in a codebase that's completely batshit), they'll pick up on that. If you're marking problematic bits of code, for crying out loud put a date on it so it's easier to review changes that led to the shenanigans in source control.

On the subject of debuggers, I can feel a twinge of solidarity on the (I'm guessing) old-school, primarily procedural guy because I come from JavaScript starting back when all IE told you was "Object not found." Why they even bothered, I don't know but when you occasionally have to deal with that sort of thing, you think a lot harder about how to structure your code in such a way that it's going to be a lot more obvious where something went wrong so you can rapidly diagnose with logging/alerts.

That said, I wouldn't trade Chrome Dev tools or Firebug for anything short of a Time-Travelling police box. But the point, I think, is this. If the first thing you do is start a trace in the debugger without even looking at the code that's involved, you may not be structuring your code as well as you could. Always strive to be as direct and obvious and minimalist and easy to read as if there were no IDE or debugger to help you. Start by looking at your code when you hit a snag first. If it's not easy to even guess where things are going wrong, you may want to put some more thought into how you'd go about writing code without modern tools. Most of the Java and C# I've ever seen is clueless about the basic fundamentals of OOP.


答:
Example of bad comment </p>

```<code>foo(); //calling function foo
</code>```

<p>Good comment </p>

```<code>foo(); // must call function foo, because of a bug {link to bug}
</code>```

Body:
Example of bad comment

foo(); //calling function foo

Good comment

foo(); // must call function foo, because of a bug {link to bug}


问:
How would you know if you've written readable and easily maintainable code?
How would one know if the code one has created is easily readable, understandable, and maintainable? Of course from the author's point of view, the code is readable and maintainable, because the author wrote it and edited it, to begin with. However, there must be an objective and quantifiable standard by which our profession can measure code.

These goals are met when one may do the following with the code without the expert advice of the original author:

It is possible to read the code and understand at a basic level the flow of logic.

It is possible to understand at a deeper level what the code is doing to include inputs, outputs, and algorithms.

Other developers can make meaningful changes to the original code such as bug fixes or refactoring.

One can write new code such as a class or module that leverages the original code.

How do we quantify or measure code quality so that we know it readable, understandable, and maintainable?

答:
Some Tests/Indicators:

Turn off the IDE. Can you still read your own code? When there's a bug is it fairly easy to trace through it by hand and figure out what class you'll need a breakpoint in to figure out that's where the problem is? Or when you do use the IDE do you just not even bother and just step through from the very beginning?

Does debug often becomes a game of wack-a-mole where fixing one bug creates 2+ more.

From trigger pull to something useful actually happening, how many method calls does it take? How many methods pass the exact same or most of the same exact parameters on to another method call?

How many files do you have to open to just add a simple new method to a class?

Think on patterns and practices you've adopted. Did you do it because they made perfect sense or because somebody convinced you that "it's the only way to do it?" or because you wanted it on your resume or because some rockstar dev said so.


问:
Are there any standard for exchanging rules rather than data?
Just out of curiosity. There are many open standards for data exchange, as well as standards for exchanging code (jsonp, for example).

But are there any standards for exchanging formulas/rules, for them to be executed on different platforms?

答:
As suggested by Deer Hunter and Justin, current practices are:

Use DB language and its interpreter

Wrap rules using standard data exchange format and then interpret.


答:
A good starting point may be a simplified version of iDistance. The full algorithm works by defining (central) cluster nodes, which are used to reduce the multiple dimensions to one. That one dimensional scalar is used to search a B+ tree. There are other algorithms like it, but they basically use the same approach. (Indexing High-Dimensional Data
for Efficient In-Memory Similarity Search gives a nice overview of several algorithms and their performance.)

However, if we allow some approximations and discarding of nodes, then it may be enough to just have a tree of cluster nodes, perhaps a few layers deep. Search that tree for the nearest cluster node, and then search for the 5 nearest points attached to that node. All brute force calculations of the distance between points in N-dimensional space. Or however you want to optimize it.

Consider the following algorithm in pseudo code:

```<code>Cluster clusters[200];

FillRandom(clusters);

for (i = 0; i < 10000; ++i)
    Vector v = randomVector();

    cluster = clusters.findNearestCluster(v); // brute force search on distance squared

    PointArray points[] = cluster.sortPointsOnDistanceSquared(v);

    selectFirstFive(points);
</code>```

Implemented in Java, 100 dimensions, each dimension between 0.0 and 10.0, runs in 5-8 seconds, on an Intel i7, second generation. Which means, well below the 1000/s stream speed. There is a lot of room for optimization. (I'd share the code, but really, it won't add anything.)

There is more than enough time to do something about rebalancing your cluster tree. Clusters that are in the middle of nowhere and get no hits can be removed. Clusters that have too many hits might be split or otherwise reduced. There should be some radius attached, some overlap tested, etcetera.

In this example code, these were some of the timings:

```<code>Minimum: 0, Maximum: 1067, #Clusters_having_points: 96, Average: 104, Time: 7498ms
Minimum: 0, Maximum: 1095, #Clusters_having_points: 97, Average: 103, Time: 7241ms
Minimum: 0, Maximum: 1010, #Clusters_having_points: 99, Average: 101, Time: 6465ms
Minimum: 0, Maximum:  832, #Clusters_having_points: 99, Average: 101, Time: 5688ms
</code>```

With Min/Max/Avg the min/max/avg points per cluster node. It's programmed in no time, and easy to play around with, to get some picture of how the data handles itself.

The way I see it, most algorithms offer exactness, and keep all their data. They spent their time on the reduction of the N-dimensional point to one dimension. They need that one dimension, to use all kinds of balancing data structures, so they can sift through gazillions of data. By letting go of that exactness (and history), you free up time to use more mundane methods to balance your search tree. "Too many points for this cluster? Throw away half, as long as we can find 5 points that are (nearly) as close as any other we'd find." That's a bit crude, but you get the idea, I hope.

It's the same principle as used in games. If you can't do the real thing, fake it. It's okay as long as it looks good.

If that's not satisfactory, though, then you may go for the more exact algorithms that are known. Searching for some of them, as mentioned in the article I linked, will easily lead to interesting reading material, including algorithms.

Title: Placing elements in graph with a streaming/online algorthm

Body:
We have a stream of points with about 1000 points per second. For each point, we have a complex vector (hundreds of dimensions). Our goal, for each point is to link it to the 5 closest points that we've already seen.

We determine "closest" by computing a distance (euclidian or other) between 2 points. Obviously, in a perfect world we would have enough money and time to compute the distance between a new point with each of the points we've already seen and it would keep the 5 closest. The world is not perfect and we're looking for a solution.

Has anyone worked with this before?

Body:
A good starting point may be a simplified version of iDistance. The full algorithm works by defining (central) cluster nodes, which are used to reduce the multiple dimensions to one. That one dimensional scalar is used to search a B+ tree. There are other algorithms like it, but they basically use the same approach. (Indexing High-Dimensional Data
for Efficient In-Memory Similarity Search gives a nice overview of several algorithms and their performance.)

However, if we allow some approximations and discarding of nodes, then it may be enough to just have a tree of cluster nodes, perhaps a few layers deep. Search that tree for the nearest cluster node, and then search for the 5 nearest points attached to that node. All brute force calculations of the distance between points in N-dimensional space. Or however you want to optimize it.

Consider the following algorithm in pseudo code:

Cluster clusters[200];

FillRandom(clusters);

for (i = 0; i < 10000; ++i)
    Vector v = randomVector();

    cluster = clusters.findNearestCluster(v); // brute force search on distance squared

    PointArray points[] = cluster.sortPointsOnDistanceSquared(v);

    selectFirstFive(points);

Implemented in Java, 100 dimensions, each dimension between 0.0 and 10.0, runs in 5-8 seconds, on an Intel i7, second generation. Which means, well below the 1000/s stream speed. There is a lot of room for optimization. (I'd share the code, but really, it won't add anything.)

There is more than enough time to do something about rebalancing your cluster tree. Clusters that are in the middle of nowhere and get no hits can be removed. Clusters that have too many hits might be split or otherwise reduced. There should be some radius attached, some overlap tested, etcetera.

In this example code, these were some of the timings:

Minimum: 0, Maximum: 1067, #Clusters_having_points: 96, Average: 104, Time: 7498ms
Minimum: 0, Maximum: 1095, #Clusters_having_points: 97, Average: 103, Time: 7241ms
Minimum: 0, Maximum: 1010, #Clusters_having_points: 99, Average: 101, Time: 6465ms
Minimum: 0, Maximum:  832, #Clusters_having_points: 99, Average: 101, Time: 5688ms

With Min/Max/Avg the min/max/avg points per cluster node. It's programmed in no time, and easy to play around with, to get some picture of how the data handles itself.

The way I see it, most algorithms offer exactness, and keep all their data. They spent their time on the reduction of the N-dimensional point to one dimension. They need that one dimension, to use all kinds of balancing data structures, so they can sift through gazillions of data. By letting go of that exactness (and history), you free up time to use more mundane methods to balance your search tree. "Too many points for this cluster? Throw away half, as long as we can find 5 points that are (nearly) as close as any other we'd find." That's a bit crude, but you get the idea, I hope.

It's the same principle as used in games. If you can't do the real thing, fake it. It's okay as long as it looks good.

If that's not satisfactory, though, then you may go for the more exact algorithms that are known. Searching for some of them, as mentioned in the article I linked, will easily lead to interesting reading material, including algorithms.


答:
Comments are very useful, and can be the difference between clear code, and unclear code.

Just because it was done one way "back in the day" doesn't mean another way is unacceptable.


答: For the condition stated in the text this implementation is good, I'd even call it first choice (except for an extra tab needed for 3 rows)

Title: How to handle complex conditions?


答:
Code Complete, the seminal work on coding style, devotes several sections (starting with 19.3 in edition 1) to the question of comments: the good, the bad and the ugly. So you, and your senior developer, should probably take a look there.

Having said that, well written and well placed comments are very important IMO, for any large scale/long-term project.

In  a perfect world, it's true that comments would not be important. But unless you have a photographic memory and everyone who works on your code is a genius, good comments just help to understand the code that much quicker when you have to go back to it a year or two later and modify it, or someone else inherits your code. (I'm saying this having worked professionally for 20 years, and as many as 5 or 7 years on one project with several other developers involved)

A few years ago I inherited a complex application that gets the job done but suffers from poor architecture and an inconsistent, bloated coding style. Luckily, the code is fairly well commented, which saved me days and weeks of getting up to speed with that code base.

Another thing that helped me get up to speed was the debugger I use. When I go to analyze a new piece of software that I have to work on, one of the first things I do is go through all the menus, make invalid or weird selections and see if I can break the app. When I do break it, I run that scenario with the debugger and see where that failure leads me. Almost invariably this leads me to important modules and junctures in the code base: A quick way to find the important places on the map.

Although with my own code I generally don't have to use the debugger very much, there are occasions where it does help - nobody is perfect, even if they are meticulous about unit testing (Which is often impossible when you've inherited tightly coupled legacy code.) And if I use a new module or component, the debugger helps me find quickly the errors and misunderstandings I have to deal with to help me get up to speed with the new stuff.

In short: Time is money, and most of us program to deliver products and pay the bills. Sitting for weeks on end going through hundreds of lines of code to find a bug the debugger would reveal in 10 seconds, or poorly written code that might be illuminated by some good comments,  won't help your bottom line very much....

Your senior developer apparently is not concerned with efficiency and would prefer to have developers spend hours and days messing with complex code, when a few comments would save the day. Same goes for his ideas about debugging. (Just curious: does the senior developer use an IDE? Why not just type everything out in a text file and do a compile and link from the command line, etc? What better way to understand every single line of code...)


答:
The comments don't say anything other than what the guy thought the
  code does at the time he put in the comment

You know, it's an extremely theoretical approach. I wouldn't surprised, if it was said by theoretical mathematician, but in sounds of senior developer it doesn't sound as if it was someone with really long practice.

Well, theoretically you can analyse the code in head, but it works only with very simple programs. With more complex, real-life ones you come across Halting problem, which is one of the most complex problems in computation theory. If someone says he can analyse programs in head, he can probably do RSA decryption in memory :)

It seems as either your senior developer has no real-life experience with complex problems, or is trying to impress you with tricks as taken from Hackers movie, or he want to justify his own laziness when it goes to writing comments.


答:
Comments in code are a Godsend when used correctly but as others here have pointed out they are often overused. I'm not going to re-iterate what has already been pointed out but I will say that you should only comment if you know that the code you are writing is complicated and there is no other viable way.

If you feel you have to comment, think about the code first and ask yourself; Why are you writing that comment? Is there another way of writing the code which wouldn't need a comment?

Don't write comments for the sake of writing comments. Comment only as a last resort or where it will help those who are going to have to work on the code further down the line. If you find yourself writing comments describing what a variable is doing then the chances are you're over-commenting. Bad programmers comment everything, good programmers comment only when necessary.

On the subject of debuggers, I work with some engineers who have gone their whole career without ever firing up a debugger. Why? A debugger is a tool like any other. Just like in most instances a ball-peen hammer will do the job, sometimes you need something with more finesse.

A debugger serves two purposes.

It is used for finding bugs

It shows a path through your code.

They can be very useful in bringing newcomers up to speed and they can be even more useful in tracing those very hard to find bugs but they are not the only way and there are times when a debugger is actually a hinderance more than a help.

As for function summary, well every function should have a docblock, this is a must but don't go making them long and elaborate. The summery should be a 1 line description with each parameter being clearly described.

```<code>/**
 * A getter method for foo
 *
 * @param bool $bar If true, bar will be attached to foo
 *
 * @return foo
 */
</code>```

Only use a detailed docblock if there is cause to. If the method is over complicated then yes, put in an explanation but where possible, try and avoid it. Good code should document itself.

Remember, everybody enjoys reading novels but nobody wants to read war and peace at 9am on a Monday morning.

Body:
Comments in code are a Godsend when used correctly but as others here have pointed out they are often overused. I'm not going to re-iterate what has already been pointed out but I will say that you should only comment if you know that the code you are writing is complicated and there is no other viable way.

If you feel you have to comment, think about the code first and ask yourself; Why are you writing that comment? Is there another way of writing the code which wouldn't need a comment?

Don't write comments for the sake of writing comments. Comment only as a last resort or where it will help those who are going to have to work on the code further down the line. If you find yourself writing comments describing what a variable is doing then the chances are you're over-commenting. Bad programmers comment everything, good programmers comment only when necessary.

On the subject of debuggers, I work with some engineers who have gone their whole career without ever firing up a debugger. Why? A debugger is a tool like any other. Just like in most instances a ball-peen hammer will do the job, sometimes you need something with more finesse.

A debugger serves two purposes.

It is used for finding bugs

It shows a path through your code.

They can be very useful in bringing newcomers up to speed and they can be even more useful in tracing those very hard to find bugs but they are not the only way and there are times when a debugger is actually a hinderance more than a help.

As for function summary, well every function should have a docblock, this is a must but don't go making them long and elaborate. The summery should be a 1 line description with each parameter being clearly described.

/**
 * A getter method for foo
 *
 * @param bool $bar If true, bar will be attached to foo
 *
 * @return foo
 */

Only use a detailed docblock if there is cause to. If the method is over complicated then yes, put in an explanation but where possible, try and avoid it. Good code should document itself.

Remember, everybody enjoys reading novels but nobody wants to read war and peace at 9am on a Monday morning.


答:
I have been writing code for about 40 years now and I may have said something very similar to what said that senior programmer. I'm also very aware of maintenance problems.

Still I believe some very important points were forgotten in the above answers:

I have unit tests for most of my code. Don't you ?

The why of the functions (the intent behind the code) is usually expressed through tests and if tests by themselves are not enough they are commented, sometimes very heavily (if some of you heard of litterate programming they may understand what i'm speaking about).

On the opposite comments in my code are very sparse, nearly nonexistent, except for two special cases:
- if what is implemented is following some normative references (like implementations of network protocols, what I'm currently working on) I usually put the reference as comment above the code.
- I also use comments to avoid breaking programming flow. I insert comments like: this or that look wrong, fix it later when I'm coding some unrelated feature. These are short term comments (like programmer defined warnings) and should be fixed later.

My rationale on doing that is that comments in code can be misleading. You can easily read a comment and believe the code is performing what the comment pretends, even if it's not true.

When comments about code are in tests, things are different. It explains how code should be called and the test ensure it is actually doing that.

I usually not much use debuggers. I keep them for some special cases (mostly when I do not understand what the code does, like strange hardware bugs).

That changed with time. 30 years ago I heavily used debuggers. What I've observed is that finding bugs is usually much slower that other methods. What I usually do now is pinpoint bugs in unit tests, the earlier the better. That has the additional advantage to give a non regression test. Never bitten twice by the same bug.

ContentLicense: CC BY-SA 4.0


问:
Object Initializer in C# problem with readability
I wonder if object initializing have some performance gain in ASP.NET website. I have an office mate that told me that object initialization is much readable and faster than constructor. But one of my office mate disagree with that and said that it always depends.
For example I am doing this:

```<code>using (var dataAccess = new DatabaseAccess { ConnectionString = ConfigurationManager.ConnectionStrings["test"].ConnectionString, Query = query, IsStoredProc = true })
{
    //some code here
}
</code>```

Is it better if I will do this way?

```<code>using (var dataAccess = new DatabaseAccess())
{
    dataAccess.ConnectionString = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
    dataAccess.Query = query;
    dataAccess.IsStoredProc = true;
}
</code>```

Thanks in advance guys!

---EDIT----

is this somehow much better:

```<code>using (
    var dataAccess = new DatabaseAccess
    {
        ConnectionString = ConfigurationManager.ConnectionStrings["test"].ConnectionString,
        Query = query,
        IsStoredProc = true
    }
)
{
    //some code here
}
</code>```

答:
The first snippet you posted isn't less readable because it uses initialization - it's less readable because it's poorly written. Each initialization assignment should have its own line (unless there's only one assignment, or the initialization block is very short.)

As for performance, I would be very surprised if the first snippet compiled differently than the second one, but I'm not 100% on that.


问:
Multiple visual studio projects/solutions on the go
I am working on a large asp.net app as a single developer.  I will often work on a number of change requests concurrently.  For example, a change required to the Finance component and a change required to the sales component.

I sometimes create a separate project to hold the changes and then reference the main application (file reference to the assembly).  Is this a common approach or are there any tool/techniques that make this easier?

For example, I make a change to the sales component, I will create a new project (SalesChange.sln) and if I make a change to the Finance component then I will create a new project called FinanceChange.sln.  FinanceChange.sln and SalesChange.sln reference MainProject.sln and will eventually be migrated to MainProject.sln.

答: It sounds like what you want is to be able to do is demo changes without having to make them to the "original" project. Most people use source control with branching to accomplish this.</p>


问:
What are considered the definitive references for bootstrapping one's client-side expertise?
I'm a server-side junkie, and by that I mean I spend time writing code that's not visible to anyone.

I'm interested in rounding out my skillset and becoming more self-sufficient with writing full-stack webapps.

But, I find it difficult to work with the the sort of 'organicity' of client-side html tech.

I know there is no substitute for time and experience, but if an experienced client-side dev was starting over from scratch, what would he read/do?

EDIT: an example of an answer that I'd give for server-side:

Learn the best practices of the language you're working in, eg. for
  java, read 'effective java'. Learn fundamentals of algorithms,
  application design concepts that are useful in any language, two good
  sources are 'design patterns', 'SICP'.

I'm not looking for:
'Learn CSS, HTML and Javascript.'

I am looking for something like:

Intent, rationale, concepts of X are well-explained in Y. Framework Z
  is a good example and the source-code is enlightening and well-documented.

答:
Good Read for an Intro to the general DOM thing: DOM Scripting - the code stuff will be a little basic for an experienced programmer but it's worth reading IMO

Best practices worth taking very seriously:

The Separation of Content/Structure, Presentation, and Behavior. Keep your HTML, CSS, and JS separated as much as possible via hooks rather than dumping inline JS into script tags, CSS in style tags and style attributes, and event handlers inline in the HTML. It makes it so much easier to think about and work with.

Semantic HTML - basically use HTML to describe content as much as possible. Avoid pointless wrappers and tags used simply to push layout. Don't kill yourself for this but keeping the HTML minimal and appropriate makes it easier to read and debug. The boon to accessibility and SEO are just nice side-effects compared to ease of development.

Really mastering CSS is actually pretty freaking hard and even a lot of designers never bother to. You probably won't want to take the time unless layout problems or UI work really interests you deeply. But pay close attention to display and position properties and how rooting of absolute parents varies depending on what positioning schemes are set on ancestors (very useful). Learning the crap out of CSS is a major competitive edge in UI. Even when you move on to more UI and JavaScript engineering type roles on the client-side.  Being great at it eliminates a ton of JavaScript.

JS itself is very different from most popular languages. It's success and ability to adapt to a wide array of platforms is in large part due to that. If you know something with c-based syntax don't expect it to behave the same. Using first-class functions, closures and learning to adapt to a highly mutable language are critical skills but fortunately it's easy enough to tinker and make things happen that you can pick up basic use of it fairly quickly. jQuery can be very helpful with all the DOM stuff, but don't let it get in the way of understanding how it's done with vanilla JS and the DOM API which is all jQuery uses under the hood.

But if you're looking for "there's only one way to do it right" you'll never find it on the client-side. The problems are too diverse and too complex. You can never stop learning either. The day you do, is the beginning of the week that your skills suddenly became obsolete.

I think there's more value in O'Reilly's definitive guide than the Good Parts personally. I'm sure at least 3 people recommended that by now though. It's not a bad read. It just gets mentioned in any remotely similar question and Crockford's take on JS isn't one I 100% agree with.


问:
Google Datastore and deep records
I'm in the beginning of creating a website that uses Google Datastore to store information related to clients and I'm curious if the record is too deep for NoSQL or if I'm fine.

Essentially I'll be storing details about clients at a fitness business that get's fairly detailed.

A completely made up record example could be

```<code>{
  firstName : "Jon",
  lastName : "Doe",
  assessment : [
    {
      date: "2013-01-31",
      flexibility:
        {
          leftShoulder: "12 whatevers",
          rightShoulder: "15 somethings",
          ...etc...
        }
      strength:
        {
          legPress: "100lb",
          shoulderPress: "22lb",
          ...etc...
        }
      ...etc...
    },
    {
      date: "2013-02-28",
      flexibility:
        {
          leftShoulder: "13 whatevers",
          rightShoulder: "14 somethings",
          ...etc...
        }
      strength:
        {
          legPress: "110lb",
          shoulderPress: "25lb",
          ...etc...
        }
      ...etc...
    }
  ],
  appearance: [
    {
      date: "2013-04-12",
      image: "http://blah"
    }
    ...etc...
  ]
  ...lots of other sub items...
}
</code>```

This record would exist long term for clients and could become a very large record over time. I've seen on MongoDB, which is also NoSQL, has a 16MB limit on a record. While this is is a large amount of space for text and is plenty for big records, I want to make sure this just doesn't indicate that I should be separating these out in regards to NoSQL.

Instead, should I be separating out assessment and appearance records into their own separate records, linked by a foreign key of some sort or does that defeat the purpose of NoSQL?

What is the best practice for designing potentially long term, deep NoSQL records.

答:
Unlike MongoDB, Datastore is not JSON-based. It does not store arrays or dictionaries. UPDATE: As of 2016, it can store arrays and dictionaries.

You can build a certain hierarchy of entities, but it mostly limits their transaction context and gives them implicit parent links. Though it allows for fetching a top entity (record) and all entities that list it as a parent, it does not provide a cascade deletion (unless expressly specified).

What I'd recommend is a top-level entity, one entity per assessment, and one entity per appearance.

Should you want to fetch all (or top few) assessment entities, use an ancestor query. But remember that reads are paid for in AppEngine, and you should be careful with the number of entities you read (or write), or you'll quickly exhaust the free quota.

Title: Google Datastore and deep records