答:
The definition of "meaningful" or even "not complicated" is far from being objective, IMHO. Also meaningful could very well be dependent on the data you're storing in your db.

As stated by mcwise, the purpose of an id is to be unique and not meaningful. Do you really have to use a manual id ? Auto-generated id prevent you from even knowing there are gaps, and will always ensure ids are unique.

If you absolutely want a unique manual and meaningful ID, try finding either a field that will always be unique in your base (for example emails for users in a web site) or generate one from several fields where you know that the combination will be unique (for example firstname-lastname-birthdate-birthplace)

Title: How to define a natural id in database?


问:
Are my negative internship experiences representative of the real world?
I'm curious if my current experiences as an intern are representative of actual industry.

As background, I'm through the better part of two computing majors and a math major at a major university; I've aced every class and adored all of them, so I'd like to think that I'm not terrible at programming. I got an internship with one of the major software companies, and half way through now I've been shocked at the extraordinarily low quality of code. Comments don't exist, it's all spaghetti code, and everything that could be wrong is even worse. I've done a ton of tutoring/TAing, so I'm very used to reading bad code, but the major industry products I've been seeing trump all of that. I work 10-12 hours a day and never feel like I'm getting anywhere, because it's endless hours of trying to figure out an undocumented API or determine the behavior of some other part of the (completely undocumented) product. I've left work hating the job every day so far, and I desperately want to know if this is what is in store for the rest of my life.

Did I draw a short straw on internships (the absurdly large paychecks imply that it's not a low quality position), or is this what the real world is like?

答:
Can't really talk for everyone but here is what I can say.

I haven't work 30+ years in the domain but I saw enough to say a few things. A project has a lifetime pretty much like a human. Initial design may not fit the current needs for let say one project after 20 years of development. That said in that amount of time, a lot of people changed the code messed with it and added things that weren't supposed to be possible at first.

It's not really difficult to imagine ugly code on legacy projects or fairly old projects. We can't expect everyone to fully understand the initial designs. It's sad but that's the way it is.

That said, you have to keep in mind that refactoring a legacy project is not always possible and sometime not even desired. I worked in a company where they were developing the replacement for the project I was working on. I wasn't allowed to refactor too much my project in fear that it would work better than the new project. I'm pretty sure there is no way this project could ever work better than a new fresh one. the phrase was a bit like "Don't make it better, just make it work".

Eventually you won't have that kind of project often, as I often read and listen. You should try to find work with startups instead of big corporation. Startups are quite interesting and you can eventually move on fast if you see that it's not going the way you want it too.

Also one thing you can do, I really don't promise anything but if you feel the code is really that bad and need refactoring. Share it with the team. Keep in mind that the people who wrote that ugly code might be working with you. It's not about hurting people's feeling but if you see that the project you're working on will collapse after sometime and people will spend more time understanding what it does instead of improving it. It's better to speak up and communicate the problem than keep it for yourself. If you're lucky enough you might end up refactoring the project.

If you end up refactoring the project, you might end up being the person pointed at for bad design choices! And then you might understand why refactoring doesn't happen that often. Hopefully if the whole team has to refactor, then nobody get pointed at. They'll just fire everyone =)

ContentLicense: CC BY-SA 3.0


问:
Undefined behaviour in Java
I was reading this question on SO which discusses some common undefined behavior in C++, and I wondered: does Java also have undefined behaviour?

If that is the case, then what are some common causes of undefined behaviour in Java?

If not, then which features of Java make it free from such behaviours and why haven't the latest versions of C and C++ been implemented with these properties?

答:
Java tries quite hard to exterminate undefined behaviour, precisely because of the lessons of earlier languages. For instance, class-level variables are automatically initialized; local variables are not auto-initialized for performance reasons, but there is sophisticated data-flow analysis to prevent anyone from writing a program that would be able to detect this. References are not pointers, so invalid references cannot exist, and dereferencing null causes a specific exception.

Of course there remain some behaviours that are not fully specified, and you can write unreliable programs if you assume that they are. For instance, if you iterate over a normal (non-sorted) Set, the language guarantees that you will see each element exactly once, but not in which order you will see them. The order might be the same on successive runs, or it might change; or it might stay the same as long as no other allocations occur, or as long as you don't update your JDK, etc. It is near-impossible to get rid of all such effects; for instance, you would have to explicitly order or randomize all Collections operations, and that is simply not worth the small additional un-undefined-ness.

Title: Undefined behaviour in Java


答:
Off the top of my head, I don't think there is any undefined behaviour in Java, at least not in the same sense as in C++.

The reason for this is that there is a different philosophy behind Java than behind C++. A core design goal of Java was to allow programs to run unchanged across platforms, so is specification defines everything very explicitly.

In contrast, a core design goal of C and C++ is efficiency: there should not be any features (including platform independance) that cost performance even if you don't need them. To this end, the specification deliberately does not define some behaviours because defining them would cause extra work on some platforms and thus reduce performance even for people who write programs specifically for one platform and are aware of all its idiosyncracies.

There's even an example where Java was forced to retroactively introduce a limited form of undefined behaviour for exactly that reason: the strictfp keyword was introduced in Java 1.2 to allow floating point calculations to deviate from following exactly the IEEE 754 standard as the spec had previously demanded, because doing so required extra work and made all floating-point calculations slower on some common CPUs, while actually producing worse results in some cases.

Title: Undefined behaviour in Java

Body:
I was reading this question on SO which discusses some common undefined behavior in C++, and I wondered: does Java also have undefined behaviour?

If that is the case, then what are some common causes of undefined behaviour in Java?

If not, then which features of Java make it free from such behaviours and why haven't the latest versions of C and C++ been implemented with these properties?


答:
In Java, you can consider behavior of incorrectly synchronized program undefined.

Java 7 JLS uses word "undefined" once, in 17.4.8. Executions and Causality Requirements:

We use f|d to denote the function given by restricting the domain of f to d. For all x in d, f|d(x) = f(x), and for all x not in d, f|d(x) is undefined...

Java API documentation specifies some cases when results are undefined - for example, in (deprecated) constructor Date(int year, int month, int day):

The result is undefined if a given argument is out of bounds...

Javadocs for ExecutorService.invokeAll(Collection) state:

The results of this method are undefined if the given collection is modified while this operation is in progress...

Less formal kind of "undefined" behavior can be found for example in ConcurrentModificationException, where API docs use term "best effort":

Note that fail-fast behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast operations throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness...

##Appendix
One of the question comments refers to an article by Eric Lippert which provides helpful introduction into topic matters: Implementation-defined behaviour.

I recommend this article for the language-agnostic reasoning, although it is worth keeping in mind that author targets C#, not Java.

Traditionally we say that a programming language idiom has undefined behaviour if use of that idiom can have any effect whatsoever; it can work the way you expect it to or it can erase your hard disk or crash your machine. Moreover, the compiler author is under no obligation to warn you about the undefined behaviour. (And in fact, there are some languages in which programs that use "undefined behaviour" idioms are permitted by the language specification to crash the compiler!)...

By contrast, an idiom that has implementation-defined behaviour is behaviour where the compiler author has several choices about how to implement the feature, and must choose one. As the name implies, implementation-defined behaviour is at least defined. For example, C# permits an implementation to throw an exception or produce a value when an integer division overflows, but the implementation must pick one. It cannot erase your hard disk...

What are some of the factors that lead a language design committee to leave certain language idioms as undefined or implementation-defined behaviours?

The first major factor is: are there two existing implementations of the language in the marketplace that disagree on the behaviour of a particular program? ...

The next major factor is: does the feature naturally present many different possibilities for implementation, some of which are clearly better than others? ...

A third factor is: is the feature so complex that a detailed breakdown of its exact behaviour would be difficult or expensive to specify? ...

A fourth factor is: does the feature impose a high burden on the compiler to analyze? ...

A fifth factor is: does the feature impose a high burden on the runtime environment? ...

A sixth factor is: does making the behaviour defined preclude some major optimization? ...

Those are just a few factors that come to mind; there are of course many, many other factors that language design committees debate before making a feature "implementation defined" or "undefined".

Above is only a very brief coverage; full article contains explanations and examples for the points mentioned in this excerpt; it is much worth reading. For example, details given for the "sixth factor" can give one an insight into motivation for many statements in Java Memory Model (JSR 133), helping to understand why some optimizations are allowed, leading to undefined behavior while others are prohibited, leading to limitations like happen-before and causality requirements.

 None of the article materials is particularly new to me but I'll be damned if I ever seen it presented in such an elegant, consise and understandable way. Amazing.

Title: Undefined behaviour in Java

ContentLicense: CC BY-SA 4.0


问:
For an ORM supporting data validation, should constraints be enforced in the database as well?
I have always applied constraints at the database level in addition to my (ActiveRecord) models. But I've been wondering if this is really required?

A little background

I recently had to unit test a basic automated timestamp generation method for a model. Normally, the test would create an instance of the model and save it without validation. But there are other required fields that aren't nullable at the in the table definition, meaning I cant save the instance even if I skip the ActiveRecord validation. So I'm thinking if I should remove such constraints from the db itself, and let the ORM handle them?

Possible advantages if I skip constraints in db, imo -

Can modify a validation rule in the model, without having to migrate
the database.

Can skip validation in testing.

Possible disadvantage?

If its possible that ORM validation fails or is bypassed, howsoever, the database does not check for constraints.

What do you think?

EDIT In this case, I'm using the Yii Framework, which generates the model from the database, hence database rules are generated also (though I could always write them post-generation myself too).

答:
I would definitely add constraints to the database as my default option. This is because for an enterprise data is king and data quality is paramount. @Yannis Rizos brought the DRY principle to the discussion. Well another principle is Defense in Depth. For Data I would use this principle.

I have worked in real enterprises where the DB has data created 30 years ago. It was and still is accessed by COBOL application and now by a .Net application. In 10 years time it may be a vendor app, who knows. There was a merger and millions of rows of data were converted and migrated from the other company to this database using SQL. No ORM can do this. Bottom line is Data remain, applications change, way that Data is generated change. So why not reduce the chance of data corruption ?


问:
Why do websites restrict the number & choice of characters in a password?
Registering on an insurance company's website right now, and my password is 16 characters long, using a nice variety of letters, numbers, special characters, etc. However, here's their list of restrictions:

Note your password:

must be between 6 and 12 characters

must not contain spaces, special/international characters

must not contain your user name, first name or last name

is case-sensitive

should contain at least 1 number and 1 letter

I can understand minimum 6 characters, not allowing parts of your name, being case-sensitive, and needing at least 1 number and letter. The part I don't get is restricting your choice of characters you can use, and having an upper bound.

Why do websites do this? The only thing I can think of it they don't know the basics of hashing a password, which would secure it better than anything, and get rid of any security concerns.

If I choose to type DELETE FROM users WHERE 1=1 as my password, I should be allowed to. PHP's MD5 hash of it becomes fe5d54132b51b7d65ab89b739b600b4b which I don't think will harm anything.

答: Usually the restrictions on "extended characters" are because the management in bank programming groups used to be COBOL programmers, and know that Character Sets Are Hard.</p>

ContentLicense: CC BY-SA 2.5


问:
How to define a natural id in database?
There are a lot of manuals. I am trying to create an database to hold information of these documents. But, there is a small problem.

How can I give meaningful id to the manuals? Are there any standard or logic behind the giving meaningful id to the documents? If there is no standard, can you tell me how I should do that?

example:

```<code> table :

         manual id | manual name
</code>```

EDIT:

```<code>Not Meaningful ID

     1        or  M1        or   foo
     2            C2             bar
     3            P123           name
    ...           ...            ...
     (i)          (ii)            (iii)
</code>```

(i) Not meaningful for me because if some item deleted, there can be gap. ex 1 33 100.

(ii) random character can be confusing when one try to give a name to new manual

(iii) Why giving name is not preferred is because finding a name to the manual as ID is hard after 500 manuals.

Meaningful :

New ID

```<code>* Can be easily produced even if after 1000 manuals
* Should not be so complicated
</code>```

答:
Meaningful and unique hardly coexist in a single place. For me I just use a system generated auto incremental no as ID when it comes to 1000's of records.

In the case of using an incremental number as an ID have an extra field that determines if the manual exist or is being deleted.All you have to do is in the select statement mention another condition in where clause.

Other advantage of using this is you need not bother about what ID is to be assigned to a new manual entry the system will take care of it.

Speaking about he logic to use for assigning ID's it solely depends on the programmer. The logic which is easier for him.

Title: How to define a natural id in database?


问:
Non-blocking ORM issues
I asked a question on SO, and found that there are no non-blocking ORMs for my favorite web framework.  By non-blocking I mean an ORM with callback support for asynchronous retrieval. The ORM would be supplied with a callback or some such to execute when data has been received.

I want to create one, but I have some questions that blocking me from starting development:

What issues might be encountered when developing ORM?

Does supporting non-blocking retrieval dramatically increase the complexity of an ORM?

Why are there so few non-blocking ORMs around?

Update: It looks like I have to improve my question. We have solutions that already allow us to receive data in non-blocking way, and I believe that most companies that use such solutions use raw SQL. We want to create a more generic solution that we can reuse in future projects. What difficulties might we encounter?

Update 2: Preferred language is python, but I'm interested in principles. This question is actually for me, as I will look at platforms which already have non-blocking ORM.

答: You didn't say which language you're using so I'm going to recommend Node.js, and an ORM for it: Node ORM, everything in node is async, this is no different. </p>

Title: Non-blocking ORM issues


答:
A human-meaningful identifier and a machine-meaningful identifier can be two separate things - both require uniqueness because of the inherent nature of the problem:

```<code>Given X, how can I find the manual I need?
</code>```

Identifiers should really be given to humans, rather than generated by humans. Humans are bad at creating consistently unique identifiers, but computers are good (or at least quick) at it.

Ideally, you'll have some sort of search mechanism when you are looking for a manual. You won't need to remember some random 16-byte number or QR-Code, because the computer will generate a list of all currently saved manuals for you when you search for "requires assembly"  or "batteries not included", and provide links to them for you.

Having said that, it is often an advantage to have a unique key which has no meaning at all. Call it "UniqueID", "MagicKey" or whatever takes your fancy, but be aware that it has no meaning outside of your database. This way, if the meaning of something to do with the manual ever changes in a way you don't expect, you don't have to change the key.

This is why Username is a poor choice for a foreign key in a database. If a user ever changes their Username (if it's based on their surname and they get married, they may want to change it), you have a lot of work to do in your database.

If you chose a meaningless "UserID" instead, and the user changes their username, you only have the change to make in one place, and everyone is happy.

Title: How to define a natural id in database?

Body:
There are a lot of manuals. I am trying to create an database to hold information of these documents. But, there is a small problem.

How can I give meaningful id to the manuals? Are there any standard or logic behind the giving meaningful id to the documents? If there is no standard, can you tell me how I should do that?

example:

```<code> table :

         manual id | manual name
</code>```

EDIT:

```<code>Not Meaningful ID

     1        or  M1        or   foo
     2            C2             bar
     3            P123           name
    ...           ...            ...
     (i)          (ii)            (iii)
</code>```

(i) Not meaningful for me because if some item deleted, there can be gap. ex 1 33 100.

(ii) random character can be confusing when one try to give a name to new manual

(iii) Why giving name is not preferred is because finding a name to the manual as ID is hard after 500 manuals.

Meaningful :

New ID

```<code>* Can be easily produced even if after 1000 manuals
* Should not be so complicated
</code>```

Body:
A human-meaningful identifier and a machine-meaningful identifier can be two separate things - both require uniqueness because of the inherent nature of the problem:

Given X, how can I find the manual I need?

Identifiers should really be given to humans, rather than generated by humans. Humans are bad at creating consistently unique identifiers, but computers are good (or at least quick) at it.

Ideally, you'll have some sort of search mechanism when you are looking for a manual. You won't need to remember some random 16-byte number or QR-Code, because the computer will generate a list of all currently saved manuals for you when you search for "requires assembly"  or "batteries not included", and provide links to them for you.

Having said that, it is often an advantage to have a unique key which has no meaning at all. Call it "UniqueID", "MagicKey" or whatever takes your fancy, but be aware that it has no meaning outside of your database. This way, if the meaning of something to do with the manual ever changes in a way you don't expect, you don't have to change the key.

This is why Username is a poor choice for a foreign key in a database. If a user ever changes their Username (if it's based on their surname and they get married, they may want to change it), you have a lot of work to do in your database.

If you chose a meaningless "UserID" instead, and the user changes their username, you only have the change to make in one place, and everyone is happy.


答:
Your concern about missing numbers, and meaningful IDs is misguided.

The ID number should be computer generated one-up number. Asking the user to pick a number invites too many problems.  There can be a typo, you could skip a number or duplicate a number. You can write software to look for these problems but it is easier to have the database take care of it on record creation.

If a manual is destroyed because it is not longer needed you don't want to recycle the number. Imagine if a somebody had a procedure where it said get manual 7 and complete the task on page 99 so the computer backups can be restored. But manual 7 is now about the smoke alarms, and only has 10 pages. If one is replaced you should have a field telling the user it is gone, and that the updated manual is now number 50.

You will be using the real titles of the manuals as a field in the database. That way when there are hundreds of them they can be searched by key words. Imagine how hard it would be to talk about books if there were no titles, only the ISBN numbers.

Title: How to define a natural id in database?


问:
A programmer should concentrate on at least how many languages?
For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?</p>

答:
Popular programming languages like C# and Java will keep you gainfully employed most places, but neither are different enough from each other to learn new ways of solving problems.  I think there are some languages that you eat with (the ones you use to do your job), and others that you play with.  Both have their purposes.

I've found that by learning new programming languages, I've also learned new and more elegant ways to solve problems.  It's not about the number of languages, or how often you pick them up.  Each programming language worth learning has a unique point of view, which forces you to approach your problems with a new mindset.  Many times the value comes from learning that mindset.

I've played with Smalltalk, and I loved it.  The language was just a pleasure to develop with.  Once you got used to the idioms, they helped you be more expressive with your code.  I didn't miss the static typing you have in Java/C++/C# at all.  The generics we live with in our statically typed languages are really constructs to work around the limitations static typing imposes.

I use Ruby and Ruby on Rails regularly, although not for paying jobs right now.  Ruby's designing principle was "increasing programmer happiness".  You gotta love that sentiment, and for the most part I think it delivers.

Eventually Java will go the way of lisp and Smalltalk, and C# will follow suit.  What will be there to take their place remains to be seen.  At the end of the day, if you know how to solve problems, and you have a number of ways to slice and dice the problem, you will be able to find a job and pick up whatever language you need for it.


答:
You have to understand the "Undefined Behavior" and its origin.

Undefined Behavior means a behavior which is not defined by the standards. C/C++ have too many different compiler implementations and additional features. These additional features tied the code to the compiler. This was because there was no centralized language development.
So some of the advanced features from some of the compilers became "undefined behaviors".

Whereas in Java the language specification is controlled by Sun-Oracle and there is nobody else trying to make specifications and thus no undefined behaviors.

Edited Specifically answering the Question

Java is free from undefined behaviors because standards were created before compilers

Modern C/C++ compilers have more/less standardized the implementations, but the features implemented before the standardization still remain tagged as "undefined behavior" because ISO kept mum on these aspects.

Title: Undefined behaviour in Java


问:
Languages with a clear distinction between subroutines that are purely functional, mutating, state-changing, etc?
Lately I've become more and more frustrated that in most modern programming languages I've worked with (C/C++, C#, F#, Ruby, Python, JS and more) there is very little, if any, language support for determining what a subroutine will actually do.

Consider the following simple pseudo-code:

```<code>var x = DoSomethingWith(y);
</code>```

How do I determine what the call to DoSomethingWith(y) will actually do? Will it mutate y, or will it return a copy of y? Does it depend on global or local state, or is it only dependent on y? Will it change the global or local state? How does closure affect the outcome of the call?

In all languages I've encountered, almost none of these questions can be answered by merely looking at the signature of the subroutine, and there is almost never any compile-time or run-time support either. Usually, the only way is to put your trust in the author of the API, and hope that the documentation and/or naming conventions reveal what the subroutine will actually do.

My question is this:
Does there exist any languages today that make symbolic distinctions between these types of scenarios, and places compile-time constraints on what code you can actually write?

(There is of course some support for this in most modern languages, such as different levels of scope and closure, the separation between static and instance code, lambda functions, et cetera. But too often these seem to come into conflict with each other. For instance, a lambda function will usually either be purely functional, and simply return a value based on input parameters, or mutate the input parameters in some way. But it is usually possible to access static variables from a lambda function, which in turn can give you access to instance variables, and then it all breaks apart.)

答: Yes, you want to look at Haskell. It does exactly what you want. All functions are pure by default and can only mutate state by using Monads. Also Haskell has very strong static guarantees about all sorts of things http://learnyouahaskell.com/</p>


答:
Not totally indicative of the industry, but from my limited experience 5+ years. I'd work through your internship and take as many lessons as you can from the experience.  Look for hallmarks, and indicators.  For example for your next position you'll without doubt have to go through a series of interviews.  This process is a two way road, and gives you a chance to get a feel for a company.  This is vitally important and will likely lead to your own happiness and well being.

To sum things up, spot the tell tale signs;

Who's running the company?  Is it a single manager, the marketing team (if so, stay away), development team, etc.  This angle means you might get more or less leverage for projects, the time spent on projects, etc.

Is there a technical appreciation?  Look how the management, supervisor, and members of the team treat each other.  I've been in an interview where the managers has been doing all kinds of eyebrow movements once the technical lead started speaking.  After that and learning they didn't use source control - you couldn't show me the door fast enough.

Business goal?  Does the company live day by day, as in daily financial targets, or does it have a long term plan which you are a part of.  Software development is generally done over months so having a company with a schizophrenic nature usually leads to messy software.

Dig around heavily - when asking technical questions and see if people shuffle.  Source control, document control, release process, bug reports, management style, T&C's, etc.

So live and learn, and think about your next role.  Having a bad experience isn't all that bad, because you'll be better educated about the world of work & business.

Title: Are my negative internship experiences representative of the real world?

Body:
I'm curious if my current experiences as an intern are representative of actual industry.

As background, I'm through the better part of two computing majors and a math major at a major university; I've aced every class and adored all of them, so I'd like to think that I'm not terrible at programming. I got an internship with one of the major software companies, and half way through now I've been shocked at the extraordinarily low quality of code. Comments don't exist, it's all spaghetti code, and everything that could be wrong is even worse. I've done a ton of tutoring/TAing, so I'm very used to reading bad code, but the major industry products I've been seeing trump all of that. I work 10-12 hours a day and never feel like I'm getting anywhere, because it's endless hours of trying to figure out an undocumented API or determine the behavior of some other part of the (completely undocumented) product. I've left work hating the job every day so far, and I desperately want to know if this is what is in store for the rest of my life.

Did I draw a short straw on internships (the absurdly large paychecks imply that it's not a low quality position), or is this what the real world is like?


答:
C and C++ have very limited support for at least part of the problem through the const keyword; while this alone does not control purity, it can be used (especially in C++) to tell the compiler that a particular data structure is not to be modified through a given pointer. Some compilers (e.g. gcc) also provide a 'pure' attribute as a language extension to fully enforce purity. (See this question for details).

The D programming language has support for declaring the purity of functions explicitly, and compilers will check and enforce purity (that is, trying to call a non-pure function from within a pure function yields a compiler error).

Haskell is completely pure, that is, the language itself cannot express impure functions, and there is no concept of a 'routine'. Anything that cannot be solved using pure functions alone is outsourced to the (impure) runtime; a program with side effects is implemented by building (using exclusively pure constructs) a lazy data structure that describes the program behavior, and then handing it to the runtime. The Haskell community is actively experimenting with a whole zoo of programming languages, some of them pure, others with explicit purity.

There may be more, but these are the ones I'm familiar with.

Title: Languages with a clear distinction between subroutines that are purely functional, mutating, state-changing, etc?

Body:
Lately I've become more and more frustrated that in most modern programming languages I've worked with (C/C++, C#, F#, Ruby, Python, JS and more) there is very little, if any, language support for determining what a subroutine will actually do.

Consider the following simple pseudo-code:

```<code>var x = DoSomethingWith(y);
</code>```

How do I determine what the call to DoSomethingWith(y) will actually do? Will it mutate y, or will it return a copy of y? Does it depend on global or local state, or is it only dependent on y? Will it change the global or local state? How does closure affect the outcome of the call?

In all languages I've encountered, almost none of these questions can be answered by merely looking at the signature of the subroutine, and there is almost never any compile-time or run-time support either. Usually, the only way is to put your trust in the author of the API, and hope that the documentation and/or naming conventions reveal what the subroutine will actually do.

My question is this:
Does there exist any languages today that make symbolic distinctions between these types of scenarios, and places compile-time constraints on what code you can actually write?

(There is of course some support for this in most modern languages, such as different levels of scope and closure, the separation between static and instance code, lambda functions, et cetera. But too often these seem to come into conflict with each other. For instance, a lambda function will usually either be purely functional, and simply return a value based on input parameters, or mutate the input parameters in some way. But it is usually possible to access static variables from a lambda function, which in turn can give you access to instance variables, and then it all breaks apart.)


答:
Well, I'm running up on my second decade in the business, and I can tell you that perfect clean code very seldom happens, and when it does happen, it doesn't long stay that way. By and large you will find yourself constantly attempting to repair the mistakes of the past, while (sadly) being forced by time constraints and poor leadership to commit the mistakes of the present.

Unless you're in a very specific kind of software business, the pressure to get a functional product out the door overrides all other concerns, and optimization beyond a certain point is considered pointless. If the program runs in 5 minutes, and we only need it to run in 5 minutes, no one is going to give you a few weeks to get the runtime down to 2 minutes.

If, by some miracle, you have that perfect confluence of competent management, a clear goal, money, talent, and time, and you produce a clean, superiour product...The only way it will stay that way is if you never touch it again. Maintenance and extension is almost always given very low priority, changes are always needed on effectively zero notice, and end up being kludged in erratically.

I was thinking about this one project yesterday. It was such an obvious pipe-dream to me, that I bounced a really minimally functional piece of crap out the door. I viewed it as a waste of time and resources.

Well, surprise, surprise, everyone loved it and it worked out well. So I jumped back to the drawing board and did it right. And the new version was amazing! But then there was a turnover in management and the whole thing was scrapped in favor of a "new business direction."

The second iteration had a really half-assed deployment within the company, and I never heard another thing about it, which is amusing because I know at least ~10 business units are still using it (the software we're commissioning to do the job is almost 2 years behind schedule) and apparently it never breaks.

This brings us to my final point. Even if you do produce something miraculous, the fact that it works so well means that NO ONE will be in the least bit familiar with it, and when it breaks (usually because they did something stupid) then they will curse your name worse than they ever curse that idiot who wrote that thing that breaks every third Tuesday.


答:
I would attempt to sum up an the answer to this questions with a simple quote:

All code turns to crap given enough time and hands.

The rest are just stories...


问:
What do you use to organize your team knowledge?
Last year, me and three good old friends of mine founded a small web/mobile development team. Things are going pretty well. We're learning a lot, and new people are joining the group.
Keeping knowledge always updated and in-sync is vital for us. Long emails threads are simply not the way to go for us: too dispersing and confusing, and hard to retrieve after a while.

How your team manages and organizes common knowledge? How do you collect and share useful resources (articles, links, libraries, etc) inside your team?

Update: Thanks for the feedback. More than using a wiki to share team common procedures or informations, I'd like to share external links, articles, code libraries, and be able to comment them easily within my team.

I was particularly interested in knowing if you're aware of any way/webservice to share a reading list with a team. I mean, something like Readitlater/Instapaper, but for teams, maybe with some stats available, like "# of coworkers who read it".

答:
Documenting knowledge and keeping it up-to-date is a huge task.

There's no silver bullet but I have used the strategies below.

There are my personal recommendations.  They work for me, some may work for you.

Maintain documentation in markdown format (the same format that Stack Overflow uses).  This can also make the documentation more usable by people on the fringe of the technical team who can read it better when the formatting is applied and it's viewed in a web browser.

Maintain other reference material in google docs and spreadsheets.  These work as there is no 'save' button and that one simple fact takes care of 5242 sharing issues that you would have otherwise.

Promote the material.  As will all aspects of life, it doesn't matter how good something is unless other people know about it.  Promote the material, make it easier to access and update.

Better code.  As you touched on code libraries I'll take this moment to say make sure people also focus on their own code, making sure that it's readable.  For example encourage

tax_total = item_price + item_tax (no comment needed).

over constructs like

ttotal = i_price + i_tax # Tax total is price + item tax

We maintain common code using git and github and we use their wiki format there.

OwnerDisplayName: Stefano Verna


问:
Pronunciation in programming?
How do you correctly or erroneously pronounce programming terms?  Any that you find need strict correction or history into the early CS culture?

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

regex = "rej ex" not "regg ex"?

sql = "s q l" not "sequel" (already answered, just i.e.)

Unixen

| = pipe not vertical bar?

bin = bin as in pin , not as in binary?

lib = lib as in library , not as in liberate?

etc = "ett see" , not "e t c" (as in /etc and not "&c")

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"

答: GUID.  I've heard some people say G-U-I-D, some people pronouncing it rhyming with "fluid" and some people pronouncing it rhyming with "squid".</p>

Title: Pronunciation in programming?


问:
Conflict resolution for two-way sync
How do you manage two-way synchronization between a 'main' database server and many 'secondary' servers, in particular conflict resolution, assuming a connection is not always available?

For example, I have a mobile app that uses CoreData as the 'database' on the iOS and I'd like to allow users to edit the contents without Internet connection. In the same time, this information is available on a website the devices will connect to. What do I do if/when the data on the two DB servers is in conflict?

(I refer to CoreData as a DB server, though I am aware it is something slightly different.)

Are there any general strategies for dealing with this sort of issue?
These are the options I can think of:

1. Always use the client-side data as higher-priority

2. Same for server-side

3. Try to resolve conflicts by marking each field's edit timestamp and taking the latest edit

Though I'm certain the 3rd option will open room for some devastating data corruption.

I'm aware that the CAP theorem concerns this, but I only want eventual consistency, so it doesn't rule it out completely, right?

Related question: Best practice patterns for two-way data synchronization. The second answer to this question says it probably can't be done.

答:
The usual solution for knowing "which change is correct" is a vector clock. You essentially keep track of counters for each repository that holds the data, and reject changes if a particular client's view of everyone else's state differs from that of the peer it is connecting to.

The big question that you have to answer is how you'll resolve rejected saves. This generally means some sort of merge operation.

Note that vector clocks do not use real-time timestamps. The problems involved in synchronizing real-time clocks is at least as difficult as synchronizing data.

Title: Conflict resolution for two-way sync


问:
How Does The Maybe Monad Relate To The Option Type?
I was doing a presentation on F# and was discussing the Option type when someone in the audience asked me if the Option type is F#'s implementation of the maybe monad.  I know that's not the case but I did want to ask how the two concepts are related.  I mean it seems to me that an option type might be the result of the operation of a maybe monad but I'm not even sure of that.

Would someone elucidate the relationship between the maybe monad and the option type in those functional languages which support it?

答:
Reading the documentation on F#'s Option type, it looks like it does behave pretty much exactly like the Maybe type in Haskell, in that it can model either 'nothing' (None in F#, Nothing in Haskell), or a value of its argument type (Some in F#, Just in Haskell).

In Haskell, however, Maybe is also a monad, and the plumbing is such that it allows for calculations on Maybe values, early-returning Nothing if any of the variables in the calculation is Nothing. Used this way, Maybe is a simple error handler (or rather, error-ignoring device), and the fact that it is a monad allows moving the boilerplate out of the way. Look at this wikipedia article for a nice concise example. I don't think Option supports this kind of monadic usage (in fact, I'm wondering whether there is any explicit concept of a monad in F# at all). If you want this behavior in .NET, I guess you'd use Option.Value for all your arguments, and wrap the whole calculation in a try / catch on NullReferenceException.

So, while Option is similar to the Maybe type, it is not an equivalent to the Maybe monad.


问:
How are comments expressed in programming language grammars?
I'm learning how to build parsers using grammars, but I got stuck trying to express comments, because they can appear almost anywhere.

This indicates that comments can be stripped from the token stream before parsing takes place.

Is that the standard practice, or are comments ever/often specified in grammars?

答:
They usually aren't.

They are removed by the lexer, when source code is transformed from characters to tokens.

Then, the parser will get tokens and build an AST. When the parser does its job, comment are already gone, so they don't have to appear in the grammar.


答:
It is very common to treat it as some form of white space.  Much in the same way as newlines in semicolon-oriented languages like C.

Once it is some form of white-space, you frequently just ignore it higher in the parser.

Title: How are comments expressed in programming language grammars?

Body:
I'm learning how to build parsers using grammars, but I got stuck trying to express comments, because they can appear almost anywhere.

This indicates that comments can be stripped from the token stream before parsing takes place.

Is that the standard practice, or are comments ever/often specified in grammars?


问:
Testing To Prevent Cascading Bugs
Yesterday, Twitter was hit with a "Cascading Bug" as described in this blog post:

A “cascading bug” is a bug with an effect that isn’t confined to a particular software element, but rather its effect “cascades” into other elements as well.

I've seen this kind of bug, on a smaller scale of course, on some projects I've worked on. They can be difficult to identify in dev/test environments, even within a test driven development environment.

My questions are...

What are some strategies you use, beyond the basic TDD and standard regression testing, to identify and prevent the potential trouble points that might only occur in the production environment?

Does the presence of such problems indicate a breakdown in the software development process or simply a by-product of complex software systems?

答:
I would argue that it is both a by-product of complex software systems AND it indicates a breakdown in the software development process.  Those two states are not mutually exclusive.

Defensive programming is the catch-all term to help prevent these types of bugs.  Some of the techniques from concurrent programming and not trusting any outside variable (I'm exaggerating) are useful as well.

From my experience, system level code reviews are best at catching these types of issues.  By "system level", I mean someone who is thinking about the entire system / module instead of just the code that changed.  First, the reviewer should spot when a variable / object is used in a way that isn't guaranteed to remain consistent.  Second, the reviewer should catch the situations when a variable is setup to be used in that situation.  The former is easier to spot than the latter.  Both require an experienced reviewer who understands the module(s) in question.

Title: Testing To Prevent Cascading Bugs


答:
Code Quality depends mainly on two factors.

First is always money. Companies that have high survical pressure usually pay low wages, engage less experienced developers, have tight schedules and neither time nor money to leverage their developers.

Second is people. First of all those who decide on budgets must opt for spending in code quality, then they have to engage people who want to "live" it. As you can imagine, It might turn out hard to convert a well-paid fifty-year-old top-down-Delphi programmer (no intent of stereotyping, sorry) into an Up-to-date Java Developer who does CI Builds  and produces loosely coupled code. Many developers have an aversion for lessons by (maybe younger)fellows, they don't like someone fishing in their pond - or rattling their throne.

So with that said, and also considering the fact that you have legacy code in next to every company, I'd say you get a lot of that in real life. What you could do is behave like a boyscout: Go into the woods, pick up some garbage and clean it out. Next time you'll have less of a mess to step through.


问:
Instantiate proper class based on some input
I'm attempting to understand how "switch as a code smell" applies when the proper code path is determined by some observable piece of data.

My Webapp object sets an internal "host" object based on the hostname of the current request. Each Host subclass corresponds to one possible hostname and application configuration: WwwHost, ApiHost, etc. What is an OOP way for a host subclass to accept responsibility for a specific hostname, and for Webapp to get an instance of the appropriate subclass?

Currently, the hostname check and Host instantiation exists within the Webapp object. I could move the test into a static method within the Host subclasses, but I would still need to explicitly list those subclasses in Webapp unless I restructure further. It seems like any solution will require new subclasses to be added to some centralized list.

答:
For the example you describe, I don't think you're experiencing a code smell.

```
Typically, similar switch statements are scattered throughout a program. If you add or
remove a clause in one switch, you often have to find and repair the others too.
```

Switches are not inherently bad - which is even mentioned in the article you linked.  Duplication of switch statements is bad.  Ditto with if/else-if blocks.  It violates DRY principles.

If you have a single spot where the switch statement invokes the correct instantiation, then it sounds like your code is OK.  Take a look at the Factory Pattern for additional information about your case.

Body:
For the example you describe, I don't think you're experiencing a code smell.

Typically, similar switch statements are scattered throughout a program. If you add or
remove a clause in one switch, you often have to find and repair the others too.

Switches are not inherently bad - which is even mentioned in the article you linked.  Duplication of switch statements is bad.  Ditto with if/else-if blocks.  It violates DRY principles.

If you have a single spot where the switch statement invokes the correct instantiation, then it sounds like your code is OK.  Take a look at the Factory Pattern for additional information about your case.


答:
Quick Short Answer

Yes, its the standard practice, to detect comments in the "lexer" or the "parser"

Sometimes, the "parser" has a built-in "lexer" or is mixed with the "parser" as a single tool ("lexer-parser").

Extended Answer

I just working in that case.

Most "scanners" ( also know as "tokenizers" or "lexers" ), detect comments, but, removed when returning tokens to the "parser".

Sometimes, a programming language, uses some comments with a special meaning, like "compiler directives" or "documentation".

Standard Comment Example:

```<code>/*
 This function does something cool.
*/
int doSomething()
{
  return 0;
}
</code>```

Directive Comment Example:

```<code>/*
 ##override
*/
int doSomething()
{
  return 0;
}
</code>```

Comment for documentation generator Example:

```<code>/*
 @description: This Function text will be turn,
  into an external pdf file, togheter with other
  similar comments.
*/
int doSomething()
{
  return 0;
}
</code>```

Most compiler-related tools, detect this special comments, with an analyzer or preprocessor, that is not the main lezxer or parser, and, even has a small lexer of its own.

Cheers.

Body:
Quick Short Answer

Yes, its the standard practice, to detect comments in the "lexer" or the "parser"

Sometimes, the "parser" has a built-in "lexer" or is mixed with the "parser" as a single tool ("lexer-parser").

Extended Answer

I just working in that case.

Most "scanners" ( also know as "tokenizers" or "lexers" ), detect comments, but, removed when returning tokens to the "parser".

Sometimes, a programming language, uses some comments with a special meaning, like "compiler directives" or "documentation".

Standard Comment Example:

/*
 This function does something cool.
*/
int doSomething()
{
  return 0;
}

Directive Comment Example:

/*
 ##override
*/
int doSomething()
{
  return 0;
}

Comment for documentation generator Example:

/*
 @description: This Function text will be turn,
  into an external pdf file, togheter with other
  similar comments.
*/
int doSomething()
{
  return 0;
}

Most compiler-related tools, detect this special comments, with an analyzer or preprocessor, that is not the main lezxer or parser, and, even has a small lexer of its own.

Cheers.


答:
To mantain a "well written code" you should think about applying the factory pattern.

The factory method pattern is an object-oriented design pattern to
  implement the concept of factories. Like other creational patterns, it
  deals with the problem of creating objects (products) without
  specifying the exact class of object that will be created. The essence
  of the Factory method Pattern is to "Define an interface for creating
  an object, but let the classes that implement the interface decide
  which class to instantiate. The Factory method lets a class defer
  instantiation to subclasses

WikiPedia

Here's an implementation in PHP

Title: Instantiate proper class based on some input

Body:
I'm attempting to understand how "switch as a code smell" applies when the proper code path is determined by some observable piece of data.

My Webapp object sets an internal "host" object based on the hostname of the current request. Each Host subclass corresponds to one possible hostname and application configuration: WwwHost, ApiHost, etc. What is an OOP way for a host subclass to accept responsibility for a specific hostname, and for Webapp to get an instance of the appropriate subclass?

Currently, the hostname check and Host instantiation exists within the Webapp object. I could move the test into a static method within the Host subclasses, but I would still need to explicitly list those subclasses in Webapp unless I restructure further. It seems like any solution will require new subclasses to be added to some centralized list.


答: You might want to check out some of these enterprise social networking apps for some more private forum for facebook style sharing. Names that come to mind are yammer or jive but there are others.</p>

Title: What do you use to organize your team knowledge?

Body:
Last year, me and three good old friends of mine founded a small web/mobile development team. Things are going pretty well. We're learning a lot, and new people are joining the group.
Keeping knowledge always updated and in-sync is vital for us. Long emails threads are simply not the way to go for us: too dispersing and confusing, and hard to retrieve after a while.

How your team manages and organizes common knowledge? How do you collect and share useful resources (articles, links, libraries, etc) inside your team?

Update: Thanks for the feedback. More than using a wiki to share team common procedures or informations, I'd like to share external links, articles, code libraries, and be able to comment them easily within my team.

I was particularly interested in knowing if you're aware of any way/webservice to share a reading list with a team. I mean, something like Readitlater/Instapaper, but for teams, maybe with some stats available, like "# of coworkers who read it".


答:
Some parsers that retain comments and/or illegal inputs in the AST add them as properties to all nodes of the AST.

You could take a look at the Microsoft roslyn project which does that if I recall correctly.


答:
Felix has three categories it seems:

functions

```<code>There is a rule for functions:

A function introduced by a fun binder is not allowed to have any side effects.

The compiler does not enforce this rule, but it does take advantage of it when
optimising your code.
</code>```

procedures

```<code>Procedures do not return a value, and may and generally should have side-effects.
</code>```

generators

```<code>A generator is a function that may have side effects.
</code>```

Body:
Felix has three categories it seems:

functions

There is a rule for functions:

A function introduced by a fun binder is not allowed to have any side effects.

The compiler does not enforce this rule, but it does take advantage of it when
optimising your code.

procedures

Procedures do not return a value, and may and generally should have side-effects.

generators

A generator is a function that may have side effects.


答:
I got an internship with one of the major software companies

Not all companies are the same. You'll find crappy teams and crappy software code bases in most companies. But you can also find great teams and great code bases.

I think the guys at Solaris did a very good and honest description of the kind of code bases that you'll find in large companies: http://hub.opensolaris.org/bin/view/Community+Group+on/dev_solaris

I've left work hating the job every day so far, and I
  desperately want to know if this is what is in store for
  the rest of my life.

No, I've been coding for more than 15 years and I still love it.

That's not to say that everything has been perfect. I've seen some horrible code bases and also some great ones. The trick is to find the right place for you.

A large company is very different from a small one. Within the same company team A sometimes is very different form team B. Find the one that has the right balance for you (e.g. challenging projects, a culture that you enjoy, good pay, et cetera)

Good luck!


答:
Welcome to code with a budget! There's a big difference when development is pushed by management to be done too soon, without planning, and with cutting corners. I had a similar experience of real world shock when I got my first programming job out of college. No documentation! Over time I learned a lot of the time, writing and keeping formal documentation up to date is just a waste of time. Luckily for me, that was an awesome team. It was lead by a guy who knew what he was doing and the other team members really cared about writing code the right way. Since then, my experiences have been similar to yours. Lots of horrible code, lots of bad code, lots of clueless "developers". For every good developer, there seem to be 100 bad ones.

You're not doomed to hate your job forever. You just have to find a company smart enough to recognize long term benefits that is willing to invest a little bit up front. I've managed to prove doing things the right way instead of the fastest way is beneficial and have become very respected and trusted for that at the companies I've worked at. Over time, the spaghetti code is fixed or becomes obsolete and your code takes over. Just be prepared to compromise. Sometimes the coolest or most robust way of programming something is just overkill and it's ok to do it the quick and dirty way.


问:
What's the career path for a developer who doesn't like management?
If you're developer (Senior or Lead Developer) and you'd rather stay with code/design than pursue a management career, what are the available career paths at your company, or any you've heard of? How far can you go?

Is it possible to continue being a geek until you bite the dust or is that too naive?

Are people like Uncle Bob for example still considered developers, as they claim?

答: Depends on the company.  A lot of companies offer two paths for advancing developers: technical and management.  If you prefer technical, you move slowly up the pay grade, developing valuable dev skills, but sticking with development- you become a guru.  It's less money than going management, but if you want to hack 'till you die, it's the way to go.</p>


问:
What kinds of projects is SCRUM considered to be suitable for?
I have been using SCRUM in three different projects over the last four years. One of SCRUM's advantages seems to be its flexibility and adaptability, e.g. wrt to changing customer requirements. Another advantage is that management can easily track the progress of a project.

SCRUM's flexibility can be an advantage e.g. when implementing a web application, where the requirements change very fast and the customers really understand what they want after they've seen a prototype.

On the other hand there are other kinds of software projects (e.g. in aerospace industry) where the requirements are pretty fixed: you get a requirement specification document and you have to come back six months later with working software and complete documentation. For this kinds of projects I doubt that the flexibility offered by SCRUM is needed (in the sense that you do not need to build prototypes and show them to the customer to get feedback on the requirements): you rather need a very structured and systematic approach, which is probably repeated over and over again for each project with little room for surprise.

So is SCRUM considered by its proponents a general-purpose software development
methodology or is it considered especially suited for certain categories
of projects or application areas?

For example, I recently looked at the website of a company producing
software for the aerospace industry and noticed that they are using the
V-model. Would a SCRUM proponent say that SCRUM is less suited for this
kind of projects or rather suggest that this company should try switching
to SCRUM?

Note that I am not asking for the opinion of the readers of this forum, but
I want to know what is the established opinion among SCRUM proposers: is SCRUM considered general-purpose or rather suitable for certain classes of
projects only? In the latter cases, for what kinds of projects?

答: SCRUM is a general purpose methodology that can work well for most projects and team sizes, but is less useful for large teams that do very large projects. The sheer number of people involved on some projects makes any agile methodology extremely difficult to near impossible because a more rigid structure is required to keep order. The aerospace industry is a good example of an industry that tends to have huge projects where agile approaches aren't always feasible.</p>


答:
Any type of project! It works well for both large and small projects.

People have used it for planning weddings, moving house etc. So, not even just software projects.

I'm a firm believer that there are many business operations which could benefit from a Scrum-like approach.

Title: What kinds of projects is SCRUM considered to be suitable for?

Body:
I have been using SCRUM in three different projects over the last four years. One of SCRUM's advantages seems to be its flexibility and adaptability, e.g. wrt to changing customer requirements. Another advantage is that management can easily track the progress of a project.

SCRUM's flexibility can be an advantage e.g. when implementing a web application, where the requirements change very fast and the customers really understand what they want after they've seen a prototype.

On the other hand there are other kinds of software projects (e.g. in aerospace industry) where the requirements are pretty fixed: you get a requirement specification document and you have to come back six months later with working software and complete documentation. For this kinds of projects I doubt that the flexibility offered by SCRUM is needed (in the sense that you do not need to build prototypes and show them to the customer to get feedback on the requirements): you rather need a very structured and systematic approach, which is probably repeated over and over again for each project with little room for surprise.

So is SCRUM considered by its proponents a general-purpose software development
methodology or is it considered especially suited for certain categories
of projects or application areas?

For example, I recently looked at the website of a company producing
software for the aerospace industry and noticed that they are using the
V-model. Would a SCRUM proponent say that SCRUM is less suited for this
kind of projects or rather suggest that this company should try switching
to SCRUM?

Note that I am not asking for the opinion of the readers of this forum, but
I want to know what is the established opinion among SCRUM proposers: is SCRUM considered general-purpose or rather suitable for certain classes of
projects only? In the latter cases, for what kinds of projects?


答:
Without knowing the specifics of the problem (and it would be instructive to all of us if Twitter could provide more info on this, though I understand why they wouldn't) I imagine it's one of those butterfly-tornado problems that are near to impossible to predict, and that only manifest themselves in a real-world situation, where you have a realistic number of users and configurations.

Yes, integration testing should have found this, and I imagine Twitter have a 'test lab' where they simulate millions of simultaneous users sending messages. However, some particular configuration, some odd setting, some happen-chance of barely-interconnected events, conspired to create a problem.

I think Twitter showed their maturity by immediately rolling back, and not attempting to hack their way out of the problem, as some might have been tempted to.

I think the only thing you can really do from things like this are to learn from them - to make the integration tests better, if possible. I don't think nessecarily there's anything they didn't do which they could have done.

I'm in the UK, and currently witnessing the effects of a cascading bug on NatWest, one of the largest banks here. Now, banking software is really well tested, yet these bugs still happen.

I think, at the end of the day, we do the best we can with the best tools and practices we know, but software is a complex and complicated thing, and sometimes bugs will happen. How we deal with them when (not if) they happen defines our competence as engineers.

Title: Testing To Prevent Cascading Bugs

Body:
Yesterday, Twitter was hit with a "Cascading Bug" as described in this blog post:

A “cascading bug” is a bug with an effect that isn’t confined to a particular software element, but rather its effect “cascades” into other elements as well.

I've seen this kind of bug, on a smaller scale of course, on some projects I've worked on. They can be difficult to identify in dev/test environments, even within a test driven development environment.

My questions are...

What are some strategies you use, beyond the basic TDD and standard regression testing, to identify and prevent the potential trouble points that might only occur in the production environment?

Does the presence of such problems indicate a breakdown in the software development process or simply a by-product of complex software systems?


问:
Are my negative internship experiences representative of the real world?
I'm curious if my current experiences as an intern are representative of actual industry.

As background, I'm through the better part of two computing majors and a math major at a major university; I've aced every class and adored all of them, so I'd like to think that I'm not terrible at programming. I got an internship with one of the major software companies, and half way through now I've been shocked at the extraordinarily low quality of code. Comments don't exist, it's all spaghetti code, and everything that could be wrong is even worse. I've done a ton of tutoring/TAing, so I'm very used to reading bad code, but the major industry products I've been seeing trump all of that. I work 10-12 hours a day and never feel like I'm getting anywhere, because it's endless hours of trying to figure out an undocumented API or determine the behavior of some other part of the (completely undocumented) product. I've left work hating the job every day so far, and I desperately want to know if this is what is in store for the rest of my life.

Did I draw a short straw on internships (the absurdly large paychecks imply that it's not a low quality position), or is this what the real world is like?

答:
This is going to be a short answer.

Education is very useful for making you feel qualified and idealistic. This is a good thing, and you should try to hold on to the idealism.

If you are at all objective, and you can look back at your own work in the future, its not going to be a very fulfilling experience. Unless you lie to yourself or you learn nothing you are going to see many ways to improve what you have done.

In general, the whole world is doing this around you. So, when you look at work from the past, exceptions aside, it will appear inferior and in need of improvment. If you don't feel like this, it means you are doing the wrong work, or its paying too well.

The good news is, you can benefit from other's mistakes and from comparison with the past. If all applications worked well and were easy to maintain new developers would not be required. In my opinion, maintaning some other developers cruft is a useful learning experience and should be an obligatory training element for all blue sky developers.


问:
What are some good, simple examples for queues?
I'm teaching CS2 (Java and data structures), and am having some difficulty coming up with good examples to use when teaching queues. The two major applications I use them for are multithreaded message passing (but MT programming is out of scope for the course), and BFS-style algorithms (and I won't be covering graphs until later in the term).

I also want to avoid contrived examples. Most things that I think of, if I were actually going to solve them in a single-threaded fashion I would just use a list rather than a queue. I tend to only use queues when processing and discovery are interleaved (e.g. search), or in other special cases like length-limited buffers (e.g. maintaining last N items). To the extent practical, I am trying to teach my students good ways to actually do things in real programs, not just toys to show off a feature.

Any suggestions of good, simple algorithms or applications of queues that I can use as examples but that require a minimum of other prior knowledge?

答:
One example which comes to my mind is a hamburger processing line in e.g. McDonalds. Ther are several kinds of different burgers, each may be produced by several different workers and each has its own queue. From there, after a while the ready burgers are taken, in FIFO order, by one of the cashiers who ordered that kind of a burger.

So there are multiple producers and consumers, and each queue is bounded.


答:
I've seen similar things as you. I have two experiences of cases when it occurs.

When the development is too project driven. The only thing that matters is to deliver functionality on time, then sign off. Next change will be done by someone else, by some other team/project manager with a new budget.

When a piece of software is maintained by just a few people over a long amount of time, developers tend to get lazy, since they know thier piece of software anyway. Academic principles are far away.

It's sad, but that's how it is at some places.

See if you can make a small change for the better, get used to it or change to another company and ask to screen some code at the interview :-)


答:
When I learned queues my teacher introduced them to me using a line-up for cars at a police control. There was a queue holding the cars ("waiting-queue") and the police man would always control the next car in the queue and either send it to his colleague for further inspections or let the car pass.

An example very often used is the queue in the super-market...

Why don't you ask your students to give some examples themselves?

Title: What are some good, simple examples for queues?

Body:
I'm teaching CS2 (Java and data structures), and am having some difficulty coming up with good examples to use when teaching queues. The two major applications I use them for are multithreaded message passing (but MT programming is out of scope for the course), and BFS-style algorithms (and I won't be covering graphs until later in the term).

I also want to avoid contrived examples. Most things that I think of, if I were actually going to solve them in a single-threaded fashion I would just use a list rather than a queue. I tend to only use queues when processing and discovery are interleaved (e.g. search), or in other special cases like length-limited buffers (e.g. maintaining last N items). To the extent practical, I am trying to teach my students good ways to actually do things in real programs, not just toys to show off a feature.

Any suggestions of good, simple algorithms or applications of queues that I can use as examples but that require a minimum of other prior knowledge?


答:
When I was learning queues, my professor always used the example of a store. There are 1 or more registers open at any given time, and the Customers enter one queue or another and move through that queue to purchase all of their items.

We actually had to implement a simple program that could move Customers through a RegisterQueue, so if you are actually looking for a program you can give the students this example is simple and straightforward, but also something that every student has seen in real life and so it may help them understand the concept better.


答:
I thought about using Amazon as an example, somewhere in their massive system there must be a queue of orders that needs to be handled. which could be handled by a simple enqueue and dequeue. the system would enqueue an order in the system every time a customer bought a book, and a storage house person would then dequeue it in order to pick it and post it.

It would then be easy to start talking about priority queues, by introducing prime customers, which might jump the queue, you could introduce priority queues.

What textbook are you using?


答: I suspect the code in question wasn't covered by unit tests. (or at least not adequately). Good unit tests cover handling exceptions gracefully as well as normal conditions.</p>

Title: Testing To Prevent Cascading Bugs


问:
Move from JSON to Protobuf. Is it worth it?
We have REST webservices that can serve XML or JSON (WCF). I'm toying with idea of implementing Protobufs. Why?

PROS

Less load on servers.

Smaller message size - less traffic.

It is easier to switch now than later.

CONS

Need to be implemented

Going to be harder to troubleshoot/sniff messages for debugging.

I can enable GZip on server and JSON will consume as much traffic

What is your suggestion and/or experience on this?

答:
Does the business value of implementing them exceed the cost?

If you implement, you need to change not just your server, but all clients (although you can support both formats and only change clients as needed). That will take time and testing, which is a direct cost. And don't underestimate the time taken to really understand protocol buffers (especially the reasons to make  field required or optional), and the time taken to integrate the protobuf compiler into your build process.

So does the value exceed that? Are you faced with a choice of "our bandwidth costs are X% of our revenues and we can't support that"? Or even "we need to spend $20,000 to add servers to support JSON"?

Unless you have a pressing business need, your "pros" aren't really pros, just premature optimization.


问:
General programming techniques to speed up coding time
I am preparing for a programming contest where we have to code in C++ and it is all about producing working code in a short time. An example would be to use a macro to get the minimum of two ints or using memsets to initialize arrays (but I was told that you shouldn't use either here).

This leads to the question, what kind of coding techniques exist to use at a real job?

答:
There have been many answers already, still I would like to add my opinion.

To speed up your coding, Become a touch typist to such a speed that while typing you are able to concentrate both on the logic and code. There are many software to learn typing (Typing Master, Rapid Typing, KTouch, gTypist for example), use them

I have seen many experienced programmers who are still two-finger typist. This leads to nasty code with no documentation and really cryptic code with macros and abbreviated type names.


问:
Layout of mathematical views (iOS)
I am trying to figure out the right way to encapsulate graphical information about mathematical objects.  It is not simple.  For example, a matrix can include square brackets around its entries, or not.  Some things carry down to sub-objects -- for example, a matrix might track the font size to be used by its entries.  Similarly, the font color and the background color would carry down to the entries.  Other things do not carry down.  For example, the entries of the matrix do not need to know whether or not the matrix has those square brackets.

Based on all of the above, I need to calculate sizes for everything, then frames.  All of this can depend on the properties stored above.  The size of a matrix depends on the sizes of its entries, and also on whether or not it has those brackets.

What I am having a hard time with is not the individual ways to calculate sensible frames for this or that.  It is the overall organizational structure of the whole thing.  How can I keep track of it all without going crazy.

One particular obstacle is worth mentioning -- for reasons I don't want to go into here, I need to calculate the sizes and frames for everything before I instantiate any actual views.  So, for example, if I have a Matrix object, I need to calculate its size before I make a MatrixView.  If I have an equation, I need to calculate the size of the view for the equation before I create the actual view.  So I clearly need separate objects for those calculations.  But I can't figure out a sensible class structure for those objects.  If I put them all into a single class, I get some advantages because copying then becomes easy.  But I also end up with a bloated class that contains info that is irrelevant for some objects -- such as whether or not to include those brackets around the matrix.  But if I use a lot of different classes, copying properties becomes a real pain.

If it matters, this is all in Objective C, for an iOS environment.  Any pointers would be greatly appreciated.

EDIT: To clarify: I have model objects that contain mathematical information and can compute the text that will be displayed.  I also think it will make sense to have style sheet objects that will know the font size.  Therefore, between the two, I can compute everything.  This still leaves the issue of how to keep track of the resulting information.  I don't want to call the "compute-your-size" methods more than necessary as they are expensive.  So I have to cache some things.  But where?  And how do I manage that caching?

答:
One way to do this that will work well in Objective-C and iOS is to use MVC as a guiding principle. You need to separate the actual data -- the terms of a polynomial, the entries in a matrix, and so on -- from the way the data is presented. This is just what MVC is good at: you'll have model objects that contain the specific equations, and view-like objects that know how to render different kinds of mathematical entities.

We often talk about MVC as an architecture for an entire application, but you can apply the same principles at smaller scales. Cocoa and Cocoa Touch do that -- witness the way that UITableView uses a delegate (which is like a controller) and a data source (which is like a model).

Anyway, if you're looking to preserve your sanity, you'll want to separate the different kinds of tasks into different kinds of classes. You won't have just one class that both represents and draws a matrix; you'll have a class that stores the data for and perhaps operates on a matrix and a class that knows how to present that data to the user.

Title: Layout of mathematical views (iOS)


答:
A perfect example of a queue would be a bank processing transactions against an account. Usually you'll see a list of "pending" transactions at the end of the day. When the accounting is done those transactions are applied to the account. You could even get into the area of priority queues with this. It seems most banks put priority on debits when processing nightly transactions so they can ding you with over draft fees before they apply any pending credits.

The transactions are inserted into the queue by order of time executed and dequeued and applied to the account by the accounting process.


答:
i maintain apis and somebody before me added protobuf (because it was "faster"). The only thing faster is RTT because of of smaller payload, and that can be fixed with gzipped JSON.

The part that is distasteful to me is the relative work to maintain protobuf (compared to JSON). I use java so we use Jackson object mapping for JSON. Adding to a response means adding a field to a POJO. But for protobuf I have to modify the .proto file, then update the serialization and deserialization logic which moves the data in/out of the protocol buffers and into POJOs. It's happened more than once that a release has happened where someone added a field and forgot to put in either the serialization or deserialization code for the protocol buffers.

Now that clients have implemented against the protocol buffers, it's almost impossible to get away from.

You can probably guess from this, my advice is don't do it.

Title: Move from JSON to Protobuf. Is it worth it?

Body:
We have REST webservices that can serve XML or JSON (WCF). I'm toying with idea of implementing Protobufs. Why?

PROS

Less load on servers.

Smaller message size - less traffic.

It is easier to switch now than later.

CONS

Need to be implemented

Going to be harder to troubleshoot/sniff messages for debugging.

I can enable GZip on server and JSON will consume as much traffic

What is your suggestion and/or experience on this?


问:
What's the most appropriate duration of the video tutorial?
It is now more and more popular to have video tutorials of the software or technology instead of writing long articles. As for me, it makes perfect sense, especially for such areas like "Getting Started" or "What's New".

What do you think is the most appropriate duration for such a videos? If you record the video tutorial yourself, would you just touch main points to keep it brief, or rather split it into a number of parts to keep the same level of details? And why?

I know this question isn't implied to have one and only answer. I'd like to hear the reasoning behind various opinions.

I have personally come across a video tutorial 45 minutes long today, and I got tired at around minute 10... So, my own impression is it's better to keep it from 5 to 10 minutes to gain visitor's attention fully.

Thanks!

答: I would tend to agree with the 5-10 minute rule. When I see a new technology, most of the time I don't want to get into the nitty-gritty details; I just want to get a general overview of it so that I can decide if it's something I want to learn more about. If the video does a B-tree traversal of everything one needs to know to use the tech, you can't get the general picture of WHY you would want it in the first place.</p>


答:
Your question focused on internships. I never had a programming one, but did intern at a radio station, not really applicable here.

Your question also mentioned your experiences during your internships. Your internship experiences and the answers you have received so far all pretty much sum up my experiences, after what is now twenty-seven years of writing software (started mid-June 1985).

I never quite believed it during school when our instructors said there is more thinking than actually writing code. They were right. And, if you're trying to figure out someone else's code, it is worse with no comments, and almost as bad with comments. Try sustaining a home-grown municipal tax collection system with no comments, no documentation, no formal build, and no source code control.

Whenever you can do well without its being a direct violation of standard orders, then do well. Always remember, it is easier to apologize for doing something you didn't ask permission to do than to have permission not be granted and go against a direct order.

Don't forget the standards you were taught in school. They're not useless, but more than likely those standards are the asymptotes in Calculus limits. You can always try to approach them, but you might never reach their value.

Good luck.


答:
Real world:

Any time that people line up: cashier at the grocery store, in the restaurant waiting for a table (you can work in those beepers that they sometimes give out into the analogy), etc. It's helpful when you notice that in the UK they often call these queues instead of lines (common in NA)

Reading book series', author.publish => queue.push and student.read => queue.pop

Non-Real World:

Processing any submitted data in a single-threaded environment where the processing takes longer than the submitting (checkout operations for online stores for eg.)

Any FIFO collection that can be iterated over can use queues and use while(queue.peek) instead of an iterator.


答:
I like to use games as an example because it is generally a little more exciting than file IO or whatever else you can come up with.

So when you want to issue several commands in a row to a unit in a strategy game (eg. Have a Zergling to scout 4 corners of a base in order, then suicide into the center of the base, a queue would be a good choice.)

Or maybe you have an application that can only process 30 frames per second, but you might get 4 or 5 inputs between frames. If you have a change weapon input and a shoot input, you want to make sure those get handled in the order they were received otherwise you may grenade when you wanted to knife. And if you grenade when you want to knife, you are gonna have a bad time. (put that on the ski instructor meme and throw it in your slides) :)

A server handling requests is another good one.

A CNC machine taking input. The machine can only go so fast, so it needs to queue up input.


答:
Your negative experience is all-too-typical of big well-known name-brand companies which a lot of developers learn to approach with a great deal more caution and trepidation than they did the first time they had an opportunity to work at one. Basically, the more layers of management you have, the more mediocrity is championed. Middle-managers don't report to upper-managers on quality of code. They report on features delivered in X amount of time and give powerpoint presentations on the neato UI feature they're hoping works just long enough to get them through it. If it all collapses in on itself a month later, that's usually somebody else's problem and they know that.

So yes, the devs that are lifers at such places tend to not care overly much. They couldn't survive there if they did. I've heard it said of Silicon Valley, that if you want to be lazy, work for one of the big names. If you want exciting work, look for a more recent startup that isn't a household name yet. I work in Chicago and can vouch for a similar phenomenon here.

As a general rule (with plenty of exceptions I'm sure), you will find a higher appreciation for quality code at companies that are smaller and managed or owned by people who also continue to write code. The compensation is often less, but the work is often much more rewarding in my opinion.

As an entry-level dev you're not likely to have a lot of control over who you work for at first but I will say that having a big name on your resume for a year or longer definitely excites recruiters and HR people. Also, you can learn quite a bit you wouldn't learn otherwise working for someone completely awful in the first six months or so and it also helps you get a better grip on which best practices actually matter and why and which ones are just tech-fads.

And of course when working with more main-stream popular corporate tools you're going to tend to find that median talent levels are going to be pretty crummy. If your primary skills are some combination of Java and C#, expand your horizons a little. You might find a happier niche at the mid-level writing Erlang or Python or :o JavaScript.

And don't let anybody tell you any different. You might not have a choice in the matter of how to proceed but crap code is !@#$ing expensive.


问:
Non-zero exit status for clean exit
Is it acceptable to return a non-zero exit code if the program in question ran properly? For example, say I have a simple program that (only) does the following:

Program takes N arguments. It returns an exit code of min(N, 255). Note that any N is valid for the program.

A more realistic program might return different codes for successfully ran programs that signify different things. Should these programs instead write this information to a stream instead, such as to stdout?

答:
Depends on what your environment expects.

My favorite for wierdness, from Wikipedia:

In OpenVMS, success is indicated by odd values and failure by even values. The value is a 32 bit integer with sub-fields: control bits, facility number, message number and severity. Severity values are divided between success (Success, Informational) and failure (Warning, Error, Fatal).

Title: Non-zero exit status for clean exit


答:
I would keep the introduction to 5 minutes. That should be long enough to hook people who are going to get hooked. Then they will be willing to watch longer videos, but even those should be no longer than 15 minutes, long enough to introduce one or two keys ideas, illustrate how they work and give the viewer some exercises for putting into practice the new ideas.

I am a very firm believer in tangibly reinforcing information very quickly after it is delivered. In addition to increasing the likelihood that the information will be truly understood and retained, it reduces the odds that the viewer will become fatigued.

I think that the Khan Academy videos are an excellent model and might even be the best and most well thought-out video instruction created to date.

Title: What's the most appropriate duration of the video tutorial?

Body:
It is now more and more popular to have video tutorials of the software or technology instead of writing long articles. As for me, it makes perfect sense, especially for such areas like "Getting Started" or "What's New".

What do you think is the most appropriate duration for such a videos? If you record the video tutorial yourself, would you just touch main points to keep it brief, or rather split it into a number of parts to keep the same level of details? And why?

I know this question isn't implied to have one and only answer. I'd like to hear the reasoning behind various opinions.

I have personally come across a video tutorial 45 minutes long today, and I got tired at around minute 10... So, my own impression is it's better to keep it from 5 to 10 minutes to gain visitor's attention fully.

Thanks!


答:
Some examples I can think of:

Calculator - can introduce prefix and postfix at the same time

Instructions to tie shoes.  Can't complete the next operation until you have done the last one

Buffers - Maybe a telephone buffer used to store numbers that the user has entered but have not made the tone sound yet

Digestion


答:
I used to be a telecom programmer so this comes to mind:

A Customer Service hotline. A call comes in, there are not enough operators to handle the call and it is placed in a queue. The next call comes in and it is also placed in the queue. Then when the next operator becomes available the first call that entered the queue gets assigned to the available operator.


答:
It depends on the environment, but I'd say it's poor style.

Unix-like systems have a strong convention that an exit status of 0 denotes success, and any non-zero exit status denotes failure. Some, but not all, programs distinguish between different kinds of failures with different non-zero exit codes; for example grep typically returns 0 if the pattern was found, 1 if it wasn't, and 2 (or more) if there was an error such as a missing file.

This convention is pretty much hard wired into Unix shells. For example, in sh, bash, and other Bourne-like shells, the if statement treats a 0 exit status as success/true, and a non-zero exit status as failure/false:

```<code>if your-command
then
    echo ok
else
    echo FAILURE
fi
</code>```

I believe the conventions under MS Windows are similar.

Now there's certainly nothing stopping you from writing your own program that uses unconventional exit codes, especially if nothing else is going to interact with it, but be aware that you're violating a well established convention, and it could come back and bite you later.

The usual way for a program to return this kind of information is to print it to stdout:

```<code>status="$(your-command)"
echo "Result is $status"
</code>```

Title: Non-zero exit status for clean exit

Body:
Is it acceptable to return a non-zero exit code if the program in question ran properly? For example, say I have a simple program that (only) does the following:

Program takes N arguments. It returns an exit code of min(N, 255). Note that any N is valid for the program.

A more realistic program might return different codes for successfully ran programs that signify different things. Should these programs instead write this information to a stream instead, such as to stdout?

Body:
It depends on the environment, but I'd say it's poor style.

Unix-like systems have a strong convention that an exit status of 0 denotes success, and any non-zero exit status denotes failure. Some, but not all, programs distinguish between different kinds of failures with different non-zero exit codes; for example grep typically returns 0 if the pattern was found, 1 if it wasn't, and 2 (or more) if there was an error such as a missing file.

This convention is pretty much hard wired into Unix shells. For example, in sh, bash, and other Bourne-like shells, the if statement treats a 0 exit status as success/true, and a non-zero exit status as failure/false:

if your-command
then
    echo ok
else
    echo FAILURE
fi

I believe the conventions under MS Windows are similar.

Now there's certainly nothing stopping you from writing your own program that uses unconventional exit codes, especially if nothing else is going to interact with it, but be aware that you're violating a well established convention, and it could come back and bite you later.

The usual way for a program to return this kind of information is to print it to stdout:

status="$(your-command)"
echo "Result is $status"


答:
not returning 0 for a successful run is a bad idea, because it can cause confusion for those running your program. What if some ran your program 100+ times with different input and wanted to know how many failed or completed successfully, having a single success value makes this much easier to spot differences than having many different values.

If you have a program that has multiple successful return paths that can all signify different things, I would say that is a sign your program is poorly designed.

Title: Non-zero exit status for clean exit


问:
Construct an array from an existing array

Given an array of integers A[1...n-1] where 'N' is the length of
  array A[ ]. Construct an array B such that B[i] = min(A[i], A[i+1],
  ..., A[i+K-1]), where K will be given.

Array B will have N-K+1 elements.

We can solve the problem using min-heaps
Construct min-heap for k elements - O(k)
For every next element delete the first element and insert the new element and heapify
Hence Worst Case Time - O( (n-k+1)*k ) + O(k)
Space - O(k)

Can we do it better?

答:
Here is my first thought, it may not be the best solution, but here it goes.

Take a look at the diagram below for K=10, N=15

You can see that when calculating each value of B, you need use the elements of A[S], A[S+1],..., A[E]. So you could do this calculation and store it first, then with each iteration use the stored value with the other A values, hence saving some iterations.

For example,

B[2] = Min(savedvalue, a[2...4],a[10...11])

This saves 3 comparisons with each iteration.


答:
The obvious Real-World examples would be things like checkout lines, and such, but since you're looking for an example rooted strictly in computing, might I suggest job scheduling queues?

I don't know how many of your students have taken an Operating Systems class, but it's a good bet that all of them have used the Task Manager to check their processes at some point or other. You could introduce a simplified example of a scheduling queue, and assign them some homework to write a program that generates (or accepts) a "task" of a given size, and processes them in FIFO order when they "start" it.

It's a fairly easy concept to understand, demonstrates the idea that queue operates on its contents in the order that it accepts them, and gives them a (very rudimentary and simplified) introduction to CPU scheduling. Just my two bits.

You might bring up their application in multithreading, but unless the students have had some experience writing threaded programs already I wouldn't assign work to them that might get two frustrating. I remember I had trouble learning data structures (especially in Java, having not done C++ and not learned a thing about pointers) in my second year of college, so a simple but practical example directly related to computing is probably best.


问:
What sort of Design Patterns do you use in Android Development?
I have been developing on Android for a couple months now, and building upon one in house program I found the scalability to be lacking. I have that gut feeling that if I applied some OO Design Patterns I would get an overall better program in speed, scalability, and readability.

Do any of you StackExchangers have ways you've applied a/many design pattern(s) that just seem to fit extremely well with the way Android works?

答: I use MVC pattern when developing for Android/Windows Phone 7.  Android Views lend themselves pretty well to it and is a great help when keeping the separate. Android code can get pretty complicated tossing views and intents around, so it helps to keep things as compartmentalized as possible.</p>