答: Use code generators whenever it's possible. Sometimes even Microsoft Excel (or OpenOffice Calc) turns out to be a powerful code generator tool.</p>

Title: How to become a "faster" programmer?

Body:
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

OwnerDisplayName: Canavar


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答: USE FRAMEWORKS!! Don't bother yourself with hardcoding!</p>

OwnerDisplayName: Nick Gotch

ContentLicense: CC BY-SA 2.5

Title: How to become a "faster" programmer?

OwnerDisplayName: Koosha


问:
Refactoring byzantine payment processing code on a limited budget
I've been working on a large Ruby on Rails application for several years. It was inherited in a poor state but most of the production bugs have been ironed out with time. There are some sections that have not been touched such as the payment processing code. The code works for the most part, except that whenever a charge is denied by the payment processor, the user gets a 500 error instead of a helpful message. I'd like to refactor the code to make it easier to maintain. I'll provide a brief run-down of how it works.

I've removed all the error-handling code from the following snippets.

The maze begins in a controller:

  def submit_credit_card
    ...
    @credit_card = CreditCard.new(params[:credit_card].merge(:user => @user))
    @credit_card.save
    ...
    @submission.do_initial_charge(@user)
    ...
  end
```

<p>Then in the <code>Submission</code> model:</p>

<pre class="lang-ruby prettyprint-override"><code>  def do_initial_charge(user)
    ...
    self.initial_charge = self.charges.create(:charge_type => ChargeType.find(1), :user => user)
    self.initial_charge.process!
    self.initial_charge.settled?
  end
</code>```

In the Charge model:

  aasm column: 'state' do
    ...
    event :process do
      transitions :from => [:created, :failed], :to => :settled, :guard => :transaction_successful?
    end
    ...
  end

  def initialize(*params)
    super(*params)
    ...
    self.amount = self.charge_type.amount
  end

  def transaction_successful?
    user.reload
    credit_card = CreditCard.where(user_id: user_id).last
    cct = self.cc_transactions.build(:user => user, :credit_card => credit_card, :cc_last_four => credit_card.num_last_four, :amount => amount, :charge_id => id)
    cct.process!
    if self.last_cc_transaction.success
      self.update_attribute(:processed, Time.now)
      return true
    else
      self.fail!
      return false
    end
  end
```

<p>There are a lot of questionable bits above such as reloading the <code>user</code> and finding the last <code>CreditCard</code> rather than passing in the one just saved. Also this code depends on a <code>ChargeType</code> loaded from the database with a hard-coded ID.</p>

<p>In <code>CcTransaction</code> we continue down the trail:</p>

<pre class="lang-ruby prettyprint-override"><code>  def do_process
    response = credit_card.process_transaction(self)
    self.authorization = response.authorization
    self.avs_result    = response.avs_result[:message]
    self.cvv_result    = response.cvv_result[:message]
    self.message       = response.message
    self.params        = response.params.inspect
    self.fraud_review  = response.fraud_review?
    self.success       = response.success?
    self.test          = response.test
    self.response      = response.inspect
    self.save!
    self.success
  end
</code>```

All this appears to do is save a record in the cc_transactions database table. The actual payment processing is performed in the CreditCard model. I won't bore you with the details of that class. The actual work is performed by ActiveMerchant::Billing::AuthorizeNetCimGateway.

So we have at least 5 models involved (Submission, Charge, ChargeType, CcTransaction, and CreditCard). If I were to do this from scratch, I would only use a single Payment model. There are only 2 charge types, so I would hard code those values as class variables. We don't store credit card details, so that model is unnecessary. Transaction info can be stored in the payments table. Failed payments do not need to be saved.

I could go in and do this refactoring fairly easily except for the requirement that nothing should ever go wrong on the production server. Each of the redundant classes has many methods that could be called from anywhere in the code base. There is a suite of integration tests but the coverage is not 100%.

How should I go about refactoring this while ensuring nothing breaks? If I went through the 5 payment classes and greped every method to find out where they're called there's a high probability I will miss something. The client is already used to how the current code runs and introducing any new bugs is unacceptable. Apart from increasing test coverage to 100%, is there any way to refactor this with certainty that nothing will break?

答:
Consider whether this code really needs refactoring.  The code may be ugly and aesthetically displeasing to you as a software developer, but if it works, you probably shouldn't redesign it.  And based on your question, it sounds like the code largely works.

This classic article from Joel on Software highlights all of the risks of unnecessarily rewriting code.  It is a costly, but very tempting, mistake.  The whole thing is worth reading before, but this passage about seemingly unnecessary complexity seems particularly appropriate:

Back to that two page function. Yes, I know, it's just a simple
  function to display a window, but it has grown little hairs and stuff
  on it and nobody knows why. Well, I'll tell you why: those are bug
  fixes. One of them fixes that bug that Nancy had when she tried to
  install the thing on a computer that didn't have Internet Explorer.
  Another one fixes that bug that occurs in low memory conditions.
  Another one fixes that bug that occurred when the file is on a floppy
  disk and the user yanks out the disk in the middle. That LoadLibrary
  call is ugly but it makes the code work on old versions of Windows 95.

Each of these bugs took weeks of real-world usage before they were
  found. The programmer might have spent a couple of days reproducing
  the bug in the lab and fixing it. If it's like a lot of bugs, the fix
  might be one line of code, or it might even be a couple of characters,
  but a lot of work and time went into those two characters.

Yes, the code is needlessly complex.  But still, some of the steps that seem unnecessary may be there for a reason.  And if you go to rewrite it, you will have to learn all of those lessons over again.

Reloading the user, for example, seems pointless: which is exactly why you should worry about changing it.  No developer (even a bad one) would have introduced a step like that in their initial design.  It was almost certainly put in there to fix some problem.  Maybe it is a problem that refactoring to the "correct" design will eliminate...but maybe not.

Also, another small point, I'm not convinced by your contention that it is unnecessary to save failed payments.  I can think of two strong reasons for doing so: logging evidence of possible fraud (e.g. someone trying various card numbers), and customer support (a customer claims they keep trying to pay, and it is not working...you would want evidence of any attempted payments to help troubleshoot this).  This makes me think that perhaps you haven't fully thought through the requirements of the system, and they aren't as simple as you believe they are.

Fix individual problems without fundamentally changing the design.  You mentioned one problem: there is a 500 error when the payment fails.  This problem should be easy to fix, probably just by adding one or two lines at the right location.  It isn't sufficient rationale for tearing everything apart to make the "correct" design.

There may be other problems, but if the code works 99% of the time right now, it is unlikely that these are going to be fundamental problems requiring a rewrite, either.

If the current design is embedded throughout the code, then even spending a fair amount of effort to fix a problem without changing the design may be warranted.

In some cases it may, indeed, be necessary to do a larger redesign.  But this would require a stronger rationale that you have given so far.  For example, if you plan to develop the payment model further and introduce significant new features, cleaning up the code would have some benefit.  Or perhaps the design contains a fundamental security flaw that needs to be fixed.

There are reasons to refactor a large chunk of code.  But if you do that, increase the test coverage to 100%.  This is probably something that will save you time overall.

ContentLicense: CC BY-SA 3.0


问:
Mocking a utilities module for unit testing?
I'm writing unit tests for a class that makes use of a general utilities module. In general I want to mock all the dependencies of the class, but mocking some of the utility functions feels weird. Some of them are simple functions for dealing with file paths, string manipulation, etc, and it seems like an implementation detail that the class under test uses this utility to implement its public API. If the code was refactored to not need that utility function, I wouldn't care and would prefer that the test not fail.

The problem is that some of the utilities functions depend on the filesystem, and obviously need to be mocked. So I'm considering either

Leaving the utilities module as-is and mocking the filesystem module

Or using most of the utilities module but mocking the individual functions that have dependencies on the filesystem

What have other people done in this scenario?

答:
It depends what you consider a "unit". Some people think a unit to be tested should be the tiniest part they can reduce matters to - , that is, just the function under test with everything it depends on mocked away. I think this is just taking things too far towards the ideology of some utopian dream of unit testing.

A unit should be a simple part of your program that is easy to test, without being too large that it becomes a mini-integration test. For many people this means the class, and many (including Martin Fowler) would argue that some dependent classes be included in that definition. So a utility class of file I/O wrappers would be perfectly fine to consider as part of the unit being tested.

So it's up to you to decide how granular to take your system for testing. If you think your filesystem module works fine (and has been tested itself perhaps) then simply include it and take the (very slight) risk that it might cause your function to fail testing (which isn't a bad thing as you can then fix it - which is what testing is all about). This may mean you spend far less time writing tests than you do fixing any potential bugs found while testing your function.

ContentLicense: CC BY-SA 4.0


答:
Don't Repeat Yourself

Re-use old projects assets.

Take a day to learn your IDE. If it doesn't provide tools like snipets, code auto-completion... consider getting a new one.

Put shortcuts to everything in key places so you can access things faster.

Get a second screen if that's not already the case.

Don't check your emails too often.

Try focusing on only one task at a time. If this is not possible, keep close track of what you're doing and don't get lost between 15 unrelated tasks.

Use paper. When I work I always have a printed version of my tasks on which I can take notes, cross off and so on. It's way faster than going on a different screen to read something or write something. At the end of the day I take 10 minutes to copy everything into the system. I realized it saved me some time every day.

Title: How to become a "faster" programmer?

OwnerDisplayName: marcgg


问:
Is this 'implementation' of a builder pattern good design
```<code>public class MyButton{
    public MyButton(){}
    public MyButton setIcon(Icon icon){return this;}
    public MyButton setText(String text){return this;}
}
</code>```

And used like:

```<code>MyButton testButton = new MyButton()
    .setIcon(MyIcon)
    .setText("MyText");
</code>```

I know its not a true implementation of the builder pattern, but is there something inherently wrong with this design?

答:
The core part of Builder patter is the build part, not the fluent syntax part.

If your class is not building another class, then it shouldn't be called builder.

In your case, I would call it "fluent property setting" or something similar.


问:
How to convert byte-array (4 bytes) back into float?
A piece of code I'm trying to debug generated a sequence of 4 bytes from a known float number. I'm trying to verify the float number given the four bytes.

The (known) float 8.03 generated the bytes 56,46,48,51 (here, it is listed according to how it was received in a buffer i.e., 56 first, then 46, then 48, then 51). But I would like to know if 56-46-48-51 (MSbyte to LSbyte) or 51-48-46-56 represents 8.03 (if it does, at all).

I'm not sure how to write code to check both cases. Can someone offer a hint?

答:
Seems there is a principal misconception here, because, citing you,

The (known) float 8.03 generated the bytes 56,46,48,51

the sequence 56,46,48,51 is 8.03 in text (ASCII), but not the binary representation according to widely used standards as IEEE754.
With IEEE754 4-byte binary, 8.03 is represented as 65,0,122,225 (in big-endian order) or 225,122,0,65 (in little-endian order, as on x86).

If it is the truly representation of this float, then

1) You can't be sure every float in text is represented in 4 bytes, unless this is stated by some spec; also please consider how the representation text is terminated;

2) The issues like "MSbyte to LSbyte" aren't usually applicable to ASCII text in RAM, because text is stored nearly always that offset 0 carries the leftmost character. Exceptions are too rare and shall be explicitly specified. But this text property doesn't apply to integer reading of the same RAM. If you read "8.03" as integer, on little-endian machines as x86 it results in 0x33302e38.

And, answering your header question "How to convert byte-array (4 bytes) back into float?", the answer, based on your example, is to call a standard library routine which parses a text form. If it's written in C, it's strtod or sscanf, and you shall provide NUL-termination of the input character array.


问:
Putting a password in a REST API call
Suppose I have a REST API that is also used to set/reset passwords. Let's also suppose that this works over a HTTPS connections. Is there any good reason not to put that password in the call path, let's also say I will encode it in BASE64?

An example would be to reset a password like this:

```<code>http://www.example.com/user/joe/resetpassword/OLDPASSWD/NEWPASSWD
</code>```

I understand BASE64 is no encryption, but I only want to protect the password to shoulder surfing in this case.

答:
What are the features of a password-reset operation?

It change something.

There is a value that it is set to.

Only some people are allowed to do it (the user, an admin, or either, perhaps with different rules as to how either can do so).

Point 1 here means you cannot use GET, you must either POST something representing the password-change operation to a URI representing a resource that handles password changes, or PUT something representing the new password to a URI representing the password or representing something (e.g. the user) of which that password is a feature.

Generally we'd POST, not least because it can be awkward PUTting something we can't later GET and of course we can't GET the password.

Point 2 therefore will be data representing the new password, in what is POSTed.

Point 3 means we'll need to authorise the request, which means that if the user is the current user we'll need the current password to be proven to us (though not necessarily receive the current password, if e.g. a hash-based challenge was used to prove knowledge of it without sending it).

The URI should therefore be something like <http://example.net/changeCurrentUserPassword> or <http://example.net/users/joe/changePassword>.

We might decide that we want to receive the current password in the POST data as well as in the general authorisation mechanism being used.

Title: Putting a password in a REST API call


答:
Simply put,
  White board -> break down into testable requirements into
tasks (I've used Team Foundation to keep track of each task and how long it should take.)

Use testing to ensure that you are getting what is required done, nothing more nothing less.
  (Don't worry about performance yet.)

Go from requirement to requirement and test after each is done.
  After each task is completed you should have an accurate estimate of the time remaining.

When all requirements are done go back and "polish" it.

Doing the leg work first forces one to iron out all the requirements which saves time by doing things right the first time.

If done properly this should allow more time to be spent on Stack Overflow :)

Good luck

Title: How to become a "faster" programmer?


答:
In general I want to mock all the dependencies of the class

I think that is where you took the wrong turn. If a class has dependencies, then those dependencies must never be mocked in the test for that class; that makes the test worthless. If that means the test for that class is not a unit test, then so be it. You can't do a stand-alone isolated test for something that is not stand-alone and isolated.

Mocking is for when an object has collaborators or outputs of some unknown type (e.g. typically the corresponding class has a field that is of an abstract or interface type).

For example, say you have:

You would mock (or otherwise stub out) FileBugRepository when testing BugService, because that's not a static class-level dependency, just one possible arrangement of objects at run-time. But when testing FileBugRepository, you should not mock FileUtils because it is being used directly, and is the only valid implementation.

In this case, FileUtils is a direct static dependency; in most languages the code of FileBugRepository will contain the name FileUtils. So you can't test it with something else without using some low-level magic to redefine the code you are testing to be something other than what it is.

That is of course the road to ruin, to thousands of tests with high coverage, high maintenance cost and no added value, and not having a good answer to the question 'why are you not mocking Integer and String'?

The general principle holds even if the code is written using the anti-pattern where every class has a separate interface, i.e. IFileUtils and FileUtilsImpl; then IFileUtils simply is an alias for FileUtilsImpl.

Title: Mocking a utilities module for unit testing?

Body:
I'm writing unit tests for a class that makes use of a general utilities module. In general I want to mock all the dependencies of the class, but mocking some of the utility functions feels weird. Some of them are simple functions for dealing with file paths, string manipulation, etc, and it seems like an implementation detail that the class under test uses this utility to implement its public API. If the code was refactored to not need that utility function, I wouldn't care and would prefer that the test not fail.

The problem is that some of the utilities functions depend on the filesystem, and obviously need to be mocked. So I'm considering either

Leaving the utilities module as-is and mocking the filesystem module

Or using most of the utilities module but mocking the individual functions that have dependencies on the filesystem

What have other people done in this scenario?


答:
Is it the builder pattern? As Euphoric explained, no, it is not. A Builder is a separate class which has the purpose to create an instance of a different class.

Is there anything wrong with the design? That depends. Does your application allow buttons which don't have a text and/or icon? If yes, then this pattern is perfectly acceptable. If no, you might want to consider writing a ButtonBuilder class which throws an exception (or at least an assert) when you call buttonBuilder.build() before setting all required properties.

Title: Is this 'implementation' of a builder pattern good design

Body:
```<code>public class MyButton{
    public MyButton(){}
    public MyButton setIcon(Icon icon){return this;}
    public MyButton setText(String text){return this;}
}
</code>```

And used like:

```<code>MyButton testButton = new MyButton()
    .setIcon(MyIcon)
    .setText("MyText");
</code>```

I know its not a true implementation of the builder pattern, but is there something inherently wrong with this design?


答:
As mentioned by @COMEFROM this question answered the question perfectly.
The style used here is called a Fluent Interface. This answer mentions a convention which is inline with standard java convention and doesn't theoretically interfere with jvm optimizations and javabean compatibility </p>


问:
Can I use Qt open-source for my web-scraping website?
I apologize if I should be understanding this more readily but I'm a little new to this and dont understand the LGPL license.  Here is the FAQ for it: http://www.qt.io/qt-licensing-terms/

I am making a website that scrapes data from other websites and organizes it in a nice manner.  I plan to try and make money off this website through advertising and also by getting commissions from linking to certain sites.  I plan on using server-side code that scrapes the website using PyQt4 (which uses Qt).  The code scrapes the website and stores the data in a sql database.  I then use the sql database to display the webpage.

I think it's fine to use the open source version of Qt right?  I'm not selling or really giving any application away.  The Qt is being used on server-side code to generate the sql database.

And if it is fine to use the open source, do I have to display a link on the website to the source code of the Qt I'm using?  Just trying to fully understand.

答:
To use the OpenSource version of Qt under the LGPL license, you must meet the following conditions:

If you distribute the Qt libraries that you use, then any changes to them must be made public under the LGPL license

Users of your application other than you must have the possibility to replace the Qt libraries it uses, either because the libraries are dynamically linked or because they have access to the code under the GPL license. If the Qt libraries are dynamically linked, you have no obligation to release your sources or to use an open-source license.

If you use the application exclusively on your own machines (including any servers that you control), then you are not distributing the software. This means that the conditions of the LGPL license are trivially met, because the set of people that they apply to is empty.

As a side note, there is only one license that includes giving remote access to your software in its definition of "distribution": The AGPL license.


答:
What are your time bottlenecks?  I find that thinking is my usual bottleneck, so improving my typing speed (already good) would do approximately nothing.  On the other hand, if typing is not fast and natural to you, it may well be slowing you up.

Are you trying to do more than is required?  Usually, a business will want lots of good work out of you rather than less but more polished work, and adding features that aren't going to be used wastes time and money with no business return.

Are you being too hasty?  Under time pressure, people frequently skimp on up-front design and planning, hoping that it'll work out anyway.  It frequently doesn't.

Are you handling time properly?  Development requires chunks of uninterrupted thinking time, or you'll be inefficient, and hence slow.

Title: How to become a "faster" programmer?

OwnerDisplayName: David Thornley


问:
Architect in our company is against DTO
I have this easy DTO (Data Transfer Object):

```<code>public class SoonestOffersModel
{
    public Offer Offer { get; set; }
    public DateTime Date { get; set; }
}
</code>```

Offer is entity.
Our architect is against these DTOs, as he is saying this is very old and it is in need only when people don't think about design to include all fields before.

He is against model or database first approach and favors code first approach.
In this case he has entity models pre-created.

So I asked him if we want to do some additional logic and apply Date with Offer entity for View purpose, he suggested I should've just add nullable DateTime field into entity model Offer itself.

First time hearing this. So if you have new requests each time to show more and more fields that correspond to Offer you are adding those in entity model?

I am not sure why DTO is bad, since I've always used it, and I don't do code first approach.

I would love to hear your opinion on how much this is true and if I should be worried about this?

答:
The "Code First" approach is awesome.  The database is just a persistence storage for the data that our code handles.  It should be expendable.  We should not need to care about it.  We should be able to just drop the database and rerun our code and have it recreate the database from scratch.

In light of this, we don't need DTOs.  Our class model is all that is necessary and sufficient to fully describe how the database schema should be.  DTOs are just an unnecessary layer, serving no purpose other than making things look familiar to people who have a more traditional view of things.

We should be focused on writing code to solve the problem at hand, we should not be wasting our time curating the persistence storage.

Edit

Of course, all of the above depends on what kind of environment you are working in.  If you are storing massive amounts of data which are being used by various different applications, then in your environment "data is king", so "code first" might be unsuitable for you.  But I would assume that the architect in your company knows best what kind of environment you have over there.

Title: Architect in our company is against DTO


答:
"Code First" is the work of the devil. The data is what is important, the code is just some temporary processing that will come and go, be refactored, and even totally rewritten in time but your data is sacrosanct. So getting your schema right is far more important in the long run.

That said, a simplistic mapping of entities to DTO like you have is lazy and probably inefficient. To get the most from your database, you should be creating methods that perform specific domain processes and create an object to pass just the required data - not all the data the table or view returns. Ideally you'd be calling a stored procedure that returned a minimal set of data for the specific task.

Title: Architect in our company is against DTO

Body:
I have this easy DTO (Data Transfer Object):

```<code>public class SoonestOffersModel
{
    public Offer Offer { get; set; }
    public DateTime Date { get; set; }
}
</code>```

Offer is entity.
Our architect is against these DTOs, as he is saying this is very old and it is in need only when people don't think about design to include all fields before.

He is against model or database first approach and favors code first approach.
In this case he has entity models pre-created.

So I asked him if we want to do some additional logic and apply Date with Offer entity for View purpose, he suggested I should've just add nullable DateTime field into entity model Offer itself.

First time hearing this. So if you have new requests each time to show more and more fields that correspond to Offer you are adding those in entity model?

I am not sure why DTO is bad, since I've always used it, and I don't do code first approach.

I would love to hear your opinion on how much this is true and if I should be worried about this?


问:
What is the difference between size and length?
It seems that the terms size and length are used interchangeably to describe how many bits, bytes or octets some data occupies, i.e. a length field in a data header is said to indicate the size of the data. Did I see this correctly? If not, how do the terms differ? Which term is most common for which usage?</p>

答:
This question is a duplicate of https://stackoverflow.com/q/300522/773113, but since that question is on stackoverflow, technically it is not a duplicate.  (I tried to mark it as a duplicate, but I was prevented, because the other question is not on Programmers SE.)

So, here is what is happening: it is all a matter of convention, and it is all arbitrary.  Different languages and environments have their own conventions, (sometimes even self-contradictory,) and you need to learn the conventions of the language you are using, and follow it.

In the old times when C ruled, "size" was the fixed number of bytes allocated for something, while "length" was the smaller, variable number of bytes actually in use.  Generally, "size" stood for something fixed, while "length" stood for something variable.  But it was still not uncommon for someone to say that "a machine word is 32 bits long" instead of "the size of a machine word is 32 bits", despite the fact that the number of bits in a machine word is, of course, very fixed.

And then comes java, which has arrays of fixed size, but their size is returned via a length property, and strings of fixed size, but their size is returned via a length() method, and collections of variable size, but their length is returned via a size() method.  So, java decided to turn things around.

Then came C#, which keeps the term "length" for stuff of fixed size, but for variable size stuff it uses the term "count", which would be perfect, if it was not for the unfortunate fact that besides being a noun it is also a verb, which can be taken to mean that when you get the "count" of a collection, the items in the collection will be counted one by one.  (O(N) instead of O(1).)

So, go figure.  There is no definitive answer, be sure to carefully study the documentation of the system that you are dealing with, and to understand the precise definition of the terms "length" and "size" within the context of that system, and be even prepared that there may be no precise definition of these terms, and they may be used interchangeably and arbitrarily.


答:
First of all, you shouldn't be designing a system based on a few meetings with end users. In fact you shouldn't be involved with the requirements phase of a project, that's for the business analysts and end users to work out.

Second phase should be your technical requirements, this is where you will start to work with the business analysts to come up with a solution to the requested specification.

Now is the important part. Make sure you understand both the end user requirements and the functional requirements, there's no use you starting out something only to find it didn't meet users expectations. Speak up if you don't understand something.

Now, time to hit the editor. But my approach is to never write real code, always write an absolute stack of comments first, do it in pseudo code if that's easy for you, whatever it doesn't matter, as long as it's clear and easy to read/understand.

Once you've done your comments you can start either
a) writing your test cases
b) writing the implementation.

Depending on your environment you would be best starting with (a) but sadly most start with (b) and then try force the tests to meet the implementation. Frankly speaking though, if you were part of a large company there would be a department writing the test cases for you before you even start doing anything.

Title: How to become a "faster" programmer?

OwnerDisplayName: Brett Ryan


问:
Is there a Factory Pattern distinct from Abstract Factory and Factory Method?
During a recent phone screen I was asked to describe the "Factory Pattern". I asked if the screener meant "Factory Method" or "Abstract Factory". He said, "No, just the Factory Pattern".

I don't know what the Factory Pattern is except in the context of the aforementioned GoF patterns. I've been researching this since the phone screen, but nothing I've found indicates that there is a third "just" Factory Pattern. The closest I came was this question, but still that seems to just distinguish Factory Method from Abstract Factory.

Is there a distinct third factory design pattern? If not, does "Factory Pattern" always just mean "Factory Method"?

答:
To the best of my knowledge, no design pattern library discusses anything called a "factory pattern". There is a general term "factory", which simply refers to an object that creates other objects. But if you're talking about the documented names for patterns, you need to be specific - after all, part of the point of design patterns is for communication, so everyone should be using the same terms.

Some sites do discuss different types of specific factories, such as Abstract Factory and Factory Method together. OODesign.com does this, and C2 wiki has a page called "FactoryPattern" that links to the pages for Abstract Factory and Factory Method.


问:
Querying large amount of data for parallel processing
I have a dataset containing list of users (around 50M).

Each user has an email address, name, and some more data columns.

I want to send a weekly email to those users, and the content of the email will be based on the user's data.

Each user should get the mail on a specific day of the week, based on his registration date.

How do I design a system that will allow me to query the users, and send them the custom email? How can I make that system scalable?

One approach I thought about is writing a worker that will query all the users that need to receive the email on the current day (this will be paginated), and will insert them to a queue where several workers can process them.

The problem with this approach is that I can't add workers that query the data and insert it to the queue, because I can't guarantee that each user will be queried by a single worker.

Maybe there is a specific DB or data access tool I can use? Is there a known pattern for this kind of processing?

I would appreciate your suggestions and thoughts on the subject.

答:
Have you considered creating an index on your user table for each day of the week? Then you should be able to quickly retrieve the subset of users you want. Creating the index will probably take a bit of time, but subsequent updates shouldn't be too bad (unless you tend to bulk-populate your user table).

If this doesn't sound feasible, then you might want to consider partitioning or sharding your database. These approaches split the table into separate tables based on some criterion (day of the week, in your case). You'd probably want to create a view that encompasses all the partitions/shards to provide a complete table, but your worker threads could just focus on one.


答:
Develop yourself more and more as a programmer, every day... Learn design patterns !

Use TDD, but in a proper way, the bugs you can have in your code is the single-most time-consuming thing.

Use ReSharper :)

Title: How to become a "faster" programmer?

OwnerDisplayName: Sapphire


问:
How to be sure that a certain code does not call interrupts?
Imagine that you have an object code file from an untrusted source. You want to run this code to know the result of its computation, and you want the code to perform fast, so setting up a whole virtual machine is a last resort. You also want nothing to happen to your system after the code is run.

Having that in mind, as far as I understand, that code would not be able to do any harm if you restrict the number of interrupts for it or disable interrupts whatsoever. One way to ensure there are no interrupts in code is to scan it instruction-wise and refuse to run if there is at least one int instruction in it. That will solve the problem, but this approach will as well disallow any system calls, and the code with no system calls is scarcely useful. If the running side decides to allow that code which only invokes some whitelisted interrupts, then the running side needs to be sure that the running code does not change itself in run time. If it does change, then each instruction to run needs to be re-scanned, what would impact performance.

It would be nice to have some kind of gateway between host and guest interrupts, which could translate guest interrupts to possibly different host interrupts or refuse to do so. Are there any solutions or researches available for this topic?

答:
This is extremely dependent on the environment that you're using, and I don't think that you can avoid tying it to one operating system. Since this kind of work is heavily dependent on the kernel (you are trying to avoid interrupts, after all, a feature of the kernel itself), do not be afraid to use a Linux- or Windows-specific solution.

Your approach of scanning the object file for specific instructions isn't sufficient, because as you said, it will also disable system calls. This is also dependent on the architecture that you're running on, and since you don't want the solution to be OS-dependent, you probably don't want an architecture-dependent one, either.

Containers have less overhead than virtual machines, and can be started up and taken down extremely quickly, but since you're talking about separation from the kernel, a container would not be sufficient.

That being said, a virtual machine is your best solution, and is what is generally used in a situation such as this. Sure, there is a little overhead when starting/stopping a virtual machine, and a little bit of runtime overhead when running the application. But these can be solved by using a hardware virtual machine, which uses a hypervisor to give the virtual machine direct access to the hardware. It's a bit difficult to set up initially, but it gets rid of the vast majority of overhead that is present when running an application in a virtual machine.


问:
What does "Linux Ready" mean in the context of a project written in Swift?
There are few GitHub repositories written in Swift that are presented to be "Linux Ready". The Zewo organization has several repositories identified as "Linux Ready". What, exactly, does this mean?</p>

答: Linux-ready implies that the project does not contain Apple Foundation frameworks, which would make the project platform specific. Once Apple releases their Swift compiler for Linux - which they announced will be by years end - Linux-ready projects should run "out of the box" on Linux.</p>


答:
At least according to a quick web search, the expression "Linux ready" does not appear to be some sort of official designation for Swift projects. It looks like only Zewo uses it in that context.

According to the project's README.md, it simply means that the project should work under Linux once a Swift implementation is available for Linux:

Features:
  No Foundation dependency (Linux ready)

So "Linux ready" seems to indicate that the project does not use the Foundation framework, which presumable will not become available under Linux in the foreseeable future.

Related question from StackOverflow: Is it possible to build Swift 2.0 code using the Foundation Framework and target linux?

Title: What does "Linux Ready" mean in the context of a project written in Swift?

Body: There are few GitHub repositories written in Swift that are presented to be "Linux Ready". The Zewo organization has several repositories identified as "Linux Ready". What, exactly, does this mean?</p>


问:
What algorithms are there for picking colors for plot lines on graphs?
I'm interested in what algorithms or rules I can programmatically implement to generate RGB or HSV colors for plotlines to keep them visually distinct from the neighbors.

I know that in professional mapmaking, there are algorithms or rules that make sure that no two adjacent countries on a map are the same color. I can also think of Microsoft office Excel as picking good tints/shades for plot lines (red, then blue, then purple/orange).

Here's an example of what I'm talking about - I need to generate colors for 12 lines on a black background. The colors here I've hardcoded by hand using web-safe RGB color codes. The problem arises when these lines overlap - it's hard to tell if one is looking at purple, slighly darker purple or violet. I'm looking for a better algorithm to produce colors for plotlines like these.

Here's an example using Flot plotting library for jQuery, it has nice succession of colors for graphs:

答:
I have experimented a bit and found out that even with HSL/HSV it's not quite easy to get a decent algorithm for nice, undisturbing, calming (all quite subjective, but...), yet contrasty colors.
Some parts of the specter are visually similar - esp. the green-blue section. So I had to add some lightness variation.

Here is what I ended up with:

```<code>$.plot($('#application_pie'), data_application_pie, {
    series: { pie: { show: true,  innerRadius: 0.55, offset: { top: 0, left: -120 } } },
    colors: $.map( data_application_pie, function (item, index) {
        return jQuery.Color({
            hue: (index*0.95*360/data_application_pie.length),
            saturation: 0.95,
            //lightness: (index%2/-4)+0.55, alpha: 1
            lightness: ((index%4 == 3 ? 1:0)/-4)+0.55, alpha: 1
        }).toHexString();
    })
});
</code>```

Body:
I have experimented a bit and found out that even with HSL/HSV it's not quite easy to get a decent algorithm for nice, undisturbing, calming (all quite subjective, but...), yet contrasty colors.
Some parts of the specter are visually similar - esp. the green-blue section. So I had to add some lightness variation.

Here is what I ended up with:

$.plot($('#application_pie'), data_application_pie, {
    series: { pie: { show: true,  innerRadius: 0.55, offset: { top: 0, left: -120 } } },
    colors: $.map( data_application_pie, function (item, index) {
        return jQuery.Color({
            hue: (index*0.95*360/data_application_pie.length),
            saturation: 0.95,
            //lightness: (index%2/-4)+0.55, alpha: 1
            lightness: ((index%4 == 3 ? 1:0)/-4)+0.55, alpha: 1
        }).toHexString();
    })
});


问:
Automatic namespace resolution in C++
My question is focused on design, and the code included in this question is meant to clarify the problem I'm experiencing.  I'm interested in conceptual level answers and not code in order to answer my question.

Background:

When programming bare-metal systems, one often has to manipulate bits in memory-mapped register controlling the behaviour of on-chip or external peripherals. Usually, there are software libraries defining these bits and registers.
A minimal example might look like this:

```<code>#include <stdio.h>
#include <stdint.h>

/* Might be in some library like this: */
#define SOME_PERIPHERAL_BASE_ADDRESS 0x8fce0000
#define SOME_PERIPHERAL_REG1 (*((uint16_t*)(SOME_PERIPHERAL_BASE_ADDRESS + 0x8e)))

#define SOME_PERIPHERAL_REG1_AM  (1 << 3)
#define SOME_PERIPHERAL_REG1_FOO (1 << 4)
#define SOME_PERIPHERAL_REG1_BAR (1 << 5)

/* User code: */
int main()
{
    /* How to use these definitions on a bare metal system: */
    /* SOME_PERIPHERAL_REG1 is initialies to the reset value by hardware, so
     * there is no need to initialise it. */
    /* printf("reg1 = %i\n", SOME_PERIPHERAL_REG1); */
    /* This will of course segfault when not on a bare metal system. */
    /* SOME_PERIPHERAL_REG1 = SOME_PERIPHERAL_REG1_AM | SOME_PERIPHERAL_REG1_BAR; */
    /* printf("reg1 = %i\n", SOME_PERIPHERAL_REG1); */

    /* Ersatz dummy code for testing on a pc: */
    uint16_t value=0;
    printf("reg1 = %i\n", value);

    value = SOME_PERIPHERAL_REG1_AM | SOME_PERIPHERAL_REG1_BAR; /* <- No type-safty! */

    printf("reg1 = %i\n", value);

    return 0;
}
</code>```

Issues with this approach:

While this code is reasonably readable and short, it lacks in certain ways:

A programmer will tediously have to retype the prefix (SOME_PERIPHERAL_REG1_ in the example) for each register value

No type safety: A programmer can easily set a register to a value that was intended for another register (e.g. set reg1 of Some_peripheral to a value intended for the control register of Another_peripheral) or not to a register value at all (e.g. set reg1 to 15 (an integer)).

Another problem with this approach is, that some registers are not accessible with simple assigns. For example, I use an SSD1289 display controller that is connected to the external memory interface of my microcontroller. To set the registers of the SSD1289, I will need to first write the address of the register to a certain address in the memory region followed by a write of the new register value to another address in that region. With plain C, there is no way of encapsulating this except of using a setter function.

Potential Solution:

To overcome this, I tried creating a register object in C++ that is parameterised with an enum containing the bit definitions and a pointer to the address of the register. A minimal example might look like this:

```<code>#include <iostream>
#include "enum_binary_operators.hpp"

// Code that should go in the library:

/**
 * \brief An object ancapsulating a memory-mapped peripheral control register.
 *
 * \param reg_bits      An enum defining the bitfields for that register.
 * \param ret_address   The memory-mapped address where the register lies in
 *                      memory
 */
template < typename reg_bits, uintptr_t reg_address >
class Register
{
    private:
        // On the intended pare metal target, this wouldn't be neccesary, as
        // the value would be stored in the memory-mapped address of the register.
        uint16_t value = 0;
    public:
        // Write a new value to the register
        inline Register& operator= (reg_bits const& val)
        {
            // This is what is intended, but of course segfaults when not on bare metal.
            //*reinterpret_cast<uint16_t*>(reg_address) = static_cast < uint16_t > (val);

            // dummy replacement of the above line.
            value = static_cast < uint16_t > (val);
            // possibly do some more things like send the value to a remote register.
            return *this;
        }
        operator uint16_t()                         // Read register
        {
            // This is what is intended, but of course segfaults when not on bare metal.
            //return *reinterpret_cast<uint16_t*>(reg_address);

            // dummy replacement of the above line.
            return value;
        }
        [[deprecated("Please only use the appropriate register bit enum values to manipulate the register!")]] Register& operator= (int val) {}
};

/**
 * \brief An Object encapsulating a memory-mapped peripheral
 *
 * \param base_address  The base address of the registers belonging to that peripheral.
 */
template < uintptr_t base_address>
class Some_peripheral
{
    public:
        // This enum should not be in global namespace to avoid name conflicts.
        // For example many peripherals might have a register named
        // "control_register".
        enum reg1_bits : uint16_t
        {
            AM  = (1 << 3),
            FOO = (1 << 4),
            BAR = (1 << 5),
        };
        // more register bit definitions

        Register < reg1_bits, base_address + 0x8e > reg1;
        // more registers

    // ...
    // possibly more high-level functions for the peripheral like
    // initialisation routines, transmission routines, etc.
};

// More peripherals

// The base address should be provided by some file defining the peripheral addresses for a given chip.gg
//extern constexpr some_peripheral_base;
constexpr uintptr_t some_peripheral_base = 0x8fce0000;

Some_peripheral<some_peripheral_base> some_peripheral1;
// And some more peripherals

// User code:

int main()
{
    // Get the current value of the register.
    std::cout<<"reg1 = "<<static_cast < uint16_t > (some_peripheral1.reg1)<<std::endl;

    // Each register can only be written with the bits that belong to it.
    some_peripheral1.reg1 = Some_peripheral<some_peripheral_base>::reg1_bits::AM
                          | Some_peripheral<some_peripheral_base>::reg1_bits::BAR;

    // This is the intended usage:
    // Somehow, operator= should be able to deduce the scope resolution automatically at runtime.
    //some_peripheral1.reg1 = AM | BAR;

    std::cout<<"reg1 = "<<static_cast < uint16_t > (some_peripheral1.reg1)<<std::endl;

    return 0;
}
</code>```

With enum_binary_operators.hpp:

```<code>#ifndef ENUM_BINARY_OPERATORS_HPP
#define ENUM_BINARY_OPERATORS_HPP

#include <type_traits>

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator|(T const& x, T const& y)       {
    return static_cast < T >   (static_cast < uint16_t > (x) | static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator&(T const& x, T const& y)       {
    return static_cast < T >   (static_cast < uint16_t > (x) & static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator^(T const& x, T const& y)       {
    return static_cast < T >   (static_cast < uint16_t > (x) ^ static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator<<(T const& x, T const& y)       {
    return static_cast < T >   (static_cast < uint16_t > (x) << static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator<<(unsigned int const x, T const& y)       {
    return static_cast < T >   (x << static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator<<(int const x, T const& y)       {
    return static_cast < T >   (x << static_cast < uint16_t > (y));
}

#endif /* ENUM_BINARY_OPERATORS_HPP */
</code>```

Questions:

Now, my questions are:

Am I correct in assuming this should come at negligible run time overhead? Compile time will be increased, of course.

Is there a better way of doing this?

And is there any way of getting rid of the long scope specifiers in the assignment?
The idea here is, that the compiler already knows, where the enum members will have to come from (since the enum is a template argument to the register class), so maybe one could get it to include the proper scope resolution on its own in some way.

答:
Well, obviously uint16_t is the wrong type, and you wanted std::underlying_type<T> in the binary operators. They're rather greedy, after all, and you can't assume all enums are unsigned 16 bits.

One alternative to make them less greedy is to put your own enums and these overloads in their own dedicated namespace. Argument-dependent lookup will then only include these overloads when applied to your enums.

As for the efficiency question, pretty much everything that the compiler does is free at runtime. Even better, because of type aliasing rules, your typesafe C++ constructs are sometimes even more efficient. A uint16_t* can't be pointing to your enums, which reduces aliasing risks.

The problem with

```<code>some_peripheral1.reg1 =
       some_peripheral<some_peripheral_base>::reg1_bits::AM |
       some_peripheral<some_peripheral_base>::reg1_bits::BAR;
</code>```

is that the C++ parse tree is analyzed bottom-up. Roughly speaking, C++ sees A = B | C which are two operator calls, quite possibly overloaded. And in your code they are actual overloads. In particular, it needs to figure out the type of (B|C) before it does overload resolution of =. So it's pretty clear that the type of A cannot reasonably affect B|C, because A isn't even considered at that time.

The argument is weaker for

```<code>some_peripheral1.reg1  = some_peripheral<some_peripheral_base>::reg1_bits::AM;
some_peripheral1.reg1 |= some_peripheral<some_peripheral_base>::reg1_bits::BAR;
</code>```

but even there the types on both sides need to be determined separately before overload resolution is done, and once overload resolution is done it's too late to affect the name lookup.

Title: Automatic namespace resolution in C++

Body:
Well, obviously uint16_t is the wrong type, and you wanted std::underlying_type<T> in the binary operators. They're rather greedy, after all, and you can't assume all enums are unsigned 16 bits.

One alternative to make them less greedy is to put your own enums and these overloads in their own dedicated namespace. Argument-dependent lookup will then only include these overloads when applied to your enums.

As for the efficiency question, pretty much everything that the compiler does is free at runtime. Even better, because of type aliasing rules, your typesafe C++ constructs are sometimes even more efficient. A uint16_t* can't be pointing to your enums, which reduces aliasing risks.

The problem with

some_peripheral1.reg1 =
       some_peripheral<some_peripheral_base>::reg1_bits::AM |
       some_peripheral<some_peripheral_base>::reg1_bits::BAR;

is that the C++ parse tree is analyzed bottom-up. Roughly speaking, C++ sees A = B | C which are two operator calls, quite possibly overloaded. And in your code they are actual overloads. In particular, it needs to figure out the type of (B|C) before it does overload resolution of =. So it's pretty clear that the type of A cannot reasonably affect B|C, because A isn't even considered at that time.

The argument is weaker for

some_peripheral1.reg1  = some_peripheral<some_peripheral_base>::reg1_bits::AM;
some_peripheral1.reg1 |= some_peripheral<some_peripheral_base>::reg1_bits::BAR;

but even there the types on both sides need to be determined separately before overload resolution is done, and once overload resolution is done it's too late to affect the name lookup.


问:
Managing Installation Packages
I'm looking at our current method of creating installation packages and quite frankly it's a bit of a mess with a large scope for human error.

We currently use InstallShield, but to get the files ready for the package, there is a lot of copy and pasting at release time and we're never quite confident that all files/dependencies are included within the installer.

Does anybody know of any standard way of managing this process, both from a workflow and tool point of view?

i.e. should we be updating the installer after every commit into source control, is there a way to automate this?

答:
to get the files ready for the package, there is a lot of copy and pasting at release time

When it comes to "copy/pasting" files, there is almost nothing you cannot encode into a script (you have to pick a scripting language, maybe the shell script language of your OS - let me guess, its MS Windows - maybe a more modern scripting language like Powershell or Python, whatever you prefer). And if you need to manipulate files during this process (for example, to increase a version number or change a GUID within a file), create some tools which do this for you.

Most modern installer frameworks (I guess Installshield, too), will allow you to automate the creation of a package. So all these steps can be included into the build process on your CI server, just as the standard compilation build you already have there implemented. How often you let the server run the automated packaging is up to you, it will surely depend on how long the process takes for your software, and how quick you need feedback if that part of the build breaks.

we're never quite confident that all files/dependencies are included within the installer

Somewhere, somewhen you will have to test the installation, and that includes running the programs after installation. You have to decide if you need to automate that part of the process, too, or if a manual test is sufficient (that will probably depend on your deployment frequency and the frequency your dependencies change). If you decide to automate the installation test, you could provide a "UI free testing mode" in your application. When this mode is activated, it just checks if all needed dependencies are fulfilled (and writes a logfile, or returns an error code if not). That will be something your CI server can check for.

However, the last step might need some effort, if you want to test the installation always in a clean production-like environment (and not in an development-like environment). Utilizing a virtual machine might be a possible approach here. You have to decide if its worth the effort for your situation.

Title: Managing Installation Packages


问:
Designing a database with circular references for the-one-of-many case
Consider the following case: there are two models Image and User. Users have associated images and they can pick one of them as their profile image. There are essentially two ways of modeling this:

1)

```<code>User:
   id - primary key
   profile_image - nullable foreign key to Image

Image:
   id - primary key
   user - foreign key to User
</code>```

2)

```<code>User:
   id - primary key

Image:
   id - primary key
   user - foreign key to User
   profile - boolean true/false
</code>```

Both of these approaches have some problems.

In the first case:

well-known chicken-egg problem (e.g. foreign keys must be off when recovering from backup)

It can happen that profile image points outside of domain of images associated with user

There is a redundant dependency link (i.e. one more relation when compared to the first solution). That will have some impact on an application code

What if we later decide to have an ordering on images where the first one is the profile one?

The second case:

There is slight data redundancy (many times false)

true can occur more than once

slightly less intuitive (at least for me)

So my question is, which of these two solutions is better/cleaner?

答:
You have to be more specific about the semantic meaning of your entities. Don't use users or user_ids, because the word "user" does not express the kind of usage. If you have some specific kind of usage in mind use that instead of just user. For example if it is an ownership, call it an ownership.

This are the entities with their primary keys.  We have images, persons and ownerships.

```<code>create table image (
  id integer,
  data text,
  primary key (id));

create table person (
  id integer,
  name text,
  profile_image integer,
  primary key (id));

create table ownership (
  image_id integer,
  person_id integer,
  primary key (image_id, person_id));
</code>```

This are the relations. An ownership is a n:m relation between images and persons. The profile image is a 1:n relation between persons and ownerships.

```<code>alter table ownership
  add foreign key (image_id) references image (id);

alter table ownership
  add foreign key (person_id) references person (id);

alter table person
  add foreign key (id, profile_image) references ownership (person_id, image_id);
</code>```

Add some images.

```<code>insert into image values (11, 'image 1');
insert into image values (12, 'image 2');
insert into image values (13, 'image 3');
</code>```

And some persons.

```<code>insert into person values (21, 'alice');
insert into person values (22, 'bob');
</code>```

And define, which person owns which image.

```<code>insert into ownership values (11, 21);
insert into ownership values (12, 22);
</code>```

And now Bob wants to set his profile image:

```<code>-- update person set profile_image = 11 where id = 22;
update person set profile_image = 12 where id = 22;
-- update person set profile_image = 13 where id = 22;
</code>```

Only the second update works fine. The first and the third fail, because of the foreign key constrain, which enforces, that only those images are used as profile image, which are owned by the specific person. The first update fails, because image 11 belongs to Alice and not Bob. And in the third update fails, because image 13 has no owner.

Body:
You have to be more specific about the semantic meaning of your entities. Don't use users or user_ids, because the word "user" does not express the kind of usage. If you have some specific kind of usage in mind use that instead of just user. For example if it is an ownership, call it an ownership.

This are the entities with their primary keys.  We have images, persons and ownerships.

create table image (
  id integer,
  data text,
  primary key (id));

create table person (
  id integer,
  name text,
  profile_image integer,
  primary key (id));

create table ownership (
  image_id integer,
  person_id integer,
  primary key (image_id, person_id));

This are the relations. An ownership is a n:m relation between images and persons. The profile image is a 1:n relation between persons and ownerships.

alter table ownership
  add foreign key (image_id) references image (id);

alter table ownership
  add foreign key (person_id) references person (id);

alter table person
  add foreign key (id, profile_image) references ownership (person_id, image_id);

Add some images.

insert into image values (11, 'image 1');
insert into image values (12, 'image 2');
insert into image values (13, 'image 3');

And some persons.

insert into person values (21, 'alice');
insert into person values (22, 'bob');

And define, which person owns which image.

insert into ownership values (11, 21);
insert into ownership values (12, 22);

And now Bob wants to set his profile image:

-- update person set profile_image = 11 where id = 22;
update person set profile_image = 12 where id = 22;
-- update person set profile_image = 13 where id = 22;

Only the second update works fine. The first and the third fail, because of the foreign key constrain, which enforces, that only those images are used as profile image, which are owned by the specific person. The first update fails, because image 11 belongs to Alice and not Bob. And in the third update fails, because image 13 has no owner.


问:
How to become a "faster" programmer?
My last job evaluation included just one weak point: timeliness. I'm already aware of some things I can do to improve this but what I'm looking for are some more.

Does anyone have tips or advice on what they do to increase the speed of their output without sacrificing its quality?

How do you estimate timelines and stick to them? What do you do to get more done in shorter time periods?

Any feedback is greatly appreciated, thanks,

答: Everyone says 'checking email' but consider the time you spend writing highly technical email.  I can easily spend an hour writing a single email.  To fix it, I could either 1) not write as much, or 2) put off the technical stuff (and the stuff that requires me to read code to answer) until it is absolutely necessary.</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: Shin


问:
What is the interplay or relationship between business, functional, and system requirements?
Does it make sense to say that I elicit business requirements from the end-user community, then take those business requirements to the functional team to create functional requirements, then take those functional requirements to the system engineers and architects to create the system requirements?

For example: business requirement is, user should be able to enter data into a text box. Functional requirement is that the text box can accept user data of 40 characters in length and no more and that the data is passed to a back-end application. System requirement is that the data is accepted and passed using Java to the backend Oracle DB.

Does that work?

答: As a business analyst, I would even say the business requirement in your example could be more of a functional requirement as it talks to a solution not a need.  To me a Business requirement is meant to be written from a business perspective and should be technology agnostic as much as possible.  Depending on the needs of the business, the need could be met by a text box, a drop down list, a combo box, etc...</p>


答:
In the terminology the terminology that I'm used to, your uses for the words don't align. However, there may be alternative definitions in use by other organizations.

In my experience, there are multiple sources that place requirements on a software product. The customer and users have requirements, which is what I would call "customer requirements". These are the characteristics of the system that the customer and the users deem necessary. However, requirements can also come from the business (the company producing the software), usually because of domain experience and insight into continuing to develop the product across customers. Requirements may also come from regulatory sources - governments, laws, industry standards.

The customer requirements may require grooming of some kind. Chances are, the customer won't hand requirements that are totally usable from a technical perspective. There may be inconsistencies, ambiguities, or incompleteness that needs to be resolved. However, even after grooming and buy-in, they are still customer requirements.

The engineering team takes requirements from these sources to develop the system (and subsystem / component) requirements that pertain to the particular product. These requirements are a refinement of the customer, business, and regulatory requirements. At the highest system level, they still need discussion and negotiation with the customer since business and regulatory requirements may conflict with customer requirements and these conflicts need to be resolved.

Functional requirements are simply a type of requirement. A requirement can typically be called a "functional requirement" or a "non-functional requirement". Non-functional requirements are also sometimes called "quality attributes". Any requirement (customer, business, or regulatory) could be functional or non-functional.

There are other things that may be included in requirements specifications. These are called design constraints - things that don't describe the functionality or characteristics of the software but impact your design. For example, if your customer only runs Windows environments, then the fact that your software is going to be deployed on Windows is a design constraint. Design constraints may also come from business or regulatory requirements, but usually customer or business requirements drive design constraints.

In your specific example, I would say that the user being able to enter data in a specific format is a user requirement. In order to maintain a product line or security needs, there may be business or regulatory requirements on data validation, data integrity, checksums, or hashing as well. Your system requirements would be enough information to someone to design and test a system. I'd call the use of Java and Oracle DB design constraints.

Title: What is the interplay or relationship between business, functional, and system requirements?

Body:
Does it make sense to say that I elicit business requirements from the end-user community, then take those business requirements to the functional team to create functional requirements, then take those functional requirements to the system engineers and architects to create the system requirements?

For example: business requirement is, user should be able to enter data into a text box. Functional requirement is that the text box can accept user data of 40 characters in length and no more and that the data is passed to a back-end application. System requirement is that the data is accepted and passed using Java to the backend Oracle DB.

Does that work?


答:
It sounds as though your architect isn't against DTOs as much as your architect is against this DTO. They argue that having a DTO that is an Offer with a Date tacked on is a bit of a smell. I don't know if the Date should just be part of the Offer or not. In some cases, they should be distinct because the domain says that they should be separate things. In others, they should be together because the domain says they should be cohesive.

DTOs though are just there to create well defined, dumb bundles of data that serve as an implementation agnostic contract to some outside code. Sometimes that is some external API, sometimes it is your data store, sometimes it's just another module. That concept is good and fine, but it's just a tool. Good tools can still be misused.

Title: Architect in our company is against DTO


答:
Since many of the other answers talk about doing designwork, I'll just stick to the pure mechanical aspect of coding faster. Most of this is probably obvious, but I'll say it anyway since I notice that many of my co-workers don't do some of these things.

Remap your IDE keyboard shortcuts so you can do most of them with your left hand. This frees up your mouse-hand for fast and furious code outlining/refactoring.

Learn how to navigate your cursor and select text using a combination of Ctrl, Shift, arrow-keys, Home and End.

Below is my C++ setup ( Visual Studio with Visual Assist X ). I have a Norwegian keyboard, so please bear with me:

Alt-Z : Change between .h and .cpp

Ctrl-Shift-< : Context sensitive jumping through references. (< for me is the key left of Z, you english guys don't have one of those. Map it to Ctrl-Shift-Z then. )

Alt-| : Implement method. By writing the header first and just hitting Alt-| all the time you can make the whole class outline in a few seconds.(| for me is the key beneath escape.)
This is especially true if you place the cpp and header files next to each other in the text editor so the header doesn't get obscured every time you perform the action.

Alt-R : Renames symbol under my caret.

Alt-D : Adds a documentation template for the selected function.

This, in addition to lightning fast code completion, makes left hand refactoring possible.

Title: How to become a "faster" programmer?

OwnerDisplayName: Nailer


答:
Your DTO in this case is nothing more than the Offer object plus one field.  I would agree with the architect in this case, one should just add the date to the offer object as opposed to creating a new object.

Typically DTOs would be smaller than your rich domain objects in your model.  For example, the offer object might contain 50 properties, but sending that data (all 50) across the wire may not be needed.  So we create a DTO with just the [N] properties that are needed to be transferred.  Maybe its just 10 or 20 properties that need to go across the wire instead of the full blown model.

You may not need DTOs at all.  If the object that is going across the wire is the same as the one in the model, why create another object?  In this case the DTO object IS the object in your domain model + one field.  Nothing wrong with that, just be careful to have a consistent approach of when and where to use a DTO.

Data and data structures are important.  A poorly designed model and structure can make the system hard and nightmarish versus easy to extend and understand.

Title: Architect in our company is against DTO


问:
My father is a doctor. He is insisting on writing a database to store non-critical patient information, with no programming background
So, my father is currently in the process of "hacking" together a database using FileMaker Pro, a GUI based databasing tool for his small (4 doctor) practice. The database will be used to help ease the burden on reporting from medical machines, streamlining quite a clumsy process.

He's got no programming background, and seems to be doing everything in his power to not learn things correctly. He's got duplicate data types, no database-enforced relationships (foreign/primary key constraints) and a dozen other issues. He's doing it all by hand via GUI tool using Youtube videos.

My issue is, that whilst I want him to succeed 100%, I don't think it's appropriate for him to be handling these types of decisions. How do I convince him that without some sort of education in these topics, a hacked together solution is a bad idea? He's can be quite stubborn and I think he sees these types of jobs as "childs play"

How should I approach this? Is it even that bad an idea - or am I correct in thinking he should hire a proper DBA/developer to handle this so that it doesn't become a maintenance nightmare?

NB: I am a developer consultant of 4 years and I've seen my share of painful customer implementations.

Update:

So it's a few years later now, and I've had time to reflect on this question. My dad ended up implementing a solution using Google Docs, FileMaker Pro and some email hooks. He set the whole thing up himself, and he says he is getting immense value from it.

If you are an experienced developer, you are perhaps reading that description and cringing. But I learnt a pretty good lesson from the whole thing actually - that people only care about the results, and not the implementation. All my dad cares about is the fact he doesn't need to enter patient information down on paper manually, and can instead quickly fill out a Google docs form. What's great is he's looking to hire a junior dev/ops person to focus solely on automation within his practice.

答:
As a recently retired software engineer for a large non-profit healthcare provider, I strongly recommend looking for a hospital or large practice nearby that can for a reasonable fee allow him to share their electronic medical records system that meets the requirements for the Meaningful Use initiative (and other government incentive programs).

I am aware that “Epic” (http://Epic.com) supports their customers allowing smaller providers to share their system, and I imagine some of their competitors do also.  Cerner is their biggest competitor, but several others are discussed at http://www.beckershospitalreview.com/healthcare-information-technology/50-things-to-know-about-epic-cerner-meditech-mckesson-athenahealth-and-other-major-ehr-vendors.html

There is a 75% subsidy from CMS for that sort of sharing.  We passed on the subsidy to our clients by making the subscription price 25% of our cost.


答:
I tend to be suspicious of DTO. One of the goal of object oriented design is to have data and logic bundled together (in a class). A DTO, by definition, is pure data, with no logic.

In your specific case, it seems the the date and the offer have strong cohesion. If you want to keep the specificities of an offer with date and an offer without date, you might want to use inheritance:

```<code>public class SoonestOffersModel : Offer
{
    public DateTime Date { get; set; }
}
</code>```

This would be a good time to re-read GRASP which will give you some pointers on how to choose where to put each responsibility...

Title: Architect in our company is against DTO

Body:
I tend to be suspicious of DTO. One of the goal of object oriented design is to have data and logic bundled together (in a class). A DTO, by definition, is pure data, with no logic.

In your specific case, it seems the the date and the offer have strong cohesion. If you want to keep the specificities of an offer with date and an offer without date, you might want to use inheritance:

public class SoonestOffersModel : Offer
{
    public DateTime Date { get; set; }
}

This would be a good time to re-read GRASP which will give you some pointers on how to choose where to put each responsibility...


问:
Should conditional logic be always coded via type system where possible?
I have a choice.

Option 1:

```<code>public class Sample
{
    bool IsRelevant { get; set; }
}
</code>```

Option 2:

```<code>public class Sample
{
}

public class RelevantSample : Sample
{
}
</code>```

Is there a clear well-known rule how to make this decision?

My research: I have heard about "Replace Conditional with Polymorphism" refactoring before, but it usually deals with large switch statements:

https://sourcemaking.com/refactoring/replace-conditional-with-polymorphism

https://stackoverflow.com/questions/234458/do-polymorphism-or-conditionals-promote-better-design

https://stackoverflow.com/questions/4866873/replace-conditional-with-polymorphism-nice-in-theory-but-not-practical

There is a somewhat related question that describes a different situation (flag as a method argument rather than part of a domain entity): Is it wrong to use a boolean parameter to determine behavior?

答:
Not in C#.

Encoding implied behavior into types is evil in C# and similar languages, because the only way to get info out of the type is if x is T sort of checks (or trickery with dynamic, or reflection). So any change to it (adding a new variant, changing the behavior of a type) mean you get to go into all your consumers, violating the Open Closed Principle.


答:
I think the language choice is irrelevant. What is important in making the decision is how the information is used.

If Samples behave differently depending on the value of isRelevent then it absolutely makes sense to break it up into three (not two) classes. The base Sample class, a RelevantSample class and a IrrelevantSample class. All sample objects would be instantiated from one of the two later classes (thus following the heuristic that base classes should be abstract.) Other objects can then inform sample objects of events without concerning themselves over whether the sample is relevant or not.

However, if it's more a matter of other objects behaving differently depending on the relevancy of the sample, then you would want to go with option 1 and make isRelevant a field that can be queried.

Title: Should conditional logic be always coded via type system where possible?

Body:
I have a choice.

Option 1:

```<code>public class Sample
{
    bool IsRelevant { get; set; }
}
</code>```

Option 2:

```<code>public class Sample
{
}

public class RelevantSample : Sample
{
}
</code>```

Is there a clear well-known rule how to make this decision?

My research: I have heard about "Replace Conditional with Polymorphism" refactoring before, but it usually deals with large switch statements:

https://sourcemaking.com/refactoring/replace-conditional-with-polymorphism

https://stackoverflow.com/questions/234458/do-polymorphism-or-conditionals-promote-better-design

https://stackoverflow.com/questions/4866873/replace-conditional-with-polymorphism-nice-in-theory-but-not-practical

There is a somewhat related question that describes a different situation (flag as a method argument rather than part of a domain entity): Is it wrong to use a boolean parameter to determine behavior?


问:
Implement Stack for Toy VM C++
Recently for fun I have decided to build a toy programming, compiler and  a low-level register based interpreted vm. While starting to implement the virtual machine I got stuck. The stack which holds the variables and structs I implemented as separate arrays for each type. The problem is when I have a reference to a struct the elements are not aligned, int struct.x might be at address 1, and float struct.y might be at address 0, so accessing the struct by a reference would be impossible, because the indexes are not linear. How could I solve this?

```<code>stack int:
//other 0: 5,
//x 1: 67

stack long:
//y 0: 56

stack reference:
//pointer to x, struct access like c array: #00x01
</code>```

For each type I mean for each primitive. I know I could implement it with unions but I want to learn how it is really implemented in java, c++ or c#, that's kind of the point of making a toy language, to better understand what you are programming.

答:
Definitely go with only one stack for everything.

You have two options:

Declare a "StackEntry" union which may hold either a primitive data type, (char, bool, int, etc.) or a pointer to a struct, and then make your stack consist of such "StackEntry" unions.  Each one of these unions will roughly be as large as a machine word.

Do it the object oriented way: declare an "Object" class to represent any kind of object, declare derived classes, one to hold each kind of primitive and one to hold a struct, and make your stack a stack of Object. Each stack entry will be exactly one machine word, (a pointer to an Object,) but then for each stack entry you will have an entire dynamically allocated Object.  This will perform worse, but it will be a lot neater and cleaner, saving you from a lot of headache on the long run.  (Besides, if this is a toy VM, you really should not care about performance.)

Title: Implement Stack for Toy VM C++


答:
You and your boss/evaluator need to determine how much time you actually have to program. Take out the meetings, emails, documentation, testing, other interuptions from the time you are expected to work and see what is left.

Try to monitor your time to get a benchmark of how long certain tasks take. There will be productive times (for me early in the day or any stretch of time I get at work without interuptions) and unproductive times. Find an average.

You may determine that a given task takes 8 hours to program, but I doubt you will get that done in one day.

I would also try to compare yourself to others. The corporate culture may be to put in a lot of hours.

Title: How to become a "faster" programmer?

OwnerDisplayName: Jeff O


问:
Best practices for logging and tracing in .NET
I've been reading a lot about tracing and logging, trying to find some golden rule for best practices in the matter, but there isn't any. People say that good programmers produce good tracing, but put it that way and it has to come from experience.

I've also read similar questions in here and through the internet and they are not really the same thing I am asking or do not have a satisfying answer, maybe because the questions lack some detail.

So, folks say that tracing should sort of replicate the experience of debugging the application in cases where you can't attach a debugger. It should provide enough context so that you can see which path is taken at each control point in the application.

Going deeper, you can even distinguish between tracing and event logging, in that "event logging is different from tracing in that it captures major states rather than detailed flow of control".

Now, say I want to do my tracing and logging using only the standard .NET classes, those in the System.Diagnostics namespace. I figured that the TraceSource class is better for the job than the static Trace class, because I want to differentiate among the trace levels and using the TraceSource class I can pass in a parameter informing the event type, while using the Trace class I must use Trace.WriteLineIf and then verify things like SourceSwitch.TraceInformation and SourceSwitch.TraceErrors, and it doesn't even have properties like TraceVerbose or TraceStart.

With all that in mind, would you consider a good practice to do as follows:

Trace a "Start" event when begining a
method, which should represent a
single logical operation or a
pipeline, along with a string
representation of the parameter
values passed in to the method.

Trace an "Information" event when
inserting an item into the database.

Trace an "Information" event when
taking one path or another in an
important if/else statement.

Trace a "Critical" or "Error" in a
catch block depending on whether it
is a recoverable error.

Trace a "Stop" event when finishing
the execution of the method.

And also, please clarify when best to trace Verbose and Warning event types. If you have examples of code with nice trace/logging and are willing to share, that would be excelent.

Note: I've found some good information here, but still not what I am looking for: http://msdn.microsoft.com/en-us/magazine/ff714589.aspx

答:
You can try out the Story framework, it has a unique approach to logging as it "makes" you write all logs (and add other relevant information) in context so when you need to read it later you get everything you need.

It will automatically add the "start" and "stop" concepts as the beginning and end of a story.

And with a rule-based system you can control what to do with each story (context) based on the information it has, for example print all stories that have an error or come from the "admin" user.

Also more information on this blog post

OwnerDisplayName: Levidad


答:
Factory pattern refers to the general principle of having an entity (be it a class, an abstract class, an interface or a method) which knows how to create instances of other entities (usually objects implementing an interface of interest) on behalf of a caller so that the caller does not have to know how to create them.

Both abstract factories and factory methods are specializations of the factory pattern.  So, I think the interviewer was a bit of a stickler.  Or perhaps they failed to communicate to you that all they wanted from you was to describe the general principle, not caring about any specifics. Or perhaps they were suspicious as to whether you understand the general principle and you have not just memorized the definitions of certain terms.

Title: Is there a Factory Pattern distinct from Abstract Factory and Factory Method?

Body:
During a recent phone screen I was asked to describe the "Factory Pattern". I asked if the screener meant "Factory Method" or "Abstract Factory". He said, "No, just the Factory Pattern".

I don't know what the Factory Pattern is except in the context of the aforementioned GoF patterns. I've been researching this since the phone screen, but nothing I've found indicates that there is a third "just" Factory Pattern. The closest I came was this question, but still that seems to just distinguish Factory Method from Abstract Factory.

Is there a distinct third factory design pattern? If not, does "Factory Pattern" always just mean "Factory Method"?


问:
Using super keyword to access super class members
I have following questions about the super keyword in java:

I have a code below with classes:

A Extends no class contains integer variable i

B Extends class A contains integer variable i

C Extends class B contains integer variable i

```<code> class A {
    int i = 20;

    A() {
        System.out.println("I am in constructor of the parent class");
    }
}
</code>```

```<code>class B extends A {
    int i = 30;

    B() {
        System.out.println("I am in constructor of the subclass");
    }
}
</code>```

```<code>class C extends B {
    int i = 40;

    C() {
        System.out.println("I am in constructor of the main class");
    }

    void display() {
        System.out.println(i);
        System.out.println(super.i);
        /*
         * My first thoughts to access the third variable 'i'
         * inherited indirectly to this class by 'class A'.
         * I thought that it would print 20 :(.
           System.out.println(super.super.i);
         */
    }

    public static void main(String[] argue) {
        C obj2 = new C();
        obj2.display();
    }
}
</code>```

Now as class B inherits class A so it must have two integer variables i. Class C inherits class B so it will have two integer variables from B and one defined in itself.

Now I can print the inherited super class variable i in class C through the display method and of course the variable i defined in class C itself. The question is how to print the third i which has the value "20".

I know I can define a method in the class B that returns super.i; and call it through its object in class A that will print the third variable i and I also known that I can create an object of class A, but is there any other way by using super or any other thing to directly access the third variable in the class C.

Also the output is:

```<code>      I am in constructor of the parent class
      I am in constructor of the subclass
      I am in constructor of the main class
      40
      30
</code>```

why like the this keyword the super keyword cannot be used inside     static methods?

why is the super class constructor called to initialize the inherited variables of a subclass? This doesn't make any sense because if a class extends another class the variables and methods will be like they were locally declared in the class in other words its own members. So why can't the constructor of the subclass initialize those inherited members and has to call the super class constructor to initialize them.

答:
Much of this is spelled out in the JLS section 15.11:

15.11.2 Accessing Superclass Members using super

  The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.

The key word there is of the current object.  If there is no current object, such as the case with a static method, you can't user the super method.

When it comes to the constructor, the super class is responsible for initializing its fields. This is necessary because there may be private fields within the super class that a subclass has no access to.

Furthermore, requiring the subclass to instantiate the state of the super class may require the subclass to have more information than necessary and also requires a tighter coupling between superclass and subclass than is desirable - any change to the fields in the superclass would require a change in all the subclasses.  This is a bad thing.

Thus, you prevent this bad thing from happening by having the subclass call the constructor of the superclass when it is created.


答:
Well, I think I'm not slow, but the work I'm given tends to fill the available time.

Regardless, I oftentimes hear "Gee, you did that quick", but it's not from being a fast coder, it's from coding less.

I think the main way to code less is to think like a DSL. If you can't get the code generated for you by a preprocessor, then write a code generator. It doesn't have to be fancy. The objective is, if you are given a single stand-alone requirement, to minimize the number of source code differences needed to implement that requirement. Ideally, that number is 1. If you can get it down around 3-6 on average, that's pretty good. (It's not just that you're writing less. The smaller this number is, the smaller is the number of bugs you're putting in, and that really saves time.)

To do this, I recommend doing performance tuning, because then you will find out what coding practices lead to the greatest slowdowns, and they also lead to bloated code. In particular, excessive data structure and event/notification-style programming. Those things alone contribute massively to code volume.

Much code volume these days is due to the user-interface, especially if it is dynamically flexible. I stumbled on a way to do that part, called Dynamic Dialogs, which has a tough learning curve but shrinks the UI code by roughly an order of magnitude.

You'll have to find your own way on this, I'm afraid, but best of luck.

Title: How to become a "faster" programmer?

OwnerDisplayName: Mike Dunlavey


答:
For the case where you don't know in advance how many distinct colors you will be needing another interesting algorithm is the golden ratio algorithm.

Simply start at your favorite color and then go around the color wheel in steps of the golden angle (137.5°). With this angle you'll ensure that after every convolution around the color wheel your new colors fall between the colors you already created.

(Image from wikipedia)

Title: What algorithms are there for picking colors for plot lines on graphs?

Body:
I'm interested in what algorithms or rules I can programmatically implement to generate RGB or HSV colors for plotlines to keep them visually distinct from the neighbors.

I know that in professional mapmaking, there are algorithms or rules that make sure that no two adjacent countries on a map are the same color. I can also think of Microsoft office Excel as picking good tints/shades for plot lines (red, then blue, then purple/orange).

Here's an example of what I'm talking about - I need to generate colors for 12 lines on a black background. The colors here I've hardcoded by hand using web-safe RGB color codes. The problem arises when these lines overlap - it's hard to tell if one is looking at purple, slighly darker purple or violet. I'm looking for a better algorithm to produce colors for plotlines like these.

Here's an example using Flot plotting library for jQuery, it has nice succession of colors for graphs:


问:
Refusing to define 2 or more classes in one .cpp file
In my company there is implicit rule not to define multiple classes inside one .cpp file. The argumentation is that it looks like a mess and hard to read. But in my opinion it will make sense if the classes is related and not meant to be used outside compilation unit. Example:

example.h:

```<code>class ExampleState;

class Example {
    ...

    void SomeMethod();
private:
    ExampleState* state_;
}
</code>```

example.cpp:

```<code>class ExampleState {
    ...
}

Example::SomeMethod() {
    state_ = new ExampleState();
    ...
}
</code>```

What is your suggestion?

答:
Both conventions will work, and given you are using a modern IDE, none has really an advantage over the other. So technically, this is purely opionated. However, if you have a lot of "cowboy coders" in the team, it is sometimes better to set more strict rules to avoid endless discussions about "when is a source file too big" and "are these classes related enough". And in a big team, once you introduce the freedom to put several classes into one file, there will be always one who starts to abuse that freedom.

So if most of the team (and especially your teamleader) really does not like the idea of putting more than one file into class, don't do it. If, however, the team takes this more as a rough guideline, and there are others thinking similar like you, and they approve the combination of two classes in one file during the usual peer review (you do regular code reviews, don't you?), then it is probably ok.

See also: How would you know if you've written readable and easily maintainable code?


答: There are a bunch of great ideas here.  To help me get in the 'zone' I use a timer set at 27 minute intervals.  I find once I'm in work mode it's easy to work well beyond the buzzer and working with flow is painless.  Getting there is hard though.</p>

Title: How to become a "faster" programmer?

OwnerDisplayName: Daver


问:
Why do we need both Priority and Severity?
I understand what they determine but is it really useful to assign those to issues found? I mean, it is either required to fixed quickly or not.

I know how to set them, categorize them etc. I know IEEE/ISO do require to do that. I just do not see why.

答: It is absolutely possible to have those values differ. If you have a sale to make to an important government agency that requires high performance but won't ever use module X, then it makes a lot of business sense to fix a minor database availability error sooner than a severe error in the X module. Basically, technical reasons are not the only factor when you run a software business.


答:
IMHO, putting both Priority and Severity is just bureaucracy.

In practice, you just need one measure of "importance". Often, priority is used for it, and severity is then used as technical term like "high = crashes system or makes it unusable", "medium = buggy behavior, potentially harmful", "low = nuisance, annoying but harmless"

Usually, priority goes hand in hand with severity. A few counter examples are a "nuisance where everyone always complains" or a "crash having occured once in an exotic environment".

...but, in the end, as a developer (or manager, etc) you only need to know in what order you should fix/improve things, that's all. So one measure is enough.

The need of priority is clear: it's to know in what order the bug reports should be tackled. The other one, IMHO as usual, is bureaucracy. Why do you need it? It's apparently useless for sorting because priority does that. And the consequences (severity description) is described in the bug report anyway.

I even think it is harmful because it makes it less clear what bug is more important:

Some may think a "critical" bug has higher priority than a "high-priority" bug.

Some users reporting a bug may confuse severity and priority

...altogether, it rather adds confusion as to what order the bugs should be tackled

Title: Why do we need both Priority and Severity?

Body:
I understand what they determine but is it really useful to assign those to issues found? I mean, it is either required to fixed quickly or not.

I know how to set them, categorize them etc. I know IEEE/ISO do require to do that. I just do not see why.


答:
For reason to strongly differ priority and severity:

A simple example. Imagine the case you have a narrow place that prevents scaling of your system - some algorithm has complexity O(N^3), where N is count of client's stores. The client says it will open 200 new stores the next year, and the needed calculations (goods distribution, transportation planning, etc.) won't be finished in time. But, currently this client has only 30 stores, and resources are enough. The task to optimize this algorithm (to O(N^2) or better) is definitely important (you'll lose the client if not implemented), but likely not urgent: you have a few months to implement the new algorithm.

Example 2: an application crashes systematically, but this version gets out of usage in a few days due to upgrade or migration. Fixing is urgent because crashes really affect user experience, but is of low importance.

Of course, both parameters are unified using some metric (either formal or informal) to produce a short-term work plan, because the latter is single-dimensional (sequence of tasks). But in long term view they shall not be unified.