问:
Inheriting from Abstract class vs Enum Types for custom exceptions
I am creating an interface and would like the implementer(s) of this interface to throw exceptions in the case that something goes wrong. Let's call the implementer a plugin. I have a director which can call any one of the plugins. Rather than each plugin throwing it's own random exception, I would like plugins to throw specific exceptions which my director can then handle. For example: If the plugins fail to authenticate with the credentials that are provided by the director or if the requested action times out on the plugin, the plugin should throw an exception. Rather than each plugin throw it's own random exception, I would like plugins to throw specific exceptions that the director knows about and can handle. I do this because if an exception is fatal (like authentication failed) I don't want to retry, whereas if it was a timeout, the director may decide to retry.

Now, I am confused as to which of the following ways is better:

Idea 1:

Create a custom exception (lets say PluginException) and have an enum type which different types of exception (such as authenticationfailed, timeoutout, permissiondenied, etc.) The director will catch all PluginExceptions and handle each exception case by case.

Idea 2:

Create an abstract exception (lets say PluginException again) and have specific exception types derive from my abstract exception (like AuthenticationFailedException, TimeoutException, etc.) The director can listen for any specific exception it is interested in and also listen for the broader PluginException if none of the above exception types match the exception thrown by the plugins.

答:
The main problem you'll have here is that C# has no way of enforcing your exception types among implementers.

The bigger problem for me is that this implies that your plugins are very closely coupled to your director. I would normally expect a simple API for communication between the plugin and director. Then too, this custom exception could run code when thrown, which to my naive sensitivities would appear to be a potential security threat.

Ultimately, I'd say that timeouts and authentication issues are owned by the code that attempts them. You don't trust a plugin to tell you it's authentication failed, you simply fail to authenticate the plugin. If a plugin times out, it lies on the implementer to solve it. I find it likely that you do not want or need this kind of crosstalk in your application.


问:
Who are the 1st and 2nd parties?
So, this is pure curiosity. I've heard the term 3rd party, as in, "3rd party library" for quite a while.

I wonder why we say 3rd and not 2nd (or 4th)?

Who are the first and second parties and where did the term come from?

答:
You, the developer, are the first party.

The customer/consumer of your application is the second party.

Anyone else that supplies libraries, icons, or other resources is a third party (in the sense of "third" meaning some other outside party).

See Also

http://en.wiktionary.org/wiki/third_party

ContentLicense: CC BY-SA 3.0

Title: Who are the 1st and 2nd parties?


答:
I think it's from contract language.

You, the 1st party, may create a contract with someone, the 2nd party, to undertake some piece of work. They may be an expert in one area of the project, but not in another and so they may choose to sub-contract that to a 3rd party.

Edit to add - In contract law you need two parties to create a contract, you will generally think of yourself as the first party and the other party to the contract as the second, but that's just a matter of perspective. One is not labelled as such. Anyone not directly involved in the contract is then a third party.

Title: Who are the 1st and 2nd parties?

Body:
So, this is pure curiosity. I've heard the term 3rd party, as in, "3rd party library" for quite a while.

I wonder why we say 3rd and not 2nd (or 4th)?

Who are the first and second parties and where did the term come from?


问:
Which language introduced the idea of private (hidden) variables?
I know C++ had private variables inside classes, and Java, C#, Javascript, and others picked up on that and ran with it. Aside from variable scope, most languages before that just made everything visible. Certainly in assembly, all of memory is accessible (except as limited by hardware).

But was C++ the first language to support the idea of encapsulation?

答:
The idea of Local Scope goes all the way back to the 1950's.  Fortran has it, Lisp has it.

See Scope (Computer Science).


问:
Is it necessary to memorize every line of code when it comes to game development?
I am currently following along a youtube tutorial here and from what I understand we are starting out by creating an engine to run the game. Should I be able to implement all of this by myself without outside help in the future or should I just make sure to have an understanding of everything that is going on? Would a professional game developer know how to implement everything that it takes to make a game or would he/she just copy and paste certain parts (like creating a buffer, or fps cap) and edit it to their taste?</p>

答:
It depends on how well you want to understand the process.

As a matter of general principle, you should never re-invent any wheel, unless you either

Think you can do it better than the experts, or

Are doing it for the learning experience.

If your goal is to get a game released as quickly and economically as possible, you should leverage the work of others as much as you possibly can, subject to monetary and licensing restraints.

If your goal is to learn as much as you can, and getting a game released is of secondary importance, then by all means... re-invent everything.

A note about Encapsulation

The reason that libraries are possible (and you don't have to understand their inner workings to utilize them) is due to the abstraction we call Encapsulation.  Abstractions like encapsulation allow us to build a black box that works, without being overly concerned about what is happening under the hood.  This is a good thing; if we had to remember how everything in a software system works, we'd quickly outstrip our mental abilities.


问:
Best practices in designing a social network app?
What are best practices when it comes to designing a social network app for Android (possible iOS port later depending on uptake)?

It's my first time architecting something this scale from scratch, and I'm probably already making mistakes in the design phase.

What I already have in mind is to:

Have a Postgresql backend to store customer data. I'm going to set up one 'app' user to handle all the incoming RESTful requests, which leads to my next point..

Connect the database to the app through a RESTful interface (I don't think the platform is overly important but I'm looking at either Go or Puma/Sinatra or Flask as I want to minimise overhead and keep everything as efficient as possible).

Authenticate users using whatever authentication plugin is suitable within the RESTful interface and then..

Tunnel all traffic through a SSL socket which I'll open on the app which will connect to the interface (this is one of the areas where I don't have a great amount of knowledge/experience)

Load data pertaining to other users and store it locally in an encrypted sqlite db on the Android device which I will create as part of the app start-up process. Images will be the only media type I'll allow. I'll wipe the sqlite db each time the user logs in to the app or once it reaches a certain size i.e. over 3 mb.

Make the app subscription based so along with checking the user credentials each time they log on I'll check their subscription status and enable different behaviour accordingly.

Deal with heavy load connection issues by putting Pgbouncer on the db.

Store the user images on my server as normal image files and when the relevant users are selected I'll send them to the app over the socket.

Run the entire server as a VM, possibly from CoreOS/Docker machines, which sounds like a good fit from what I've read.

Is there anything wrong with any part of my intended design?
Is there anything necessary I've missed out?

答:
I am going to be overly critical. I don't mean this to be mean, but to provide the most accurate feedback I can:

What are best practices when it comes to designing a social network app for Android (possible iOS port later depending on uptake)?

Focusing on a specific platform for architecture is unwise. Mobile apps have their own foibles (is it connected to the internet or not, limited permissions/disk space/screen space/user times) but many of these foibles come in the design of your product (usability, target audience, etc) not in the design. The difficult technical challenges aren't on the client side.

That said, look at facebook. They've largely defined best practice.

Is there anything necessary I've missed out?

Yes. This is a small list based on my limited experience. I expect there to be about 5 times as many issues. Many of which I expect to me more severe/nuanced.

A single database. Even the beefiest database machine is only going to scale so far. That database tends to be the first chokepoint to scalability. It also will be the most severe, and the one that will last the longest in almost every arena. Disk space, processor, ram, disk latency, network latency.. all of these are issues, but the most pervasive is that this is a single touchpoint/source of truth for your system.

SSL. The rule of thumb I've heard is that SSL will add about 20% to your bandwidth. Worse, it impacts the latency and processing power of your web servers, meaning you need more to serve the same amount of traffic. Certain specialized hardware can help, but is costly. I question the benefit of having all social networking traffic encrypted.

Data size. You are absurdly underestimating the amount of data that is involved in synchronizing user data to devices. Assume you have (merely) 10 friends. These 10 friends have 8 pictures. Let's be generous and say the pictures are only 50k. That alone is 4 megs of data to push to every single one of your users.

CDN. Now go back to that last example and realize that it's pretty damned likely that 4 of those pictures are really the same picture - reposted 10 times by each of your friends. Sure, a relational database can reduce that duplication, but the common best practice is to use some sort of CDN to spread the wealth (read: load). Why send them via socket from your server when you can use built-in http libraries to get them from companies specialized to distribute and deliver content for you?

Subscriptions(!) Ignoring the challenges of getting people to pay for something new when they can get dozens of other awesome options for free... Subscriptions place a far greater burden on your design, because now you can't trust the client. You need to check to see who this client is, do they have rights, did the rights expire, did the payment go through... And they need to be dead simple to not become some role/tier based monstrosity.

Load Balancer. Multi-threaded web servers on a cluster are all fine and dandy, but something needs to take incoming traffic and divvy it out. CoreOS likely has something to do that, but I imagine specialized hardware will be necessary shortly thereafter.

Caching. There's no talk about caching in your points. Having caching (or more likely, some NoSQL implementation) will be the first vital step to scaling past the limitations of your single database server.

All in all, you're tossing out technologies as though they're going to solve your architecture problems for you. They will not. The tools are good, and the tools are necessary - but if applied in the wrong places or in the wrong ways, it's not going to work. And given the ambient force of large, highly concurrent applications things rarely "sorta" work. They either scale out nicely or they die horrible, horrible deaths under that pressure.


问:
Filtering a List
I will try to simplify my problem. Let say I have a collection (more specifically a List) with different types of elements, for explanation purpose let say we have objects "Person" with different age of birth and an ID. I will represent a person like this: {<id>,<year>}

At some point, I want to get a sub list of all the persons born on 1988 and 1989, and if there is no persons born on that years, I want all the persons born in 1990:

```<code>[{1,1988},{2,1988},{3,1982},{4,1995},{5,1989},{6,1989},{7,1990}] ==>
[{1,1988},{2,1988},{5,1989},{6,1989}]

[{1,1990},{2,1981},{3,1983},{4,1993},{5,1981},{6,1989},{7,1990}] ==>
[{6,1989}]

[{1,1990},{2,1981},{3,1983},{4,1993},{5,1981},{6,1985},{7,1990}] ==>
[{1,1990},{7,1990}]
</code>```

Option 0

At first I though about using the filter method on the apache commons library, but this wouldn't work as I would need to know about all the element on the list to decide if a particular element goes on the sub list or not, so I ruled this option out.

Option 1

Then, the simplest way I can see to do this is loop through the list looking for elements that match the first condition (1988 or 1989), and then, if I can't find any, loop again to look for elements that match the second condition (1900). But I don't like this because you have to loop through the list more than once.

Option 2

The other option I can think about is to loop through the list only once, and to have two different sub list, one with the elements that match the first condition and another with the elements that match the second condition. At the end, if the first sub list is empty, we return the second sub list.

Which one of these two is better (more efficient)?

Which would you use and why?

Do you think there is a better solution than these?

答:
Which one of these two is better (more efficient)?

You did not really define what you mean by "efficient", but on the other hand, your actual problem is a little more complex than what you described.
I'd be interested to have more details, if possible.

Since there is no specific timing or memory usage requirements, nor clear external constraints about your inputs, the problem is a little too general: you should not really worry about which option is more efficient.

Let's see, for example, the worst case complexity:

Option 1: O(n) time, O(n) space

Option 2: O(n) time, O(n) space

I now more than one people who would instantly say:
 "If it is linear, don't waste your  time with it!"

Now, practically, Option 2 might seem more interesting because:

you only need to loop once over your data and,

for most people (myself included), the mental representation of how computation is done  assumes that it is better to compute everything in one pass instead of doing multiple passes (because list traversal might require some overhead); that model does not necessarly takes into accout external constraints like I/O, memory, caches and so on, and how they interact. In fact, I find it  really difficult to know beforehand what option is best, in general. However, multiple passes are a great way to separate work into readable chunks (e.g. see how compilers don't try to do everything at once).

If you have some objective evidence that you need to optimize that part, experiment and measure for a specific metric with representative inputs.

Which would you use and why?

I would use Option 1, mostly in order to Keep It Simple, Stupid, and also because there is no apparent reason that "efficiency" is critical here.

Option 1 is readable, easy to understand, easy to maintain.

Do you think there is a better solution than these?

"Better" is equally hard to understand, here, for the same reasons as above.
But if we assume that "Option 2" definitely is better than "Option 1", then Option 2 can be even more better:

As soon as you encounter 1988 or 1989, stop populating the second list.

Then, you never will store more than N elements (in either output lists), if your input list has N elements.

For the fun of it, here is a prototype implementation in Common Lisp. Remember, I don't recommend this approach, I'd personnally stick with Option 1.

First, here are some test sequences (yours included):

```<code>   (defparameter *test*
     '(((c 1990) (x 1990))
       ((a 1989) (b 1988) (c 1990))
       ((a 1990) (b 1985) (c 1998))
       ((a 1990) (b 1985) (c 1988))
       ((1 1990) (2 1981) (3 1983) (4 1993) (5 1981) (6 1985) (7 1990))
       ((1 1990) (2 1981) (3 1983) (4 1993) (5 1981) (6 1989) (7 1990))
       ((1 1988) (2 1988) (3 1982) (4 1995) (5 1989) (6 1989) (7 1990))))
</code>```

Here is a modified option 2 which does not collect "1990" elements if some current or previous element was a member of {1988,1989}:

```<code> (defun option-2 (pair-list)
   (loop for (name year) in pair-list
         for member-p = (member year '(1989 1988) :test #'eql)
         for some-member-p = member-p then (or some-member-p member-p)
         when member-p
           collect (list name year) into bag-a
         when (and (not some-member-p) (eql year 1990))
           collect (list name year) into bag-b
         finally (return (if some-member-p bag-a bag-b))))

   (mapcar #'option-2 *test*)

   => (((C 1990) (X 1990)) ((A 1989) (B 1988)) ((A 1990)) ((C 1988))
      ((1 1990) (7 1990)) ((6 1989)) ((1 1988) (2 1988) (5 1989) (6 1989)))
</code>```

For comparison, here is Option 1. It is  easier to understand, IMHO:

```<code> (defun option-1 (pair-list)
      (or (remove-if-not (lambda (x) (member x '(1989 1988) :test #'eql))
                         pair-list :key #'second)
          (remove-if-not (lambda (x) (eql x 1990))
                         pair-list :key #'second))))

 (mapcar #'option-1 *test*)

  => (((C 1990) (X 1990)) ((A 1989) (B 1988)) ((A 1990)) ((C 1988))
      ((1 1990) (7 1990)) ((6 1989)) ((1 1988) (2 1988) (5 1989) (6 1989)))
</code>```

Title: Filtering a List

Body:
Which one of these two is better (more efficient)?

You did not really define what you mean by "efficient", but on the other hand, your actual problem is a little more complex than what you described.
I'd be interested to have more details, if possible.

Since there is no specific timing or memory usage requirements, nor clear external constraints about your inputs, the problem is a little too general: you should not really worry about which option is more efficient.

Let's see, for example, the worst case complexity:

Option 1: O(n) time, O(n) space

Option 2: O(n) time, O(n) space

I now more than one people who would instantly say:
 "If it is linear, don't waste your  time with it!"

Now, practically, Option 2 might seem more interesting because:

you only need to loop once over your data and,

for most people (myself included), the mental representation of how computation is done  assumes that it is better to compute everything in one pass instead of doing multiple passes (because list traversal might require some overhead); that model does not necessarly takes into accout external constraints like I/O, memory, caches and so on, and how they interact. In fact, I find it  really difficult to know beforehand what option is best, in general. However, multiple passes are a great way to separate work into readable chunks (e.g. see how compilers don't try to do everything at once).

If you have some objective evidence that you need to optimize that part, experiment and measure for a specific metric with representative inputs.

Which would you use and why?

I would use Option 1, mostly in order to Keep It Simple, Stupid, and also because there is no apparent reason that "efficiency" is critical here.

Option 1 is readable, easy to understand, easy to maintain.

Do you think there is a better solution than these?

"Better" is equally hard to understand, here, for the same reasons as above.
But if we assume that "Option 2" definitely is better than "Option 1", then Option 2 can be even more better:

As soon as you encounter 1988 or 1989, stop populating the second list.

Then, you never will store more than N elements (in either output lists), if your input list has N elements.

For the fun of it, here is a prototype implementation in Common Lisp. Remember, I don't recommend this approach, I'd personnally stick with Option 1.

First, here are some test sequences (yours included):

   (defparameter *test*
     '(((c 1990) (x 1990))
       ((a 1989) (b 1988) (c 1990))
       ((a 1990) (b 1985) (c 1998))
       ((a 1990) (b 1985) (c 1988))
       ((1 1990) (2 1981) (3 1983) (4 1993) (5 1981) (6 1985) (7 1990))
       ((1 1990) (2 1981) (3 1983) (4 1993) (5 1981) (6 1989) (7 1990))
       ((1 1988) (2 1988) (3 1982) (4 1995) (5 1989) (6 1989) (7 1990))))

Here is a modified option 2 which does not collect "1990" elements if some current or previous element was a member of {1988,1989}:

 (defun option-2 (pair-list)
   (loop for (name year) in pair-list
         for member-p = (member year '(1989 1988) :test #'eql)
         for some-member-p = member-p then (or some-member-p member-p)
         when member-p
           collect (list name year) into bag-a
         when (and (not some-member-p) (eql year 1990))
           collect (list name year) into bag-b
         finally (return (if some-member-p bag-a bag-b))))

   (mapcar #'option-2 *test*)

   => (((C 1990) (X 1990)) ((A 1989) (B 1988)) ((A 1990)) ((C 1988))
      ((1 1990) (7 1990)) ((6 1989)) ((1 1988) (2 1988) (5 1989) (6 1989)))

For comparison, here is Option 1. It is  easier to understand, IMHO:

 (defun option-1 (pair-list)
      (or (remove-if-not (lambda (x) (member x '(1989 1988) :test #'eql))
                         pair-list :key #'second)
          (remove-if-not (lambda (x) (eql x 1990))
                         pair-list :key #'second))))

 (mapcar #'option-1 *test*)

  => (((C 1990) (X 1990)) ((A 1989) (B 1988)) ((A 1990)) ((C 1988))
      ((1 1990) (7 1990)) ((6 1989)) ((1 1988) (2 1988) (5 1989) (6 1989)))


答:
As the other guy said, local variables go all the way back to FORTRAN.

The groundwork for what we now call "object-oriented programming", specifically classes with methods and public and private instance variables, was laid down in Simula 67 by Ole-Johan Dahl.  He wrote a good bit of it up in his section of "Structured Programming" [Dahl, Dijkstra & Hoare].  (No, you CAN'T borrow my copy!)

Title: Which language introduced the idea of private (hidden) variables?

Body:
I know C++ had private variables inside classes, and Java, C#, Javascript, and others picked up on that and ran with it. Aside from variable scope, most languages before that just made everything visible. Certainly in assembly, all of memory is accessible (except as limited by hardware).

But was C++ the first language to support the idea of encapsulation?


问:
Should client ideas about the UI turn into User Stories?
I'm trying to learn about Agile methodologies through the Head First Software Development book and after reading about it, I've tried to apply the concept of User Stories to a recent mini-project (set of new features added to an existing application).

Besides the fact that I have a hard time not thinking in terms of "tasks", I've also had trouble with the fact the client has asked things in a way that, to me, include implementation.

For example, instead of asking "we want Limited Users to have an Address now, just like Regular Users" and leaving the rest to us, they would say "we want Limited Users to appear in the same list as Regular Users and we want them to have an Address too, and it should be editable in the same Address Editing screen as Regular Users".

It seems to me that User Stories are meant to express a business need, but not its technical implementation, nor its UI implementation. That said, does it make sense that a client would impose its vision of the UI and have that be their business need?

How would I turn the client's request into one or more User Stories? Should I say "woah there! Tell me your ultimate goals and we'll see how we can get the UI to accomodate them later"? Should I make multiple stories, one for the main business need (Limited Users have an Address) and additional ones for the UI requests? Should I just make the business need a single story and have other concerns as details / acceptance tests?

Admittedly I'm quite wet behind the ears when it comes to Agile and User Stories and I have trouble defining how much goes into them and where the rest would go too.

答:
There's a finer line between requirement and implementation than what you're seeing.  Reading over the example you provided, all I saw were requirements.

So let's break it down:

we want Limited Users to appear in the same list as Regular Users and we want them to have an Address too, and it should be editable in the same Address Editing screen as Regular Users

And we can extract the following requirements:

we want Limited Users [should] to appear in the same list as Regular Users

and we want them to [Limited Users should] have an Address too,

and it [The Limited User's address] should be editable in the same Address Editing screen as Regular Users

So with a little bit of editing we go from a perceived single requirement with implementation details to three separate requirements.

In the example, the client is giving you the leeway to figure out how to add in the actual implementation details.  For example, if you need another table to store Limited User addresses, then use another table.  If you want to re-use the same table as regular users, then go for it.

Now, whether you make one large user story or multiple stories will depend upon how big those tasks are and how long your sprints last.  If you can complete all three requirements within a sprint, then handle it with one story.  If it makes more sense to break it out into separate user stories, then do so.  It really depends upon your team at that point.


问:
How important is automated testing in rapid release, non-critical (web) apps?
I think I understand the theoretical benefits of automated testing, especially unit testing.  However, I'm not sure what the optimal amount of testing is when the project is a non-critical, rapidly developed (and deployed) web app with a reasonably large user base.  My current reasoning goes like this:

Most of the core functionality of our app can be manually tested in a matter of seconds.  (The site is a type of search engine, so basically - run search, get results, it works.)

Of course, there are many edge cases and options and such that could be tested, as well as unit testing of underlying logic, but if anything significant breaks and isn't caught before it's made live, we literally tend to get email from users within an hour.  (Within minutes if it's a major problem, but very rarely does one of those get out.)

So the consequence of any significant problem going live is that a few people are inconvenienced for a few minutes.  Maybe some percentage of new visitors we get in that period would be lost, although the numbers should be very low since the time period is so short.

Lower impact bugs might take longer for someone to email about - days, or even weeks depending on the severity - but they will also have less of an impact on users, so from a business perspective likely don't "matter" as much.

Now, I'm not saying that excellent test coverage is useless.  Of course it would be nice to catch every issue before it goes live.  But in the cost/benefit tradeoff between working on tests and responding quickly to user feedback / adding and refining features, the latter seems to win.

The one exception I've found is in code that doesn't directly affect the user.  For example, ad serving code, or data collection.  These don't directly impact the user's value from the site, so people are unlikely to let us know when they break.  They will also be less noticeable in our feature testing.  So I can see a strong case for well-defined unit tests there.  (And from there, there ironically seems to be a spectrum where good test coverage becomes less important as features become more important, to the point where code that is critical to the site's operation doesn't really need to be tested (in a well defined manner) at all.)

So my question is, am I way off base here?  Is widespread test coverage and/or test-driven development optimal even in a non-critical, continuous-release environment?  And if so, where am I failing in my reasoning?

Or, assuming we fix bugs immediately when reported, is it reasonable to focus on rapid, nimble development, knowing that our users will let us know if we break something?  (With the exception that we will have formal tests for functionality that is not directly exposed to the user.)

答:
This depends on how good you are at writing tests, as well as, how much you want to maintain and improve your test writing skills. If you're not good at it and don't care to learn, it could increase the amount of time wasted.

Of course you may think having to write tests will slow down your rapid release cycle, but at some point the application may become so complex that having the tests will save time in the long run.

You can create all types of scenarios where it appears you can avoid following sound coding habits, but they rarely exist. How much coding can you get away without having source control?  It's like not requiring a strong foundation for a house because you don't plan on having a lot of people in it at one time. Cutting corners will probably cause you to end up spending a disproportionate amount of time fixing a bug. Wouldn't that really be the true waste of time on a non-critical app?


问:
What is meant by "OOP hides the state"?
In one of many anti-OOP rants on cat-v.org I found a passage by Joe Armstrong raising several objections against the OOP model, one of which was the following:

Objection 4 – Objects have private state

State is the root of all evil. In particular functions with side effects should be avoided.

While state in programming languages is undesirable, in the real world state abounds. I am highly interested in the state of my bank account, and when I deposit or withdraw money from my bank I expect the state of my bank account to be correctly updated.

Given that state exists in the real world what facilities should programming language provide for dealing with state?

OOPLs say “hide the state from the programmer”. The states is hidden and visible only through access functions.
  Conventional programming languages (C, Pascal) say that the visibility of state variables is controlled by the scope rules of the language.
  Pure declarative languages say that there is no state.
  The global state of the system is carried into all functions and comes out from all functions. Mechanisms like monads (for FPLs) and DCGs (logic languages) are used to hide state from the programmer so they can program “as if state didn’t matter” but have full access to the state of the system should this be necessary.

The “hide the state from the programmer” option chosen by OOPLs is the worse possible choice. Instead of revealing the state and trying to find ways to minimise the nuisance of state, they hide it away.

What exactly is meant by this?  I have very little low level or procedural experience, mostly OOP, so that probably explains how unfamiliar with this I am.  And from a more modern standpoint, now that most of the Object-Oriented hysteria is passed (at least as far as I can tell), how accurate/relevant do you guys think that passage is?

Thanks for your help.

答:
At the risk of going beyond answering the question, it's easy to see flaws in the idea of OOP, but I'm inclined to think the power of an idea is reflected in it's ability to be abused.

After all, everyone has their favorite language, that they describe in terms like "very very powerful" meaning they really really like it. But the wonder of computational universality is that no matter how glorious a language is, if it's truly powerful it can simulate assembly language. And if it can, someone will see that it does.
(Not that there's anything wrong with assembly language.)

My personal feeling about the OOP bandwagon is that it represents a stunting of people's education in software engineering / computer science.
They are stunted at a level where they think it's all about data structure.
Classes, inheritance, containers, iterators, hash maps, properties, state hiding, etc. - all about data structure - the more the merrier.

I personally would like to see a next level where people would learn to solve problems by looking at them linguistically.
Where they would understand the concept of domain-specific-languages, how to easily make them and let their creation be an integral part of problem-solving.
It's not incorrect to say that a data structure is a language.
People should have that skill of language design, so they are not just bumbling through it.

Then as a next level, I would like to see artificial intelligence reinvigorated.
I would like to see programmers move beyond bytes and threads and virtual function tables and CUDAs and move into how to get machines to reason, learn, and create.
I know this has advanced very far in little corners of the field, but nowhere near broadly enough.

Title: What is meant by "OOP hides the state"?


问:
Are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?
I'm a long-time Python user. A few years ago, I started learning C++ to see what it could offer in terms of speed. During this time, I would continue to use Python as a tool for prototyping. This, it seemed, was a good system: agile development with Python, fast execution in C++.

Recently, I've been using Python more and more again, and learning how to avoid all of the pitfalls and anti-patterns that I was quick to use in my earlier years with the language. It's my understanding that using certain features (list comprehensions, enumerations, etc.) can increase performance.

But are there technical limitations or language features that prevent my Python script from being as fast as an equivalent C++ program?

答:
There are three main factors that affect the performance of all dynamic languages, some more than others.

Interpretive overhead. At runtime there is some kind of byte code rather than machine instructions and there is a fixed overhead to executing this code.

Dispatch overhead. The target for a function call is not known until runtime, and finding out which method to call carries a cost.

Memory management overhead. Dynamic languages store stuff in objects that have to be allocated and deallocated, and that carries performance overhead.

For C/C++ the relative costs of these 3 factors are almost zero. Instructions are executed directly by the processor, dispatch takes at most an indirection or two, heap memory is never allocated unless you say so. Well-written code may approach assembly language.

For C#/Java with JIT compilation the first two are low but garbage collected memory has a cost. Well written code may approach 2x C/C++.

For Python/Ruby/Perl the cost of all three of these factors is relatively high. Think 5x compared to C/C++ or worse. (*)

Remember that runtime library code may well be written in the same language as your programs and have the same performance limitations.

(*) As Just-In_Time (JIT) compilation is extended to these languages they too will approach (typically 2x) the speed of well-written C/C++ code.

It should also be noted that once the gap is narrow (between competing languages), then differences are dominated by algorithms and implementation details. JIT code may beat C/C++ and C/C++ may beat assembly language because it's just easier to write good code.


问:
When is the register keyword actually useful in C?
I am confused about the use of register keyword in C. It is generally told that its use isn't needed like in this question on stackoverflow.

Is this keyword totally redundant in C due to modern compilers or are there situations in which it can still be useful? If yes, what are some situations in which use of register keyword is actually helpful?

答:
As already mentioned, compiler optimizers essentially render the register keyword obsolete for purposes other than preventing aliasing. However, there are entire codebases which are compiled with optimization turned off (-O0 in gcc-speak). For such code, the register keyword can have great effect. Specifically, variables that would otherwise get a slot on the stack (i.e. all function parameters and automatic variables) may be placed directly into a register if declared with the register keyword.

Here's a real-world example: assume that some database retrieval has occurred and that the retrieval code has stuffed the retrieved tuple into a C struct. Further, assume that some subset of this C struct needs to be copied to another struct—maybe this second struct is a cache record that represents the metadata stored in the database that, due to memory constraints only caches a subset of each metadata record as stored in the database.

Given a function that takes a pointer to each struct type and whose sole job it is to copy some members from the initial struct to the second struct: the struct pointer variables will live on the stack. As assignments occur from one struct's members to the other's, the struct's addresses will, for each assignment, be loaded into a register in order to perform the access of the struct's members that are being copied. If the struct pointers were to be declared with the register keyword, the structs‘ addresses would remain in the registers, effectively cutting out the load-address-into-register instructions for each assignment.

Again, remember that the description above applies to unoptimized code.


问:
How did you learn about security in your web development?
I've been developing intranet web sites and public web sites with no big issues concerning security. There were nothing to steal and nothing to gain. Nothing to attract people to try to reach the website behind the scene. I don't talk about login & password but more about the security against user attacks.

So, what's the best way to learn to secure the access to a site, to learn about common mistakes or weakness to think about ? Do I have to find a framework related to the language I use and rely on it or is there a source (book, website, ...) where I can find information about general design and tricks ?

答: You can learn about this by yourself, but a framework would help you avoid making common mistakes and be a lot more secure. </p>

ContentLicense: CC BY-SA 2.5


答:
To be honest, these days I am more and more inclined to simply comment on this as unprofessional behavior. There are very good books like Legacy Code 1, Refactoring [2], or Clean Code [3], which explain much better why professional software development should always include tests.

Warning: the following are my opinions and sometimes phrased rather strongly, because I do strongly believe them, not because I want to put you or your project into a bad light.

Advantages

You gave a few reasons, why one might want to add tests, however, you seemed to have missed a few details on those.

Code that doesn't directly affect the user

This is a double-edged sword at best, or just plain pointless. If it doesn't affect your user, then it's simply by the very definition of the word useless. Every piece of code should affect your user, because it is the reason why your user wants your app at all. Of course, you meant it in the sense of code that relates to the visually observable aspects of your app (aka GUI parts). But that means we're discounting such a small portion of your overall codebase, that it's not really worth discussing. It's like having a warehouse full of plums and wondering whether it's worth it to buy a corer for the plums at all, because it may not even work for that one apple in your hand.

Consequence is inconvenience

You are quite correct in that existing users are inconvenienced. But I do hope you are the market leader, or even better the monopolist. If there is a second app available to the user which does not inconvenience her - guess what? she'll switch. Often this happens faster than you can say "I'll fix it". Obviously, newcomers to your app will just throw it into the trash right away.. it's not working at all when they try, so why bother? However, apart from simply losing direct sales on your app, there is another thing at stake: your company's reputation. What do you want people to think and tell others about your company? "These guys know what they're doing. Almost never do I have an issue with their products and if I do, they fix it asap", or do you prefer "I have no idea what these guys are doing.. every once in a while their products just stop working for a few hours. They should have fixed that long ago, but somehow they just can't get it right". The more impact your products have, the worse the problem. As a rather extreme case look at something like the Diablo 3 game, which was not functional for the first week after its release due to the massive demand of players. What did function very well though was the users venting their frustration everywhere on the net.. even today, the game has not exceeded 3 stars on amazon - granted, there are other issues with it, but the name Blizzard is marked in players' heads as "do not even expect to play on release dates. they'll screw it up again.".

Complexity of test suite

(you mentioned that one in your comment) Oh so true, more complex software means more complex tests.. or maybe not. This is a typical fallacy. Stop believing this. It is on the same line as "Sht in, sht out".. if your software is ever-so-complex, then tests or their complexity are not your problem. It's simply that software's complexity. Increased test complexity is just a symptom of that original problem. Tackle the real problem and make your software less complex, and lo and behold, your tests don't need to be complex either. It is also a very short-sighted argument that you lose time due to having to update tests when you make changes. Look at what really happens: you change the code and a test fails. Duh.. stupid tests.. but really, this just told you that you changed the code in a way that also changes the previously specified behavior of your program. Were you aware of that even? If not, then stop complaining right now, because you have been acting carelessly! If you do want to change the specified behavior, then tests even ensure that you did just that. What if you want to change from previous behavior to a new one, so you change the code, but no test fails? Oh oh.. major problem spotted right there. Complexity is a beast and truly unavoidable overall. But tests are the cage that keep it at bay and help you deal with it in a controlled manner.

And several more you missed:

Legacy code

Most developers consider the code you are writing for your app today as legacy code. In 1 legacy code is even defined as code without tests. So what are the problems of legacy code? oh right.. that one guy which knew the code was just hit by the bus (aka left the company for a better opportunity). I bet your successor would contemplate giving his left foot for solid test coverage when he realizes that he now has to maintain someone else's software which goes into production to thousands of users, which even expect bugs to be fixed by the hour.

Refactoring

You can't do that. Period. The evolvability of your software is crippled to the point of non-existence. Everything you add to the product, every bug you fix, every minute you invest into that code, translates to even more costs further down the road. There is no risk-free clean up and there quickly comes a limit when you will no longer be able to just say "oh let's rewrite that.. if we mess up we'll hear from our users soon". Since you have no evolvability and refactoring, it just snowballs from there.. code complexity will rise together with bug counts and costs, each trying to out-do the other. Of course, this is no issue for you and your software, because it's small, simple, easy to maintain - step back just one step and look into the mirror. When you tell that to others what they hear is "famous last words". Stop fooling yourself if you really still believe that. In my experience, the only software that does not grow is the one that has utterly failed all of its assigned tasks - and you have bigger worries than testing in those projects.

Development speed

Every fix, every new feature, every single line of code you add or change, profit from tests. Combined with active refactoring of your codebase the development speed surpasses a project without tests very very quickly. The keyword here is feedback loop. While the feedback loop you have described via your customers is indeed a very short one, which is good!, it is also a very costly one (see above). Tests simply mean that you get an earlier feedback loop that is shorter and cheaper.

Multi-Project view: When working on source code in a company, your project seldomly works in isolation. Projects can cross-fertilize each other by re-using or sharing common code. While this does add complexity and gives your architects headaches, it is all based on the very foundation of testing. Do not even dare to think about re-using or sharing code that is untested - you'll sacrifice both projects on the altar of ignorance that way.

Regression

Even though you can fix bugs within an hour (I do certainly not admire your sleeping pattern if that is for real!), your customers MAY (yes, that is a huge may) accept that for new features and previously unknown bugs. It is simply unacceptable and projects an immensely bad picture of your company, if the same bugs appear again lateron. If you start fixing a bug without writing a test to verify its existence first, then you are making a huge and costly mistake. If you cannot write a test against the bug, then you definitely are in no position whatsoever to even attempt to fix it. And if you wrote that test, you immediately see when it is fixed (because the test should of course assert the correct behavior, hence, turn from red to green due to the fix). Finally, the very same test serves as a regression test from now on to ensure your users will never ever see that identical bug again. (Off-topic: I'm sometimes wondering if it's worthwhile to introduce a saying like "Write once, profit everywhere" to capture this..)

Professionalism

What do you tell your manager? Do you have any moral conflict in confidently stating that you made this piece of software? or do you feel slightly ashamed, knowing that you just hacked it together and most of your confidence of the software's capabilities relies on sheer hope? Have you really done the company a service, or did you just create further obligations it has to pay for dearly in the future?

The other side of the coin

While I do argument in favor of automated testing, it was correctly pointed out, that this answer was one-sided, so let's take a look at the cons of automated testing.

I have written another lengthy answer that goes into more detail on the general disadvantages of all automated testing. But in short, these disadvantages turn into advantages when you do not implement automated testing. Here's that same list in its "advantage"-point of view formulation:

Development time: You get faster time-to-market

Skill level: Your developers don't need to know anything about automated testing.

Tooling: You don't need these tools or licenses.

Failed and non-failed tests: You are not wasting time on tests anyways.

Deployment costs: Costs are reduced to what you need for operation. Testing infrastructure cost is no longer needed.

Summary

In the end, its up to a lot of factors on what the best approach is. I would argue that there is no objective answer that holds for all projects and is concrete enough to implement.

You can of course say that there are costs/profits (positive and/or negative) over time and you can think of two mathematical functions, one for automated tests, one for development without them. At the very least, there will be an intersection somewhere after which if you spend more time on the project, automated tests will have a better overall cost/profit. That point is definitely too late for a switching strategy though.

Personally, in my experience, people severely over-estimate how long it takes to reach the point when automation pays off - myself included. Even projects that are supposed to only take 2 weeks have that tendency to keep going. Since the automated tests already help during development, the time delay caused by adding automated testing is similarly over-estimated. I am still unsure at what point automated tests start to pay off, but in my past that point was reached already a week or two into the project. In some projects the tests were there and a retrospective revealed the benefit, in other projects problems soon (and later) started to come up that would have been avoidable.

I'd suggest to dismiss the notion of automated testing yes-or-no, and instead have automated testing and think of it as a tradeoff trying to find out just how much of it you need.

1 Michael Feathers' Working Effectively with Legacy Code (ISBN 0-13-117705-2)

[2] 1999. Refactoring: Improving the Design of Existing Code, With Kent Beck, John Brant, William Opdyke, and Don Roberts (June 1999). . Addison-Wesley. ISBN 0-201-48567-2.

[3] Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall PTR. 2008. ISBN 0-13-235088-2

Title: How important is automated testing in rapid release, non-critical (web) apps?

Body:
I think I understand the theoretical benefits of automated testing, especially unit testing.  However, I'm not sure what the optimal amount of testing is when the project is a non-critical, rapidly developed (and deployed) web app with a reasonably large user base.  My current reasoning goes like this:

Most of the core functionality of our app can be manually tested in a matter of seconds.  (The site is a type of search engine, so basically - run search, get results, it works.)

Of course, there are many edge cases and options and such that could be tested, as well as unit testing of underlying logic, but if anything significant breaks and isn't caught before it's made live, we literally tend to get email from users within an hour.  (Within minutes if it's a major problem, but very rarely does one of those get out.)

So the consequence of any significant problem going live is that a few people are inconvenienced for a few minutes.  Maybe some percentage of new visitors we get in that period would be lost, although the numbers should be very low since the time period is so short.

Lower impact bugs might take longer for someone to email about - days, or even weeks depending on the severity - but they will also have less of an impact on users, so from a business perspective likely don't "matter" as much.

Now, I'm not saying that excellent test coverage is useless.  Of course it would be nice to catch every issue before it goes live.  But in the cost/benefit tradeoff between working on tests and responding quickly to user feedback / adding and refining features, the latter seems to win.

The one exception I've found is in code that doesn't directly affect the user.  For example, ad serving code, or data collection.  These don't directly impact the user's value from the site, so people are unlikely to let us know when they break.  They will also be less noticeable in our feature testing.  So I can see a strong case for well-defined unit tests there.  (And from there, there ironically seems to be a spectrum where good test coverage becomes less important as features become more important, to the point where code that is critical to the site's operation doesn't really need to be tested (in a well defined manner) at all.)

So my question is, am I way off base here?  Is widespread test coverage and/or test-driven development optimal even in a non-critical, continuous-release environment?  And if so, where am I failing in my reasoning?

Or, assuming we fix bugs immediately when reported, is it reasonable to focus on rapid, nimble development, knowing that our users will let us know if we break something?  (With the exception that we will have formal tests for functionality that is not directly exposed to the user.)


问:
How far can I drift from my original domain model and still have the benefits of an ORM?
I have the following domain models:

```<code>public class User
{
    public int Id { get; set; }
    public ICollection<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public decimal Price { get; set; }
}
</code>```

My User entity has a collection of Products, and no Product can be created without an User.
I am using EntityFramework Code First approach, which requires me to declare the Foreign Key on my Product entity, thus changing it to:

```<code>public class Product
{
    public int Id { get; set; }
    public decimal Price { get; set; }
    public int UserId { get; set; }
}
</code>```

I dont quite like this because, from the domain point of view, it is not interesting to have the User foreign key shown in my Product entity. This, however, does not bring any harm to me and I can live with it. Please, mind that I am using an ORM to simplify my work, so I am okay with it to an extent.

Is it okay to my domain entities having properties or such things only to satisfy my ORM of choice requirements?

答: I've heard Vaugn Vernon say about EF that you shouldn't spend time battling EF in order to make it look like a domain model because EF is much more inflexible than other ORMs. So his advise if you want to use EF is to just have a state object behind the scenes which fits EF and then just let your domain model use that for data storage.</p>


问:
How to avoid reinventing the wheel when using complex frameworks?
For the backstory, I'm developing a GUI application in C#/WPF. I already had in my code quite many instances of

```<code><ComboBox ItemsSource="{Binding Items}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ItemName}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate/>
</ComboBox>
</code>```

when I accidentally stumbled upon DisplayMemberPath during a marginally related StackOverflow search, which makes the above

```<code><ComboBox ItemsSource="{Binding Items}"
          DisplayMemberPath="ItemName"/>
</code>```

Now ComboBox has 158 public properties, and I really doubt that I should read all of their descriptions before even starting to use a ComboBox. On the other hand I'm really afraid of encountering this problem on a larger scale, since this is my first WPF app and I sometimes get the feeling of doing it wrong.

Note that online tutorials apart from the official documentation are very unreliable, often wrong and/or poorly written; at least I found it hard to find a good one. On the other hand, any programming books I've encountered went into too much detail, taking whole chapters explaining things that were obvious to me after the first paragraph, so I skipped a lot of parts.

When using a complex framework or library, how can I avoid accidentally skipping a relevant part of the impenetrably huge documentation, therefore creating unnecessary work for myself?

I don't think this is a duplicate of What kind of process should I use to learn a big system? or How do you dive into large code bases?, because these are about learning a codebase that you have to understand/work on/modify/improve, also assuming that you have access to the code itself. My question is about being a user of a framework, and the task at hand is "given the huge official documentation and Google, efficiently find those parts of the framework that I can use to make my work easier".

答:
When using a complex framework or library, how can I avoid accidentally skipping a relevant part of the impenetrably huge documentation, therefore creating unnecessary work for myself?

You can never know everything yourself. By exposing your code to others, you will have other people with other knowledge seeing how things are done and correcting you.

Think of colleagues, but also things like open source projects or even https://codereview.stackexchange.com/ .


问:
I don't understand the arguments against operator overloading
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.

答:
Abstraction 'hides' code so you don't have to be concerned about the inner workings and often so you can't change them, but the intention was not to prevent you from looking at it. We just make assumptions about operators and like Joel said, it could be anywhere. Having a programming feature requiring all overloaded operators to be established in a specific location may help to find it, but I'm not sure it makes using it any easier.

I don't see making * do something that doesn't closely resemble multiplication any better than a function called Get_Some_Data that deletes data.


问:
Unit testing - should tests for a method validate the results of other methods?
One thing that bothers me while I'm writing unit tests of my code is if tests of methods should include validation of the outcome of other methods? Of course, public methods. Let's see a - rather trivial - example:

```<code>public int Solve(string forumla)
{
    if (forumla.Contains("+"))
    {
        return SolveAddition(formula);
    }
    if (forumla.Contains("-"))
    {
        return SolveSubstraction(formula);
    }
    throw new ArgumentException();
}

public int SolveAddition(string formula)
{
    var strings = formula.Split('+');
    if (strings.Length != 2)
    {
        throw new ArgumentException();
    }
    int firstFactor = int.Parse(strings[0]);
    int secondFactor = int.Parse(strings[0]);
    return firstFactor + secondFactor;
}
</code>```

In this case, should tests of Solve methods only test control flow, or each possible scenario of SolveAddition? Let's assume, that SolveAddition and  SolveSubstraction have their own tests.

Using other words, did test scenarios for Solve should contains only:

2+2

2-2

2:2

Or also include:

2+2+2+2

2-2-2-2

potato - hamster

Best regards

答:
No, a unit test should test the thing it's targetting and nothing else. You're allowed to assume that any other method that this method calls does the right thing, because they must have their own unit tests.

If one of those helper methods were wrong, you'd get an alert when that other test is run, and since you're supposed to run the entire test suite and only push when the entire suite succeeds, testing the same thing a second time is just a waste of time.


问:
Is too much whitespace a bad thing?
I'm often told by my friends and colleagues that I use way to much whitespace. I guess I do use a little too much whitespace. I often add a line break almost after every line and large blocks of whitespace, often 3 or 4 lines because it helps me see what I've written and understand what I've written when I look back on it at a later time. I also think it just looks cleaner.

Although I can see two issues with this, 1) It can increase the file size of the source files, even just a line break every two or three lines can add up in a long file. I know that a good compiler will optimize all the white space out (I'm not actually sure, I think LLVM/Clang does this) but the source file is still large.

And 2) it may cause some people to think I'm embellishing my code to make it look longer and "bigger" to make others think I'm doing more work than I actually am (consider 3000 lines vs. 6000 lines, 3000 being newlines). Which I am not doing that by the way. Is using too much whitespace bad from a technical standpoint and/or a professional standpoint?

答:
Whitespace in code can be used to create emphasis, a blank line before and after a block of code can be used to indicate that the code in the block is a little closer tied to itself than it is to the surrounding code. If you put a blank line between every line of code you have prevented yourself from using this method of emphasis, so you use multiple blank lines where you need this emphasis. You gained nothing in terms of emphasis, you just gained a lot of blank lines.

You think your code looks cleaner. The funny thing about the state of being clean is that it is actually the lack of anything that is considered dirty. Looking clean, as opposed to actually being clean, simply means that you can't see the dirt. So yes, blank lines a plethora undoubtedly does make your code look cleaner as it limits how much code is visible at the same time, and therefore also how much code uncleanliness is visible at the same time. But your code simply looking clean does nothing to help you or anyone else write or maintain it. On the contrary, being able to see the dirt is a prerequisite for being able to deal with it.

There is a somewhat similar argument to be made about the much more widespread practice of excessive use of spaces, take a piece of code like:

```<code>while ( x > y || foo != bar || ! ( a in b ) ) {
</code>```

By using a style with no default spaces a few spaces could have been used to emphasise the three distinct parts of the condition:

```<code>while(x>y || foo!=bar || !(a in b)){
</code>```

If you have a hard time getting used to cutting down on whitespace consider configuring your editor to use a bigger font and/or more linespacing, then at least your colleagues can read your code without hassle, and given time you may be able to gradually change your settings towards normal.

Title: Is too much whitespace a bad thing?

Body:
Whitespace in code can be used to create emphasis, a blank line before and after a block of code can be used to indicate that the code in the block is a little closer tied to itself than it is to the surrounding code. If you put a blank line between every line of code you have prevented yourself from using this method of emphasis, so you use multiple blank lines where you need this emphasis. You gained nothing in terms of emphasis, you just gained a lot of blank lines.

You think your code looks cleaner. The funny thing about the state of being clean is that it is actually the lack of anything that is considered dirty. Looking clean, as opposed to actually being clean, simply means that you can't see the dirt. So yes, blank lines a plethora undoubtedly does make your code look cleaner as it limits how much code is visible at the same time, and therefore also how much code uncleanliness is visible at the same time. But your code simply looking clean does nothing to help you or anyone else write or maintain it. On the contrary, being able to see the dirt is a prerequisite for being able to deal with it.

There is a somewhat similar argument to be made about the much more widespread practice of excessive use of spaces, take a piece of code like:

while ( x > y || foo != bar || ! ( a in b ) ) {

By using a style with no default spaces a few spaces could have been used to emphasise the three distinct parts of the condition:

while(x>y || foo!=bar || !(a in b)){

If you have a hard time getting used to cutting down on whitespace consider configuring your editor to use a bigger font and/or more linespacing, then at least your colleagues can read your code without hassle, and given time you may be able to gradually change your settings towards normal.


问:
If your workmate is quitting his job, would you notify your boss?
If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>

答:
Generally no, for all the reasons already given. In a sane environment, nobody expects you to snitch on him.

The only possible exception might be if said coworker plans the breach his contract in a way that severely hurts your company. E.g. if he has a cancelation period of, say, 3 months, but plans to walk away without notice, it would be justified to interfere. Otherwise, just stay out.


问:
Should data be stored to local database in Android when heavily using REST services?
Let's say I have an application that has constantly changing data. Changes are so frequent that you basically need to refresh data every time you open some screen and keep refreshing it. Is it worth implementing local database for such application?

Implementing database in such application seems redundant because:

Data structure might be complex (arrays, optional parameters and etc) and so using cursors is not a very efficient way to pass it around

Data does not need to be stored for long time

If optimized to request filtered data in certain screens (to reduce data traffic), must make sure to filter database updates in such way that unfiltered data (which might be used by other screens) is not affected. Not that hard but still something to develop (and test)

However, implementing local database might mean faster navigation. But again, that's not true if service requests are highly optimized to avoid sending redundant data.

Do applications like Play Store, Facebook, Google+ use local database to replicate data structures stored in remote database? I just wanna know what is the common practice for developing applications heavily based on web services.

答:
as long as

it is ok that the app does not work when there is no networkconnection available (similar to a web-page)

your app does not need to store additional info like "user has seen this info at 15:30"

you donot need to implement a cache.

if you want to cache the data for faster access why putting it into a database with complex datastructure?

isnt it enough to save every service result as one file where the search-parameters create the filename (i.e. based on the rest-url)?

a webbrowser stores raw html/gif/css files instead of analysing it and storing in tables like page, link, caption, ....

you should already have a serialisation format for the transportation from service to android client (JSON, XML, ....) why not using this format for the file cache, too


答:
To answer directly, unit testing is critical, even for non-critical web applications. Have you considered what vulnerabilities exist in your search engine? There may be issues in your web app that some customers have noticed and not provided notification. Unit testing at the very least can check for input validation (or lack thereof) in all layers of your software.

Another thing to consider is how much you value your own time as a developer. Fixing bugs that could have been caught with simple unit tests, or making re-fixes because one defect affected another are known time-wasters. Take the effort to write unit tests.


问:
How to write JavaScript while keeping HTML/CSS out of it
What is / are some recommended ways to write JavaScript as to control behavior of showing HTML on screen, while keeping well-maintainable code?  Basically, I started to look for ways to keep HTML/CSS out of JS (assuming it's the recommended practice), but I might as well check into the latest ways of writing JavaScript well.  See below for more details.

My specific problem

I have JS files that look something like this:

var selection = eval("(" + document.getElementById("result").innerHTML + ")");

if (selection[index].selected) {
    result += '
';
    result += '
';
    result += 'Data	';
    result += '
';

    var flag = "All";

    if (selection[index].flag == 'P')
        flag = "Premium";

    result += '
';
    result += 'Flag	';
    result += '' + flag + '	';
    result += '
';
    result += '
';
}

document.getElementById('final').innerHTML = result;
```

In fact, entire JS codebase I work with is plagued by this.  You can see here HTML, CSS JS, and JSON (selection var gets its content from JSON prepared by PHP earlier).  I want to make this better.

My experience level

I am new to writing good JS or to having experience with JS patterns, tools, tips, techniques, and so on.  I am looking for help with those.

My specific issue:

I have a series of tables and data to be shown to the user.  It is a "series", so user can select which "element" of the series is currently active on the screen.  An "element" is essentially an HTML partial (with JS and CSS and HTML), and is described below:

"element":  a block of HTML that serves as static data (tables, titles, and divs), and a long JSON string that encodes some previously prepared data.  JSON string is assigned to a JS variable and that JSON data/JS variable stores records numbered 1 through n, where each i holds various data to be injected into the block of HTML, forming "HTML partial".

I have navigational buttons on the screen, allowing user to step through the "series", where the HTML is the same, but the data inside it changes.

I am looking for a good way to write this "step through HTML blocks" functionality using what is considered to be good maintainable JS code.  Namely, I am looking for the following characteristics:

separation of concern

cleaner code - I need tools or techniques to allow me to avoid mixing HTML with JS with CSS (as in seen my example), unless where necessary or convenient.  (what I have now is not convenient)

I prefer techniques rather than tools, but open to considering/evaluating well-established tools.  By "techniques", I mean pure JS, HTML, CSS, PHP approaches.  By "tools", I currently know and trust jQuery, and for other tools prefer to have some track record to them.

Note on HTML visibility/hiding

I should also perhaps note that in my case HTML is static, aka it does not change structurally, as I step through the elements.  However, based on the JSON/selection variable, some blocks of HTML are show/hidden (as is shown in my example).  Once they are shown/hidden at page render time, they stay shown/hidden throughout stepping through selection.

答:
Loading data

var selection = eval("(" + document.getElementById("result").innerHTML + ")");
```
<p>That is a pretty horrible method. First of all, any legal HTML tags in the JSON code would be parsed as so, this could be used for an injection attack. Second, depending on browser, a lot details may be different in the <code>innerHTML</code> string from the original text. In general, setting <code>innerHTML</code> should be done with caution, and only if it provides substantial advantages to the alternatives. And I simply can't think of any legitimate reasons for reading from <code>innerHTML</code>.</p>
<p>I would consider a separate JSON file loaded with <code>XMLHttpRequest</code> to be the prime method for delivering data to a JavaScript browser application. On the back-end you can generate the JSON file with PHP if you like.</p>
<p>If you really want the data directly in the HTML file a much better place to put it would be inside a script tag, PHP can do that just fine:</p>
<pre class="lang-html prettyprint-override"><code><script>
    var dataFromServer = <?php echo str_replace('</','<\\/',$wellFormedJSON)?>
</script>
</code>```

Note that since the sequence </script> may be part of well-formed JSON, but not part of JavaScript in an HTML file it is necessary to escape the </ sequence, this is usually done as <\/ which is equivalent as part of a JSON or JavaScript string.

Alternately you can make a JSONP file and load it with a normal script tag, but note that this makes the data available to other domains, thus you cannot put private data in such a file.

Dynamic page

Hiding and showing elements using CSS is a reasonable method of making dynamic content, but it doesn't work for everything, and it places the HTML far from the code that modifies it, which can be a bit of a pain.

innerHTML seems easy to use, unfortunately it is a method quite prone to introducing security issues, as what you thought was simple text may be interpreted as HTML tags. It is perfectly possible to use innerHTML in a safe manner by escaping everything dangerous, but you only need to make one mistake to introduce a hole. It is usually the best performing method of generating new DOM, but save for the few cases where this actually matters I'd advice that you stay clear of it, especially as an inexperienced developer.

You can create DOM elements using document.createElement and related methods. It is relatively straightforward and doesn't have any security traps. It also allows attaching functions in a local scope as event handlers, which is quite nifty once you start using closures. But the resulting code tend to be quite long and a somewhat tedious to write, which I would consider the primary reason to get a library for DOM building.

Body:
Loading data

var selection = eval("(" + document.getElementById("result").innerHTML + ")");

That is a pretty horrible method. First of all, any legal HTML tags in the JSON code would be parsed as so, this could be used for an injection attack. Second, depending on browser, a lot details may be different in the innerHTML string from the original text. In general, setting innerHTML should be done with caution, and only if it provides substantial advantages to the alternatives. And I simply can't think of any legitimate reasons for reading from innerHTML.

I would consider a separate JSON file loaded with XMLHttpRequest to be the prime method for delivering data to a JavaScript browser application. On the back-end you can generate the JSON file with PHP if you like.

If you really want the data directly in the HTML file a much better place to put it would be inside a script tag, PHP can do that just fine:

<script>
    var dataFromServer = <?php echo str_replace('</','<\\/',$wellFormedJSON)?>
</script>

Note that since the sequence </script> may be part of well-formed JSON, but not part of JavaScript in an HTML file it is necessary to escape the </ sequence, this is usually done as <\/ which is equivalent as part of a JSON or JavaScript string.

Alternately you can make a JSONP file and load it with a normal script tag, but note that this makes the data available to other domains, thus you cannot put private data in such a file.

Dynamic page

Hiding and showing elements using CSS is a reasonable method of making dynamic content, but it doesn't work for everything, and it places the HTML far from the code that modifies it, which can be a bit of a pain.

innerHTML seems easy to use, unfortunately it is a method quite prone to introducing security issues, as what you thought was simple text may be interpreted as HTML tags. It is perfectly possible to use innerHTML in a safe manner by escaping everything dangerous, but you only need to make one mistake to introduce a hole. It is usually the best performing method of generating new DOM, but save for the few cases where this actually matters I'd advice that you stay clear of it, especially as an inexperienced developer.

You can create DOM elements using document.createElement and related methods. It is relatively straightforward and doesn't have any security traps. It also allows attaching functions in a local scope as event handlers, which is quite nifty once you start using closures. But the resulting code tend to be quite long and a somewhat tedious to write, which I would consider the primary reason to get a library for DOM building.


答:
Adding lots of whitespace into a function may break it up into handy blocks, but it conveys no useful information.

If you feel the need to add more than one blank line between sections, you should also be adding a comment to explain what the next bit of code is going to do.

Plus, as Thomas Junk has pointed out, over-long functions would be better split into smaller, more managable ones.

Title: Is too much whitespace a bad thing?

Body:
I'm often told by my friends and colleagues that I use way to much whitespace. I guess I do use a little too much whitespace. I often add a line break almost after every line and large blocks of whitespace, often 3 or 4 lines because it helps me see what I've written and understand what I've written when I look back on it at a later time. I also think it just looks cleaner.

Although I can see two issues with this, 1) It can increase the file size of the source files, even just a line break every two or three lines can add up in a long file. I know that a good compiler will optimize all the white space out (I'm not actually sure, I think LLVM/Clang does this) but the source file is still large.

And 2) it may cause some people to think I'm embellishing my code to make it look longer and "bigger" to make others think I'm doing more work than I actually am (consider 3000 lines vs. 6000 lines, 3000 being newlines). Which I am not doing that by the way. Is using too much whitespace bad from a technical standpoint and/or a professional standpoint?


问:
Implementation strategies for atomic counter
I basically have a counter variable that is decremented and frequently polled. There are three options to implement that, that I can think of:

Number 1:

```<code>private volatile int count;
public void Finished() {
    Interlocked.Decrement(ref count);
}

public bool Done() {
    return count == 0;
}
</code>```

Number 2:

```<code>private int count;
public void Finished() {
    Interlocked.Decrement(ref count);
}

public bool Done() {
    return Volatile.Read(ref count) == 0;
}
</code>```

Number 3:

```<code>struct AtomicInteger {
    private int value;

    public int Get() {
        return Volatile.Read(ref value);
    }
    // other methods
}
// In actual class:
private AtomicInteger count;
public bool Done() {
     return count.Get() == 0;
}
</code>```

The first one gives a compiler warning because of passing a volatile variable by reference. On the other hand it's clear from the variable definition that the variable is accessed concurrently which is clearly a warning sign to anybody looking at the code.
If I ever decide that I actually need a long, this method does not work at all any more.

The second one doesn't give any warnings, but just from reading private int count it's not clear that the variable is used concurrently, so this has to be explicitly stated with a comment (I actually had a bug where I used a normal read in an assertion instead of Volatile.Read - such an easy thing to overlook.)
Changing the variable to a long on the other hand does not introduce any additional work.

I do like number 3 and it shouldn't result in any performance overhead compared to the other solutions after inlining.
Downside: Code duplication for every primitive. On the other hand the code is simple enough and can be copy-pasted without fear of problems and is unlikely to ever change.

Any comments on advantages/disadvantages of each method that I've overlooked or what would be considered idiomatic in C#?

答:
None of those are actually atomic. The idiomatic approach would be something like</p>

```<code>class Countdown {
  private int count;

  public Countdown(int ct) {
    count = ct;
  }

 public bool Do(Action stuff) { // or whatever good name makes sense; possibly Func<T> returning T not bool
     var isDone = Interlocked.Decrement(ref count) == 0;
     if (!isDone) {
          // possibly try/catch
          stuff();
          return true;
     }

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

Body:
None of those are actually atomic. The idiomatic approach would be something like

class Countdown {
  private int count;

  public Countdown(int ct) {
    count = ct;
  }

 public bool Do(Action stuff) { // or whatever good name makes sense; possibly Func<T> returning T not bool
     var isDone = Interlocked.Decrement(ref count) == 0;
     if (!isDone) {
          // possibly try/catch
          stuff();
          return true;
     }

     return false;
  }
}


问:
Should all HTTP requests including credentials be made using a POST even if it is actually just a request for data?
Assume there is a request which is going to look up a list of items from a service which requires authorisation (e.g. it's behind a Basic Authentication domain). If the service didn't require authentication, I would always make this request as a GET (it's idempotent). But because the credentials would end up in the query string, I'm basically required to do this as a POST. Is there any alternative to this method?</p>

答:
If you let the browser handle the authentication, it will pop-up a login screen.  The results will be included in a request header rather than as query parameters.  This login header will be included in every request after the user logs in until the browser is closed.

If you want your own login form, then you will need to POST the id and password to keep them from being query parameters.  After the login, you need to use a mechanism to track the login.  This is usually done with a session id cookie, although there are mechanisms to include the session id in the URL.  With session ids the userid and password only need to be sent once.  This is more secure, if you allow the user to access the site using HTTP after login.  Consider using a secure cookie for the session id if you want to restrict logged in access to HTTPS.


答:
Given that thread-safety is a very tricky issue, I can't comment on the correctness of this code. If you spot an error, just let me know and it will edit or delete my answer.

As an overview of the purpose of the various memory semantics modifiers in C#, please see:

SO: Volatile vs. Interlocked vs. lock

Note: do not take the accepted answer at face-value. Read the reference links (especially from the authors of C# specification and framework) and decide for yourself.

Also recommended:

Eric Lippert's Blog at MSDN Atomicity, volatility and immutability are different, part three

Also, Joe Duffy's Volatile class, which is part of .NET 4.5

Sayonara volatile

Also, note the difference between "ought to be" vs. "the way it is / will be implemented". Pragmatically, only the latter matters.

Based on feedback from @Euphoric, it appears that OP's Number 2 is indeed the solution that will satisfy OP's requirement.

Wrapping of the code into a class (i.e. Number 3) is a matter of coding style and refactoring.

Title: Implementation strategies for atomic counter

Body:
I basically have a counter variable that is decremented and frequently polled. There are three options to implement that, that I can think of:

Number 1:

```<code>private volatile int count;
public void Finished() {
    Interlocked.Decrement(ref count);
}

public bool Done() {
    return count == 0;
}
</code>```

Number 2:

```<code>private int count;
public void Finished() {
    Interlocked.Decrement(ref count);
}

public bool Done() {
    return Volatile.Read(ref count) == 0;
}
</code>```

Number 3:

```<code>struct AtomicInteger {
    private int value;

    public int Get() {
        return Volatile.Read(ref value);
    }
    // other methods
}
// In actual class:
private AtomicInteger count;
public bool Done() {
     return count.Get() == 0;
}
</code>```

The first one gives a compiler warning because of passing a volatile variable by reference. On the other hand it's clear from the variable definition that the variable is accessed concurrently which is clearly a warning sign to anybody looking at the code.
If I ever decide that I actually need a long, this method does not work at all any more.

The second one doesn't give any warnings, but just from reading private int count it's not clear that the variable is used concurrently, so this has to be explicitly stated with a comment (I actually had a bug where I used a normal read in an assertion instead of Volatile.Read - such an easy thing to overlook.)
Changing the variable to a long on the other hand does not introduce any additional work.

I do like number 3 and it shouldn't result in any performance overhead compared to the other solutions after inlining.
Downside: Code duplication for every primitive. On the other hand the code is simple enough and can be copy-pasted without fear of problems and is unlikely to ever change.

Any comments on advantages/disadvantages of each method that I've overlooked or what would be considered idiomatic in C#?

ContentLicense: CC BY-SA 4.0


问:
How to allow multiple plugins to provide data for multiple aggregation processes?
I'm working on a Java project in which we want to have data collection plugins that collect data to be processed by one or more data aggregation modules. The plugins will all written in-house. Say for example we have data collection plugins A, B and C and data aggegration module X. The modules A, B & C input data into tables that are different but have a few certain fields in common that X cares about. Sometimes the names of the fields are different, but as far as the algorithm is concerned they are "the same".

What's the best way to get X to operate on these different data sources while still allowing for a new data collection plugin D to be integrated, as well as the possibility of a new aggregation module Y that operates on some or all of the data sources?

My main concerns are about dependencies - for example, should the data collection plugins know about the aggregation modules, or the other way round? Or neither? Should the collection plugins implement interfaces that the aggregators can then make use of, and if so then where should be interfaces be defined?

答:
Provide a API containing the Interfaces and the JavaDoc that the AggregationModul respects, you can add some tools, you can add some extra custom-annotations like @MustBeThredSave or @DoNotSynchronize or @Obsolete, a few simple Tools like conversation-methods or Helper are ok in the api too. Use @Documented and @Since-Annotations too, use them to let the InputModules know when a Version will support the Modul.

JSF handle this by having a jsf-impl.jar and a jsf-api.jar and it works like a charm.

Also its a good idea to use the SecurityManager in the AggregationModul and the InputModuls A,B,C (http://docs.oracle.com/javase/tutorial/security/userperm/).


问:
Client-side coding: How to prevent malicious use?
Over the last few years, the trend for client-side (browser) applications has really taken off.

For my latest project, I have decided to try and move with the times and write a client-side application.

Part of this application involves sending transaction emails to users (for example, validate signup, password reset emails, etc.). I am using a third-party API to send the emails.

Normally I would have my application running on a server. I would call the third-party API from code on my server.

Running a client-side application means this now needs to happen on a user's browser. The third-party API provides the necessary JavaScript files to achieve this.

The first glaring issue I can see is I need to use an API key. This would normally be safely stored on my server, but now presumably I will need to provide this key to the client browser.

Assuming I can get round this problem, the next problem is what stops a tech-savvy user loading up the JavaScript developers tool on a browser and using the email API anyway they like, rather than say adhering to any rules I have set in the application.

I guess my general question is - how can we prevent malicious use of a client-side application?

答:
I'd argue that you really can't.  If you're willing to send the data to the client, you must expect that it will be abused - however possible.  Your example regarding the API key is illustrative of the point, and I would not include that in your client side JS - it will be stolen and abused.

You definitely will still need some amount of server code to keep things secure.  Even something as simple as retrieving just the data related to the logged in user.  That authentication can't all be done client side or again you will be taken advantage of and your data is not secure.

I would always view the JS client side experience to be an addition to server code.  Validation on client provides a nice user experience, but if you don't verify that POST data on the receiving server as well, you're opening yourself up to attack.  Anything from the client should be considered suspect.


答: I think that overloading math operators is not the real issue with operator overloading in C++. I think overloading operators that should not rely on the context of the expression (i.e. type) is "evil". E.g. overloading , [ ] ( ) -> ->* new delete or even the unary *. You have a certain set of expectations from those operators that should never change.

Title: I don't understand the arguments against operator overloading

Body:
I just read one of Joel's articles in which he says:

In general, I have to admit that I’m a little bit scared of language features that hide things. When you see the code

```<code>i = j * 5;
</code>```

… in C you know, at least, that j is being multiplied by five and the results stored in i.

But if you see that same snippet of code in C++, you don’t know anything. Nothing. The only way to know what’s really happening in C++ is to find out what types i and j are, something which might be declared somewhere altogether else. That’s because j might be of a type that has operator* overloaded and it does something terribly witty when you try to multiply it.

(Emphasis mine.) Scared of language features that hide things? How can you be scared of that? Isn't hiding things (also known as abstraction) one of the key ideas of object-oriented programming? Everytime you call a method a.foo(b), you don't have any idea what that might do. You have to find out what types a and b are, something which might be declared somewhere  altogether else. So should we do away with object-oriented programming, because it hides too much things from the programmer?

And how is j * 5 any different from j.multiply(5), which you might have to write in a language that does not support operator overloading? Again, you would have to find out the type of j and peek inside the multiply method, because lo and behold, j might be of a type that has a multiply method that does something terribly witty.

"Muahaha, I'm an evil programmer that names a method multiply, but what it actually does is totally obscure and non-intuitive and has absolutely nothing to do whatsoever with multiplying things." Is that a scenario we must take into consideration when designing a programming language? Then we have to abandon identifiers from programming languages on the grounds that they might be misleading!

If you want to know what a method does, you can either glance at the documentation or peek inside the implementation. Operator overloading is just syntactic sugar, and I don't see how it changes the game at all.

Please enlighten me.


答:
You can't, and the more people understand this, and the deeper they understand, the better for the world.

Code that runs on a device under the user's control cannot be controlled. Smartphones can be jailbroken. Set-top boxes can be cracked. Ordinary browsers don't even attempt to prevent access to JavaScript code. If you have something worth stealing or abusing, a determined attacker will be able to do that unless you validate everything you cherish server-side.

Obfuscation is of very little help; the kind of opponent you will attract as soon as anything remotely financial is involved reads assembly language like classified ads. Encryption cannot help you, because the device that would guard the key is the same device you have to assume is cracked. There are many other, seemingly-obvious countermeasures that don't work, for similar reasons.

Unfortunately, this is a very inconvenient truth. The world is full of small-time and big-time operators who think they can somehow get around the fundamental brokenness of remote trust, simply because it would be oh so nice if we could assume that our code will be run the way we assumed. And yes, it would make everything so much easier that it isn't even funny. But wishing doesn't make it so, and hoping against hope that you are the one smart cookie who can avoid the unpleasantness will only burn you and your clients. Therefore, get into the mindset that the Internet is enemy territory, include that added cost in your estimates, and you'll be fine.

That said, of course there is such a thing as defense in depth. Obfuscating your JavaScript doesn't put off a determined attacker, but it may put off some less-determined attackers. If your assets are worth enough to protect, but not at any cost, any of those measures may add business value to your system; it just can't be perfect. As long as you are fully aware of the trade-off you are making, that may be a reasonable strategy.

Title: Client-side coding: How to prevent malicious use?

Body:
Over the last few years, the trend for client-side (browser) applications has really taken off.

For my latest project, I have decided to try and move with the times and write a client-side application.

Part of this application involves sending transaction emails to users (for example, validate signup, password reset emails, etc.). I am using a third-party API to send the emails.

Normally I would have my application running on a server. I would call the third-party API from code on my server.

Running a client-side application means this now needs to happen on a user's browser. The third-party API provides the necessary JavaScript files to achieve this.

The first glaring issue I can see is I need to use an API key. This would normally be safely stored on my server, but now presumably I will need to provide this key to the client browser.

Assuming I can get round this problem, the next problem is what stops a tech-savvy user loading up the JavaScript developers tool on a browser and using the email API anyway they like, rather than say adhering to any rules I have set in the application.

I guess my general question is - how can we prevent malicious use of a client-side application?


答:
This is exactly the case where making it a completely client-side application is not appropriate.

You can make the logic and basic validation of forms client-side (you still have to revalidate on server, because someone may try to fake the request) to improve responsiveness, you can do HTTP requests from JavaScript passing data there and back in JSON to avoid re-sending page decorations and such, but if the transaction itself needs to be authenticated and authorized, it should still happen on a server.


问:
Will object reuse optimize this often-called function?
Suppose I have a function that I need to call a lot, maybe a few thousand times on every mouse down or mouse move. It uses an instance of a function (class), called Transform:

```<code>function func1(a, b, c) {
  var t = new Transform();
  t.rotate(a);
  t.scale(b, c);
  return t.m[0];
}
</code>```

So I'm creating thousands of new transforms as I call this func1 lots.

What if, instead of creating new Transform()s every time, I created a small system to allocate extra transforms only as they are needed, and re-use them:

```<code>window.Util = {
  _CachedTransforms: [],
  tempTransform: function() {
    var arr = Util._CachedTransforms;
    var temp = arr.pop();
    if (temp === undefined) return new Transform();
    return temp;
  },
  freeTransform: function(temp) {
    Util._CachedTransforms.push(temp);
  }
}
</code>```

Then instead I could call func2:

```<code>function func2(a, b, c) {
  var t = Util.tempTransform();
  t.reset();
  t.rotate(a);
  t.scale(b, c);
  var result = t.m[0];
  Util.freeTransform(t);
  return result;
}
</code>```

Using func2 several thousand times, new Transform is only ever called once. This might suggest a benefit, but the numbers from jsperf don't seem to suggest any.

If you want to see these two functions in action as well as the Transform class, take a look at jsperf: http://jsperf.com/transforms

And especially: http://jsperf.com/transforms/2

To simulate it occuring lots during an event, my jsperf test does:

```<code>var a;
for (var i = 0; i < 4000; i++) {
  a += func1(1, i, 3); // vs func2
}
</code>```

There may be better ways to test if this is advantageous or not. Am I missing something?

More broadly, is object reuse like this still a good idea in this scenario, or ever?

答:
This is a method known as "object pooling", and you are correct that it can speed up performance. Object creation is usually a fairly inexpensive task in Javascript (though Object.create can be pretty slow surprisingly in my experience), but needing to invoke the GC repeatedly can cause noticeable performance issues.

Of course, you should only optimize if you have figures that suggest you have to.

I'm kind of on the same page as Avner Shahar-Kashtan in that object creation might not even be required in this case.

OwnerDisplayName: Simon Sarris