答:
TLDR What is the value of a Primary Key annotation? The primary key denotes the quickest means of locating a record. As you mentioned in your question, most SQL implementations use the primary key to denote where in the table file the record is stored. Using a auto-incrementing numeric key avoids unnecessary fragmentation of the file. (Reducing the file size and write time)

As a rule of thumb, a primary key should have no significance to the business. I.E. an SSN should not be used as a primary key. The reason for this is that business rules change. A value that is "always" unique like an SSN usually has an exception that is discovered down the road there are only a Billion possible combinations of 9 digits there are 300 million citizens in America.

Likewise values that will "always" be present have exceptions too. our HR System has to support companies outside of America where employees don't have a Social Security Number

The purpose of a primary key is to give a unchanging identifier to an entity so that I always know where to find that entity. Non-primary keys or Indexes are used to enable a user to easily lookup an entity given knowledge of that attribute.

Think of the primary key as an address to a block of memory. If another entity holds that address, we expect to be able to jump to that address and find the original entity.

Edit
I don't tend to write answers on here without knowing what I'm talking about. I know the difference between a surrogate and a primary key. If you want a second opinion. Here you go

You have three choices for defining the primary key for most tables: a 'natural' key, a >system generated or 'internal' key, and (for smaller lookup tables) a mnemonic code.

Internal ID numbers

Rule of thumb: for any table over 100 records, use a system-generated
  number as the primary key.

Any time your system stores a record, particularly when the record's
  'natural' key ID number is controlled by an outside source, there is a
  risk that the outside source may do odd things with its data - it may
  re-use the ID number, it may update a record by changing the ID, or
  the system may have a problem talking to the outside source and may
  get the same record sent twice. In every such case, your system must
  not be tightly coupled to the outside source - where "tightly coupled"
  means that a problem in the outside source system causes your system
  to fail to work correctly.

Therefore, as a form of humility, your system should accept at face
  value whatever the outside sources send. The system should not try to
  fix other systems, nor modify their data, nor maintain referential
  integrity for them. (Your system should do all of those things for its
  own internally created data, but not for other systems' data that is
  imported.)

When other systems do make corrections to earlier errors, your system
  should take the later data at face value and overwrite any earlier
  records they sent. In every case, your system should faithfully and
  accurately record whatever is sent from other systems.

This approach can only be made to work with system generated ID
  numbers. Other keys could be created instead, such as the external
  system's primary key plus (say) the date, but this merely tries to
  obtain the benefits of humility without acknowledging the work, and
  exposes your system to problems if any of the above mentioned problems
  were to occur within the course of a single day (when the dates would
  be duplicated).

(On an earlier system I tried the external-key-plus-datetime approach,
  only to find that duplicates arrived within the same datetime down to
  the second -- one second being the finest granularity of an Oracle
  datetime.)

Note: this does NOT mean your system allows users to enter bad data.
  Data that users enter directly in the system is part of the system's
  own data, and therefore it takes responsibility for that data's
  cleanliness and accuracy. All data entry screens will provide and
  enforce "edits" to ensure the correctness of data entered by users
  directly into your system.

Natural Keys

Rule of thumb: don't use natural keys as primary keys; instead, store
  them as attributes.

I view 'natural' keys as actually just the keys of an external system
  -- even if that external system is the outside world. Generally, natural keys are untrustworthy in the extreme. Here are some examples
  of their untrustworthy behavior:

A criminal steals someone's (US Government generated) Social Security
  Number (SSN) to commit fraud (now two people have one SSN). Later, the
  victim is assigned a new SSN (now one person has had two SSNs at
  different times.) A system that used SSNs as a 'natural' key would
  have a terrible time with this scenario. A visitor to the US (or an
  American child) who has no SSN cannot be tracked by the system, and
  essentially doesn't exist.

A supplier re-uses SKUs (Stock Keeping Units), i.e. when a product
  becomes obsolete its SKU is reassigned to a new product.

You'll still want to store the supplier SKU -- you just need to be
  alert to its potential for misbehavior.

Mnemonic Codes

Rule of thumb: for any table over 100 records, use a system-generated
  number as the primary key.

For lookup tables, I like to take advantage of the fact that primary
  key values of lookup tables become foreign key values in the tables
  that reference them -- and if a code is mnemonic (its meaning is
  easily remembered) then often the user doesn't even need to do a join
  to know what the key means.


问:
Painfully Stupid Method Names in Legacy Code: Fix or Leave as Warning?
For this case let's assume something like... "removedNonPriceChangingConfermations" that is in no way relating to things that happened in the past tense, nor does it return a list of removed items (which you would never need in this context).

If you can't spot the other thing wrong with it, I challenge you to a high-stakes spelling contest.

The Dilemma:

Is it better to rename the method to more accurately and less painfully describe what it actually does?

Or given that it sits within a 20-class roller coaster of fail (mapping a db queried table to a bean) is it better to leave it as a sort of a warning buoy of the unique minds that crafted the code with comments to explain what it really does at the definition? At least until we can properly refactor the silly thing.

If relevant, assume a high turnover rate but always good intentions.

Please Note: It's not hard to change the method name. This question is more generally about whether it isn't better to leave a really dumb method name intact so people can see that they're walking into "one of those parts" of the code base or if I should in fact change it to better reflect what it actually does.

答:
How I would approach this:

If refactoring is actually going to happen at some point then I would leave it as is with a comment.

If it's only called in a few spots and has good test coverage then I would change it.

If neither of those situations apply but it keeps you up at night I would change it.

Else, move on to something more important.

ContentLicense: CC BY-SA 3.0


答:
I'd probably fix it, especially if I had some work to do in that area...  No need to leave bad code around.  Examples of good names trump examples of bad names.

But, some things that might affect that decision are whether I can test it for unintended consequences.  Especially if it's public and from an interface in legacy code.

I ran into that today, in fact, a method that was public and in an interface, which didn't seem to be referenced from anywhere, until I ran the application and found out a legacy framework in our app that is configured with method names in XML used it.

If I couldn't confirm that things still worked correctly after the change, I'd probably just leave it to ferment.

Title: Painfully Stupid Method Names in Legacy Code: Fix or Leave as Warning?

Body:
For this case let's assume something like... "removedNonPriceChangingConfermations" that is in no way relating to things that happened in the past tense, nor does it return a list of removed items (which you would never need in this context).

If you can't spot the other thing wrong with it, I challenge you to a high-stakes spelling contest.

The Dilemma:

Is it better to rename the method to more accurately and less painfully describe what it actually does?

Or given that it sits within a 20-class roller coaster of fail (mapping a db queried table to a bean) is it better to leave it as a sort of a warning buoy of the unique minds that crafted the code with comments to explain what it really does at the definition? At least until we can properly refactor the silly thing.

If relevant, assume a high turnover rate but always good intentions.

Please Note: It's not hard to change the method name. This question is more generally about whether it isn't better to leave a really dumb method name intact so people can see that they're walking into "one of those parts" of the code base or if I should in fact change it to better reflect what it actually does.


答:
Grep the entire code base for the name of the method. Find out how public it is, how many configs mention it, etc.

Rename the method mercilessly (a good IDE can do this), grep again, manually update any references that the IDE has missed. Add a comment explaining method's peculiarities, if any.

If the method is not public (only has package visibility or narrower), you're done!

If the method is somehow public (exposed to 3rd parties or just has public visibility for no apparent reason), create a method with the old name that calls the newly renamed method and logs the fact. This way you will find out what other clients of this methods are. If these are under your control, eventually make them use the new name.

Run tests. If you don't have a test for that method, or for some of its clients, it's a good moment to add them.


答: Refactor it, but make a hardprint first. Frame it. And put it on a fame hall of shame.</p>


问:
Is there value denoting a key as "Primary"?
Question: Is there value in denoting a key as "Primary"?

This question is not about the definition of a primary key. It is not about the fact primary's aren't nullable. It is not about implementations such as MySQL which automatically perform clustered index voodoo behind the scenes on primary keys.

NOTE: The question is not about the benefits of auto-number-ID surrogates over natural keys.

Suppose a table has 3 candidate keys. All non-nullable. All immutable. I find no value denoting a key as "secondary" or "tertiary". I don't find the concept of precedence useful when dealing with multiple keys. I find the same logic against "secondary" and "tertiary" flags applies to the "primary" flag.

I even feel the word "candidate" is not useful for a key. It implies the candidate is not as important as the key that won the primary election. I don't feel precedence has any place in describing keys. The attributes of the key itself (unique, non-nullable, etc) should be sufficient.

Would the relational model be missing anything if we did not have the "primary" attribute to describe 1 of a table's keys?

答:
Technically speaking, a primary key is not different from any other unique non-nullable key: you can get the exact same schema restrictions by just making your columns non-nullable (and even that isn't really a requirement IIRC), and defining a unique key for them.

However, declaring a key as PRIMARY signals that you intend this particular key to be the default way of referencing rows in this table. This marker is important for other people working with your schema, because it tells them that they can expect this key to stay intact, and that you will check any foreign keys in other tables that reference it before changing it. But it is also of interest to the database engine, if only because this extra information can be used for query optimization and caching heuristics.


问:
Is it possible to encapsulate the object itself within a dynamic property?
I ask this question out of curiosity.

Lets say the class Foo is a singleton and I want to call Foo instead of Foo.Instance to access the static object.

Would it be possible to encapsulate the object itself within a dynamic property?

Would C# allow me to create a dynamic property that refers to anything but a property of the said object?

Like so:

```<code>private static Foo _instance;

public static Foo this {
    get {
        if (_instance == null) {
            _instance = new Foo();
        }
        return _instance;
    }
}
public void Bar(){}
</code>```

this would allow me to call

```<code>Foo.Bar();
</code>```

instead of

```<code>Foo.Instance.Bar();
</code>```

If this is possible, then in witch situation would it be viable to encapsulate any kind of object like this whithout using heritage

for example instead of:

```<code>class Ploof : List{}
</code>```

we would have:

```<code>class Ploof {
    private List _list;
    public List this { get {  return _list; } }
}
</code>```

答:
No, it isn't.

But if you use the singleton often, you can always create local variable with reference to the instance.

But I would consider such heavy use of singleton as code smell and I would question if you really should be using a singleton.


问:
register variable in C and C++
I know the concept of register variable and it's use cases but there are few questions in my mind based on what I have tried.

I cannot access the address of a register variable in C though I can do it C++! Why? Is there any issue in accessing the addressing of a register variable?

Suppose if I declare a string variable in C++ as register, then where will that variable be stored? What is the point in declaring the storage class of non-numeric data types such as 'string' in C++ to be register??

UPDATE:
I thought that C++ allows us to fetch the address of a register variable, as I was not getting any error in my program which is as follows:

```<code>#include<iostream>
#include<time.h>

using namespace std;

clock_t beg, en;

int main(){

    int j, k=0;

    beg=clock();
    for(register int i=0;i<10000000;i++){
        /*if(k==0){
            cout<<&i<<endl;    // if this code is uncommented, then C++ rejects the recommendation to make 'i' as register
            k++;
        }*/
    }
    en=clock();

    cout<<en-beg<<endl;

    cout<<&j<<endl<<&k;

    return 0;
}
</code>```

What I have observed is, if I make the variable 'i' as register and don't try to print the address using '&i' then C++ accepts the recommendation and stores 'i' in register, this can be infered from running time of for loop which will always be around 4-12 ms if 'i' is in register. But if I try to print address of variable 'i' then though I don't get any error but C++ rejects the recommendation and this can be infered from the time of execution of loop which is always more than 25 if i is not register!!

So, basically I cannot fetch address of a variable with storage class as register!! WHY?

答:
The variables of a program (on modern non-embedded architectures) can live in one of 2 places, the RAM and the registers. The RAM is indexed and registers can be accessed directly in the opcodes.

The address of a variable is the index where it lives in the RAM, a register doesn't live in the RAM so there is no way to create a meaningful address for it unless you put it on the stack but that defeats the purpose of the register keyword.

As fun as the keyword is, these days compilers are good enough to decide for themselves which variables never need to get copied on the stack or not (the sub branch there is called register allocation).

And as with most old school optimizations giving hints to the optimizer is more likely to confuse and/or hinder it if you don't know exactly what the results are. Because optimizers are geared towards the idiomatic language constructs, and unless there is a bottle neck in the function don't worry about it. Don't shave off 1 or 2 cycles of a rarely used function when the true bottle neck is the DB access.

Title: register variable in C and C++


问:
What are some standard design methods to add GUI to a command line app?
I have an embedded Linux C application that runs with a simple CLI. I am now tasked with creating a GUI that accomplishes the same functionality as the command line program. I am not an accomplished GUI designer and the majority if my experience is in deeply embedded C  coding.

My initial thought is to use qtcreator to create the GUI, but there are several issues I'm ruminating over.

Moving forward I want to maintain both the CL program and the GUI program, and preferably even have them be the exact same executable that can be launched in either mode. Unless this is a bad idea?

My code is in C so far, and qt is natively c++

I would like a direct correlation where button presses in the GUI call the same functions that I call from the CLI

How do I best do this cleanly and efficiently? Is there some other thecnology or library that simplifies this? I don't have to use qt if there is something better.

答:
Usually, this can be solved by writing a GUI front-end that builds a command line. At that point you simply call the old CLI "main()" function with the arguments in the appropriate order.

What you need to do then, depends on the output. You might do well by wrapping all printf()'s in a generic output variadic function, that in the CLI version will just pass control to printf while in the GUI version sends output to a scrolldown log window or something like that.

This way, the CLI application is mostly unchanged and the GUI front-end, while losing in efficiency, remains loosely coupled and can be maintained independently (in some cases, a mockup - or even a real alternative to the GUI - might be an independent application that then spawns the CLI binary with the proper arguments; sort of what you can do with AutoIt on Windows, so to speak).

But this strongly depends on what the application actually does. This approach can still be pursued to a greater or lesser extent, but it might become awkward if, for example, you wanted to execute the CLI routine cyclically or something like that; or if the program expected to operate on an input from stdin.


答:
the first thing you want to do is make the back end (behind the current CLI) separated from the frontend (the CLI)

essentially separate the view/controller (CLI) from the model so all the functionality code can be separated out into it's own stand-alone module (that you can compile into a static lib for example)

then you can use the public C interface of that module to code against in you QT GUI

for the correlation of the button presses there is a extensive signal-slot implementation in QT and QT creator will handle a lot of the binding for you (its as simple as right click-> go to slot...-> clicked() -> type foo())

Title: What are some standard design methods to add GUI to a command line app?

Body:
I have an embedded Linux C application that runs with a simple CLI. I am now tasked with creating a GUI that accomplishes the same functionality as the command line program. I am not an accomplished GUI designer and the majority if my experience is in deeply embedded C  coding.

My initial thought is to use qtcreator to create the GUI, but there are several issues I'm ruminating over.

Moving forward I want to maintain both the CL program and the GUI program, and preferably even have them be the exact same executable that can be launched in either mode. Unless this is a bad idea?

My code is in C so far, and qt is natively c++

I would like a direct correlation where button presses in the GUI call the same functions that I call from the CLI

How do I best do this cleanly and efficiently? Is there some other thecnology or library that simplifies this? I don't have to use qt if there is something better.


答:
If a table has three candidate keys, all unique, non-nullable and immutable, the best choice for a primary key is the smallest candidate key (both in terms of number of fields and field size) that is of sufficient size that you will never run out of possible values to store in it. Ideally, a table's primary key should be one field (which, coupled with the data independence and immutability advantages, make autonumber fields a pretty easy choice for many DBAs, with GUIDs a close second).

The primary key has special conceptual significance over any other candidate key, because it is the one that is used to reference that record as a foreign key on any other table. Every RDBMS I can think of enforces this; you can't specify a unique index as the foreign key; it has to be the primary key. Foreign keys, in turn, enforce referential integrity; the value stored as the foreign key reference in a record of another table must exist as the primary key of the referenced table, meaning you can't save a record referencing a nonexistent PK value, and you can't delete a record whose PK value is referenced by another record as a foreign key.

Now, you might say you can join tables on any field you like, including a unique index for another candidate key. That's correct. You could also say that you could define constraints requiring the value to exist in a query of the other table, and triggers to prevent deletion of a record referenced by another table. That's also correct. My question to you would be, "WHY?". Foreign keys exist to provide all this functionality; why reinvent the wheel, especially when it requires so much work to do so?

Leading back into things you didn't want to talk about, but that are significant when making keying decisions, virtually all RDBMSes (not just MySQL) define the primary key as an index, which determines how the data for the table is structured in the underlying data files. In MSSQL, that's a "clustered" index which means that records are arranged and grouped within the filesystem according to their PK, in addition to the PK appearing in search trees. Not all RDBMSes arrange their data in the same way, but as sequential data access is often important for performance, proper indexing is key to working with real-world RDBMS implementations in an efficient way.

Title: Is there value denoting a key as "Primary"?

Body:
Question: Is there value in denoting a key as "Primary"?

This question is not about the definition of a primary key. It is not about the fact primary's aren't nullable. It is not about implementations such as MySQL which automatically perform clustered index voodoo behind the scenes on primary keys.

NOTE: The question is not about the benefits of auto-number-ID surrogates over natural keys.

Suppose a table has 3 candidate keys. All non-nullable. All immutable. I find no value denoting a key as "secondary" or "tertiary". I don't find the concept of precedence useful when dealing with multiple keys. I find the same logic against "secondary" and "tertiary" flags applies to the "primary" flag.

I even feel the word "candidate" is not useful for a key. It implies the candidate is not as important as the key that won the primary election. I don't feel precedence has any place in describing keys. The attributes of the key itself (unique, non-nullable, etc) should be sufficient.

Would the relational model be missing anything if we did not have the "primary" attribute to describe 1 of a table's keys?


答:
Is it useful as a warning sign? Not really. It will just confuse people and be hard to remember.

A well named function that tells someone unfamiliar what hairy code actually does is very useful. Bad or confusing code, which you imply is in the function, can be horrible to work out. If you've done that and can give a good description for the function in the name then you've made the next programmer's job much easier.

Commenting what it does is also useful, but comments are not always read, but the function name is.

Broken windows should always be fixed. Not fixing the name will leave a broken window, and encourage the next programmer not to start re-factoring.


答:
No, there is (as far as I know) currently a limitation in the DLR where the dynamic overrides are not applied to static members. You can do tricks with a variable so that it redirects all calls to a singletone, or even via extension methods so that every object has a .Foo() member you can call a singleton .Bar() on. You can even do tricks with implicit conversion operators so that Ploof looks and acts like a list.

But again, this is all horrible and ill advised - even more than singletons in the first place.

Title: Is it possible to encapsulate the object itself within a dynamic property?

Body:
I ask this question out of curiosity.

Lets say the class Foo is a singleton and I want to call Foo instead of Foo.Instance to access the static object.

Would it be possible to encapsulate the object itself within a dynamic property?

Would C# allow me to create a dynamic property that refers to anything but a property of the said object?

Like so:

```<code>private static Foo _instance;

public static Foo this {
    get {
        if (_instance == null) {
            _instance = new Foo();
        }
        return _instance;
    }
}
public void Bar(){}
</code>```

this would allow me to call

```<code>Foo.Bar();
</code>```

instead of

```<code>Foo.Instance.Bar();
</code>```

If this is possible, then in witch situation would it be viable to encapsulate any kind of object like this whithout using heritage

for example instead of:

```<code>class Ploof : List{}
</code>```

we would have:

```<code>class Ploof {
    private List _list;
    public List this { get {  return _list; } }
}
</code>```


问:
Programming by dictation?
ie. you speak out the code, and someone else across the room types it in

Anyone tried this?

Obviously the person taking the dictation would need to be a coder too, so you didn't have to explain everything and go into tedious detail (not 'open bracket, new line...' but more like 'create a new class called myParser that takes three arguments, first one is...').

I thought of it because sometimes I'm too easily distracted at my computer. Surrounded by buttons, instant gratification a click away, the world at my fingertips. To get stuff done, I want to get away, write my code on paper. But that would mean losing access to necessary resources, and necessitate tedious typing-up later on.  The solution? Dictate.

Pros:

no chance to check reddit, stackexchange, gmail, etc.

code while you pace the room, lie down, play billiards, whatever

train your brain to think more abstractedly (have to visualize things if you can't just see the screen)

skip the tedious details (closing brackets etc.)

the typist gets to shadow a more experienced programmer and learn how they work

the typist can provide assistance/suggestions

external pressure of typist expecting instructions, urging you to stay focussed

Cons

might be too hard

might not work any better

rather inefficient use of assisting programmer

need to find/pay someone to do this

答:
Let's take a step back. The problem you seem to want to solve with is one of focus. That problem already has a solution, similar in look but very different in practice, which others have mentioned; pair programming.

Pair programming between two competent developers of roughly equal knowledge should not be programming by dictating. Instead, one programmer codes, the other one observes. Both are thinking, and of course communication is key, but both typist and observer are equal partners; the observer should neither be a backseat driver nor be catching Zs. The pair will also switch often, with observer coding and coder observing.

The main point is to stay focused, which is what you want. If one coder spends more than a few seconds on an IM or updating his Facebook status, the other can politely clear his throat and bring the coder back to the task at hand. Of course both coders can get distracted, either on the same or different things, but usually not for very long; one of them will soon enough resolve his distraction and be tapping their feet waiting for the other. If both of them are lost in Stack Overflow, Reddit or YouTubes, well that's a problem, but it's unlikely; one or the other is going to get self-conscious about wasting the other's valuable time with lolcats or skateboard bails and suggest they get back to work.

The second point is to have two pairs of eyes looking at the code, and two brains thinking about it. Pair programming provides a real-time code review process. This requires some tact; the observer has to allow the coder the time to go back and fix the typo he made. Immediately pointing out fat-fingers and other typos when the coder, more often than not, knew exactly what he did and just wants to finish his thought before correcting it, is extremely frustrating, bordering on dictation. However, if the coding partner seems to be moving on and has genuinely missed something, the observer can point it out so it gets fixed before they waste time with a build or a test run. By the same token, if the observer thinks they know a better way, they can not only tell that to their coding partner, they can take the wheel and drive for a while.

My experience with pair programming is typically positive. My experience with programming by dictation is typically negative. As the dictator, I feel handcuffed by not having my hands on the keyboard (this is alto true with pair programming when I'm observing, but to a lesser extent). I know my way around this application (be it what we're coding or what we're coding in). I know what I want to do and exactly how to do it. Yet I'm stuck watching this other guy constantly hesitating, searching for the right command or identifier, while doing something not quite what I had in mind, but close enough that I don't call it out because that would be micromanaging (but I sock it away with all the other things that give me nervous tics by the end of the day). Whenever I've been required to dictate code, it has almost always been to a guy fresh out of college who's had maybe two semesters' academic experience with the language and IDE, and I find I have to dictate every keystroke, because if I make any assumptions that the typist knows what I want when I describe what to do in more abstract terms, I'm disappointed as he types in something so obviously wrong that even Notepad would cry.

I imagine people who have typed according to my dictation have had similar levels of frustration. They're not in my head, they don't know what I know or what I'm thinking right now, and I think much faster than I can talk so I'm probably not helping. They often don't have my fancy $130 code formatting tool, so as much as they may care about proper indentation or naming conventions, it's a hell of a lot more work for them to get there on their box than for me on mine (we're trying to fix that). They're trying to keep up, and you'd be surprised how many really smart coders are lousy touch typists. It doesn't help that coding commonly uses symbols and character combinations that don't often pop up in the everyday administrative assistant's typing test, to say nothing of a friendly IM conversation.

Programming by dictation is, IMHO, one big fat sack of "no". It is the anti-pattern to pair programming's good practice.

ContentLicense: CC BY-SA 2.5

Title: Programming by dictation?


答:
What you seem to want is a straight-up static class. The class and all its members are simply declared static. For instance:

```<code>public static class Foo
{
   static Foo()
   {
       //initialize any state data needed by methods
   }

   public static void Bar()
   {
      //...
   }
}

//usage, just as you wanted
Foo.Bar();
</code>```

The basic problem with this is that everything in the class has to be declared static, and must always be accessed statically. That in turn means that once this code's used in more than a couple of places, you really can't ever change its architecture to be more object-oriented. It also usually means that the class can't have any inheritance hierarchy,  because any parent or child would also have to be static, and if the parent's static and all children are static, you really just have three partial classes. In C# for instance, you can't derive a static from any other class, and can't inherit from a static; they're single, isolated, widely-scoped oddities of your codebase.

Statics in general are to be minimized because, as above, they violate some key principles of SOLID code design, and of object-oriented code in general (in the real world which OOA&D attempts to model, there are very, very few object generalizations that have no parents, no children, and there are and can only ever be one of them).

These are the problems that the Singleton pattern solves, for the most part. The class itself is not static, but it has two or three static members; a constructor so it can self-initialize, and an instance accessor (which may use a specific backing field, or it may be an auto-property). While you still have static state and static availability which are kind of no-nos, the singleton allows you to use its instance as an instance, passing it around between classes and methods as a dependency, with none of those lower-level objects having to know it's statically scoped or that there can only ever be one instance. Because the class itself isn't static, if you wanted to, you could implement interfaces or even extend base classes, and you can theoretically derive from it, although that gets very tricky very quickly.

The tradeoff is always referencing the instance when using the singleton in static state. There are cute ways to mitigate it, but I only included the examples below because I thought they were funny; DO NOT USE THESE EVER:

```<code>public class F
{
   static F() {instance = new F();}

   private F() {...}
   public static F oo {get{return instance;}}

   public void Bar() {...}
}

...

//FXCop (and most of your fellow coders) will curse your name
F.oo.Bar();

public class Fo
{
   static Fo() {instance = new Fo();}

   private Fo() {...}
   public static F this(int useZeroItsFunny) {get{return instance;}}

   public void Bar() {...}
}

//a WTF if there ever was one...
Fo[0].Bar();
</code>```

Body:
What you seem to want is a straight-up static class. The class and all its members are simply declared static. For instance:

public static class Foo
{
   static Foo()
   {
       //initialize any state data needed by methods
   }

   public static void Bar()
   {
      //...
   }
}

//usage, just as you wanted
Foo.Bar();

The basic problem with this is that everything in the class has to be declared static, and must always be accessed statically. That in turn means that once this code's used in more than a couple of places, you really can't ever change its architecture to be more object-oriented. It also usually means that the class can't have any inheritance hierarchy,  because any parent or child would also have to be static, and if the parent's static and all children are static, you really just have three partial classes. In C# for instance, you can't derive a static from any other class, and can't inherit from a static; they're single, isolated, widely-scoped oddities of your codebase.

Statics in general are to be minimized because, as above, they violate some key principles of SOLID code design, and of object-oriented code in general (in the real world which OOA&D attempts to model, there are very, very few object generalizations that have no parents, no children, and there are and can only ever be one of them).

These are the problems that the Singleton pattern solves, for the most part. The class itself is not static, but it has two or three static members; a constructor so it can self-initialize, and an instance accessor (which may use a specific backing field, or it may be an auto-property). While you still have static state and static availability which are kind of no-nos, the singleton allows you to use its instance as an instance, passing it around between classes and methods as a dependency, with none of those lower-level objects having to know it's statically scoped or that there can only ever be one instance. Because the class itself isn't static, if you wanted to, you could implement interfaces or even extend base classes, and you can theoretically derive from it, although that gets very tricky very quickly.

The tradeoff is always referencing the instance when using the singleton in static state. There are cute ways to mitigate it, but I only included the examples below because I thought they were funny; DO NOT USE THESE EVER:

public class F
{
   static F() {instance = new F();}

   private F() {...}
   public static F oo {get{return instance;}}

   public void Bar() {...}
}

...

//FXCop (and most of your fellow coders) will curse your name
F.oo.Bar();

public class Fo
{
   static Fo() {instance = new Fo();}

   private Fo() {...}
   public static F this(int useZeroItsFunny) {get{return instance;}}

   public void Bar() {...}
}

//a WTF if there ever was one...
Fo[0].Bar();


答:
I would fix it. The question infers Java, but I code in C# for a living and own a copy of ReSharper, and so changing the name of a code member, from a private field all the way up to the namespace root, is pretty simple; right-click->Refactor->Rename. So, I just do it, because it really is just that simple (99% of the time; if I'm working in libraries shared between distinct codebases, I might be more cautious as quite a bit of our legacy code has no automated build in TeamCity).

I do not know what kinds of tools along these lines are available for Eclipse, but JetBrains also writes IntelliJ IDEA which has many of these types of refactor operations built right in.


问:
What does scannerless parsing have to do with the "Dangling Else Problem"?
I do not understand this sentence from the Wikipedia article on the Dangling Else problem:

[The Dangling Else problem] is a problem that often comes up in compiler construction, especially scannerless parsing.

Can someone explain to me how scannerless parsing techniques might exacerbate this problem?  It seems to me that the problem is with the grammar -- since it's ambiguous -- not with the choice of parsing technique.  What am I missing?

答:
Just to state the problem, the Dangling Else Problem is an ambiguity in code syntax specification where it may be unclear, in cases of nexted ifs and elses, which else belongs to which if.

The simplest and classic example:

```<code>if(conditionA)
if(conditionB)
   doFoo();
else
   doBar();
</code>```

It is unclear, to those who don't know the specifics of the language specification by heart, which if gets the else (and this particular code snippet is valid in half a dozen languages, but may perform differently in each).

The Dangling Else construct poses a potential problem for scannerless parser implementations, because the strategy is to slurp up the file stream one character at a time, until the parser sees that it has enough to tokenize (digest into the assembly or intermediate language it's compiling). This allows the parser to maintain minimal state; as soon as it thinks it has enough information to write the tokens it's parsed to the file, it will do so. That's the end goal of a scannerless parser; fast, simple, lightweight compilation.

Assuming newlines and whitespace before or after punctuation are meaningless (as they are in most C-style languages), this statement would appear to the compiler as:

```<code>if(conditionA)if(conditionB)doFoo();else doBar;
</code>```

Perfectly parse-able to a computer, so let's see. I get one character at a time until I have:

```<code>if(conditionA)
</code>```

Oh, I know what that means (in C#), it means "push conditionA onto the eval stack and then call brfalse to jump to the statement after the next semicolon if it's not true". Right now I don't see a semicolon, so for now I'll set my jump offset to the next space after this instruction, and I'll increment that offset as I insert more instructions until I see a semicolon. Continuing to parse...

```<code>if(conditionB)
</code>```

OK, this parses out to a similar pair of IL operations, and it goes immediately after the instruction I just parsed. I don't see a semicolon, so I will increment the jump offset of my previous statement by the length of my two commands (one for the push and one for the break) and keep looking.

```<code>doFoo();
</code>```

Ok, that's easy. That's "call doFoo". And is that a semicolon I see? Well, that's great, that's the end of the line. I'll increment both my blocks' jump offsets by the length of these two commands and forget I ever cared. OK, moving on...

```<code>else
</code>```

... Uh-oh. This isn't as simple as it looked. OK, I forgot what I was just doing, but an else means there's a conditional break statement somewhere that I've already seen, so let me look back... yep, there it is, brfalse, right after I push some "conditionB" on the stack, whatever that was. OK, now I need an unconditional break as the next statement. The statement that will come after that is now definitely my conditional break's target, so I'll make sure I have it right, and I will increment the unconditional break I put in. Moving on...

```<code>doBar();
</code>```

That's easy. "call doBar". And there's a semicolon, and I never saw any braces. So, the unconditional break should jump to the next statement, whatever it is, and I can forget I ever cared.

So, what do we have... (note: it's 10:00 PM and I don't feel like converting bit offsets to hexadecimal or filling out the full IL shell of a function with these commands, so this is just pseudo-IL using line numbers where there would normally be byte offsets):

```<code>ldarg.1 //conditionA
brfalse <line 6> //jumps to "break"
ldarg.2 //conditionB
brfalse <line 7> //jumps to "call doBar"
call doFoo
break <line 8> //jumps beyond statement in scope
call doBar
<line 8 is here>
</code>```

Well, that actually executes correctly, IF the rule (as in most C-style languages) is that the else goes with the closest if. Indented to follow execution nesting, it would execute like this, where if conditionA is false, the entire remainder of the snippet is skipped:

```<code>if(conditionA)
    if(conditionB)
       doFoo();
    else
       doBar();
</code>```

... but it does so by serendipity, because the break associated with the outer if statement jumps to the break statement at the end of the inner if, which takes the execution pointer beyond the entire statement. It's an extra unneeded jump, and if this example were any more complex it might no longer function if parsed and tokenized this way.

Also, what if the language specification said that a dangling else belongs to the first if, and if conditionA is false then doBar is executed, while if conditionA is true but not conditionB then nothing happens, like so?

```<code>if(conditionA)
    if(conditionB)
       doFoo();
else
   doBar();
</code>```

The parser had forgotten the first if ever existed, and so this simple parser algorithm would not produce correct code, to say nothing of efficient code.

Now, the parser could be smart enough to remember the ifs and elses it has for a longer time, but if the language spec says a single else after two ifs matches to the first if, that causes a problem with two ifs with matching elses:

```<code>if(conditionA)
    if(conditionB)
       doFoo();
    else
       doBar();
else
    doBaz();
</code>```

The parser will see the first else, match to the first if, then see the second one and go into panic "what the hell was I doing again" mode. At this point the parser's got rather a lot of code in a mutable state that it would much rather have already pushed out to the output filestream.

There are solutions to all these problems and what-ifs. But, either the code needed to be that smart increases the complexity of the parser algorithm, or the language spec allowing the parser to be this dumb increases the verbosity of the language source code, such as by requiring terminating statements like end if, or brackets indicating nested blocks if the if statement has an else (both of which are commonly seen in other language styles).

This is just one, simple example of a couple of if statements, and look at all the decisions the compiler had to make, and where it could very easily have messed up anyway. This is the detail behind that innocuous statement from Wikipedia in your question.

Body:
Just to state the problem, the Dangling Else Problem is an ambiguity in code syntax specification where it may be unclear, in cases of nexted ifs and elses, which else belongs to which if.

The simplest and classic example:

if(conditionA)
if(conditionB)
   doFoo();
else
   doBar();

It is unclear, to those who don't know the specifics of the language specification by heart, which if gets the else (and this particular code snippet is valid in half a dozen languages, but may perform differently in each).

The Dangling Else construct poses a potential problem for scannerless parser implementations, because the strategy is to slurp up the file stream one character at a time, until the parser sees that it has enough to tokenize (digest into the assembly or intermediate language it's compiling). This allows the parser to maintain minimal state; as soon as it thinks it has enough information to write the tokens it's parsed to the file, it will do so. That's the end goal of a scannerless parser; fast, simple, lightweight compilation.

Assuming newlines and whitespace before or after punctuation are meaningless (as they are in most C-style languages), this statement would appear to the compiler as:

if(conditionA)if(conditionB)doFoo();else doBar;

Perfectly parse-able to a computer, so let's see. I get one character at a time until I have:

if(conditionA)

Oh, I know what that means (in C#), it means "push conditionA onto the eval stack and then call brfalse to jump to the statement after the next semicolon if it's not true". Right now I don't see a semicolon, so for now I'll set my jump offset to the next space after this instruction, and I'll increment that offset as I insert more instructions until I see a semicolon. Continuing to parse...

if(conditionB)

OK, this parses out to a similar pair of IL operations, and it goes immediately after the instruction I just parsed. I don't see a semicolon, so I will increment the jump offset of my previous statement by the length of my two commands (one for the push and one for the break) and keep looking.

doFoo();

Ok, that's easy. That's "call doFoo". And is that a semicolon I see? Well, that's great, that's the end of the line. I'll increment both my blocks' jump offsets by the length of these two commands and forget I ever cared. OK, moving on...

else

... Uh-oh. This isn't as simple as it looked. OK, I forgot what I was just doing, but an else means there's a conditional break statement somewhere that I've already seen, so let me look back... yep, there it is, brfalse, right after I push some "conditionB" on the stack, whatever that was. OK, now I need an unconditional break as the next statement. The statement that will come after that is now definitely my conditional break's target, so I'll make sure I have it right, and I will increment the unconditional break I put in. Moving on...

doBar();

That's easy. "call doBar". And there's a semicolon, and I never saw any braces. So, the unconditional break should jump to the next statement, whatever it is, and I can forget I ever cared.

So, what do we have... (note: it's 10:00 PM and I don't feel like converting bit offsets to hexadecimal or filling out the full IL shell of a function with these commands, so this is just pseudo-IL using line numbers where there would normally be byte offsets):

ldarg.1 //conditionA
brfalse <line 6> //jumps to "break"
ldarg.2 //conditionB
brfalse <line 7> //jumps to "call doBar"
call doFoo
break <line 8> //jumps beyond statement in scope
call doBar
<line 8 is here>

Well, that actually executes correctly, IF the rule (as in most C-style languages) is that the else goes with the closest if. Indented to follow execution nesting, it would execute like this, where if conditionA is false, the entire remainder of the snippet is skipped:

if(conditionA)
    if(conditionB)
       doFoo();
    else
       doBar();

... but it does so by serendipity, because the break associated with the outer if statement jumps to the break statement at the end of the inner if, which takes the execution pointer beyond the entire statement. It's an extra unneeded jump, and if this example were any more complex it might no longer function if parsed and tokenized this way.

Also, what if the language specification said that a dangling else belongs to the first if, and if conditionA is false then doBar is executed, while if conditionA is true but not conditionB then nothing happens, like so?

if(conditionA)
    if(conditionB)
       doFoo();
else
   doBar();

The parser had forgotten the first if ever existed, and so this simple parser algorithm would not produce correct code, to say nothing of efficient code.

Now, the parser could be smart enough to remember the ifs and elses it has for a longer time, but if the language spec says a single else after two ifs matches to the first if, that causes a problem with two ifs with matching elses:

if(conditionA)
    if(conditionB)
       doFoo();
    else
       doBar();
else
    doBaz();

The parser will see the first else, match to the first if, then see the second one and go into panic "what the hell was I doing again" mode. At this point the parser's got rather a lot of code in a mutable state that it would much rather have already pushed out to the output filestream.

There are solutions to all these problems and what-ifs. But, either the code needed to be that smart increases the complexity of the parser algorithm, or the language spec allowing the parser to be this dumb increases the verbosity of the language source code, such as by requiring terminating statements like end if, or brackets indicating nested blocks if the if statement has an else (both of which are commonly seen in other language styles).

This is just one, simple example of a couple of if statements, and look at all the decisions the compiler had to make, and where it could very easily have messed up anyway. This is the detail behind that innocuous statement from Wikipedia in your question.


问:
Adding correct documentation for a method
I have method like this:

```<code>methodA(someParams)
{
  do some initializations,etc;
  call methodB(someParams);
}

methodB(someParams)
{
  do work;
  if blah then raise exception::FileNotFound
  if blahblah then raise exception::ResourceNotFound
}
</code>```

When I am adding documentation for methodB, I am also documenting the exceptions it can raise.

But how about documentation of methodA ? It IS consuming methodB that may raise exceptions, so should I still document those exceptions for methodA as well? Right? wrong?

答:
Imagine that tomorrow you will alter methodA so that initialization may throw an exception. Will you document it?

What if you alter methodA so that it catches one of methodB's exceptions and retries?

I think you should copy-paste the @throws clauses from methodB and keep them current with methodA's state.

One of the advantages is that your IDE will readily show you the complete and correct javadoc of methodA, and you will not have to think or to remember its implementation details.


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答:
I know you are asking about Java, but I use mutable vs immutable all the time in objective-c. There is a immutable array NSArray, and a mutable array NSMutableArray. These are two different classes written specifically in an optimized way to handle the exact use. If I need to create an array and never alter it's contents, I'd use NSArray, which is a smaller object and is much faster at what it does, compared to a mutable array.

So if you create a Person object that is immutable then you only need a constructor and getters, thus the object will be smaller and use less memory, which in turn will make your program actually faster. If you need to change the object after creation then a mutable Person object will be better so that it can change the values instead of creating a new object.

So: depending on what you plan on doing with the object, choosing mutable vs immutable can make a huge difference, when it comes to performance.


问:
How should modules access data outside their scope?
I run into this same problem quite often. First, I create a namespace and then add modules to this namespace. Then issue I always run into is how best to initialize the application? Naturally, each module has its own startup procedure so should this data(not code in some cases, just a list of items to run) stay with the module? Or should there be a startup procedure in the global namespace which has the startup data for ALL the modules.

Which is the more robust way of organizing this situation? Should some things be made centralized or should there be strict adherence to modules encapsulating everything about themselves?

Though this is a general architecture questions, Javascript centric answers would be really appreciated!

答: It all depends on your needs what your script will do. You may call the procedure which will initialize the data for all listed modules then it may occur that by now you required no manipulation on data and but later on future it is demanded. And yes the race condition as stated above may bring you in trouble. So I recommend first analyze your script how's the flow in operation and there by decide how to make initialization.</p>


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
It may be of benefit as a decider I'd say. Like MS certifications

It'd never be the sole reason to employ someone.

It might be a reason to not employ someone if they spend many hours a day here...


问:
Should integration test be included in continuous integration (CI)?
Assume that we are developing a web application, and Hudson does typical jobs such as compile, unit test and static code analysis.

But the tricky part is: Hudson deploys and starts up application server to do integration tests, once the previous jobs done.

That means some difficult things, such as database connection, 3rd part application connection, socket port listening, environment variables, server start up failure handing, etc.  We have to set up and tear down these things correctly each time, it’s hard thing. Worse, the integration tests can break the integration test easily.

Do you think if integration test should be included in continues integration (CI)? Can it be manually? Or simplify integration test?

答:
the name Continuous Integration says a lot. What better place to do integration testing than where you're integrating already?

Of course it should not be the only place those tests take place, when developing you should try to ensure that you don't break things after all, not just that your changes work in isolation.

In the end, it's the responsibility of every team member that things don't break, trying to lay blame and rigidly define people or stages to which testing is restricted are counter productive.

ContentLicense: CC BY-SA 4.0


答:
Do you think if integration test should be included in continues integration (CI)?

If you have integration tests that are passing, and do not require someone to actually stand there and press buttons, then yes - you should add them into CI system.

But, since the integration tests can take very long to execute, you should limit how often they are run. They can be executed during a night, when the CI server is idle.

Title: Should integration test be included in continuous integration (CI)?

Body:
Assume that we are developing a web application, and Hudson does typical jobs such as compile, unit test and static code analysis.

But the tricky part is: Hudson deploys and starts up application server to do integration tests, once the previous jobs done.

That means some difficult things, such as database connection, 3rd part application connection, socket port listening, environment variables, server start up failure handing, etc.  We have to set up and tear down these things correctly each time, it’s hard thing. Worse, the integration tests can break the integration test easily.

Do you think if integration test should be included in continues integration (CI)? Can it be manually? Or simplify integration test?


问:
HTML5 canvas performance and performance monitoring tool for Javascript
I have made a program in Javascript and HTML5 canvas and I am wondering what happens when you draw a shape on a certain location of canvas then draw another shape on top of that same object. Does it consume more memory because I am drawing new object on top of each others? (Currently, rendering process of my program is not that fast, I am assuming it is due to I am drawing new object on top of old object, is that right?). Also, I want to know what kind of performance monitoring tools available out there for Javascript programs. I want to figure out which fragment of my program consumes the most memory so I can optimise that particular process to be faster. Thank you.</p>

答:
Use for example Google Chrome developer tools, see:
https://stackoverflow.com/questions/855126/what-is-the-best-way-to-profile-javascript-execution

It seems this has not been discussed a lot on programmers.SE but on stack exchange you can find a lot practical tools and methods to perform this task.

Generally Google Chrome is a good tool for it but off-course it is not cross browser. So, if performance in other browsers should be as good take a look on the specific tools for those browsers (look for profiler / performance profiler / etc).

There are also JS based tools (not sure how accurate they are since they measure from within the javascript engine):

http://code.google.com/p/jslitmus/


问:
Why is binary search,which needs sorted data, considered better than linear search?
I have always heard that linear search is a naive approach and binary search is better than it in performance due to better asymptotic complexity. But I never understood why is it better than linear search when sorting is required before binary search?

Linear search is O(n) and binary search is O(log n). That seems to be the basis of saying that binary search is better. But binary search requires sorting which is O(n log n) for the best algorithms. So binary search shouldn't be actually faster as it requires sorting.

I am reading CLRS in which the author implies that in insertion sort instead of using the naive linear search approach it is better to use binary search for finding the place where item has to be inserted.  In this case this seems to be justified as at each loop iteration there is a sorted list over which the binary search can be applied. But in the general case where there is no guarantee about the data set in which we need to search isn't using binary search actually worse than linear search due to sorting requirements?

Are there any practical considerations that I am overlooking which make binary search better than linear search? Or is binary search considered better than linear search without considering the computation time required for sorting?

答: because once you have a sorted list you don't need to re-sort it each time which means that if you have more than O(log n) searches sorting in advance will net you a gain win (O(n log n + k log n) vs O(k*n)


答:
Are there any practical considerations that I am overlooking which making binary search better than linear search?

Yes - you have to do the O(n log n) sorting only once, and then you can do the O(log n) binary search as often as you want, whereas linear search is O(n) every time.

Of course, this is only an advantage if you actually do multiple searches on the same data. But "write once, read often" scenarios are quite common.

Title: Why is binary search,which needs sorted data, considered better than linear search?

Body:
I have always heard that linear search is a naive approach and binary search is better than it in performance due to better asymptotic complexity. But I never understood why is it better than linear search when sorting is required before binary search?

Linear search is O(n) and binary search is O(log n). That seems to be the basis of saying that binary search is better. But binary search requires sorting which is O(n log n) for the best algorithms. So binary search shouldn't be actually faster as it requires sorting.

I am reading CLRS in which the author implies that in insertion sort instead of using the naive linear search approach it is better to use binary search for finding the place where item has to be inserted.  In this case this seems to be justified as at each loop iteration there is a sorted list over which the binary search can be applied. But in the general case where there is no guarantee about the data set in which we need to search isn't using binary search actually worse than linear search due to sorting requirements?

Are there any practical considerations that I am overlooking which make binary search better than linear search? Or is binary search considered better than linear search without considering the computation time required for sorting?


答:
The basic assumption is that you do not make one search.

So if you need to search the same data multiple times then you only have to sort once and can profit from binary search.

If you a searching often and have changing data it is worth to use a sorted list where new entries are sorted into the list.

So basically binary search is better when you search the same list multiple times without the need of resorting.

When you need to sort every time before searching there is no advantage.

Pleas note that there are sorting algorithms which are very fast when the list is already sorted (or nearly sorted). Most performance determinations expect an unsorted list.


问:
What is the value of OOP in ASP.NET MVC?
As a C++ developer from the 90s during the great OOP wars, I put high value to OOP as a basis for hiring new C# developers into the company.

However, there are plenty of frameworks today like ASP.NET MVC that handles most of the OOP heavy lifting. Programmers without deep knowledge of OOP can just as easily follow the paradigm and still be able to complete their projects. OOP may not be as compelling as it was before for us application developers, especially with a framework like MVC.

I can see a few instance where OOP will be really handy, like for example developing a workflow type of a project. Or those with state-machine requirements. But really, most projects that really come by (at least to us here anyway) are just CRUD functionalities.

Below is my list when hiring. Is it fair to have OOP there as the number one item?

OOP and Design

Server side programming: C#, ASP.NET MVC and EF

Client side programming: JQuery, CSS, HTML, etc.

Database design

答:
When I was learning MVC in PHP, I often thought that "this OO stuff is just functions wrapped by classes", especially since I was used to a procedural style of coding.
But then I got more and more into researching design patterns, proper encapsulation, decoupling and general theory behind OOP.

I can say that understanding the OOP principles in the context of MVC really made a difference in the Model part of the app. While the controllers are still pretty much already laid out and all you need to do is fill the action methods with the proper code, and views are just html with some code here and there, the model is where knowledge of OO principles shows. When you have anything more than a dead simple CRUD app, it involves planning the domain classes. Then you throw in an ORM like EF to take care of persistence, and add some repositories to decouple from the EF implementation. Then you implement a unit-of-work to do persistence for each request. Then you throw in a DI container like Unity, to keep all of this nicely decoupled, mostly to allow for proper testing.

The "application" is in essence the domain model, with the entity classes, services and repositories, and if this part is done right, it almost makes no difference what kind of UI you put on top of it, be it an MVC app which serves pages, or some REST app which will send JSON to a mobile app, or a desktop app. A well designed Model can be reused across different applications.

Also, knowing OO principles will make it easier to understand how the MVC thing works in the first place, and help clear out some of the "magic" that might be happening under the covers, and it will make it easier to switch languages if necessary (and if the other language is also object-oriented).

In conclusion, I'd say yes, OOP and design is essential.


答:
Being that C# is an object oriented language I guess it goes without saying that OOP is on the checklist for a C# developer, however it's amazing to me how many programmers (green or experienced) actually understand and live by the principles of OOP.

If I were you I would probably replace number one with SOLID principles.

Title: What is the value of OOP in ASP.NET MVC?

Body:
As a C++ developer from the 90s during the great OOP wars, I put high value to OOP as a basis for hiring new C# developers into the company.

However, there are plenty of frameworks today like ASP.NET MVC that handles most of the OOP heavy lifting. Programmers without deep knowledge of OOP can just as easily follow the paradigm and still be able to complete their projects. OOP may not be as compelling as it was before for us application developers, especially with a framework like MVC.

I can see a few instance where OOP will be really handy, like for example developing a workflow type of a project. Or those with state-machine requirements. But really, most projects that really come by (at least to us here anyway) are just CRUD functionalities.

Below is my list when hiring. Is it fair to have OOP there as the number one item?

OOP and Design

Server side programming: C#, ASP.NET MVC and EF

Client side programming: JQuery, CSS, HTML, etc.

Database design


答:
Does it consume more memory because I am drawing new object on top of each others?

Very unlikely. A canvas is technically just a two-dimensional array of pixels. When you draw a blue rectangle to the canvas, you just change the color values of the pixels which were there before. The old color values of the affected pixels are lost. The information that these now-blue pixels belong to a rectangle object isn't save either. They are just color values with no special relation to each other.

Title: HTML5 canvas performance and performance monitoring tool for Javascript

Body: I have made a program in Javascript and HTML5 canvas and I am wondering what happens when you draw a shape on a certain location of canvas then draw another shape on top of that same object. Does it consume more memory because I am drawing new object on top of each others? (Currently, rendering process of my program is not that fast, I am assuming it is due to I am drawing new object on top of old object, is that right?). Also, I want to know what kind of performance monitoring tools available out there for Javascript programs. I want to figure out which fragment of my program consumes the most memory so I can optimise that particular process to be faster. Thank you.</p>


答:
I’m also in charge of the technical interview in my company.

It’s hard to tell you what would be my number one item as I like people having a wide technical knowledge.

But, one thing that is sure, even if most of the actual frameworks we’re using tend to abstract the OOP thing, developers should know and understand at least a bit, what they’re using.

From my point of view OOP is still an important part to know and understand.

I’m still astonished by the number of people that cannot explain me the usefulness of an Interface! Or even what’s the difference between an Interface and an Abstract Class!

We’re really into Clean Architecture and we’re fan of the Onion one. How could a developer code the Application Core without knowing at least what an Interface is?

Knowing how to use EF, how to write some MVC or having basic knowledge of JQuery, is within reach for all developers.

Having good knowledge of what OOP is, how useful it is and when is it important to use it, might be the key difference between an average developer and the-one-that-you-really-want-to-hire.


问:
What's the difference between these property definitions in C#
```<code>class myClass
{
 int age;

 public int Age
{
 get{return age;}
 set{age = value;}
}
</code>```

Versus

```<code>class myClass
{
 public int Age{get; set;}
}
</code>```

What's the difference between these two? Are they both the same?

答:
They both compile to the same IL.

An automatic property is simply shorthand for the same thing with a private backing field (your first example).

From Auto-Implemented Properties on MSDN:

When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

As @svick commented, the obvious difference is that you can access the backing field directly in your first example, whereas you can't in the second (as it is a generated, anonymous field).


答: U catch the exception thrown by method B and take necessary steps in method A. Then if its necessary and inevitable, U can throw a exception of same type or another type from method A and document about that exception for method A.</p>

Title: Adding correct documentation for a method

Body:
I have method like this:

```<code>methodA(someParams)
{
  do some initializations,etc;
  call methodB(someParams);
}

methodB(someParams)
{
  do work;
  if blah then raise exception::FileNotFound
  if blahblah then raise exception::ResourceNotFound
}
</code>```

When I am adding documentation for methodB, I am also documenting the exceptions it can raise.

But how about documentation of methodA ? It IS consuming methodB that may raise exceptions, so should I still document those exceptions for methodA as well? Right? wrong?


问:
How to properly conduct a feature development meeting?
I am a Product Manager, under me I have about 10 developers, UX designers and marketers. Marketers research about the demands of features, UX designers providing UI mockups, and develkopers write code.

Now, we want to do our feature development monthly meeting (sprint) in a more structured manner ( previously, feature priority is decided in a somewhat adhoc manner, we want to change this). The goals of the meeting are

To set the priority ( urgent, important, normal, not important) of each feature

To make sure that everyone knows what to do for this coming milestone after the meeting is over.

But given that we have 10 people on the team and usually, we have more than 50 features to discussed, I afraid that the whole meeting will drag on for a long time. Also, for the second step, I would need to allow time for everyone to check their schedule, as not everyone is fully available to work on the features ( some would need to fix bugs, provide technical supports etc), so if I ask them to do this in the meeting, then there will be some lull time and disrupt the flow of the meeting.

Is there any well-established meeting procedure that is fitting to my situation above?

答:
Stop wasting time!

The main point I want to make is that the more people you have in a meeting, the more time you are wasting. Whenever you are discussing something not directly relating to employee X, you are wasting employee X's time.

Why is this a bad thing? Obviously there is a direct cost (assuming you are paying employee X for his/her time!) but there's also an indirect one - you are demoralising employee X. Every time he/she is up against a tight deadline, or having to work overtime, they are going to think about the wasted time they spent in that meeting when they could have been achieving something.

So, keep your meetings as small as possible. You do this by organising people into teams. Think of a team as the set of people who need to be involved in order to implement a task. This might be specific people, or it might be "two developers and one UX designer". One person can be in more than one team, and you may well need to create different teams for each feature.

If 2 teams need to work together - e.g. team A can't start their feature until team B finishes theirs. In this case try to get one or two representatives from each team involved instead of bringing the whole team in.

Deciding priorities

Ultimately the product is being developed for a customer (or customers), and it's the customer who decides which features are most important. Your marketers are the ones dealing with the customers, so it's their job to find out what features the customers need/want next and assign priorities to those features.

To decide how to prioritise features, your marketers need to define the requirements, which they can then use to get an idea of how much development/design time is going to be required for each of them. This is one of those meetings where you get representatives from each team together.

Your devs/designers might need to have a discussion with their respective teams to come up with a decent estimate, so allow space in your scheduling for that. I'd suggest making these meetings fairly frequent - either as and when new features are thought up, or on a weekly/bi-weekly basis.

The other important thing to consider is that some features depend on other features. If feature A is a prerequisite for feature B, then feature A has to come before feature B in the priority list.

Another point here is that bug fixes should be treated as features here. It's up to the customer to decide if they thing new feature A is more important than fixing that niggly bug with existing feature B! This should also simplify your scheduling.

Planning for the next milestone

With your prioritised list of features (with time estimates) this part should be pretty straightforward. Basically, just take the next achievable feature* off the top of the list until you've filled up people's time!

If you find that you can't do the top item on the list because it a required person/team already has a full schedule, leave it for the next milestone and find the next achievable feature.

Get everyone to give you copies of their schedules and you should have all the information you need in order to do the milestone planning on your own. Just remember to leave some time for dealing with the unexpected!

Further reading/where to go from here

I've barely skimmed the surface here. I strongly recommend you spend some time reading up on different development methodologies and working out what would suit your team's situation best. Agile development is the "in thing" (there are various types - e.g. Scrum and Kanban are popular) but it might not be the best fit for your team.

The final point I'd like to make is not to change things too quickly!


问:
I have only two languages on my resume - how bad is this?
I have a question that can be best answered here, given the vast experience some of you guys have!

I am going to finish my bachelor's degree in CS and let's face it, I am just comfortable with C++ and Python. C++ - I have no experience to show for and I can't quote the C++ standard like some of the guys on SO do but yet I am comfortable with the language basics and the stuff that mostly matters. With Python, I have demonstrated work experience with a good company, so I can safely put that.

I have never touched C, though I have been meaning to do it now. So I cannot write C on my resume because I have not done it ever. Sure I can finish K & R and get a sense of the language in a month, but I don't feel like writing it cause that would be being unfaithful to myself.

So the big question is, are two languages on a a resume considered OK or that is usually a bad sign? Most resumes I have seen mention lots of languages and hence my question. Under the language section of my resume, I just mention: C++ and Python and that kinda looks empty!

What are your views on this and what do you feel about such a situation?

PS: I really don't want to write every single library or API I am familiar with. Or should I?

答: As long as you know how to think the problems through, it does not matter how many languages you are proficient in. But since you are proficient with C++, you could invest a few months time to gain some skill in C# or Java (or Ruby, for that matter).</p>


问:
If my team has low skill, should I lower the skill of my code?
For example, there is a common snippet in JS to get a default value:

```<code>function f(x) {
    x = x || 'default_value';
}
</code>```

This kind of snippet is not easily understood by all the members of my team, their JS level being low.

Should I not use this trick then? It makes the code less readable by peers, but more readable than the following according to any JS dev:

```<code>function f(x) {
    if (!x) {
        x = 'default_value';
    }
}
</code>```

Sure, if I use this trick and a colleague sees it, then they can learn something. But the case is often that they see this as "trying to be clever".

So, should I lower the level of my code if my teammates have a lower level than me?

答:
Reading this question and the subsequent answers and discussions there seems to be two points. The first: is it OK to use advanced language features? The second: how can I do this without appearing as though I'm 'showing off'?

In the first case, it makes sense to use improvements and advanced features. For example: in C# you don't have to use Linq or Lambda expressions but most people do because it makes the code tidier and easier to understand, once you actually know what it's doing. At first it just looks strange.

People get used to patterns and in many cases people use the set way of doing things just to get the job done. I'm as guilty of this as the next man. We all have deadlines. In some respects you are guilty of introducing new ideas and new ways of thinking! This comes on to the second point and this is probably where you might be encountering the most resistance.

To the person using the website they don't care which style is used all they care about is does it work? Is it quick? So, if there is no performance advantage to your way then there is no right way or wrong way in the example you give. Does your way make code more readable or not? It might do once your colleagues are used to it.

So, how do you introduce these changes? Try and have discussions with your colleagues along these lines : did you know that this function can be written this way? Code reviews and pair programming can be good times to allow for 'cross-pollination' of ideas. It's tricky for me to prescribe what to do because I don't know the environment you are working in. I find that some programmers can be very defensive and resistant to change. Again I've been guilty of this. The best way to work with these kinds of programmers is to spend some time learning what makes them tick, learn their background and then compare and contrast your styles and experiences with theirs. It takes time but it is time well spent. If possible try and encourage them.


答:
I would expect a C# developer to have a good understanding of OOP. However, I get the impression from your list that your developer will be a generalist, and not a C# specialist.

If you choose your developers depending on their OOP knowledge, you might have a very clean controller and model; but they may not be able to write optimized SQL queries when the need arises, and your front-end architecture could end up being a huge mess.

Maybe you could try hiring people with complementary skills.


问:
Is where a link goes part of a view use case?
Say I got a minimal use case such as "view home page" or "view banner ad". Should it be included or exluded in the use case actually following the link? What I mean is that whether it belongs to the use case "view page 1" if a report is that "The link from page 1 to page 2 is not working" in the common case of a "link not working". </p>

答:
In general, use cases should not concern themselves with implementation details such as links, home pages or banner ads. If you have a use case for delivering a report, then that use case should be equally satisfied if the report is hand-written and delivered by an office clerk, if it is a multi-page PDF document or if it is a collection of web pages with navigation links.

The only place where a good use case would refer to technology is in describing the alternative scenarios of what might go wrong. And even there I would not mention broken links, as they can occur anywhere. Such errors are better dealt with in generic requirements outside the context of a use case.

Besides the behaviour related requirements that can be described very well with use cases, each project will invariably have some requirements that don't really fit the pattern of a use case, such as non-functional requirements and functional requirements that apply to a large portion of the use cases. You should not try to force these requirements into the pattern of a use case, but rather let them stand alone as non-use case requirements.


问:
Should I use semicolons to delimit Scala statements?
I'm used to delimit statements by a semicolon from Java, so naturally I do it in Scala code too. I also feel that the code is easier to read, because it's evident where one statement ends and another begins. But many times when I post a piece of Scala code on SO, the code gets edited just to get semicolons removed.

Should I use semicolons or not? Are there any "official" guidelines or coding style?

Are there cases where semicolons are required, otherwise the code is ambiguous?

答:
There is no officially "right" way of doing it, but most practitioners omit semicolons wherever they can (which is why so many people remove semicolons reflexively).

The language tries very hard to make you forget about the need to terminate statements at all. Unfortunately, it doesn't quite succeed, so there are various intricate situations in which semicolons, or an extra set of parenthesis, or similar "hints" are necessary to avoid unwanted semantics. Such situations are almost rare enough that normally you don't have to think about them. Opinions differ on whether this means you should punctuate defensively (that's what I think) or never punctuate until you run into trouble (that's what the majority of users think). Ultimately, it comes own to whether you self-identify as a renegade or a model citizen.


问:
When to use HTTP status code 404 in an API
I am working on a project and after arguing with people at work for about more than a hour. I decided to know what people on stack-exchange might say.

We're writing an API for a system, there is a query that should return a tree of Organization or a tree of Goals.

The tree of Organization is the organization in which the user is present, In other words, this tree should always exists. In the organization, a tree of goal should be always present. (that's where the argument started). In case where the tree doesn't exist, my co-worker decided that it would be right to answer response with status code 200. And then started asking me to fix my code because the application was falling apart when there is no tree.

I'll try to spare flames and fury.

I suggested to raise a 404 error when there is no tree. It would at least let me know that something is wrong. When using 200, I have to add special check to my response in the success callback to handle errors. I'm expecting to receive an object, but I may actually receive an empty response because nothing is found. It sounds totally fair to mark the response as a 404. And then war started and I got the message that I didn't understand HTTP status code schema. So I'm here and asking what's wrong with 404 in this case? I even got the argument "It found nothing, so it's right to return 200". I believe that it's wrong since the tree should be always present. If we found nothing and we are expecting something, it should be a 404.

More info,

I forgot to add the urls that are fetched.

Organizations

```<code>/OrgTree/Get
</code>```

Goals

```<code>/GoalTree/GetByDate?versionDate=...
/GoalTree/GetById?versionId=...
</code>```

My mistake, both parameters are required. If any versionDate that can be parsed to a date is provided, it will return the closes revision. If you enter something in the past, it will return the first revision. If by Id with a id that doesn't exists, I suspect it's going to return an empty response with 200.

Extra

Also, I believe the best answer to the problem is to create default objects when organizations are created, having no tree shouldn't be a valid case and should be seen as an undefined behavior. There is no way an account can be used without both trees. For that reasons, they should be always present.

also I got linked this (one similar but I can't find it)

http://viswaug.files.wordpress.com/2008/11/http-headers-status1.png

答:
Taking a tangential stab at this:
If a human is eventually using the API (through a GUI) I would suggest doing whatever makes life easy for the end user .
The non existence of the tree when it should exist is a "Domain model inconsistency" error. A system error is when you ran out of memory or had some other systemic failure.
So returning 5xx is inappropriate.
As mentioned by several folks above, 4xx might be appropriate if the tree itself had its own URI, which is not the case here. But here's what 404 tells the client: you can try again and again till you get something back.
If you returned 200, you could return sufficient diagnostics back to the user or user agent so that the user agent can display a meaaage so that the user stops retrying and just contacts support.
On the other hand if this API is intended for systems only, an "exception message" must be a part of the API so that you don't have to rely on the inherent vagueness of HTTP error codes, and can return something meaningful which can be logged by the consumer and escalated. </p>


问:
What are some standard design methods to add GUI to a command line app?
I have an embedded Linux C application that runs with a simple CLI. I am now tasked with creating a GUI that accomplishes the same functionality as the command line program. I am not an accomplished GUI designer and the majority if my experience is in deeply embedded C  coding.

My initial thought is to use qtcreator to create the GUI, but there are several issues I'm ruminating over.

Moving forward I want to maintain both the CL program and the GUI program, and preferably even have them be the exact same executable that can be launched in either mode. Unless this is a bad idea?

My code is in C so far, and qt is natively c++

I would like a direct correlation where button presses in the GUI call the same functions that I call from the CLI

How do I best do this cleanly and efficiently? Is there some other thecnology or library that simplifies this? I don't have to use qt if there is something better.

答:
If your current CLI application uses a reasonably structured input and output format (particularly the output. It should be structured enough to be parsed by a machine), then you can always create a separate GUI application that communicates with the CLI application through pipes and/or temporary files.

To integrate the GUI with the current application, you need to be able to completely separate the I/O handling from the rest of the application, so you can build the I/O-less part as a library and bolt a user interface (either GUI or CLI) on to that. If the original application was never designed for this, it might be a hard task, because it is so easy to scatter printf calls all over the place.

The fact that Qt is C++ and your application is in C should not be a major stumbling block for an integrated application, as long as the interface to the back-end part is written in the common subset of C and C++. Then you just have the learning curve of C++ to overcome.


问:
Is the List interface a leaky abstraction?
If I have a variable containing a List it could contain objects of a lot of different types e.g. ArrayList or LinkedList. The difference between a LinkedList and an ArrayList is pretty big. The big O behavior of the methods differs greatly. For example sorting the List and then using it to do binary searches is perfectly ok for an ArrayList but would not make sense with a LinkedList.

答:
All non-trivial abstractions, to some degree, are leaky. That said, I'm not really sure it applies here. :-)

Abstractions are concerned with behaviour. Unless the behaviour specifies particular performance (which Java's List does not) it's an implementation detail - i.e. irrelevant.

Java doesn't allow you to specify minimum performance for interfaces outside of documentation, and I'm not aware of any languages which do - it would be incredibly hard (impossible?) for the compiler to verify. I can see a couple of options if performance is a concern:

Document it in the class/interface the list instance will belong to.

Create a new interface - e.g. BinarySearchPerformantList (yuck!) - which specifies the performance requirements of the various methods.

Option 2 is probably the better abstraction, but comes with extra overhead.


问:
What is the most inspiring speech from a developer you ever watched?
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)

答:
Steve Yegge's talk at OSCON 2007: How to Ignore Marketing and Become Irrelevant in Two Easy Steps.

This talk is inspiring because he did the whole thing with broken PowerPoint slides. The focus of the talk should be on the speaker, not the slides, and the lack of slides did not detract from his talk at all.


答:
I wouldn't say so.

A leaky abstraction is one that forces you to deal with implementation details that it's supposed to abstract away. But performance always differs between implementations, so if you count that as leaking, then there are no non-leaking abstractions.

If something is declared as List without further documentation, it should be understood that there are simply no guarantees about performance, and if you're going to do anything performance-sensitive with it, you should make a copy and work with that.

Also, don't forget that there's an even more general interface that is often sufficient in functionality and does not tempt you to make as many assumptions about performance: Collection.

Title: Is the List interface a leaky abstraction?

Body: If I have a variable containing a List it could contain objects of a lot of different types e.g. ArrayList or LinkedList. The difference between a LinkedList and an ArrayList is pretty big. The big O behavior of the methods differs greatly. For example sorting the List and then using it to do binary searches is perfectly ok for an ArrayList but would not make sense with a LinkedList.


问:
Job interview for Trainee Programmer, how to increase chances of success?
I have my first programming job interview today (in a few hours!) and would like some advice.

The job title is Trainee Programmer and it is for a secure printing company.

I have found a lot on the internet about programming interviews, but since this is a Trainee role I have no idea what to expect.

I know that the company prefers Java and C#, and I have a little knowledge of them, but my main language is C++.

I would like:

Some pointers on what to expect from this Trainee interview.

Tips on how to improve my chances.

答:
just from reading your question I think you're missing something important; it's a trainee position! They aren't expecting you to know or be able to do everything, that's why they're going to train you. They are hiring you, not your skills or knowledge.

I would say there are two things that you need to show; that you really want the position, and that you will work harder than anybody else. As a trainee you need to show a willingness to learn and a real enthusiasm for the job. Show passion and show interest.

Good luck!


问:
When to use interfaces (unit testing, IoC?)
I suspect I've made a schoolboy error here, and am looking for clarification. A lot of the classes in my solution (C#) - dare I say the majority - I've ended up writing a corresponding interface for. E.g. an "ICalculator" interface and a "Calculator" class that implements it, even though I'm never likely to replace that calculator with a different implementation. Also, most of these classes reside in the same project as their dependencies - they really only need to be internal, but have ended up being public as a side-effect of implementing their respective interfaces.

I think this practice of creating interfaces for everything stemmed from a few falsehoods:-

1) I originally thought that an interface was necessary to create unit test mocks (I'm using Moq), but I've since discovered that a class can be mocked if its members are virtual, and it has a parameterless constructor (correct me if I'm wrong).

2) I originally thought an interface was necessary to register a class with the IoC framework (Castle Windsor), e.g.

```<code>Container.Register(Component.For<ICalculator>().ImplementedBy<Calculator>()...
</code>```

when in fact I could just register the concrete type against itself:

```<code>Container.Register(Component.For<Calculator>().ImplementedBy<Calculator>()...
</code>```

3) Using interfaces, e.g. constructor parameters for dependency injection, results in "loose coupling".

So have I gone mad with interfaces?! I'm aware of the scenarios where you would "normally" use an interface, e.g. exposing a public API, or for things like "pluggable" functionality. My solution has a small number of classes that fit such use cases, but I wonder if all the other interfaces are unnecessary, and should be removed? Regarding point 3) above, won't I be violating "loose coupling" if I was to do this?

Edit:- I'm just having a play with Moq, and it seems to require methods to be public and virtual, and have a public parameterless constructor, in order to be able to mock them. So it looks like I can't have internal classes then?

答:
The idea of IoC is to make the concrete types replaceable. So even if (right now) you only have a single Calculator that implements ICalculator, a second implementation could depend only on the interface and not on implementation details from Calculator.

Therefore, the first version of your IoC-Container registration is the correct one, and the one you should use in future.

If you make your classes public or internal is not really related, and neither is the moq-ing.


答:
Most programming interviews involve simple questions which infer whether or not you understand basic programming concepts like pointers, recursion, memory leaks, streams.  Since you're applying for a trainee position, you may receive none of these questions, and even if they do, I'm sure it is just to get a basic understanding of your level, so don't stress it too much.

However, if you have a couple hours time on your hands, I would read up on basic Java and C# language questions so that if it did come up, you would have an answer to simple questions.  If they ask a question that you don't know the answer to, don't be afraid to say you don't know.  The worst thing you could do is try to wing it.  They never ask questions which they don't know the answer to already.

That said, confidence can go a long way, so try to relax and I'm sure the interview will go just fine.  A simple trick I always used was to drink a beer an hour before the interview as it always seemed to calm my nerves and take the edge off.  Good luck!

Title: Job interview for Trainee Programmer, how to increase chances of success?

Body:
I have my first programming job interview today (in a few hours!) and would like some advice.

The job title is Trainee Programmer and it is for a secure printing company.

I have found a lot on the internet about programming interviews, but since this is a Trainee role I have no idea what to expect.

I know that the company prefers Java and C#, and I have a little knowledge of them, but my main language is C++.

I would like:

Some pointers on what to expect from this Trainee interview.

Tips on how to improve my chances.