答:
If you reasonably expect you will principally be writing code during lifetime, or hell, even if not -- you should get an extensible editor/IDE and start learning it. If you can't afford anything, go with Notepad++ or similar -- something that will let you begin on your life-long task of deciding "how I like my hotkeys", and learning the conventional ones.

Your tooling IDE's, as I call them -- Visual Studio, Eclipse, What-have-you, will come and go and evolve, often becoming too bulky and non-responsive to be used when you just want to blurt out code, or massage/refactor it in certain ways.

Thus, you have your "home" editor, the one that stays with you a lifetime, whom you love more than your GF.

You will get to the point where it will be perfectly natural and productive to work on something using both your Tooling IDE and your Home IDE at the same time, leveraging the best of both worlds.

My Home IDE is SlickEdit, which I have used and extended over the last 10+ years, in such time I have written 120+ Macro modules for it, and I have 1000+ hotkeys going.

Do I remember them all? No, probably about half at any given time, maybe 60%, but the others are for specialized tasks, that I end up looking up in an on-demand fashion.

Remember, life is short, and if you do the math on any big project you will see that even if benevolent aliens where telepathically dictating perfect code into your head for you to type out 8 hours a day -- it would still take MONTHS to write something big (without a smart editor, macros, templates, etc).

This is why. Plan long term, pave the road into the future every so often.

Actually, very often. Even though it costs you now.


问:
Does an unexperienced programmer need an IDE?
Reading this other question makes me wonder if I (as an absolute beginner PHP programmer) should stick with WAMP and Notepad++ or to switch to some IDE like Eclipse.

It's understandable that skilled developers will benefit from a big shiny IDE. But why should an absolute beginner use an IDE? Do the benefits outweigh the extra challenge of learning the IDE on top of learning to develop?

Update for clarification:

My goal is to get some basic programming experience. By choosing PHP and WAMP (and FogBugz and Kiln) I hope to avoid having to navigate the tricky / messy OS specifics and compiling etc. and just focus on basic functionality like an online user registration form.

I've got lots of theoretical understanding from university a decade ago but no practical experience. I want to remedy that with a hobby project that would be similar to a real-world sellable web app.

There are so many questions to ask. So many pitfalls I probably have to blunder into. This question is just one piece (my first!) of that puzzle.

答:
As someone trying to learn a new language on a small hobby project I would say stick to a text editor with syntax highlighting.

When you are first starting out you are going to make mistakes. You will forget a semi-colon somewhere or misspell a variable name. Without and IDE you will have to focus just on the language and how you wrote it. This is valuable learning.

A big shiny IDE will try to save you time by trying to catch these mistakes, which robs you from your learning. Also as others have said learning the IDE will also place more overhead on your learning. Imagine when the IDE suggests something, you will wonder why it is making the suggestion, or even is it the right thing. This will just add confusion.

I like to start a new language with just the text editor, then I look into any Eclipse plug-ins once I'm confident enough.

ContentLicense: CC BY-SA 3.0


问:
How do I get over my .NET hump?
I've been teaching myself how to write code with the help of a very talented friend, who unfortunately is talented enough that he has never free time. I've read and worked out of a couple books, but I feel more like I'm going through motions, rather than elegantly solving real world problems. What did you guys do to get out of your larval stage?

Is there a course or educational product out there that isn't quite the $1500 all encompassing lecture, but more than just a dry,"regurgitate this example," type book?

答:
You need something forgiving, cheap, ubiquitous that will allow you to write cool stuff fast and learn OO principles without involving a lot of libraries, which are a mountain to climb in themselves.

The answer is Javascript and the DOM. The challenge is, write your own windowing/control system from scratch. No helper libraries. Once you have written the sizable, draggable, minimizable, etc window, implement all the standard controls. If you get this far you should have a decent grasp of OO and architecture and be itching to do something "real" where all the controls are provided for you (C#). If not, you might continue making a GUI designer for all your controls, and give them persistence.

You will stumble, you will fall, you will bleed and be scarred -- but you will know the minefield now, the WHY and not just the HOW.

Sure, you can steal bits of code from the net, but be sure to make it your own, make it something other than what it was, better, more integrated, more intelligent.

Once you feel at ease with JS, moving to C# is much more fluid.

Another approach if this sounds too cheesy for your abilities, is to go into ActionScript, try to build the same spec I have given on that platform.

Title: How do I get over my .NET hump?


问:
How can I motivate myself to start learning more?
I've been interested in programming for a while now, and have been slowly, slowly, slowly working on things over the years. However, I don't feel like I've learned much.

I've only really stuck with familiar languages (Java, C# and I've tried a little bit of PHP). The problem is that in those languages, I've only brushed upon the surface of them and have restricted myself to doing fairly simple things.

For example, as a Java project, I've downloaded the source code for some game and changed a few things to my liking, but nothing terribly difficult. In C#, I've made a few WinForm and console projects to do some repetitious or routine tasks for me, which is nice, but again nothing too complicated.

I've just barely begun to grasp the concept of classes, multithreading and some basic but essential tools that are required in modern object-oriented programming. ("Why can't I just shove everything into one monster-sized class?" "Why can't I just run everything in one thread?" are questions I used to wonder about)

I've never made a large project by myself. Ultimately, my kind of "dream" hobby project is that I would like to create a game using DirectX technology. I say that because I've used XNA but it requires the user to install a framework to get it running, and I also feel that if I use the framework, that a lot of the back-end work is being obscured from me. (DirectX or OpenGL seem to be about as close to the machine as I can get without going overboard in complexity. DirectX is also installed on most [if not all] Windows machines that plan on running games.)

But I haven't even begun to even think about starting that. The amount of things I need to know to undertake a task is absolutely overwhelming. I wouldn't know where to begin. Likewise, I also feel inadequate because I've restricted myself to [what I see as] easy languages. I feel like I should start learning some scripting language or learn this or learn that, which is quite daunting.

--

tl;dr: I've been slowly teaching myself to program for a while now, but have been restricting my knowledge to limited languages and only scratching the surface of what I can do. I want to learn more and possibly start a decent-sized project (I can only make so many text-based RPGs and calculators), but the massive amount of knowledge I'll need is very intimidating.

One of my concerns is that I know so little about programming languages in general. Is it better to learn several languages or to be able to delve deep into one single language?

How can I motivate myself to learn more?

Am I thinking about this the wrong way?

答:
I would ask myself 3 questions:

What is smallest/attainable step I need to take first? Break down the long term into small bite-size tasks.

Why did I get into programing in the first place? Go back to your real passion and use that as your fuel for motivation.

Who do I know who can work on a project with me? Accountability is key in accomplishing tasks that seem overwhelming.

ContentLicense: CC BY-SA 2.5


问:
Should I refactor this rails application?
I have taken over the code base for a ruby-on-rails application which relies very heavily on ActiveRecord callbacks to perform domain rules.

The application can be compared to a bank application, where a customer has an Account. On each account you can register a Transaction (an amount of money that is either inserted or removed from the account). The Account has an account_balance that is updated every time a transaction is created. This update happens as an ActiveRecord callback.

```<code>class Account < ActiveRecord::Base

  has_many :transactions

  def update_account_balance
    account_balance = 0
    self.transaction_logs.each do |transaction|
      account_balance = account_balance + (transaction.amount + transaction.commission)
    end
    self.account_balance = account_balance
  end
end

class Transaction < ActiveRecord::Base

  belongs_to :account

  after_save :update_account_value

  def update_account_value
    self.account.update_account_balance
    self.account.save!
  end
end
</code>```

I find that this way of coding makes it very difficult to figure out what happens (and what goes wrong when a bug occurs). Also, since the account needs to load all transactions, this will be heavier as more and more transactions are added.

Had I been developing an application like this in .NET (in which I am much more familiar) I would have created something like this:

```<code>public class Account {

  public void AddTransaction(decimal amount) {
    this.Transactions.Add(new Transaction(amount));
    this.AccountValue += amount;
  }
}
</code>```

And then made sure that a Transaction object is immutable.

I am very tempted to refactor the system into something like that. But should I? Would that be the "rails way"?

The drawback, as far as I can tell, is that my controller needs to explicitly handle controlling database transactions, something which happened implicitly in the Transaction.save! call currently called in the application. Are there other factors I should be aware of?

答:
The existing application logic isn't terrible. I wouldn't make any changes move logic up into the controller; that's the opposite direction from the preferred methodology of pushing logic down into the model as much as possible.

The only thing that sticks out to me as potentially (or perhaps inevitably) dangerous is that, as you mentioned, Account#update_account_balance is iterating over every transaction to find what its balance should be, every time a new Transaction is saved. This is not only a potential performance bottleneck, but also a potential race condition, if two transactions are saved at nearly the same time and one is excluded from the set returned by the call to Account#transaction_logs.

My suggested refactoring:

class Account < ActiveRecord::Base
  attr_protected :account_balance

  has_many :transactions

  def update_account_balance(transaction)
    self.account_balance = (self.account_balance + transaction.amount + transaction.commission)
    self.save!
  end

end

class Transaction < ActiveRecord::Base
  attr_readonly :amount, :commission

  belongs_to :account

end

class TransactionObserver < ActiveRecord::Observer

  def after_create(transaction)
    transaction.account.update_account_balance(transaction)
  end

end
```

The use of ActiveRecord::Observer here helps you to follow the Single Responsibility Principle; updating an Account isn't part of the core responsibility of a Transaction, but it does have to occur each time a Transaction is persisted.

The use of attr_readonly in Transaction protects the values from update operations, and attr_protected prevents mass assignment on :account_balance.

Body:
The existing application logic isn't terrible. I wouldn't make any changes move logic up into the controller; that's the opposite direction from the preferred methodology of pushing logic down into the model as much as possible.

The only thing that sticks out to me as potentially (or perhaps inevitably) dangerous is that, as you mentioned, Account#update_account_balance is iterating over every transaction to find what its balance should be, every time a new Transaction is saved. This is not only a potential performance bottleneck, but also a potential race condition, if two transactions are saved at nearly the same time and one is excluded from the set returned by the call to Account#transaction_logs.

My suggested refactoring:

class Account < ActiveRecord::Base
  attr_protected :account_balance

  has_many :transactions

  def update_account_balance(transaction)
    self.account_balance = (self.account_balance + transaction.amount + transaction.commission)
    self.save!
  end

end

class Transaction < ActiveRecord::Base
  attr_readonly :amount, :commission

  belongs_to :account

end

class TransactionObserver < ActiveRecord::Observer

  def after_create(transaction)
    transaction.account.update_account_balance(transaction)
  end

end

The use of ActiveRecord::Observer here helps you to follow the Single Responsibility Principle; updating an Account isn't part of the core responsibility of a Transaction, but it does have to occur each time a Transaction is persisted.

The use of attr_readonly in Transaction protects the values from update operations, and attr_protected prevents mass assignment on :account_balance.


问:
Technique for multiple users on same datasets
This is more a learning question than coding, but I'm certain it's a common issue for anyone developing administration systems or applications in php/mysql/js etc.

I've developed quite a complex application that lets users upload images, and define hotspots in them with associated actions. The images are stored in a table, and the actions in another, with json data for every action in a text field. However, like I say, the problem is generic.

Basically, my fear is that if someone is editing the same image and set of actions at the same time, and they both submit changes, or if it was edited by someone else then there's a whole series of structures that potentially will fail on submission.

I don't want to implement a locking system, as the system is very wide ranging (links to other images, etc), and I think it's a bit ugly. I saw this link (MSDN Multi-tenant architecture article) in another question, but it seems a little overwhelming and specialised for sql server.

So - what are the terms for data and system architecture here that I can investigate, or are there some good articles to do with this topic that people can recommend? Specifically for php/web world would be great!

答:
In a lot of situations, the simple technique of "last writer wins" can be sufficient.

Last writer wins means that the last person to save has his changes kept; any changes made while that person was editing are lost.

While this might seem a crazy approach, consider that in many systems the source of change is to synchronise with the real world.

Consider a system listing customers with their addresses and phone numbers. Imagine that one of their customers, Mary, has recently moved house. She sent in a change of address card to  your compand. Her husband, John, didn't know about this and has phoned in to update details through the customer centre. Coincidentally, the change of address card is being processed concurrently with the phone call.

Which change should be kept? It doesn't matter - because both edits will be changing the house address to the same value.

You also need to keep in mind the potential frequency of concurrent updates - it's actually pretty unlikely that the phone call and processing of the change of address card would happen at the same time. If the card was processed first, John would find the details already correct when he called; if the card was processed last, the operator would find the details already correct. In either case, no conflict.


问:
Porting library, what to do with JavaDoc comments/credits
I ported a library to Java, but am wondering what to do with the JavaDoc comments. The original library used javadoc comments too, so do I leave the @author tags from the original code? And how do I give myself credit as the person who ported it over?</p>

答:
The license that governs the original code will likely define what is required - many licenses require you to explicitly give credit if you create a derived work.

In terms of what is appropriate, I'd suggest that it's always appropriate to give credit to your sources, for example:

```<code>@author Java port by Adam Harte, based on ActionScript original by Bill Gates
</code>```

(And yes, I know this isn't accurate, as the OP didn't tell us the original language or author, it's just an example.)

Body:
The license that governs the original code will likely define what is required - many licenses require you to explicitly give credit if you create a derived work.

In terms of what is appropriate, I'd suggest that it's always appropriate to give credit to your sources, for example:

@author Java port by Adam Harte, based on ActionScript original by Bill Gates

(And yes, I know this isn't accurate, as the OP didn't tell us the original language or author, it's just an example.)


答:
I always use an IDE (Eclipse) and would recommend it even for a beginner. Main advantages if you are starting out:

Instant feedback on bad code (e.g. syntax errors in code)

Takes care of setting up projects using standard conventions so you don't have to worry about configuration / OS specifics etc.

Can often generate sample code that you can build upon and learn from

Avoids you having to remember a whole set of arcane command line options and invocations so you can focus on the code.

However, although I think you should use an IDE in gerneral, I think it is worth doing at least one or two manual executions of your code at the command line. This is so that you understand what is happening under the hood. This understanding will help you if you need to debug issues later on.

Title: Does an unexperienced programmer need an IDE?

Body:
Reading this other question makes me wonder if I (as an absolute beginner PHP programmer) should stick with WAMP and Notepad++ or to switch to some IDE like Eclipse.

It's understandable that skilled developers will benefit from a big shiny IDE. But why should an absolute beginner use an IDE? Do the benefits outweigh the extra challenge of learning the IDE on top of learning to develop?

Update for clarification:

My goal is to get some basic programming experience. By choosing PHP and WAMP (and FogBugz and Kiln) I hope to avoid having to navigate the tricky / messy OS specifics and compiling etc. and just focus on basic functionality like an online user registration form.

I've got lots of theoretical understanding from university a decade ago but no practical experience. I want to remedy that with a hobby project that would be similar to a real-world sellable web app.

There are so many questions to ask. So many pitfalls I probably have to blunder into. This question is just one piece (my first!) of that puzzle.


问:
Rails generators for subscription and payment processing services?
I've been thinking about making a generator for managing subscriptions with options for a couple different payment processing services, it is something that I would use. Are there any existing examples of this, or any thoughts on a generator. I thought it might work like the scaffold function, similar to the authentication function in nifty-generators.

EDIT: Also, It seems that there should be a lot of security concerns when implementing payment processing, having a consistent and common way to generate this would let me make sure best practices and security are followed the same in all my apps.

答:
Given the pain you'll experience when you start to navigate the byzantine requirements of PCI compliance, I think "best practices" in this area is not to handle payment processing in the first place.

At least, not within your application.

Stripe is an online payment processor geared toward developers. It's a breeze to accept credit card payments through their API, and it offloads responsibility (and liability) for PCI regulation issues to someone else. Which is a Good Thing.

There's even a Railscasts episode all about using Stripe to handle payments, and the stripe-rails gem will bootstrap the process for you.

Oh, and Stripe handles periodic billing (for subscriptions) for you.

Before you head down this road, I highly recommend taking a look at available technologies you might leverage. Although the code for payment processing is often fairly straightforward, the liability issues are massive.

P.S. I don't work for Stripe or anything. I just think their product/service is excellent, and a good match for your use case.


问:
Organizing Class Members in Regards to Access Modifier
If we look at typical implementation of a Class, we usually see the private members defined at the beginning and public( mostly functions and Accessors) defined towards the bottom. Now, is this a Industry standard agreed by a lot of people?

How about keeping the private members towards the end as updates and additions are usually done to the Public Members(mostly functions), to fix bug or provide enhancement, so we don't have to scroll down towards the end to get to the function definition section.

I understand, good IDEs will allow us to Jump towards a specific attribute, but considering other factors, such as Code Review, it may be convenient to have the Public Definitions towards the beginning.

What is the most accepted standard for Class Member Organization?

答:
I use the following breakdown and will try to justify it after the description.

```<code><class>
members (as in vars)
  internal members
    internal const members
    internal static members
     internal static const members
  (repeat with public, protected, private)
properties (same as members)
  ...
ctors (internal, public, protected, private)
commands (ie void returns, or success or other returns that are not pure functions)
  (internal, etc)
event handlers
 control event handlers
 remote event handlers
 other event handlers
functions (ie queries)
 (internal, etc)
</code>```

You will notice an indentation scheme applied here. This is to indicate the presence of what I call the structured comments template which is created first thing when the file is blank. What the comments do is give you proper indentation layout (for code folding) and slots where new members are inserted according to the given attributes.

Here is a peak at that in C#, though I also use it for other languages.

The top:

```<code>//# namespace
  // Z_DOT package UtilsCL ::UtilsWin32::UtilsCL:UtilsWin32.cs  z.6566885600116177.2009.04.27.14.18.06|package
    namespace UtilsCL{
      //#class
        // Z_DOT class UtilsWin32::UtilsWin32::UtilsCL:UtilsWin32.cs  z.3959885600116177.2009.04.27.14.18.09|static-class
           /// <summary>
           /// Win32 PInvoke
           /// </summary>
          // ReSharper disable ClassNeverInstantiated.Global
          public class UtilsWin32{
            // ReSharper restore ClassNeverInstantiated.Global
            // ReSharper restore UnusedMember.Global
            //#, members
                 // ReSharper disable UnusedMember.Local
                  /// <summary>
                  /// Does nothing
                  /// </summary>
                 private void __(){
                   // ReSharper restore UnusedMember.Local
                 }
              //#i, internal    members
                //;
                //#i*, internal static     members
                  //;
                  //#i*@, internal static const members
                    //;
                //#i@, internal const     members
                  //;
                //;
</code>```

A midsection, note the comment:

```<code>//#-. private                      properties
  //;
  //#-*. private static     properties
    //;
    //#-*@. private static const properties
      // ReSharper disable InconsistentNaming
      // ReSharper disable UnaccessedField.Local
      #pragma warning disable 169
       /// <summary>
       /// Private Static Const Properties
       /// </summary>
      [SuppressMessage("Gendarme.Rules.Performance", "AvoidUnusedPrivateFieldsRule")]
      private static object __God_private_static_const_properties;
      #pragma warning restore 169
      // ReSharper restore InconsistentNaming// ReSharper restore UnaccessedField.Local
      #region "private_static_const_properties"
      // Z_DOT ppt  def:Set ::God::mrobbinsassoc::com::OmegaApp:God.cs  z.7121082100597177.2009.10.18.23.33.21|-*@.
         /// <summary>
         /// Gets the def.
         /// </summary>
         /// <value>The def. from Settings.Default</value>
        // ReSharper disable MemberCanBePrivate.Global
        private static Set def{
          // ReSharper restore MemberCanBePrivate.Global
          get{
            return Set.Default;
          }
        }
      //;                        //<====================== Insertion POINT
      #endregion
  //#-@. private const     properties
</code>```

Now, for the promised justification, having member vars at the top is the programmers view of things obviously not the best for the client, but that is why we have Doc Tools right?

Keeping code as rigid as this I am sure has its benefits for doing diffs. Also the general layout forces you to think about the architecture you are building. During the workflow I am putting in those Z_DOT identifiers via a macro which relies on the fn sig to be present and proper, before I hit that macro I affirm that I am scoping the member correctly etc. "Is this really what I want to do" instead of just injecting code anywhere in the class where I happen to be sitting and then reordering it later (ie if I wasn't using such a strict system)

The main benefit is now I can write macros that address the code precisely, as well as create external analysis/refactoring/generation tools.

It is very useful to have this second-level breakdown of not only access modifier, but of var, property backer, properties, commands, events, and (pure) functions. It gives you a view-on-things and makes you think in terms of that view.

Wire up a few macros to take you to each insertion point in the file (which doesn't actually have that big arrow thing I put there to demo it) and you are good to go.

Body:
I use the following breakdown and will try to justify it after the description.

<class>
members (as in vars)
  internal members
    internal const members
    internal static members
     internal static const members
  (repeat with public, protected, private)
properties (same as members)
  ...
ctors (internal, public, protected, private)
commands (ie void returns, or success or other returns that are not pure functions)
  (internal, etc)
event handlers
 control event handlers
 remote event handlers
 other event handlers
functions (ie queries)
 (internal, etc)

You will notice an indentation scheme applied here. This is to indicate the presence of what I call the structured comments template which is created first thing when the file is blank. What the comments do is give you proper indentation layout (for code folding) and slots where new members are inserted according to the given attributes.

Here is a peak at that in C#, though I also use it for other languages.

The top:

//# namespace
  // Z_DOT package UtilsCL ::UtilsWin32::UtilsCL:UtilsWin32.cs  z.6566885600116177.2009.04.27.14.18.06|package
    namespace UtilsCL{
      //#class
        // Z_DOT class UtilsWin32::UtilsWin32::UtilsCL:UtilsWin32.cs  z.3959885600116177.2009.04.27.14.18.09|static-class
           /// <summary>
           /// Win32 PInvoke
           /// </summary>
          // ReSharper disable ClassNeverInstantiated.Global
          public class UtilsWin32{
            // ReSharper restore ClassNeverInstantiated.Global
            // ReSharper restore UnusedMember.Global
            //#, members
                 // ReSharper disable UnusedMember.Local
                  /// <summary>
                  /// Does nothing
                  /// </summary>
                 private void __(){
                   // ReSharper restore UnusedMember.Local
                 }
              //#i, internal    members
                //;
                //#i*, internal static     members
                  //;
                  //#i*@, internal static const members
                    //;
                //#i@, internal const     members
                  //;
                //;

A midsection, note the comment:

//#-. private                      properties
  //;
  //#-*. private static     properties
    //;
    //#-*@. private static const properties
      // ReSharper disable InconsistentNaming
      // ReSharper disable UnaccessedField.Local
      #pragma warning disable 169
       /// <summary>
       /// Private Static Const Properties
       /// </summary>
      [SuppressMessage("Gendarme.Rules.Performance", "AvoidUnusedPrivateFieldsRule")]
      private static object __God_private_static_const_properties;
      #pragma warning restore 169
      // ReSharper restore InconsistentNaming// ReSharper restore UnaccessedField.Local
      #region "private_static_const_properties"
      // Z_DOT ppt  def:Set ::God::mrobbinsassoc::com::OmegaApp:God.cs  z.7121082100597177.2009.10.18.23.33.21|-*@.
         /// <summary>
         /// Gets the def.
         /// </summary>
         /// <value>The def. from Settings.Default</value>
        // ReSharper disable MemberCanBePrivate.Global
        private static Set def{
          // ReSharper restore MemberCanBePrivate.Global
          get{
            return Set.Default;
          }
        }
      //;                        //<====================== Insertion POINT
      #endregion
  //#-@. private const     properties

Now, for the promised justification, having member vars at the top is the programmers view of things obviously not the best for the client, but that is why we have Doc Tools right?

Keeping code as rigid as this I am sure has its benefits for doing diffs. Also the general layout forces you to think about the architecture you are building. During the workflow I am putting in those Z_DOT identifiers via a macro which relies on the fn sig to be present and proper, before I hit that macro I affirm that I am scoping the member correctly etc. "Is this really what I want to do" instead of just injecting code anywhere in the class where I happen to be sitting and then reordering it later (ie if I wasn't using such a strict system)

The main benefit is now I can write macros that address the code precisely, as well as create external analysis/refactoring/generation tools.

It is very useful to have this second-level breakdown of not only access modifier, but of var, property backer, properties, commands, events, and (pure) functions. It gives you a view-on-things and makes you think in terms of that view.

Wire up a few macros to take you to each insertion point in the file (which doesn't actually have that big arrow thing I put there to demo it) and you are good to go.


问:
Best practices for team workflow with RoR/Github for designer + coder?
My friend and I have started to try to collaborate on some projects. For background, I come from a PHP/Wordpress/Drupal coding background, but recently I've become more experienced with the RoR framework, while he is more experienced as an HTML/CSS designer, working with PHP and WordPress.

We're both relatively new to RoR I think, and so we're trying to figure out our collaborative workflow, but we have no idea where to start.

For instance, we were trying to figure out how he could do some minor edits to the CSS file without having to do a full RoR deploy on his box. We still haven't figured out a solution, so I think it's best if we start to set some sort of workflow based on best practices.

I was wondering if you guys have any insight or links to articles/case studies regarding this topic?

答:
Particularly if you're targeting Rails 3.1, he'll need to be able to run rails on his own machine because the asset pipeline produces all of your CSS and JavaScript from Sass and CoffeeScript source in app/assets. (You can still use regular CSS and JavaScript, but once your designer friend tries Sass, he'll never want to go back).

But a 'full rails deployment' for development is pretty straightforward:

Install Ruby

sudo gem install rails

????

PROFIT

I would do this: generate the scaffold for a dummy resource just to have something to design against. Then you'll at least have some views for him to work with. He can get started on the styles, scripting, and layouts while you start building out the logic. Use Github Issues to keep track of who's working on what, and to reassign issues based on when things are ready for him to start creating the views. And as Samus_ mentioned, definitely use topic branches as you work, merging features back into master as they are completed.

Also, take a look at Haml. Every designer I've ever introduced to Haml wept openly for joy (slight exaggeration) because it's so much more elegant than HTML.

OwnerDisplayName: Josh


问:
C++ for C# Developers
I know C# pretty well (self-taught, sadly) and need to do some C++ programming for a Windows application.  I have been able to find a ton of information for C++ developers learning C# but haven't been able to find much on learning C++ when you already know C#.  Has anyone come across a good rundown of the basics?

MSDN has a comparison but it is not very in-depth.

I can piece together several sources but figured something was out there - I just can't find it.  Thanks for your help.

答: I would recommend going to Rosetta Code and comparing the two. While you are there keep handy a link of C++ idioms and try to spot them. Then spend some time on the pointer/reference/memory/destructor realm. After that learn about the preprocessor -- it can really be your friend when it comes to hiding the uglies, I kind of miss it. Finally, the STL.</p>

Title: C++ for C# Developers


问:
Best practices in comment writing and documentation
Commenting nowadays is easier than ever.  In Java, there are some nice techniques for linking comments to classes, and Java IDEs are good at making comment shells for you. Languages like Clojure even allow you to add a description of a function in the function code itself as an argument.

However we still live in an age where there are often obsolete or poor comments written by good developers - I'm interested in improving the robustness and usefulness of my comments.

In particular I'm interested in Java/Clojure/Python here, but answers don't need be language-specific.

Are there any emerging techniques that validate comments and automatically detect either "flimsy" comments (for example comments with magic numbers, incomplete sentences, etc..) or incorrect comments (for example, detecting mispelled variables or the like).

And more importantly: Are there accepted "commenting-policies" or strategies out there? There is plenty of advice out there on how to code - but what about "how to comment?"

答:
Specific to Java one source I've enjoyed is Oracle's How to Write Doc Comments for the Javadoc Tool:

This document describes the style guide, tag and image conventions we use in documentation comments for Java programs written at Java Software, Sun Microsystems.

And Item 44: Write doc comments for all exposed API elements:

If an API is to be usable, it must be documented. Traditionally API documentation was generated manually, and keeping it in sync with code was a chore. The Java programming environment eases this task with the Javadoc utility. Javadoc generates API documentation automatically from source code with specially formatted documentation comments, more commonly known as doc comments.

from Effective Java 2nd Edition.


问:
Is there really such a thing as "push"?
Once you escape the realm of electrical signals and are dealing with software, is there really such a thing as a "push" architecture where there isn't periodic polling?

I can't think of any design where it's not polling at some level. It seems like it's always just a level or two beneath the actual abstraction/API you are dealing with. Sockets at the receiving end of most "push" connections just poll for incoming requests, etc.

答: I think Windows required applications to poll for IO until NT and Windows 95. Modern general purpose operating systems have pretty much eliminated the need for polling. When your application requests to read from a socket, the read function has to make a call to operating system kernel. The OS puts the calling thread into a suspended state. As network packets come in they trigger a hardware interrupt that is handled by the OS. If the packet is the one your application is looking for, the OS takes the thread out of the suspended state, and the read can proceed. In other words your application is in fact coupled to the realm of the electrical signals via the OS.</p>

OwnerDisplayName: John Cromartie

Title: Is there really such a thing as "push"?


问:
Are buffer overflows no longer a threat these days?
After following buffer overflow examples and reading on them in various books/websites it seems there are lots of preventative measures in place to protect against them these days. ASLR, /GS flag security cookie, stack-protector in linux, etc, etc...

Some of the examples I have looked at give instructions on how to disable certain security features so that the examples will run...This seems like a really stupid idea to me - when running code against a real system you are not going to have the luxury of disabling its security features.

So what is the deal with buffer overflows these days, have them been rendered redundant by advances in security or are they still of use?

答:
Yes, they are of use, and yes, the protections are routinely turned off, off by default, or non-existant on various platforms.

To make the point explicit, I'm sure a modern product developed by smart people like Google Chrome would never have something as mundane as a buffer overflow. (Pick any word; those are just from 2011.)

EDIT To the question of why. Lots of answers. One simple one is that canaries only protect the return address, not the individual variables on the stack. Nor do stack canaries or non-executable stacks protect against heap-based overflows. If you have writable vtables (or any kind of function pointer), then attackers can rewrite your function calls on the stack or heap without touching the canary. There's a major performance trade-off for every additional protection you put in. And the stricter you make your execution environment, the more likely you won't be able to reuse legacy code without reworking it (and retesting it).

Attackers have to be more clever today than when Aleph One was writing about stack smashing. Some of the older attacks don't work widely anymore. But the basic idea of a buffer overflow has many forms, and many of those forms still work.

OwnerDisplayName: John McDonald

OwnerDisplayName: Rob Napier


答:
Three words:  "Defense In Depth".

The meaning:  The more you can do to prevent vulnerabilities, the better.  Don't rely on any one thing (or even a couple of things) to protect you.  They could be broken -- or, as you've seen, disabled.

Consider that even if you turn on all the paranoid security measures, if someone figures out how (or is lucky enough) to bypass any or all of the countermeasures put in place by your OS, then your only remaining defense is the correctness and robustness of your own code.

Plus, arbitrary code execution is just the worst of the worst as far as vulnerabilities go.  Whether your broken code allows arbitrary native code execution or just crashes, that's still someone else causing your computer to do something it shouldn't, and potentially costing you lots of money.

Title: Are buffer overflows no longer a threat these days?

Body:
After following buffer overflow examples and reading on them in various books/websites it seems there are lots of preventative measures in place to protect against them these days. ASLR, /GS flag security cookie, stack-protector in linux, etc, etc...

Some of the examples I have looked at give instructions on how to disable certain security features so that the examples will run...This seems like a really stupid idea to me - when running code against a real system you are not going to have the luxury of disabling its security features.

So what is the deal with buffer overflows these days, have them been rendered redundant by advances in security or are they still of use?

OwnerDisplayName: cHao


答: A lot of these countermeasures can be defeated by advanced exploitation techniques such as Return Oriented Programming (ROP). To answer your question, anti-exploitation techniques have made things much more difficult for a would-be attacker to exploit a buffer overflow but it's absolutely still possible and the severity of the consequences when one is successfully exploited is very high, as they typically allow arbitrary code execution.</p>

OwnerDisplayName: jeffsix


答:
In my computer science classes, we did not start off with an IDE. It was something we did AFTER we understood what we were doing.

IDEs tend to abstract away too much for beginners and ends up producing educated fools. In the beginning, it is critical you get a good understanding or you will end up thinking in the IDE alone and cannot figure out basic things without it. You will also be limited to only what the IDE can do. Some IDEs are downright malicious in having such abstractions and having their own paradigm that it actually makes people dumber using it. Case in point web forms for ASP.NET.

There is something to be said for bootstrapping yourself.


答:
I would also consider sockets that Charles already presented to certainly be "push" design. He walked you all the way from the realm of the electrical signals up, but another topic to consider are "push" designs which are purely application architecture decisions and happen at much higher abstraction layers.

Typical event frameworks would be considered push, since event source will fire events regardless of who is listening for them, or if the event sink is able to keep up with those events.

Another example, which is the area where I work in, is video streaming. We work with RTP (real-time transport protocol). It is UDP/IP based and by nature it is a push protocol. The sender will keep sending video at the rate it chooses without ever caring if the receiver is keeping up with it.

Title: Is there really such a thing as "push"?

Body:
Once you escape the realm of electrical signals and are dealing with software, is there really such a thing as a "push" architecture where there isn't periodic polling?

I can't think of any design where it's not polling at some level. It seems like it's always just a level or two beneath the actual abstraction/API you are dealing with. Sockets at the receiving end of most "push" connections just poll for incoming requests, etc.


问:
How important are Haskell's advanced concepts like Monads and Applicative Functors for most routine programming tasks?
I've read the Learn You a Haskell book up to the point where they introduce Monads and stuff like Just a. These are so counterintuitive for me that I just feel like giving up trying to learn it.

But I really want to try.

I'm wondering if I can at least avoid the advanced concepts for a while and just starting using the other parts of the language to do a lot of practical tasks with the more basic parts of Haskell, i.e. functions, standard IO, file handling, database interfacing and the like.

Is this a reasonable approach to learning how to use Haskell?

答:
How important are Haskell's advanced concepts like Monads and Applicative Functors for most routine programming tasks?

They are essential. Without them, it's all too easy to use Haskell as just another imperative language, and although Simon Peyton Jones once called Haskell, "the world's finest imperative programming language", you're still missing out on the best part.

Monads, Monad Transforms, Monoids, Functors, Applicative Functors, Contravarient Functors, Arrows, Categories, etc, are design patterns. Once you fit the specific thing that your making into one of them, you are able to draw on a huge wealth of functions that are written abstractly. These type-classes are not simply there to confuse you, they're there to make your life easier and to make you more productive. They are, in my opinion, the biggest reason for the conciseness of good Haskell code.


问:
Do Universal iOS Apps have more "issues" when new versions of iOS come out?
I was discussing developing an iOS App with a client and I mentioned that we should ideally have a Universal App that would perform as an iPhone App on an iPhone and as an iPad App on an iPad.

The client likes the idea of an iPad-specific version of the App but prefers the idea of a separate App entirely for the iPad version. And not for some "Angry Birds/Angry Birds HD" type of reason (the App in question will be free, so there's nothing to be gained financially) but rather because "other [organizations in his industry] have told him" that "Universal Apps have more compatibility issues with older devices when new versions of the operating system [iOS] are released" and having discrete apps for this alleviates this issue.

I believe he may have been referring to the concept of an App requiring a version of iOS that is more recent than the last one available on the phone. Or maybe the concept of releasing an App or an update that requires a version of iOS beyond the last one available on a device (original iPhone is stuck at 3.1.3 forever, iPhone 3G is stuck at 4.2.1 forever). But I presume you can still make a Universal App for 3.1.3 since the original iPad shipped with iOS 3.2 and Universal Apps existed before 4.0. And while I'm having a difficult time finding out what the minimum iOS version is for Apps submitted to the App Store, I presume that the original iPhone can still download and buy Apps or else the one guy in the office here who still has his OG iPhone would probably have complained more by now.

But I really don't know. Do Universal Apps have more issues with compatibility on devices (and more specifically older devices) than individually developed separate (but otherwise pretty equivalent) Apps? Has anyone ever run into this?

答:
Hi I have been in iOS development since last 2 years.

Answer:

1) No this is not at all true. In fact it is better to build a Universal app rather than separate iPhone and iPad versions of the App. As such if there is not much difference in iPhone and iPad version of the application functionality-wise, then it is better that we make a universal app. It saves a lot of effort and time and also it is convenient for the end users as most of them would want to buy one app and use it on their multiple iDevices.

2) Also one more point from programmer's perspective is that it is very much easier when the client wants updates in the application once it is released as we as programmers have to make changes in the same application rather than two parallel applications.

Conclusion:

So overall, I would say that Universal apps are "better" than separate versions of the app and also there is no extra problems faced when new iOS version is out.

Hope this helps you.


问:
Polymorphism confusion
I have read once in a book about exception where "an object of type Exception can be an instance of any
subclassof Exception". I kinda get it, but there's still confusion can anyone clarify me the meaning of this? </p>

答:
Exception subclasses consist of objects that extend Exception, ie NullPointerException, ClassNotFoundException, OutOfRangeException.  Only subclasses of Exception will ever be an Exception object.

From wikipedia;

In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects.

Boxer, Beagle, Collie = Subclasses of Dog

Title: Polymorphism confusion


答:
Author means to say that base class pointers can point to any object of derived classes.

A derived class will have the public/protected members of the base class. So, the casting is implicit and not harmful.

Example:
We have a class vehicle.

Class car is derived from it, and so is truck.

So, if you create an object of car or truck type, the object can obviously point to its base class vehicle. This crux of it is the is-a relationship. A car is-a vehicle.

Title: Polymorphism confusion

Body:
I have read once in a book about exception where "an object of type Exception can be an instance of any
subclassof Exception". I kinda get it, but there's still confusion can anyone clarify me the meaning of this? </p>


答: The point the author is getting at is when you have a variable that's declared to be of type Exception, the actual object assigned to that variable is not necessarily an instance of Exception itself - it may also be any of the subclasses of Exception.

Title: Polymorphism confusion


问:
What is the "architecture" that provides functionality to application-level URI interfaces, like chrome:// and Firefox's about:config, etc?
According to Wikipedia,

about is an internal URI scheme (also known as a "URL scheme" or, erroneously, "protocol") in various web browsers to display certain built-in functions. It is not an officially registered scheme, and has no standard syntax.

my question is...  what "powers" these "interfaces"? there doesn't seem to be any kind of "application server" running - that would conventionally support such a front-end - were it to be running remotely.. i'm sure the reason for the dearth of information out there - is that these all break the psuedo-promise that anything "you do" in the browser - won't "effect" your system.  these interfaces clearly have access to system level resources and permissions, etc..  are they all simply custom, c-coded hooks to the internal code of the parent applications - or are they a more abstract, ui--layer?

i admit to little knowledge of plug-in authoring, but can this type of functionality be achieved via the typical plug-in API's, or are they too limited? i have spent some time in the webkit source code poking around - but it is so massive and convoluted that its hard to deduct much...

it would seem that however these vendors are implementing these features might be an appealing alternative to say, the various language-specific bridges that webkit implements on various platforms.  i personally find the bridges frustrating, which is probably what led me down this train of thought...

any insights appreciated.

答:
As already said in two previous answers, those are not real schemes with system hooks, but just a browser feature which responds to some types of addresses.

I just want to add that there is a simple way to figure it out:

If it was a real scheme or a hook, it would work in any browser.

Open Chrome.

Open Internet Explorer.

Open chrome://settings/ in IE.

You see a 404 instead of Chrome Settings. A scheme or hook is not intended to behave like this: it is expected to work for any browser, either by showing something, like http://, or by redirecting the user to an external application, like ed2k://, or by showing an error message, like unexistent://.

If it was a real scheme, it would be registered. In Windows, for example, this means that there would be a registry key in a specific place for this scheme.

these all break the psuedo-promise that anything "you do" in the browser - won't "effect" your system. these interfaces clearly have access to system level resources and permissions

What makes you think so? In Windows, an URL scheme is just a registry key. If Chrome registered the chrome:// scheme, a call to chrome://hello/world would call an instance of chrome.exe, passing hello/world as an argument. Yes, installation of Chrome affected your system by adding another registry key, but any installation of any software affects your system. Browser sandbox model remains active: it's not by calling a registered scheme that you'll break something (well, you can, and to avoid this, browsers ask you to confirm what you're doing when using a new scheme for the first time).


问:
How is Scala scalable?

Possible Duplicate:

  Why is Scala more scalable than other languages?

The Wikipedia page on Scala says:

The name Scala is a portmanteau of "scalable" and "language", signifying that it is designed to grow with the demands of its users.

I've also read that:

And that's Scala's dirty little secret. Scala is only scalable in the sense that it runs on the reliable, high-performing JVM platform.

and also that "languages don't scale, platforms scale."

How does Scala grow with demands of its users? Isn't it true to say that Scala "actually is scalable"? And as per line just above, isn't every language scalable?

答:
Scala is very concise. The language allows you to write small scripts and simple programs with very few lines of code. Scala is excellent for small programs and removes much of the boilerplate you'd have to add in Java. For example Scala scripts don't even have to declare a Main class as entry point.

For medium sized projects Scala has very comfortable syntax that makes declarations short and precise. First class functions, closures and the likes help you to concentrate on the logic itself, not how to map it to language concepts

Scala excels at large projects. The beautiful mix of object-oriented and functional programming helps you to follow almost any programming pattern. Implicit conversions, traits, actors, ....

Title: How is Scala scalable?


问:
What is the best IDE for Scala?
I tried programming Scala in Netbeans and Eclipse, but it is not what I'm looking for. In Netbeans suggestions for method names etc. are not working. In Eclipse I can't go to some classes sources by pressing F3. (e.g. scala List).

Is support in IntelliJ IDEA any better? Are there other IDE's supporting Scala?

答:
There's an official plugin for eclipse now.
http://scala-ide.org/
I've tried it myself and it works perfect. Nevertheless all the IDEs here are great. They will probably all do what you want. You should go with the one you feel most comfortable with.</p>

Title: What is the best IDE for Scala?


问:
Do you write bad code when under pressure?
When you are under pressure, the deadline is approaching, and a manager is breathing down your neck do you find yourself starting to write bad code? Do TDD and best practices slip by the wayside in order to get things done? What do you do in situations like that? What were your experiences?</p>

答:
Depends.

Is the pressure because there is no way everything can get done and because major new features are being added hours before release?

Bad code coming up!

But if it is because the schedule is simply really really tight but the overall plan is solid and I just have to work much harder than usual and keep continually focused while tweaking a few features hear and there... Then I produce much better code than if the schedule allows tons of time. Even if it means I don't get all the unit tests written but cover the major parts of the code.


问:
Why doesn't "object reference not set to an instance of an object" tell us which object?
We're launching a system, and we sometimes get the famous exception NullReferenceException with the message Object reference not set to an instance of an object.

However, in a method where we have almost 20 objects, having a log which says an object is null, is really of no use at all. It's like telling you, when you are the security agent of a seminar, that a man among 100 attendees is a terrorist. That's really of no use to you at all. You should get more information, if you want to detect which man is the threatening man.

Likewise, if we want to remove the bug, we do need to know which object is null.

Now, something has obsessed my mind for several months, and that is:

Why doesn't .NET give us the name, or at least the type of the object reference, which is null?. Can't it understand the type from reflection or any other source?

Also, what are the best practices to understand which object is null? Should we always test nullability of objects in these contexts manually and log the result? Is there a better way?

Update:
The exception The system cannot find the file specified has the same nature. You can't find which file, until you attach to the process and debug. I guess these types of exceptions can become more intelligent. Wouldn't it be better if .NET could tell us c:\temp.txt doesn't exist. instead of that general message? As a developer, I vote yes.

答:
Your log should include a stack trace - that usually gives you a hint as to which line in the method has the problem. You may need to make your release build include PDB symbols so you have an idea which line the error is on.

Granted, it won't help you in this case:

```<code>Foo.Bar.Baz.DoSomething()
</code>```

The tell don't ask principle can help to avoid such code.

As to why the information isn't included, I'm not sure - I suspect that at least in a debug build, if they really wanted to, they could figure it out. Taking a crash dump and opening in WinDBG may help.

Body:
Your log should include a stack trace - that usually gives you a hint as to which line in the method has the problem. You may need to make your release build include PDB symbols so you have an idea which line the error is on.

Granted, it won't help you in this case:

Foo.Bar.Baz.DoSomething()

The tell don't ask principle can help to avoid such code.

As to why the information isn't included, I'm not sure - I suspect that at least in a debug build, if they really wanted to, they could figure it out. Taking a crash dump and opening in WinDBG may help.


答:
The NullReferenceException basically tells you: you are doing it wrong. Nothing more, nothing less. It's not a full-fledged debugging tool, on the contrary. In this case I'd say you're doing it wrong both because

there is a NullReferenceException

you didn't prevent it in a way you know why/where it happened

and also maybe: a method requiring 20 objects seems a bit off

I'm a big fan of checking everything before things start going wrong, and providing good information to the developer. In short: write checks using ArgumentNullException and the likes and write the name yourself. Here's a sample:

void Method(string a, SomeObject b)
{
    if (a == null) throw ArgumentNullException("a");
    if (b == null) throw ArgumentNullException("b");

    // See how nice this is, and what peace of mind this provides? As long as
    // nothing modifies a or b you can use them here and be 100% sure they're not
    // null. Should they be when entering the method, at least you know which one
    // is null.
    var c = FetchSomeObject();
    if(c == null)
    {
        throw InvalidOperationException("Fetching B failed!!");
    }

    // etc.
}
```
<p>You could also look into Code Contracts, it has it quirks but it works pretty well and saves you some typing.</p>
<p><strong>update</strong> in .Net 6 there's ThrowIfNull which removes the need for stating the parameter name. And since C# version 6, there's the nameof operator removing the rather error-prone need to repeat the argument name in a hardcoded string.</p>
```void Method(string a, SomeObject b)
{
  //.Net 6
  ArgumentNullException.ThrowIfNull(a);

  //C# 6
  if (b == null) {
    throw new ArgumentNullException(nameof(b));
  }
}
```

As to why this is not the default: we can only guess (or try to dig up notes somehow from people working on C# and/or .Net). My guess:

sometimes it's not needed or wanted

sometimes the message should have more than just the parameter name

there are alternatives (stacktrace, adding it manually)

it gives developers a choice

adding this everywhere by default isn't cheap because it means nearly all argument and variable names must be added as strings in the executable

Title: Why doesn't "object reference not set to an instance of an object" tell us which object?

Body:
We're launching a system, and we sometimes get the famous exception NullReferenceException with the message Object reference not set to an instance of an object.

However, in a method where we have almost 20 objects, having a log which says an object is null, is really of no use at all. It's like telling you, when you are the security agent of a seminar, that a man among 100 attendees is a terrorist. That's really of no use to you at all. You should get more information, if you want to detect which man is the threatening man.

Likewise, if we want to remove the bug, we do need to know which object is null.

Now, something has obsessed my mind for several months, and that is:

Why doesn't .NET give us the name, or at least the type of the object reference, which is null?. Can't it understand the type from reflection or any other source?

Also, what are the best practices to understand which object is null? Should we always test nullability of objects in these contexts manually and log the result? Is there a better way?

Update:
The exception The system cannot find the file specified has the same nature. You can't find which file, until you attach to the process and debug. I guess these types of exceptions can become more intelligent. Wouldn't it be better if .NET could tell us c:\temp.txt doesn't exist. instead of that general message? As a developer, I vote yes.

Body:
The NullReferenceException basically tells you: you are doing it wrong. Nothing more, nothing less. It's not a full-fledged debugging tool, on the contrary. In this case I'd say you're doing it wrong both because

there is a NullReferenceException

you didn't prevent it in a way you know why/where it happened

and also maybe: a method requiring 20 objects seems a bit off

I'm a big fan of checking everything before things start going wrong, and providing good information to the developer. In short: write checks using ArgumentNullException and the likes and write the name yourself. Here's a sample:

void Method(string a, SomeObject b)
{
    if (a == null) throw ArgumentNullException("a");
    if (b == null) throw ArgumentNullException("b");

    // See how nice this is, and what peace of mind this provides? As long as
    // nothing modifies a or b you can use them here and be 100% sure they're not
    // null. Should they be when entering the method, at least you know which one
    // is null.
    var c = FetchSomeObject();
    if(c == null)
    {
        throw InvalidOperationException("Fetching B failed!!");
    }

    // etc.
}

You could also look into Code Contracts, it has it quirks but it works pretty well and saves you some typing.

update in .Net 6 there's ThrowIfNull which removes the need for stating the parameter name. And since C# version 6, there's the nameof operator removing the rather error-prone need to repeat the argument name in a hardcoded string.

void Method(string a, SomeObject b)
{
  //.Net 6
  ArgumentNullException.ThrowIfNull(a);

  //C# 6
  if (b == null) {
    throw new ArgumentNullException(nameof(b));
  }
}

As to why this is not the default: we can only guess (or try to dig up notes somehow from people working on C# and/or .Net). My guess:

sometimes it's not needed or wanted

sometimes the message should have more than just the parameter name

there are alternatives (stacktrace, adding it manually)

it gives developers a choice

adding this everywhere by default isn't cheap because it means nearly all argument and variable names must be added as strings in the executable

ContentLicense: CC BY-SA 4.0


问:
UUID collisions
Has anybody done any real research on the probability of UUID collisions, especially with version 4 (random) UUIDs, given that the random number generators we use aren't truly random and that we might have dozens or hundreds of identical machines running the same code generating UUIDs?

My co-workers consider testing for UUID collision to be a complete waste of time, but I always put in code to catch a duplicate key exception from the database and try again with a new UUID.  But that's not going to solve the problem if the UUID comes from another process and refers to a real object.

答:
I've tested it once using a quite simple (brute force) program that generated 10 million UUID-s and I haven't experienced collision.

The UUID RFC says that the UUID is not just a bunch of (pseudo) random numbers.

Title: UUID collisions


问:
Optimistic work sharing on sparsely distributed systems
What would a system like BOINC look like if it were written today?
At the time BOINC was written, databases were the primary choice for maintaining a shared state and concurrency among nodes.

Since then, many approaches have been developed for tasking with optimistic concurrency (OT, synchronization primitives like vector clocks, virtual synchrony, shared iterators etc.)

Is there a paradigm for optimistically distributing units of work on sparsely distributing systems which communicate through message passing?

Sorry if this is a bit vague.

P.S.
The concept of Tuple-spaces is great, but locking is inherent to its definition.

Edit2:

The entire system is sparsely distributed - they can communicate only through WAN. And communication can be slow and faulty. The question is about how to best distribute units of work among them without a central co-ordinator and with as little consensus as possible (because consensus is expensive).

The answers here seem to be talking about databases - data isn't the problem. The problem is in distributing work.

Edit:

I already have a federation system which works well. I'm looking to extend it to get clients to do units of work.

答: The easiest solution is usually the best. There's nothing wrong with a central server distributing work to a number of workers provided you can make the jobs big enough that the overhead is not overwhelming. There's no point redesigning BOINC just because fashions have changed.</p>


问:
What suitable Q & A application can integrate with a Java portal?
I'm looking for suggestions on whether we should build or are there readymade applications that do the following:

Allow admins to build a structured
workflow of support Q & A, similar to
Windows Troubleshooting i.e. when you
try one tip, you then get the next
one.

Allow end-users to search and follow
the Q & A

We have an existing Liferay portal which we would like to plug in this app to it - is there some suitable app like a CMS which does this? I mean building the structured questions - not just plain content like a wiki.

Open source options are welcome, but I'd like to know of COTS as well.

答:
Moodle is a free CMS that has several survey-like modules. It's in PHP so it could run on a Java platform or even embed a portal within the php pages:

a Course Management System (CMS), also known as a Learning Management
  System (LMS) or a Virtual Learning Environment (VLE). It is a Free web
  application that educators can use to create effective online learning
  sites.


答: Sure there is.  UDP socket applications in Unix, for example, can be pure-push.  The best known would be the classic BSD Unix syslogd, which declares its willingness to accept incoming ("pushed") packets and processes them.  No reverse communication at the application or protocol level (the "pusher" doesn't even know if the packet was correctly received and processed).  At an API level within the receiving application, there may be polling, synchronous, or callback reception mechanisms, the latter two of which are pure-push.

Title: Is there really such a thing as "push"?


问:
Meaningful concise method naming guidelines
Recently I started releasing an open source project, while I was the only user of the library I did not care about the names, but know I want to assign clever names to each methods to make it easier to learn, but I also need to use concise names so they are easy to write as well.

I was thinking about some guidelines about the naming, I am aware of lots of guidelines that only care about letters casing or some simple notes. Here, I am looking after guidelines for meaningful but yet concise naming.

For example, this could be part of the guidelines I am looking after:

Use Add when an existing item is going to be added to a target, Use
Create when a new item is being created and added to a target.

Use Remove when an existing item is going to be removed from a target,
Use delete when an item is going to be removed permanently.

Pair AddXXX methods with RemoveXXX and Pair CreateXXX methods with
DeleteXXX methods, but do not mix them.

As the above samples show,I would like to find some online material helping me with naming methods and other item complying with English grammar and word meanings.

The above guidance may be intuitive for native English speakers, but for me that English is my second language I need to be told about things like this.

答:
Use prefix. If a bunch of methods are used to do something similar or can be in some way grouped together, put a common prefix before their names to show what these methods have in common.

Do not use unclear abbreviation if you want others to understand the names instantly (important in API naming)


问:
What are the steps in beginning a large project, when all I have is a big idea?
I am computer engineering student. I've been thinking about
how I can handle a big project. What should be my first step to reach my goal in a more efficient and effective way?

When I come up with a project, I don't know how I should start working on it. Many times, I just ignore it. However, I don't want to ignore my project ideas anymore.

Now, I am asking to all of you, can anyone share his/her experiences? How should I start a project when all I have is an idea?

答:
All the answers here are nice and all, but in all honesty, it doesn't matter how much version control, gitting, flow-chart and mark-ups you make, all that matters is that you have a functional application, a functional application is defined as one which solves the problem for which it was concieved, all the other things are pretty much irrelevant.

Start coding, code it to a functional phase, run some tests, debug, launch and re-iterate with new features and functionality (if you deem it necessary), much in the way of a lean startup - which is an agile method of managment and development to create less waste (or as someone defined: half finished masterpieces).


问:
Porting library, what to do with JavaDoc comments/credits
I ported a library to Java, but am wondering what to do with the JavaDoc comments. The original library used javadoc comments too, so do I leave the @author tags from the original code? And how do I give myself credit as the person who ported it over?</p>

答:
Legally, in most places where software is written (including NZ), your port is a copyrightable derivative work (through either translation or adaptation, it's not obvious which) based on another copyrighted work.  Assuming the license on the original work allows you to do the port at all, you must respect the rights of the original authors, including attributing their work to them.

Ethically, unless your port involves significant creative effort, it isn't even clear that you deserve any credit at all.  Many is the time I have "transliterated" an algorithm from one programming language to another, where my effort consisted merely of mapping one set of keywords and special symbols to another.  Java and C#, for example, are so closely related that I'd have a hard time claiming a copyright in any code I moved from one to the other.


问:
What programming language to choose for this XML and data processing task?
I currently code in PHP. Recently I've been working on a project using PHP and Symfony that:

reads large XML files (lots of DOM parsing/reading),

converts large XML files to large arrays,

merges 2 large arrays (lots of array sorting),

takes the 2 large arrays and turns them into a large CSV file.

I finished it in PHP but now it is kind of memory intensive and requires about 8-15 seconds to run. So now I have the following options and need help choosing one:

Try rewriting/refactoring it using better methods in PHP

Choose a different programming language (I have been wanting to learn one, possibly another language processes these things a lot faster?)

Do 1 or 2 and additionally set up something to be constantly reading xml files and write them to MongoDB documents to serve clients from the database instead of scrapping the data.

I am inclined to do 2 or 3 (using a different language), since I am sure there is another language that handles these kind of tasks much faster (e.g Python, C etc.). It's just that I am not sure which.

答:
The language I would recommend for working with XML is XSLT which is designed for this purpose. It is ideally suited to merging XML files and producing a CSV file as output.

XSLT stands for XSL Transformations, and is a W3C (World Wide Web Consortium recommendation since 1999. XML is also a W3C standard, and thus both XML and XSLT are related standards. In fact XSLT is in fact XML, so if you know XML, which presumably you do if you are working with XML documents, then you already understand the structure of an XSLT program.

Firefox, IE and Google Chrome all implement XSLT processors. Further Microsoft, Apple have implemented XSLT processors and opens source processors such as the toolkit of Gnome exist as well.

Since there have been so many implementations of XSLT processors, the offerings from major vendors are highly optimized an IMHO you are unlikely to find an alternative implementation f0r working with XML files that would outperform on speed.

According to Wikipedia:

Increasingly, however, XSLT processors use optimization techniques
  found in functional programming languages and database query
  languages, such as static rewriting of an expression tree (e.g., to
  move calculations out of loops), and lazy pipelined evaluation to
  reduce the memory footprint of intermediate results (and allow "early
  exit" when the processor can evaluate an expression such as
  following-sibling::*1 without a complete evaluation of all
  subexpressions). Many processors also use tree representations that
  are significantly more efficient (in both space and time) than
  general-purpose DOM implementations.

You may want to see these other questions as well:
https://softwareengineering.stackexchange.com/questions/25202/what-is-the-reason-for-using-xslt
& https://softwareengineering.stackexchange.com/questions/13477/xslt-for-beginners


答: If you aim at improving the runtime of your program, i think a compiled language ( c, c++ ..) would perform better than an interpreted one (PHP, python) for doing redundant tasks. On googling for an XML parser in C i found http://www.codeproject.com/KB/XML/CXMLFile.aspx. Hope this helps. </p>

Title: What programming language to choose for this XML and data processing task?

Body:
I currently code in PHP. Recently I've been working on a project using PHP and Symfony that:

reads large XML files (lots of DOM parsing/reading),

converts large XML files to large arrays,

merges 2 large arrays (lots of array sorting),

takes the 2 large arrays and turns them into a large CSV file.

I finished it in PHP but now it is kind of memory intensive and requires about 8-15 seconds to run. So now I have the following options and need help choosing one:

Try rewriting/refactoring it using better methods in PHP

Choose a different programming language (I have been wanting to learn one, possibly another language processes these things a lot faster?)

Do 1 or 2 and additionally set up something to be constantly reading xml files and write them to MongoDB documents to serve clients from the database instead of scrapping the data.

I am inclined to do 2 or 3 (using a different language), since I am sure there is another language that handles these kind of tasks much faster (e.g Python, C etc.). It's just that I am not sure which.


问:
Is there a general method to evaluate the optimality of an optimization algorithm?
is there a general method to evaluate the optimality of an optimization algorithm, for example an algorithm solving an otherwise NP-hard or NP-complete problem?

The only method I came up so far is comparing the results of the algorithm against already known optimal solutions.

If not, are there specific methods for some special problems?

EDIT To clarify: By optimality I mean how close the result is to an optimal solutions result.

答:
I don't think there's a general way of doing it, but there are certainly methods of doing so.

Take, for example, the problem SET-COVER. For those who don't know the problem is as follows:

Given a set of elements B={1,2,...,m} and a number of subsets S_1, S_2, ..., S_n whose union is B. You are trying to find the minimum number of these subsets such that the union is still B. A real-world typical example of this problem is where you're given a collection of neighborhoods and you are trying to find the optimal places to place schools such that each neighborhood is serviced less than some distance d away from the nearest school. In this case, B is the set of neighborhoods and S_x consists of all sets within d of town x.

You prove that this problem is NP-COMPLETE. However there is a simple greedy solution where you repeatedly pick the set S_i with the largest number of uncovered elements. And you can prove that this algorithm does well.

If the optimal algorithm consists of k sets, the greedy algorithm will consist of no more than k ln(n) sets where ln is the natural logarithm.


问:
Intellectual Property cost
If a piece of bespoke software was developed by a company and the Intellectual Property was retained by the company that wrote it, but now the client of the software company wants to get that source code (and its IP) how much should it cost them? How would you calculate a fair cost for the purchase of that source and IP?

UPDATE: Just to add, the software in question is of no use to anyone else (for any legitimate purpose) as it ties in directly with the business processes of one company. It is not something that can be subsequently sub-licensed or installed outside the company in question. There are links of to third party services (but these were existing services that the bespoke software had to integrate with in the first place).

答:
As much as the client is prepared to pay.

Any more and the client won't buy. Any less and the developer is selling the IP for less than its market value.

So, how much is that?

1) How much would it cost to have someone else redevelop the product? All else being equal, the developer should charge a little less to ensure that s/he gets the business.

2) How urgent is the IP aquisition? It it is urgent, the developer can charge a premium for producing the source code immediately whereas another vender will have to work on it.

3) Are there any other benefits that the client has for buying from the developer? Or from elsewhere? The developer can charge for the former, discount for the latter.

Interestingly, the original cost of developing the product and its original licencing cost need have little to do with the present price of the IP, despite the appeal factoring these in to the sale price.

So, having decided on price point, the developer must decide if s/he is willing to sell at that price. This should be based on any long-term gains / losses from selling the IP:

a) Will transfer of the IP result in lost revenue? For example, retaining the IP may mean that the developer will be paid for updates and enhancements to the original product. Are these losses covered by the payment for the IP?

b) Will retaining the IP damage the relationship with the client, resulting in loss of future business? Or will the sale result in recommendations to other clients?

Finally, the developer and client need a clear and accurate written record regarding the  terms of both the original licencing agreement and the terms of the IP sale.

Title: Intellectual Property cost


答:
Before choosing a different language, first make sure the language is the bottleneck. So did you actually measure the time for the 4 steps? Do you know that, for example, most waiting time for step 1 is spend in your language interpreter (and not caused by disk IO)? If the latter is the case, then chosing a language like C++ (or even assembler) may not bring you any relevant speed increasement.

XML processing is often dependent on the speed of the XML parser, so that may be the next thing to look at, something that is only partially language dependent. libxml is very fast, it is a C library, but also available as a PHP extension. Building large arrays may be speeded up by a language change, sorting, however, probably not (or not much), if you are using the builtin sort function of PHP (which is a library function coded most probably in C or C++ itself). And writing data into a file is mostly dominated by disk I/O  - again something where another language won't help.

So first make sure where the real problem is, otherwise you will be astonished how wrong one can be when making assumptions in optimizing without measuring.


问:
Time complexity of a nested loop where the inner value is decreased in every step
I have problems to give the right time complexity in O notation for the following loop:

```<code>k := 0
for i := 0 to N
   for j := k to M
     // something
   k = k + 1
</code>```

Where N = M. Without the modified starting value of j of the inner value this would be of course O(N * M), but with the decreasing running time of the inner loop in every step of the outer loop I am quite confused. How can this be approached?

答:
actually it's O(N*(N+1)/2)...
why ??

it's looks like this...

```<code>1
1 2
1 2 3
1 2 3 4
</code>```

gauss summation..
and because, asymptotic notation ignore constant value, then it will be O(N*N)...=)

Body:
actually it's O(N*(N+1)/2)...
why ??

it's looks like this...

1
1 2
1 2 3
1 2 3 4

gauss summation..
and because, asymptotic notation ignore constant value, then it will be O(N*N)...=)


答:
If you can learn and use tool  other than PHP then MS LinQtoXML is good option, works great for me to load XML from files, Serialize, Query XML like SQL, Add, Remove, SetValues and merge the collections.

Please check this for further detail by Microsoft LINQ to XML Overview

and this LINQ to XML vs. Other XML Technologies

Here is simple example to Generate CSV file from XML
     msdn.microsoft.com/en-us/library/bb387094.aspx

you can find .Net Mono framework and code editor to play with this from here www.mono-project.com and editor monodevelop from here monodevelop.com/ if you are not using windows platform.

Hope this will help.


问:
Is there really such a thing as "push"?
Once you escape the realm of electrical signals and are dealing with software, is there really such a thing as a "push" architecture where there isn't periodic polling?

I can't think of any design where it's not polling at some level. It seems like it's always just a level or two beneath the actual abstraction/API you are dealing with. Sockets at the receiving end of most "push" connections just poll for incoming requests, etc.

答:
websocket architecture is a push architecture, actually so is exchange & outlook.
These protocols stay connected to the server at all times and the server sends messages (pushes them) whenever there are messages...</p>

Title: Is there really such a thing as "push"?


问:
Polymorphism confusion
I have read once in a book about exception where "an object of type Exception can be an instance of any
subclassof Exception". I kinda get it, but there's still confusion can anyone clarify me the meaning of this? </p>

答:
The point of polymorphism is that objects of a certain class can be treated in the same way as objects of their parent class, although their behavior may be different.

The prime example in Java is the Object class.  All other classes in Java are subclasses of Object, and so can be used wherever Object can.  A List is an ordered collection of Objects--thus (at least prior to Java 1.5) a List could hold 3 Foo objects, 14 Bar objects, and single Bat object.  You don't necessarily know up front what the actual class of the objects in the List are, except that they are Objects.

Another good example in Java is the Number class.  An Integer is an Number, so anywhere you can use a Number, you can use an Integer, or any of the other subclasses of Number (Long, Float, Double, Short, BigDecimal, AtomicInteger, etc).  All of these subclasses of Number are a little different--Floats represent real numbers, whereas Integers represent integers--but all of them are Numbers and so can be described and accessed in terms of them being numbers.

Title: Polymorphism confusion


答:
You should certainly detect if a collision occurs, and your application should throw an exception if it does happen. E.g. if the UUID is used as primary key in the database, then the database should throw an error when inserting a colliding ID.

However, I would believe that writing code for generating a new UUID in the case of a collision and trying again to be a waste of time. The chance of a collision occurring is so small that throwing an exception would be a perfectly reasonable way of dealing with it.

Remember, it is not only a waste of your own time writing the code, but it also makes the code more complex, making it more difficult for the next person to read, for almost no gain at all.

Title: UUID collisions

Body:
Has anybody done any real research on the probability of UUID collisions, especially with version 4 (random) UUIDs, given that the random number generators we use aren't truly random and that we might have dozens or hundreds of identical machines running the same code generating UUIDs?

My co-workers consider testing for UUID collision to be a complete waste of time, but I always put in code to catch a duplicate key exception from the database and try again with a new UUID.  But that's not going to solve the problem if the UUID comes from another process and refers to a real object.


答:
Wikipedia has some details:

http://en.wikipedia.org/wiki/Universally_unique_identifier

http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates

But the probability only holds if the bits are perfectly random. However, the RFC https://www.rfc-editor.org/rfc/rfc4122#page-14 linked in the other answer defines this for version 4:

"4.4. [...] The version 4 UUID is meant for generating UUIDs from
truly-random or pseudo-random numbers. [...] Set all the other bits to
randomly (or pseudo-randomly) chosen values."

This pretty much allows anything from the xkcd random generator http://xkcd.com/221/ to a hardware device using quantum noise. The security considerations in the RFC:

"6. Distributed applications generating UUIDs at a variety of hosts
must be willing to rely on the random number source at all hosts.  If
this is not feasible, the namespace variant should be used."

I read this as: You're on your own. You're responsible for your random generator within your own application, but this and anything else is based on trust. If you don't trust your own ability to correctly understand and use the random generator of your choice, then it is indeed a good idea to check for collisions. If you do not trust the programmer of the other processes, then check for collisions or use a different UUID version.

Title: UUID collisions


答:
I want to try.

The 'something' would be done N*M if there was no 'k'.

How many 'something' would not be done because of k ?

First iteration, there will be no removed 'something'.
Second iteration, there will be one removed.
Third, two.
So, the number of 'something' that would not be done because of k is equal to sum from 1 to M.

Sum from 1 to M is equal to M*(M+1)*(1/2).
So :

O((M*N)-M(M+1)*1/2)

Title: Time complexity of a nested loop where the inner value is decreased in every step

Body:
I have problems to give the right time complexity in O notation for the following loop:

```<code>k := 0
for i := 0 to N
   for j := k to M
     // something
   k = k + 1
</code>```

Where N = M. Without the modified starting value of j of the inner value this would be of course O(N * M), but with the decreasing running time of the inner loop in every step of the outer loop I am quite confused. How can this be approached?


问:
Word for red flags / warning signs?
When reading about best practices and code reviews, I have come across a word/phrase that people on forums have used to describe code that should be a warning sign that the programmer may have missed something or made a mistake.

A sample sentence would have gone something like this: "Often if you see a single if statement with 10 ands/ors, it is a _____, though in certain cases it can be correct."

What is this word? I want to include this in a code review document I am writing.

答:
"Code smell" is probably the word you're looking for:

In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problem.

Title: Word for red flags / warning signs?


问:
How should I implement my chosen software license?
I have always kind of wondered, but never took my time to actually ask these questions regarding licensing. Most of these questions are presumably pretty basic, but I have no idea what I'm dealing with here.

The thing that baffles me the most is how exactly you "implement" the license for your OSS. Is just saying in the post you're publishing the code on, "by the way, this is licensed under GPL" enough? Or should something more delicate take place, like registering the software somewhere? Also,

If I just say I use a particular license, is that enough?

Do I add a copy of the license to the distributed code?

Am I required to add a header on every file detailing the licensing information? Do I manage this with my version control system (e.g. Subversion)?

Is the above not enough?

What are the most commonly used software licenses?

Are there any gotchas/licenses that are better left alone?

答:
I'm not a lawyer, and this depends on which country you are in.

Having said that, I understand that saying you use a particular license and attaching a notice to that effect within the source code is sufficient. Adding license text to every file is probably over-cautious.

Remember: if there is no license, then someone isn't allowed to copy your code at all under copyright law (with certain fair use exceptions).

Ultimately it's up to the courts to decide. But I think that if you published your source code with the clear intent to offer it under a particular license, a court would agree that the license was intended to apply to the complete work.

If you are choosing an open source license, please stick with one of the major ones. This avoids confusion about unusual licenses and significantly increases opportunities for collaboration and code sharing. In particular, the OSI lists a number of "Licenses that are popular and widely used or with strong communities". I'd strongly recommend sticking to one of these!

Apache License, 2.0 (Apache-2.0)

BSD 3-Clause "New" or "Revised" license (BSD-3-Clause)

BSD 3-Clause "Simplified" or "FreeBSD" license (BSD-2-Clause)

GNU General Public License (GPL)

GNU Library or "Lesser" General Public License (LGPL)

MIT license (MIT)

Mozilla Public License 2.0 (MPL-2.0)

Common Development and Distribution License (CDDL-1.0)

Eclipse Public License (EPL-1.0)

The Free Software Federation / GNU project also has some useful pages about open source licensing, including the recommended copyleft licenses.


答:
Commonly used licenses:

GNU General Public License (GPL)

GNU Affero General Public License (AGPL)

Apache license

MIT license

Typically, you will need a file called COPYING or LICENSE which includes the full-text of the license. Each file in your project should have copyright information and should say that the project is licensed under a particular license.

Most licenses include some boiler-plate text to include at the top of each file that's part of the project. The GNU project has a page explaining how to do this with their licenses.

Title: How should I implement my chosen software license?

Body:
I have always kind of wondered, but never took my time to actually ask these questions regarding licensing. Most of these questions are presumably pretty basic, but I have no idea what I'm dealing with here.

The thing that baffles me the most is how exactly you "implement" the license for your OSS. Is just saying in the post you're publishing the code on, "by the way, this is licensed under GPL" enough? Or should something more delicate take place, like registering the software somewhere? Also,

If I just say I use a particular license, is that enough?

Do I add a copy of the license to the distributed code?

Am I required to add a header on every file detailing the licensing information? Do I manage this with my version control system (e.g. Subversion)?

Is the above not enough?

What are the most commonly used software licenses?

Are there any gotchas/licenses that are better left alone?


答:
The issue you have is that if you use a "Random number generator" and you don't know how random that generator is, then the probability of collision is actually unknown. If the random number generators are correlated in some way, the probability of collision may  dramatically increase - possibly many, many orders or magnitude.

Even if you have a very small probability of collision, you have a fundamental problem: The probability is NOT 0. This means that a collision WILL eventually occur, they just won't occur very often.

The more frequently you generate and use the UUIDs the sooner that collision is likely to be seen. (generating 1 a year means a longer waiting time than generating a million per second, all other things being equal).

If that probability is finite, unknown, and you use a lot of UUIDs then you need to consider the consequences of a collision. If it is not acceptable to throw an exception and shut down a business application, then don't do it! (Examples off the top of my head: "It's OK to shut down the web server in the middle of updating a library checkin... it won't happen often" and "It's ok to shut down the payroll system in the middle of doing the pay run". These decisions may be career limiting moves.)

You may have a worse case though, again depending on your application. If you test for presence of a UUID (ie, do a lookup) and then make a new one if one is not already there - which is a common enough kind of thing to do - then you may find you are linking records or making relationships, when in fact you are hooking up 2 things via a UUID that should not be hooked up. This is something where throwing an exception won't solve anything and you have an undetectable mess created somewhere. This is the kind of thing that leads to information leakage and can be very embarrassing. (ex: Log in to your bank and find you can see the balance of somebody elses account! Bad!)

Summary: you need to consider the way your UUIDs are used, and the consequences of a collision. This determines if you should take care to detect and avoid collisions, take some simple action in the event of a collision, or do nothing. A simple, single, one-fits-all solution is likely to be inappropriate in some circumstances.

Title: UUID collisions


答:
Surprised that no one mentioned this, but instead of reading/parsing the XML data into a DOMDocument, you can use SAX processing. This means that while the XML data is read and parsed, there are functions that you add that will be executed. For example, when the starting tag of an element named "root" happens, it will execute a function called "root_start" or whatever you want.

You can use the SAX processing method by using the XML Parser library. They include a few examples.

You can then skip over storing the XML data as a DOMDocument, and store the data as those large arrays you mention. Then continue to merge/sort as you did before. This should decrease both the memory consumption and the time taken for the task.

Make sure you're using a good sorting/merging algorithm as well. You might want to do some sorting or merging while you're processing the XML document...