答:
If you play with many Zorglub objects in your methods, you "could" make a mistake and return the wrong one, or/and you could be tempted to name the others zorglub1, zorglub2, etc.

If you name it result, there is no chance for you to make a mistake like that. Plus, I find that is a good name; I've also seen returnedValue or returnedObject several times, it's also clear although a bit lengthy.

Title: Is it a good practice to name the returned variable "result"?

Body:
Is it a good practice to call the variable a method returns with a variable name result?

For instance:

```<code>public Zorglub calculate() {
    Zorglub result = [...]
    [...]
    return result;
}
</code>```

Or should I name it by its type?

```<code>public Zorglub calculate() {
    Zorglub zorglub = [...]
    [...]
    return zorglub;
}
</code>```

I have seen both in the wild, if I need to choose one what reasons could make me prefer the former or latter (or any better name)?

I am mainly thinking about Java.


问:
Is it a good practice to name the returned variable "result"?
Is it a good practice to call the variable a method returns with a variable name result?

For instance:

```<code>public Zorglub calculate() {
    Zorglub result = [...]
    [...]
    return result;
}
</code>```

Or should I name it by its type?

```<code>public Zorglub calculate() {
    Zorglub zorglub = [...]
    [...]
    return zorglub;
}
</code>```

I have seen both in the wild, if I need to choose one what reasons could make me prefer the former or latter (or any better name)?

I am mainly thinking about Java.

答: I personally use the name result for the value to be returned from function/method. It makes it explicit that it is the value to be returned. Naming it by type does not seem useful, because there may be more than one variable of that same type.

ContentLicense: CC BY-SA 3.0


答: Cross-reading is made easier if the variable is named result. This makes your intention clear.


答:
Whats the difference?
its just 2 different words there that will do the same thing so the real problem is which one sounds more clear to you?

The "result" or "zorglub".

I would prefer using ZorglubResult for a starter to see that result returns from Zorglub easier to compare with other results you may have and its a result as you can see..


问:
Clever PHP Application Organization Structures?
There are a million-and-one file-system structures that go into the myriad of Open Source projects available. Things like modules, language files, domains, third-party libraries, migrations, internationalization, backups, and syslinks to other parts of the system have given rise to many approaches to organize the filesystem of a project.

As a PHP developer I'm wondering if any type of standardization is starting to emerge among projects. With PSR-0 we finally have a standard for naming and loading files - but it nothing to my knowledge about the rest of the components that make up the system or how they can be handled in a sane way.

We are dealing with a lot more than just MVC, so what examples are there of  large projects correctly handling all of these things?

答:
There doesn't seem to be much of a standardization effort going on, and to be honest, I don't see the benefit. There is only one rule you should adhere to, which is that you should never have things under the docroot that don't belong there (a basic security precaution).

Other than that, I'd just go with what makes sense for the project.

If you're using MVC (either through a framework or ad-hoc), then a base structure with /models, /views and /controllers makes sense. But even if you're not, you usually have some sort of data access layer with classes that map to your data entities; it makes sense to have a directory for those; you also usually have a bunch of business logic classes and utility functions, so another directory for those; if you use a template system, templates go into another directory; and then you probably want a 'libraries' directory, where you put all third-party libraries. (Once you've reached this point, you're pretty much doing MVC anyway).

If the project is really large, it can probably divided into functional submodules; if the submodules are fairly independent, it makes sense to use those as your top-level instead, with one additional directory for the common code.


问:
Redis vs Zookeeper
It seems silly to compare these two servers considering that they're meant for very different things.  But if you think about it, they can do lots of similar things:  store configuration data, distributed locking, queueing, etc.

I've got an instance of Redis that I'm using for some production-related things, but would like to do some simple synchronization between servers (mostly configuration changes that don't require pushing up code and simple locking between servers).  What does Zookeeper give me that Redis wouldn't?

答:
We use both Redis and Zookeeper at work so this is from first hand experience

Redis is fast; really, really fast. It is also immediately consistent, so it's good for fast moving data sets. The downside is that, running on one server, if it fails then you lose write access until another server takes it's place. Replacing the server is a manual operation unless you automate it yourself. (You can still get read access to your data if you configure a slave instance).

Zookeeper also features immediately consistency. It's not half as quick, but it will recover automatically (where possible) in the face of failure, so if you need continuous write access, even when your servers fail on you then you'll want to use Zookeeper.

My advice is, use zookeeper for coordination: tracking which nodes are active, leader election amongst a group, etc. Use redis for datasets that need fast writes but where the occasional outage isn't a disaster. Hit counters for web pages for example.

Title: Redis vs Zookeeper


答:
I personally am not completely comfortable using result as a variable name. Fair enough, it tells me that the associated value is the result of some computation - however, I guess that is true to about (or over) 90% of the variables / fields used in a program.

Moreover, as several other answers noted, it may be used to mark the value to be returned from a method / function. However, if I keep my methods short, focused on doing one thing only and staying consistently on a single level of abstraction, I won't have many local variables and it will be trivial to see what a method is going to return.

So I prefer to keep my methods short and clean, and name my variables to express the meaning of the value they hold, rather than its local role inside the enclosing method. However, (e.g. in legacy code) Zorglub result may certainly be easier to understand than Zorglub zorglub.


答:
I like combining them, shows what it is and that it is intended to be returned.

so in your example it would be resultZorglub

if what it is doesn't really matter than it would just be result (not resultString)


答:
If I need a return variable (which is actually happens rarely), I always call it ret and always define it right below the function head. The function already has a name, which says all about what it returns.

If I have myFunction I could name it's return variable myFunctionReturnValue to say exactly the same thing, only I'd have to say it explicitly every single time. Since functions should generally be short, there is no need for such explicitness. And even if I lose track, I can jump to the declaration and will land right below the function definition.

But any other name, that doesn't implicitly (like ret or result) or explicitly (like myFunctionReturnValue or myFunctionResult) state, that this is the current functions return variable is too generic.

In your second example zorglub is a terrible choice. All the declaration really tells me is that you created a variable, the name of which is equal to the type annotation found right next to the name. It's about as helpful as int someInt or Zorglub z.

In your first example, when I look at the code, I first see the function name, that tells me, that this function calculates a Zorglub. As I read the second line I see "ok, here's the zorglub, that is going to be returned, but it evidently can't be returned right away and is therefore stored in the result variable" (as a side note: If you're not going to reassign the value, then you best declare the variable final to communicate that), and then I think "so now let's see what happens to it before it gets returned". Unlike in the first example I don't need to actually read any further than that to know that this is the variable, that's going to be returned and that I want to follow in the function body if I want to understand it.

You might want to read up on Spartan Programming, which is rather related to your question.


问:
Do threads use virtual memory or real memory?
I was trying to optimize my Linux server to handle 10,000 threads per process while it does just 382 right now. As per this article the following formula is used to find out total possible threads:

```<code>number of threads = total virtual memory / (stack size*1024*1024)
</code>```

This means threads store all their data in virtual memory. And to the best of my knowledge, virtual memory is swap space in a Linux machine which is stored on harddisk than RAM or cache.

So my question is does our threads uses harddisk to store for processing/store its data.

If yes, then doesnt this effect performance? Can we enhance the performance by putting in them on RAM or cache? How?

If no, how exactly do threads works?

Update:

According to useless's answer, virtual memory is a system comprising roughly:

physical memory (RAM)

any swapfiles you have attached

hardware support for translating virtual to physical addresses and
issuing page faults when a virtual address isn't available in
physical memory

(kernel) software support for: managing the lookup tables used by
that hardware handling those page faults by pulling pages in from
swap on demand

Thus, Everything that is on virtual memory is collectively on RAM(Real Memory) and Hard Disk(Swap Files). And as James explain in his answer decision on Ram vs HDD is taken by Kernel using algorithims such as LRU.

答:
First of all, you need to read more on computer memory, because you seems to lack the knowledge in that field.

A thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process. Multiple threads can exist within the same process and share resources such as memory, while different processes do not share these resources.

So, threads are going to use available memory - whatever kind of it is available. How many threads you can start depends on the memory size and how much memory is needed per thread. If thread uses heap (not only stack), then it needs more memory, and in that case you can start less threads.


答:
If the thread is actually running then the current instruction , and, any variables the thread is using must be in physical memory.

Most (in fact nearly all) programs reside in virtual memory, and, most programs use virtual memory for storage of variables.

Virtual addresses organized into chunks called pages (these are usually 4096 or 8192 byte blocks).

At any given time each block of virtual memory is stored somewhere in real memory or on the disk in the "swap space" reserved for this.

Your program code deals with virtual addresses, when you branch to a virtual address, or, request access to storage at a virtual address the system (usually at hardware level) locates the current location of the address request and maps it to your virtual address, if the address currently resides on the disk it pages it into real memory and then maps the address.

Obviously when all physical memory is in use if something is paged in then something else must be paged out, so the system looks for the "Least Recently Used" page and copies this out to disk before copying the page you requested in.

In modern systems there are several optimizations and tricks associated with virtual storage.

Addresses are mapped on a "per process" basis so for instance all C programs in a Linux box start the "main" process at the same address.

This can enable several 32 bit processes to occupy and use much more than 4GB on a machine as a 32 bit virtual address can be mapped to a real 64 bit address.

When processes end or memory is otherwise "free"ed the the system just marks the pages as free, they are never copied back to the swap disk.

Similarly when a new block of storage is requested the system just grabs a free page in real memory, no, disk IO takes place.

The sleep and hibernate functions force all the memory to be copied to the swap space so that all current processes and there current memory contents can be recreated on wake-up.

Title: Do threads use virtual memory or real memory?

Body:
I was trying to optimize my Linux server to handle 10,000 threads per process while it does just 382 right now. As per this article the following formula is used to find out total possible threads:

```<code>number of threads = total virtual memory / (stack size*1024*1024)
</code>```

This means threads store all their data in virtual memory. And to the best of my knowledge, virtual memory is swap space in a Linux machine which is stored on harddisk than RAM or cache.

So my question is does our threads uses harddisk to store for processing/store its data.

If yes, then doesnt this effect performance? Can we enhance the performance by putting in them on RAM or cache? How?

If no, how exactly do threads works?

Update:

According to useless's answer, virtual memory is a system comprising roughly:

physical memory (RAM)

any swapfiles you have attached

hardware support for translating virtual to physical addresses and
issuing page faults when a virtual address isn't available in
physical memory

(kernel) software support for: managing the lookup tables used by
that hardware handling those page faults by pulling pages in from
swap on demand

Thus, Everything that is on virtual memory is collectively on RAM(Real Memory) and Hard Disk(Swap Files). And as James explain in his answer decision on Ram vs HDD is taken by Kernel using algorithims such as LRU.


问:
How can a child state machine relinquish control back to the parent state machine?
My top level state machine has some states and edges. I will call this the parent state machine.

```<code>A ----> B ----> C
</code>```

Any state within the parent state machine can be a state machine too. I will call these children state machines.

```<code>           ___________
         /            \
A ----> |  B0->B1->B2  | ----> C
         \____________/
</code>```

If the parent state machine transitions from A to B, B's state machine takes over. Once B is done running, how should it relinquish control to the parent state machine and transition to state C? Which design pattern do you use?

If you're wondering, I have children state machines within parent state machines because my exact project is quite complex and it is natural to encapsulate the internal workings of a child state.

答:
The solution depends on 1) whether A's sub-states are visble to B's sub-states. 2) Do A B and C derive from a common parent. If they have a common parent and the visibility is universal, you shouldnt have too much trouble moving from B's sub state to A's sub state.

If you have isolated them via namespaces and/or A, B and C dont have a common parent, then your best wayy is tohave an external state change driver for A , B and C machines. THis can be done via an event handler. Simply have an observer in A which can listens to events raised in B and transitions to its own sub state based on the event.


问:
Who does test-driven development?
I've been working in the enterprise space for the past 4½ years and have noticed that generally speaking, enterprises are not conducive environments for the test-first style of development. Projects are usually fixed-cost, fixed-timeline and waterfall style. Any unit testing, if done at all, usually comes after development in the QA phase and done by another team.

Prior to working for an enterprise, I consulted for many small to medium sized companies, and none of them were willing to pay for a test-first style of development project. They usually wanted development started immediately, or after a short design stint: i.e., something more akin to Agile, though some clients wanted everything mapped out similar to waterfall.

With what types of shops, companies, and clients does test-driven development work
best? What types of projects tend to be conducive to TDD?

答:
My boss fed me a good one today on this, I think I'm going to steal it like he was stealing it from someone else.

"Would you expect a carpenter to
  measure the board before he cuts it?"

I took wood shop class in high school and worked construction through school. Our mantra was always "measure twice, cut once" which got followed up by the sarcastic "I cut it and cut it again and it was still too short!"

Title: Who does test-driven development?

ContentLicense: CC BY-SA 2.5


问:
Session size management
From what I know, the session information is usually saved on the server.

In Java the data is handled as a Map which I guess contains the a String identifier and an object reference which points to a memory zone from the server.

Considering that, is it safe to assume that storing a Properties file on the session will not have a critical effect on performance?

I have to handle some Language Properties files (ResourceBundle). For some reason I have to translate at every request at least 30 strings in one of 3 languages. This results in many conditional clauses which can be avoided by storing the Properties file on the session.

Note:
The Properties file is just an example. The aim of the question is to determine why and how placing an Properties object in the session differs from pacing an String object. I am aware of the size aspect but does this issue stands while all Objects are stored on the server?

答:
You shouldn't store it in session but at the same time you also shouldn't load the Properties file after each request because of the detrimental impact that repeated file I/O will incur.

Store it on the ApplicationContext which allows the one Properties file to be loaded into memory once and can be used to the beneft of all users on all sessions.

Title: Session size management


答:
In your second example, you're conflating the type of the result with what it is.

```<code>Zorglub zorglub;
</code>```

just tells me it's a Zorglub, twice. Three times if I bother to read the method return type. However,

```<code>double variance;
</code>```

for example, gives me a clue about what the return value means, in terms of program semantics. It may or may not be any clearer than just calling it result, depending on the size of the method - that's a judgement call for each method IMO.

Body:
In your second example, you're conflating the type of the result with what it is.

Zorglub zorglub;

just tells me it's a Zorglub, twice. Three times if I bother to read the method return type. However,

double variance;

for example, gives me a clue about what the return value means, in terms of program semantics. It may or may not be any clearer than just calling it result, depending on the size of the method - that's a judgement call for each method IMO.


答:
The simple answer to your question is, they use virtual memory. everything uses virtual memory except a handful of processes related to the OS.

On the other hand, when your thread (or any thread, in any process) is actually running, it is using physical memory. The memory pages associated with that process are swapped in to physical memory which is where the processor does its work.


问:
Regulation of the software industry
Every few years someone proposes tighter regulation for the software industry.

This IEEE article has been getting some attention lately on the subject.

If software engineers who write programs for systems that expose the public to physical or financial risk knew they would be tested on their competence, the thinking goes, it would reduce the flaws and failures in code—and maybe save a few lives in the bargain.

I'm skeptical about the value and merit of this. To my mind it looks like a land grab by those that proposed it.

The quote that clinches that for me is:

The exam will test for basic knowledge, not mastery of subject matter

because the big failures (e.g. THERAC-25) seem to be complex, subtle issues that "basic knowledge" would never be sufficient to prevent.

Ignoring any local issues (such as existing protections of the title Engineer in some jurisdictions):

The aims are noble - avoid the quacks/charlatans1 and make that distinction more obvious to those that buy their software. Can tighter regulation of the software industry ever achieve it's original goal?

1 Exactly as regulation of the medical profession was intended to do.

答:
I have to answer this one...

Starting with what @JonathanHenson said and the entry of @gnat, what I say is ok, people that have money can pay for certified stuff, people or countries that don't have money can't pay for licenses (so much for certified stuff), so there will still be renegades if that gets into practise. Even if traditional (and not so traditional) delivering methods are closed, people will still find ways to deliver software to interested users. Even if it means to develop another HTTP protocol or even an alternative whole network stack, only focused in making connections undetectable (see the last paragraph, for someone who might be able to do this).

Also, the idea of paying for something, is at risk, since the world is getting poorer and poorer, so more and more people will have less and less money to pay for things, there are even countries that only use FOSS software, without any certification (Brazil and India come to mind, but there are sure others), and some of those countries are getting big, really big. And they use uncertified software made by unknown programmers, whose skill is unknown.

Also, even if there is some type of certification, the certification will only certify the knowledge, not the ethics, just think that some doctors do use organs that are removed in an unauthorised way from people, so there would be also certified programmers who would have no ethics and write sloppy code either intentionally or unintentionally. While in most FOSS projects, most potentially unskilled programmers also review code from others and try to find errors, in a way that makes pair programming, something little.

At last, what do you say of hacking groups (not black hat hacker groups, but white or grey hat groups), that know much more about security and develop security software in a way that only matches the most specialised programmers from certain government departments.

Title: Regulation of the software industry


答:
to the best of my knowledge, virtual memory is swap space in a Linux machine

Nope, virtual memory is a system comprising roughly:

physical memory (RAM)

any swapfiles you have attached

hardware support for translating virtual to physical addresses and issuing page faults when a virtual address isn't available in physical memory

(kernel) software support for:

managing the lookup tables used by that hardware

handling those page faults by pulling pages in from swap on demand

It's up to the kernel to make sure the virtual memory you want is cached into RAM when you want it - unless you're writing your own userspace VM layer (such as databases often do, iiuc), just don't worry about it.


问:
Do GUI programmers have an undue advantage over others?
It is easy for managers and customers to appreciate what they can see.

I have seen many GUI developers who are average programmers with minimal knowledge of design principles or other programming idioms. However, these shortcomings often go unnoticed, specially by management and customers, if the programmer can create an impressive looking user interface. So much so that many GUI developers I know spend hours beautifying the GUI at the expense of writing bad, unmaintainable code.

On the other hand, middle tier programmers who develop APIs or business functionality or database code (SQLs etc.) are at a disadvantage as there is nothing tangible to showcase. Perhaps a code reviewer or an architect may appreciate the elegance, good design, scalability etc. of code but it means nothing to the outside world. Your code may run for years without breaking, may be very easy to maintain and have good performance, yet it never elicits the 'wow' that a slick looking GUI does.

In my opinion, a corollary to this is (and I am going to get heavily downvoted for this, I know) that there is less motivation for a GUI programmer to write good clean code.

EDIT: I must explain here that by GUI programmer, I don't mean a full-fledged web/GUI designer but a front-end programmer e.g., a java-swing programmer.

Does the rest of the community agree ?

答:
As the "UI expert" at my company (the guy in charge of all the UI development, not just the design), I think you might be missing some part of the story. While I'm the guy in charge of the UI, I also work the on back-end, on the databases, etc. I do it all (we're a small team). [C# and ASP.Net WebForms development]

First of all, yes it is much easier for non-technical people to appreciate the work of a GUI developer because that's what's in the face of people. To non-technical people, the GUI is the application. The drawback is that the GUI is also the first one to be blamed when something goes wrong.

Second of all, developing the front-end has been much more challenging for me than the back-end ever was (obscure/complex algorithms aside). There's so much more to guard against, it's stateless (our apps are on the Web), browsers don't behave consistently (JavaScript libraries were a godsend), etc. I'm hoping most of this complexity is due to the framework I have to work with (ASP.Net WebForms) and that all the difficult stuff won't be an issue in the future.

Overall, I've had much more difficulty solving UI issues than back-end issues.


问:
How do you name your GUI controls?
It's a generally considered a bad practice to use the Hungarian notation, but is common to find GUI controls named userNameTextBox and userNameLabel.

Do you put the control type in it's name? Isn't this a kind of Hungarian notation?

答:
Actually I use Hungarian notation, only for GUI controls. I use something like lblText, rbGroup1, lvTable etc for labels, radio buttons and list views.

They never tend to change anyway and it's clear what variable is a GUI control and what is not.

However, since I use WPF with binding possibilities it is not really necessary anymore to name them at all, since it is binded to a C# property.

Btw, don't make the mistake to call a control lvListViewPersons what I occasionaly see. If a variable is prefixed with lv you can see it is a listview already.

Title: How do you name your GUI controls?


答:
Like you say. In general, Hungarian notation is a bad practice. I like to keep my names as close to the domain as possible, but sometimes what you are trying to say is that this is the textbox and this is the label.

See Kramii's answer to another question for his very reasonable take on why he still uses Hungarian in certain situations.

As with all code, consistency and self evaluation is key. If you and your team agree on how different GUI-controls are labeled, and what elements need labels, you'll be fine :)

Title: How do you name your GUI controls?

Body:
It's a generally considered a bad practice to use the Hungarian notation, but is common to find GUI controls named userNameTextBox and userNameLabel.

Do you put the control type in it's name? Isn't this a kind of Hungarian notation?


答:
I don't see much of a difference between setting a return value at some point and then using conditionals to skip over all code that might modify it, and returning right away, so I go for the direct return, hence there is no result variable.

If you have an intermediate value that may or may not be changed by conditional code, then it is not a result (yet), so it certainly should not be named so.


答:
You don't need to code any conditionals to get the appropriate translation for a given property, just a Locale for the current user; provide that when retrieving a ResourceBundle:

```<code>ResourceBundle localeSpecificBundle = ResourceBundle.getBundle("bundleBaseName", userLocale);
String translated = localeSpecificBundle.getString("someKey");
</code>```

In addition, ResourceBundle does some caching through the static getBundle method so that you don't have to worry about doing your own caching to avoid file I/O. From the ResourceBundle doc:

Resource bundle instances created by the getBundle factory methods are cached by default, and the factory methods return the same resource bundle instance multiple times if it has been cached. getBundle clients may clear the cache, manage the lifetime of cached resource bundle instances using time-to-live values, or specify not to cache resource bundle instances.

The actual caching is done with a static ConcurrentMap:

The cache is a map from cache keys (with bundle base name, locale, and class loader) to either a resource bundle or NONEXISTENT_BUNDLE wrapped by a BundleReference. The cache is a ConcurrentMap, allowing the cache to be searched concurrently by multiple threads. This will also allow the cache keys to be reclaimed along with the ClassLoaders they reference.

Title: Session size management

Body:
From what I know, the session information is usually saved on the server.

In Java the data is handled as a Map which I guess contains the a String identifier and an object reference which points to a memory zone from the server.

Considering that, is it safe to assume that storing a Properties file on the session will not have a critical effect on performance?

I have to handle some Language Properties files (ResourceBundle). For some reason I have to translate at every request at least 30 strings in one of 3 languages. This results in many conditional clauses which can be avoided by storing the Properties file on the session.

Note:
The Properties file is just an example. The aim of the question is to determine why and how placing an Properties object in the session differs from pacing an String object. I am aware of the size aspect but does this issue stands while all Objects are stored on the server?

Body:
You don't need to code any conditionals to get the appropriate translation for a given property, just a Locale for the current user; provide that when retrieving a ResourceBundle:

ResourceBundle localeSpecificBundle = ResourceBundle.getBundle("bundleBaseName", userLocale);
String translated = localeSpecificBundle.getString("someKey");

In addition, ResourceBundle does some caching through the static getBundle method so that you don't have to worry about doing your own caching to avoid file I/O. From the ResourceBundle doc:

Resource bundle instances created by the getBundle factory methods are cached by default, and the factory methods return the same resource bundle instance multiple times if it has been cached. getBundle clients may clear the cache, manage the lifetime of cached resource bundle instances using time-to-live values, or specify not to cache resource bundle instances.

The actual caching is done with a static ConcurrentMap:

The cache is a map from cache keys (with bundle base name, locale, and class loader) to either a resource bundle or NONEXISTENT_BUNDLE wrapped by a BundleReference. The cache is a ConcurrentMap, allowing the cache to be searched concurrently by multiple threads. This will also allow the cache keys to be reclaimed along with the ClassLoaders they reference.


问:
Why are shortcuts like x += y considered good practice?
I have no idea what these are actually called, but I see them all the time. The Python implementation is something like:

x += 5 as a shorthand notation for x = x + 5.

But why is this considered good practice? I've run across it in nearly every book or programming tutorial I've read for Python, C, R so on and so forth. I get that it's convenient, saving three keystrokes including spaces. But they always seem to trip me up when I'm reading code, and at least to my mind, make it less readable, not more.

Am I missing some clear and obvious reason these are used all over the place?

答:
The other answers target the more common cases, but there is another reason: In some programming languages, it can be overloaded; e.g. Scala.

Small Scala lesson:

```<code>var j = 5 #Creates a variable
j += 4    #Compiles

val i = 5 #Creates a constant
i += 4    #Doesn’t compile
</code>```

If a class only defines the + operator, x+=y is indeed a shortcut of x=x+y.

If a class overloads +=, however, they are not:

```<code>var a = ""
a += "This works. a now points to a new String."

val b = ""
b += "This doesn’t compile, as b cannot be reassigned."

val c = StringBuffer() #implements +=
c += "This works, as StringBuffer implements “+=(c: String)”."
</code>```

Additionally, operators + and += are two separate operators (and not only these: +a, ++a, a++, a+b a += b are different operators as well); in languages where operator overloading is available this might create interesting situations. Just as described above - if you'll overload the + operator to perform the adding, bear in mind that += will have to be overloaded as well.

Body:
The other answers target the more common cases, but there is another reason: In some programming languages, it can be overloaded; e.g. Scala.

Small Scala lesson:

var j = 5 #Creates a variable
j += 4    #Compiles

val i = 5 #Creates a constant
i += 4    #Doesn’t compile

If a class only defines the + operator, x+=y is indeed a shortcut of x=x+y.

If a class overloads +=, however, they are not:

var a = ""
a += "This works. a now points to a new String."

val b = ""
b += "This doesn’t compile, as b cannot be reassigned."

val c = StringBuffer() #implements +=
c += "This works, as StringBuffer implements “+=(c: String)”."

Additionally, operators + and += are two separate operators (and not only these: +a, ++a, a++, a+b a += b are different operators as well); in languages where operator overloading is available this might create interesting situations. Just as described above - if you'll overload the + operator to perform the adding, bear in mind that += will have to be overloaded as well.


答:
It depends on the audience. I work with a lot of financial analysts and their idea of a good gui design is one that has as many fields as you can possibly jam onto one form. Seriously, I'm talking 75 - 100. They're data junkies who always want more. I recently improved the performance on a few stored procedures that could take 45 seconds to load (calculate weighted averages since the beginning of time stuff). Got it down to 30 seconds; I'm thinking wow, cut one-third of the time; it should be a line item on my resume. No one even noticed. Kept working on it and got it to 15-20. Noticable change. Everyone was very happy. I still think the GUI is an abomination and if we took out this useless crap, it would load in 2 seconds, but when there are 15 different multi-line text boxes (You know the ones that have all the formating capability with MAX character settings.), it's hopeless.

So if you want users to really love you, remember that the best user interface is no interface at all (wish I remembered who said that). After wanting to see all these data, my analysts have realized they are the ones to do all the data entry - the horror.

Title: Do GUI programmers have an undue advantage over others?

Body:
It is easy for managers and customers to appreciate what they can see.

I have seen many GUI developers who are average programmers with minimal knowledge of design principles or other programming idioms. However, these shortcomings often go unnoticed, specially by management and customers, if the programmer can create an impressive looking user interface. So much so that many GUI developers I know spend hours beautifying the GUI at the expense of writing bad, unmaintainable code.

On the other hand, middle tier programmers who develop APIs or business functionality or database code (SQLs etc.) are at a disadvantage as there is nothing tangible to showcase. Perhaps a code reviewer or an architect may appreciate the elegance, good design, scalability etc. of code but it means nothing to the outside world. Your code may run for years without breaking, may be very easy to maintain and have good performance, yet it never elicits the 'wow' that a slick looking GUI does.

In my opinion, a corollary to this is (and I am going to get heavily downvoted for this, I know) that there is less motivation for a GUI programmer to write good clean code.

EDIT: I must explain here that by GUI programmer, I don't mean a full-fledged web/GUI designer but a front-end programmer e.g., a java-swing programmer.

Does the rest of the community agree ?


问:
Managing constants in application
Our application is having 2 parts a web app running ROR and a web service running Sinatra. The application communicates with the mobile device for which we use different constants depending on the message we need to the send to the device.
We are currently using integer constants saved up in a module. Eg:

```<code>SEND_HI="122"
</code>```

As the application has grown and we have around 50+ constants we are realizing that this is a bad way to handle constants as different developer seems to give different constants and clashes occur. Also there is a mismatch between the constant values in ROR and sinatra (due to developers mistake obviously).
What is a pain free way to handle constants or message identifiers.

答:
Well, first of all, you should probably avoid storing all your constants in the same place. If you have two different services you should use two different modules to store them. Place them as submodules if you like, e.g. Constants.Ror and Constants.Sinatra. Logically separating the two will help avoid naming clashes and make it easier to find which constants apply for what service.

I'm not very familiar with Ruby. Does it have an enum structure? Since you are using integer constants (which I assume would be unique), an enum would be ideal for preventing constant conflicts.

Title: Managing constants in application


答:
Virtual memory is your RAM plus your swap space.  Virtual just means the address your program sees is different than the address the RAM chip sees.  If you need to access memory in swap, the OS will move it into RAM first.  If you don't want any swapping, just disable it.  If you have enough RAM you don't really need it.

That being said, unless you have a 10,000 core processor, increasing to 10,000 threads isn't really an "optimization."  Once you have enough threads to consume all the cores, plus a spare or two for when those threads are blocked, adding more threads decreases performance due to the switching overhead and cache misses.  You might still want to use more threads if it makes your program logic simpler, but you will be trading off performance.


问:
Assembly in a research paper
I am doing a research paper on programming, and I need to somehow explain assembly... I've never learned the language, but I understand what it is used for and kinda what it looks like...

```<code>MOV A,47
ADD A,B
HALT
</code>```

And from what I understand, it is used for writing some compilers, small bits of code that need to be really fast, and other tasks... But this is kind of a question for people who have used/studied assembly and understand it fairly well. And no, I'm not asking for you to type up this segment of the research paper for me. That would be selfish. I just need a brief explanation, clarification on the subject (I'm just unsure if what I know is true or not) and a pointer in the right direction.

For a research paper (I need to explain this VERY simply...) what is purpose of using Assembly in today's society? Of course it was important back in the day but now with all the high level languages, when is this low level language used?

答:
The assembler is usually used when you need some heavy optimization. Take for example here, where the guy optimized the processing 6 times.

However take a note that modern compilers are very good in optimization, and unless you really knows what you are doing, you will not beat the compiler.

Title: Assembly in a research paper


问:
Lexical Analysis without regular expressions
I've been looking at a few lexers in various higher level langauges (Python, PHP, Javascript among others) and they all seem to use regular expressions in one form or another. While I'm sure regex's are probably the best way to do this, I was wondering if there was any way to achieve basic lexing without regular expressions, maybe some sort of direct string parsing or something.

So yeah, is it possible to implement some sort of basic lexing in a higher level language* without using regular expressions in any form?

*Higher level languages being things like Perl/PHP/Python/Javascript etc. I'm sure there is a way to do it in C

答:
Of course you can use other parsers, as every regular language is also context free. The question really comes down to why you would want to.

There's not really anything simpler than regular expressions (how can you improve O(N)?) and trying to simplify won't help. You can always use simple backtracking as Jetti has pointed out, although I recommend avoiding it if possible.

If you're going to use a more advanced parser for lexing then you likely don't need a lexing phase at all. In fact, the reasons why we have a lexing phase is that it's faster to parse lexed tokens than to parse characters, along with it drastically simplifying our parsing step. So by using a more advanced parser you simply lose all benefit of lexing in the first place.


问:
Managing multiple versions of a web application using Git
We have a family of apps, all having the same base. Until now I've been developing this base, and the Git workflow was very simple:

Development is done in develop branch

New features are developed in name-of-the-feature branch

Releases are made in release-** branch

Until now, the code was the same for every app of the family. Let's say the base they share is now complete, and from now on the code will be different for every app.

I'm not sure how should I deal with git and this multiple apps that have the same base.

Should each one of them have its own git project?

Should they be on the same project, but each one in its own branch?

The point is: if I put them on separate projects, every modification done in the base of the app will have to me repeated in each of the apps. I'm not very familiar with git, but if  I store each project in a branch, will be possible to merge the base modification with each app?

Does anyone have experienced a situation like this? I'm not sure how to proceed.

Thanks!

EDITED
When I said version I didn't mean like version numbers. They are actually different apps that share the same base.

答: If the apps won't modify the base itself, consider leaving the base in its own repository. Then create a new repository for each of the individual apps and add the base as a git submodule.</p>


答:
First of all, there have been regular expression libraries for C since before your "higher-level" languages were invented.  Just saying, C programs aren't as podunk as some people seem to think.

For most grammars, lexing is a matter of searching for whitespace and a few other characters like ()[]{}; to split the words, and then matching against a list of keywords to see if any match.

Title: Lexical Analysis without regular expressions

Body:
I've been looking at a few lexers in various higher level langauges (Python, PHP, Javascript among others) and they all seem to use regular expressions in one form or another. While I'm sure regex's are probably the best way to do this, I was wondering if there was any way to achieve basic lexing without regular expressions, maybe some sort of direct string parsing or something.

So yeah, is it possible to implement some sort of basic lexing in a higher level language* without using regular expressions in any form?

*Higher level languages being things like Perl/PHP/Python/Javascript etc. I'm sure there is a way to do it in C


答:
While VJovic makes a good point, there are still a few situations where you will need to learn an assembly language.

1.) If you are writing a compiler and want to compile to native code. Although, you can translate to a language with a native compiler (such as C) and then use a C compiler to go from there.

2.) You are writing an operating system. While most operating systems are written in C (or another high level language) there are still parts that are written in assembly

3.) Embedded and/or limited device programming. Sometimes you need to get into the nitty gritty because your hardware doesn't have a C compiler (though this is becoming more and more rare)

Title: Assembly in a research paper

Body:
I am doing a research paper on programming, and I need to somehow explain assembly... I've never learned the language, but I understand what it is used for and kinda what it looks like...

```<code>MOV A,47
ADD A,B
HALT
</code>```

And from what I understand, it is used for writing some compilers, small bits of code that need to be really fast, and other tasks... But this is kind of a question for people who have used/studied assembly and understand it fairly well. And no, I'm not asking for you to type up this segment of the research paper for me. That would be selfish. I just need a brief explanation, clarification on the subject (I'm just unsure if what I know is true or not) and a pointer in the right direction.

For a research paper (I need to explain this VERY simply...) what is purpose of using Assembly in today's society? Of course it was important back in the day but now with all the high level languages, when is this low level language used?


答:
It's essential for implementing compilers, operating systems, and highly optimized code, especially on embedded systems.

It also can be used for debugging as viewing the compiler's output is a helpful thing.

Additionally, many architectures provide special instructions that can be reliably accessed with assembly, again used for optimization.

Title: Assembly in a research paper


问:
Is it unreasonable to write user documentation in the style of a technical book?
Tell me if this sounds familiar:

something something something... as seen in figure 1-1 on the next page...

It's in practically every book I've ever read about programming. So when I was writing a small instructional booklet on how to use some in-house software, which had images of the screen that the user will be on at this certain step I wrote something like "The screen that pops up looks like the one shown in figure 1-1 below."

But I'm thinking: I'm used to that style of writing, but if my target audience is the 'average person' are they going to be confused?

So, more generally, are there any common practices in technical books that should be avoided when writing documentation for average people?

答:
If you want a better answer to your question and a real awakening as to how well you write instructional manuals, hand the lady at the desk your instructions and watch over her shoulder as she tries to follow. Don't interject; pretend your not there. Ask her to think outloud. Take lots of notes. Prepared to be shocked.

Go back and rewrite the instructions with all the feedback you received.

At least with the romance novels, you know who's banging who. Our instructions are rarely that clear.


问:
industry averages for time spent on maintenance
A manager recently announced that were were spending far too much time fixing bugs. I guess he thinks we should write perfect code all the time (whilst still hitting those impossible deadlines of course!) and it made me wonder what the industry average of time spent bug fixing v writing new code was.

So does anyone have any metrics on time spent bug fixing against new code development? Or is there any empirical analysis of bug fixing time for the industry as a whole? Is 50% spent bug fixing too much, or about right? How about 20% or 33%?

I'm happy to accept anecdotal evidence from personal experience as that would form part of some statistics here that I could compare our performance against.

答:
It depends on how much code you have out there, how long it has been out there, etc.

The time spent fixing bugs in software should be front-loaded to the first 6-12 months of release, however as time approaches infinity, the time spent on maintenance versus the time spent on initial development will exceed 100% - that's just the way things work.

While I don't have any hard statistics (Code Complete does, but I can't tell you exactly which page/section), in my experience roughly 40% of development (sometimes as high as 60%) is spent on maintenance. It's obvious that the more code you release, the more maintenance time you will have. Bugs are not always functional, and are as much a result of uncertainty as they are programmatical defects.


问:
Is using dynamically generated code as cache a good idea?
I have a web search interface that can compare products in a table. This data set changes a few times a week.

I have been storing a "DISTINCT" list (used for parametric selection) in a cache table. The query is computationally expensive because it involves table joins and thousands of records, hence the reason to cache it.

I was wondering if it is a good idea to "cache" certain data in PHP in dynamically generated code.

The idea is that I could create a cache.php file that is 'included' which has the data in arrays for PHP to use without going to the database. This PHP file could be cached using any of the PHP compiler caches out there.

I'm not having speed issues (yet), but I don't like the idea of having to ask the database for cache data, as it seems the overhead of the php->mysql transaction is expensive.

答:
Yes, it's fine. It's a very common practice, and I can't think of a mature framework I've used that doesn't have some sort of code generation caching as part of the optimization scheme.

That said, if your database supports views, I would recommend using that.


答:
The first question to ask is if your "bug fixing" is actually fixing coding bugs or something else. The fixing of actual code bugs should be relatively small in most cases as long as you have a good code base. If you're working with a poor code base, extensive bug fixing is inevitable.

However, in the course of putting a program into production, you'll find requirements that weren't documented, unexpected user activity, data anomalies, hardware incompatibilities, installation issues and other problems that aren't strictly code bugs. Often managers and users will think of these production support/maintenance problems as bugs since they typically require code changes.

I've also encountered managers who would group what should have been termed as minor enhancement requests as bugs. Often these get entered into a bug tracking or problem reporting system and this can make your "bug" stats higher than they really are.

Title: industry averages for time spent on maintenance

Body:
A manager recently announced that were were spending far too much time fixing bugs. I guess he thinks we should write perfect code all the time (whilst still hitting those impossible deadlines of course!) and it made me wonder what the industry average of time spent bug fixing v writing new code was.

So does anyone have any metrics on time spent bug fixing against new code development? Or is there any empirical analysis of bug fixing time for the industry as a whole? Is 50% spent bug fixing too much, or about right? How about 20% or 33%?

I'm happy to accept anecdotal evidence from personal experience as that would form part of some statistics here that I could compare our performance against.


答:
I'm of two minds about the use of assembly today.  First, it's handy for low-level, highly optimized systems (usually embedded systems.)  It is also useful for optimizing some parts of a system (like an operating system or a network stack, for example) that are have heavy performance demands placed upon them.  It also can be used to create compilers for other languages, but I think most are now done in C.

Secondly, though, I think it has an educational use.  It's like learning Latin.  Although there isn't a country in which Latin is spoken, it's still widely taught because of its use in science, medicine, and is the antecedent of many of the the more modern languages.

Assembly is like that.  Learning exactly how the bits flow around the computer gives a programmer a deeper understanding of the functioning of the machine, and that understanding may give him insight in writing higher-level languages.  Assembly is as close to the machine (e.g. "close to the metal") as you can get.

Title: Assembly in a research paper


问:
How can I communicate the risks of altering vendor software?
We have a major problem where I work, and it's name is "customization". We have an old (10+ years) vendor software system that our IT and accounting departments previously loved to customize. Somewhere along the line this software started getting very buggy. Then, I was hired after the bulk of the customization.

Nearly every problem I've found with the system is a direct result of customization; everything we change risks breaking business critical financial software. Yet the accounting department keeps suggesting changes (because we always said yes!) and there seems to be little respect for how impactful changes might be.

Some changes cause no problems; forms can be (and are meant to be) customized in the vendor software, we can move around form fields, remove them, ect. But for every harmless customization like that they also suggest changes like stored procedures and triggers to manipulate data in the database for the vendor application.

I recently (barely) got them to stop trying to import customers from one vendor program into another as the information was completely incompatible. My problem with how that was resolved is because I found the system didn't work on the user side; the task was more complicated than they thought so they gave up. Regardless of how easy the user-side task is, the operation they wanted shouldn't have been performed.

How can I communicate that changing how this system works has risks, particularly when data validity is at stake? I'm a new (6 months) hire and it's become the status quo, but it's risking the validity of our financial data and our support contracts--once the vendor's support hears "X has been customized" that gives them that much reason not to support us or tell us it's our fault.

答:
Communicating to office dwellers? I'd go with analogies.

Tell them that all these changes are turning your typical 4-door domestic sedan into an exotic foreign car. Every time you bring it into the mechanic shop, from the tune-up, to the crushed light, to the transmission overhaul, it's going to be more expensive. "We don't have the parts, only the dealer with special knowledge can touch that, we tried but the manual is in German".

You are the mechanic in charge of keeping it running. The database is the engine. The whole system is the car. The accountants drive the car around. The cute little bunny the accountants swerved to miss is an umlaut character in the last name of a new customer. The light pole they wrapped their car around is the critical bug that was introduced when they wanted to add a disco ball inside the car.


问:
Is it a good practice to name the returned variable "result"?
Is it a good practice to call the variable a method returns with a variable name result?

For instance:

```<code>public Zorglub calculate() {
    Zorglub result = [...]
    [...]
    return result;
}
</code>```

Or should I name it by its type?

```<code>public Zorglub calculate() {
    Zorglub zorglub = [...]
    [...]
    return zorglub;
}
</code>```

I have seen both in the wild, if I need to choose one what reasons could make me prefer the former or latter (or any better name)?

I am mainly thinking about Java.

答:
When I was working in C++ and I guess this may apply in Java I did.

e.g.

```<code>int Width() const
{
    Requires(....);
    Requires(....);

    //calculation

    Ensures(...);
    Ensures(...);
    return Result;
}
</code>```

This is design by contract, as the ensure block should be at the end of the method. But the return must be last. We had the rule that return Result was the only thing that could follow the ensure block.

Body:
When I was working in C++ and I guess this may apply in Java I did.

e.g.

int Width() const
{
    Requires(....);
    Requires(....);

    //calculation

    Ensures(...);
    Ensures(...);
    return Result;
}

This is design by contract, as the ensure block should be at the end of the method. But the return must be last. We had the rule that return Result was the only thing that could follow the ensure block.


问:
What defines a software architect?
At what  point does a developer stop being simply a developer and turns into a software architect. Or in other words, what's the minimum job description of a software architect?  </p>

答: Like most IT job titles there is no definition, it is just a made up term. I would describe a Software Architect as someone who is in charge of the technical application design, building things like base libraries, application frameworks etc. Of all the various IT 'Architecture' jobs this is probably the lowest one on the food chain.</p>

OwnerDisplayName: mumtaz

LastEditorDisplayName: mumtaz

Title: What defines a software architect?


答:
The risk/reward of customizing systems is to provide a competitive advantage which allows your company to offer something differently than the other businesses in your space.

The larger organizations that I have worked with derive a competitive advantage from customization and in that mind set, they make them do things more efficiently, provide more features or make more money.

The fact that I communicate in these situations is that it is a trade off.  In making these changes to a system, the organization is developing its own internal knowledge base/expertise of their systems that they won't be able to easily do with out.  This internal knowledge base needs to be better maintained and organized so that these changes can be tracked and managed.  It also means that it could invalidate vendor support contracts and other aspects that the IT assets that the company uses for this process.

The biggest risk I talk about is version upgrades to vendor software when a company adopts this data management philosophy..  This is one of the most likely risks where something is going to break.  The company needs to understand the trade offs that are being made and everyone needs to be on board with the process that it takes to support them.

For your culture, you can introduce an analogy or philosophy but you need someone who is responsible for the business to realize that they are creating an environment that has even further dependencies on internal business specialist who make changes to these systems.

For the car analogy, its not the mechanic who needs to know what changes are being made to a car, its the owner who needs to understand that it may take special mechanics, more money or loss of that service for period of time.  Educate the owner is the key to this conversation.

Title: How can I communicate the risks of altering vendor software?

Body:
We have a major problem where I work, and it's name is "customization". We have an old (10+ years) vendor software system that our IT and accounting departments previously loved to customize. Somewhere along the line this software started getting very buggy. Then, I was hired after the bulk of the customization.

Nearly every problem I've found with the system is a direct result of customization; everything we change risks breaking business critical financial software. Yet the accounting department keeps suggesting changes (because we always said yes!) and there seems to be little respect for how impactful changes might be.

Some changes cause no problems; forms can be (and are meant to be) customized in the vendor software, we can move around form fields, remove them, ect. But for every harmless customization like that they also suggest changes like stored procedures and triggers to manipulate data in the database for the vendor application.

I recently (barely) got them to stop trying to import customers from one vendor program into another as the information was completely incompatible. My problem with how that was resolved is because I found the system didn't work on the user side; the task was more complicated than they thought so they gave up. Regardless of how easy the user-side task is, the operation they wanted shouldn't have been performed.

How can I communicate that changing how this system works has risks, particularly when data validity is at stake? I'm a new (6 months) hire and it's become the status quo, but it's risking the validity of our financial data and our support contracts--once the vendor's support hears "X has been customized" that gives them that much reason not to support us or tell us it's our fault.


答:
Leave the base app in it's own repository, and create new projects that depend on the jar you compile from that repository.

Git branches are not for multiple apps. Git prefers that you use one repository for each project or a related family of projects. Branches are there so that you can develop features in isolation, not so you can create entirely new project without leaving the repository.

You don't want to have multiple apps that share code - that's a maintenance nightmare. If as you suggest you develop each as a branch in your central repo, you will have a lot of merging going on to propagate the changes to each app. It's much easier to depend on a single, separate library and use something like Apache Maven to pull in project dependencies.

Title: Managing multiple versions of a web application using Git

Body:
We have a family of apps, all having the same base. Until now I've been developing this base, and the Git workflow was very simple:

Development is done in develop branch

New features are developed in name-of-the-feature branch

Releases are made in release-** branch

Until now, the code was the same for every app of the family. Let's say the base they share is now complete, and from now on the code will be different for every app.

I'm not sure how should I deal with git and this multiple apps that have the same base.

Should each one of them have its own git project?

Should they be on the same project, but each one in its own branch?

The point is: if I put them on separate projects, every modification done in the base of the app will have to me repeated in each of the apps. I'm not very familiar with git, but if  I store each project in a branch, will be possible to merge the base modification with each app?

Does anyone have experienced a situation like this? I'm not sure how to proceed.

Thanks!

EDITED
When I said version I didn't mean like version numbers. They are actually different apps that share the same base.


问:
What do you name functions/variables/etc when you can't think of a good name?
When you are defining a function/variable/etc and are not sure what to name it, what do you name it? How do you come up with a name?

If you use a temporary name as a place-card until you give it it's real name, what temporary name do you use?

update

I have been using things like WILL_NAME_LATER, NEEDS_NAME, or TO_BE_NAMED. I was hoping there was an adopted convention, I was actually hoping that if I used this adopted convention my IDE would highlight the name until I changed it.

答:
Sometimes I use zzzz temporarily.

A good rule to help you is this:

Does it return a boolean and have no side effects: Then use an adjective (start with is, was) but never future tense.

Does it return a different type and have no side effects: Then use a noun.

Does it return nothing but do something: Then use a verb.

Is it a class: Then use a noun.


问:
LINQ TO SQL or ADO.NET?
What is the best choice LINQ TO SQL (.DBML) or using ADO.NET with procedures for a database with 29 tables and about 30 concurrent users that will run the system that I am going to build?

I know that ADO.NET is faster than LINQ TO SQL but it is so much simpler to work with LINQ TO SQL. Will LINQ TO SQL handle all the concurrency? Or will there be problems in performance?

The system I am going to build will be a WCF service using multiple layers:

Service layer

Business

Repositories

Data Access Layer

答:
I would recommend to use an Entity Framework ORM platform with Linq To Entities for working with data.

Since you are just starting a project (it seems), you should have no problem using the latest tools right from the start.

Title: LINQ TO SQL or ADO.NET?


答:
Assembly in and of itself consists of commands that can run directly on a machine. It's pretty much as low as you can go down the language/abstraction stack before you run into physics.

Higher level languages are built on top of assembly: C gets compiled into assembly commands. The compiler necessarily is written in assembly. Other interpreters/compilers (and their associated languages/frameworks) are built in a similar fashion up higher levels of abstraction.

The value of these abstractions is that they allow various kinds of nitty-gritty and difficult specifics to be transparent, freeing up developers to think and write at higher and higher levels. Imagine trying to write any modern app if you had to write it entirely in assembly, It may be possible, but maintainability, development time, and performance would very likely suffer.

However, Abstractions are Leaky. At a high-level, the only reasons to write assembly are that the required abstraction doesn't exist, or that the existing abstractions are leaky in a way that you need them to not be. More specifically, an embedded system may have very strict and stringent requirements (say...program size), and skilled assembly programmer may be able to beat a C compiler. The compiler's less than optimal performance in this regard(lines of assembly in the compiled output), is a leak in the abstraction.

When you're dealing with any tool used to abstract away complexity, you should only dive down the stack when you really need to.

The most common optimizations I know of are for program-size, and performance. And of course, the compiler itself must be at the assembly level.

Title: Assembly in a research paper


答:
It depends on what your system is like in terms of accessing and manipulating the data.  ORMs (LINQ to Entities, etc.) are great at simplifying simple data manipulations like CRUD.  What they aren't especially good at are complex and flexible reporting.

So the answer depends on the emphasis of your system.  If it's mostly entering data then use an ORM.  If it's mostly querying and reporting then write stored procs to extract and manipulate the data and pick your favourite access layer to output the data.

Title: LINQ TO SQL or ADO.NET?

Body:
What is the best choice LINQ TO SQL (.DBML) or using ADO.NET with procedures for a database with 29 tables and about 30 concurrent users that will run the system that I am going to build?

I know that ADO.NET is faster than LINQ TO SQL but it is so much simpler to work with LINQ TO SQL. Will LINQ TO SQL handle all the concurrency? Or will there be problems in performance?

The system I am going to build will be a WCF service using multiple layers:

Service layer

Business

Repositories

Data Access Layer


答:
There are also a few products out there that were never refactored to use a new language, I used to work on pharamcy software that was still written in a Series/1 macro assembler language.

There was so much business and clinical knowledge locked into the code that management never wanted to do a complete re-write, along with the constantly changing regulations they believed it was easier to emulate the environment that the code ran on and keep on making additions.

The code base was constantly evolving, but a couple of times a year I would work on code that was written before I was born (I'm in my early 30's).

I imagine that this senario is rare, but I doubt that's the only company that is keeping old assembly code alive.

Title: Assembly in a research paper


问:
Considering consistent change, how short of a planning period is too short?
Change is not uncommon, change in requirements, change in specs change in workflow. I've accepted that there will be change, but I wonder: knowing that change is going to happen, how short of a planning period is too short? (Justifications are encouraged)

An iteration (2-4 weeks)?

A week?

A 2-3 day period?

A day?

1/2 a day?

Assume that the company 'plans' 1 [time interval (from above)] in advance from the current so that any plan sounds like:

"[this morning/today/this week/etc.] you'll work on this and [this afternoon/tomorrow/next week/etc.] you'll be working on that.

Also assume that the changes in focus/direction will consistently occur every second to third time interval.

答:
I break things down like this:

Any significant project/application development - 1 week.

Simple one-off enhancements are thrown into a list, prioritized, and each one gets addressed in half to full day periods.

Bug fixes usually take priority and go through a similar process as #2, but can sometimes be fixed much quicker.

The key factor here is how much planning can you actually do for a given task? Starting a brand new website that does yadda, yadda, yadda, there is more planning up front than fixing a bug. Who plans bugs in advance? Department manager discovers they forgot something and need it for the end of the quarter reporting, you have to put things aside and work on it.

A weekly iteration may have 10 hrs or may have 50. It all depends on how much other stuff is immediate. I think it is much easier for management to understand the time contraints when you ask, if you should put a project aside to make a small addition? I'm pleasantly surprised when they identify that little change as unecessary and I should keep working on the yadda-yadda-yadda-website.


问:
Is it a must for every programmer to learn regular expressions?
I am new to programming, and at an interview I got a question on regular expressions; needless to say I couldn't answer. So I was wondering whether I should learn regular expression? Is it a must for every programmer of all fields? Or it is a must for programming for some particular fields?

Related questions:

Why are regular expressions so morbidly attractive?

When you should NOT use Regular Expressions?

答:
Short Answer: No But.... knowledge is power.

I'm a web developer and i find any Regular Expression i generally need has already been written for me. However i have had problems with copying and pasting and not realizing what it was doing or not, which is a danger of copying and pasting ANYTHING.

One example: An email regex i copied and pasted didn't allow for a period or plus in an email which is allowed in the email address spec. In fact many people use gmail with actualemail+sitename@gmail.com so that it becomes easy to filter 'sitename' should they choose to spam.


答: You are basically developing software and as such you need a development methodolgy. How are changes documented? Tested? Deployed to QA? Deployed to production? etc. I think if you start coming up with a methodolgy and the costs associated with it they will start to understand. Perhaps the costs are well justified and you just need to implement a procedure so the car never wraps itself around a light pole.</p>


答:
Others have provided some good examples of using analogies and other language to answer your primary question, which was "How can I communicate that changing how this system works has risks, particularly when data validity is at stake?"

But based on your clarifying comment about how the task assignment gets to you, I'm not sure that any analogy is going to help you in the situation -- it doesn't really seem that people misunderstand what they're asking for, but rather that they don't care.  I've been there -- we've probably all been there -- and in these situations I tend put forth a greater effort to be perfectly clear as to the issues, rather than couch them in terms meant to teach rather than warn.

Focus on what you can do, which is not single-handedly changing the minds of everyone asking for customizations that put data integrity and vendor support contracts at risk, but instead is speaking directly to your CTO (and in turn, the CFO) and being very clear as to the issues at hand.

Specifically:

Ask your CTO or CFO (or whomever holds it) to see the service
contract with the vendor, because (and I'd say these words) you're
being asked to perform tasks that are potentially in violation of the
agreement and you want to be able to point that out in your task
feasibility report.  They might not give it to you, but saying those
words has often made folks in those positions better understand that
you're serious, and the situation is potentially serious.

If you do get a copy of the agreement, then when you write your task feasibility report, quote directly from it when there is a clear violation.

If you do not get a copy of the agreement, then make your reservations very clear as to how the change could put the company in a bad position as regards the relationship with the vendor.

If your concern isn't problematic because of the vendor agreement but is"simply" problematic because of the cascading effects of the change, outline what that means: if it's as messy as you say it is, then you probably only have one or two bullet points before you can use the "and it will topple like a house of cards" line.

In short, do what you can to very clearly and concisely point out the issue and its effects even a step or two down the line.  That you have the opportunity already to put a feasibility report in front of the decision-makers is a good thing; you don't have the structure or management support (or ethos) to say "I need you to sign this saying you understand that this is a bad thing and I do not recommend it and am not going to be responsible for the effects of this bad decision" (like you might if you were a vendor and they were a client), but you can still put a lot of things on paper that show you are considering what is in the best interest of the company and its assets.


问:
Do you think that exposure to BASIC can mutilate your mind?

It is practically impossible to teach good programming to students that have had a prior exposure to BASIC: as potential programmers they are mentally mutilated beyond hope of regeneration

-- Edsger W. Dijkstra

I have deep respect to Dijkstra but I don't agree with everything he said/wrote. I disagree specially with this quote on linked paper wrote 35 years ago about the Dartmouth BASIC implementation.

Many of my coworkers or friends programmers started with BASIC, questions below have answers that indicate many programmers had their first experience on programming at BASIC. AFAIK many good programmers started at BASIC programming.

I'm not talking about Visual Basic or other "modern" dialects of BASIC running on machines full of resources. I'm talking about old times BASIC running on "toy" computer, that the programmer had to worry about saving small numbers that need not be calculated as a string to save a measly byte because the computer had only a few hundreds of them, or have to use computed goto for lack of a more powerful feature, and many other things which require the programmer to think much before doing something and forcing the programmer to be creative.

If you had experience with old time BASIC on a machine with limited resources (have in mind that a simple micro-controller today has much more resources than a computer in 1975, do you think that BASIC help your mind to find better solutions, to think like an engineer or BASIC drag you to dark side of programming and mutilated you mentally?

Is good to learn a programming language running on a computer full of resources where the novice programmer can do all wrong and the program runs without big problems? Or is it better to learn where the programmer can't go wrong?

What can you say about the BASIC have helped you to be a better/worse programmer?

Would you teach old BASIC running on a 2KB (virtual) machine to a coming programmer?

Sure, only exposure to BASIC is bad. Maybe you share my opinion that modern BASIC doesn't help too much because modern BASIC, as long other programming languages, gives facilities which allow the programmer doesn't think deeper.

Additional information: Why BASIC?

答:
I think, given that this quote is 35 years old, it has a lot to do with the lack of abstraction that was available in programming languages, and what was required for you to know to develop well, back when it was said.

Being given a language like BASIC teaches you little about how to program at a low level, something far more necessary in the past than now, and would give you the mistaken impression that programming was simpler than it really is.

I remember disctinctly trying to learn 'machine code' at the age of 15 after over 3 years of VZ200, C64 and Apple ][e BASIC, it was a rude wake up call.

These days, however, although I am a complete snob about these things, and you wil not find me working happily in any language with BASIC in the name (I tend to start yelling at the monitor phrases like 'stupid Fisher Price Language' as it, yet again, rejects my careless curly braces),I admit it is easier to do productive things with languages that abstract the mechanics of the CPU than it was 35 years back (or 25 years ago, in my own personal experience and example)


问:
what does "domain" mean when referring to DDD
What does the word domain mean regarding driven design/development?

Not in terms of semantics or a scholarly definition but in terms of how it modifies processes or philosophies?

I was reading a post: https://softwareengineering.stackexchange.com/questions/57828/your-software-problem-solution-approach

I came across this buzzword, DDD, and didn't really know what that meant.

答: Domain refers to the specific subject that the project is being developed for. Accounting is a common domain for DDD. The goal of DDD is to limit complexity of a solution by tailoring it as close as possible to the domain with the help of experts in that domain.</p>


问:
Understanding Loose / Tight Coupling in the "Real World"
I wont say what "community" because I want a non-biased explanation, but let's say you're building a reusable module and that module requires 3+ dependent modules and removing 1 of them causes a breaking error not only in your app as a whole which uses this module, but the module itself.

From my understanding (which must be wrong) a loosely coupled modular system will not break by simply removing one module. The app should still run but without that "feature" / module and the module itself shouldn't causes everything to not run simply because a dependent module doesn't exist.

Is this wrong? If so, if modules are still dependent to the point of everything not working whats the difference between tight/loose coupling?

答: Not quite --- removing the module could well break the system. The idea behind loosely coupled systems is that swapping in a completely different module will work just fine so long as the new module conforms to the same interface requirements as the old one. If it were tightly coupled, the surrounding code would make presumptions about the internals and would start to fail if a new module was introduced.</p>

OwnerDisplayName: Oscar Godson

OwnerDisplayName: Wyatt Barnett


答:
It depends, even on what you specify as module. Some parts of the system should be tightly coupled (for example, your entities should be reused across entire app), but some systems should be loose, either with interface separations, or if we are talking about not breaking the application if you remove the module, then that module must be wired up somehow dynamically, maybe through IoC container or something.

Also, tight coupling means that some part depends on specific module implementation, not the definition of module or something.

Title: Understanding Loose / Tight Coupling in the "Real World"

Body:
I wont say what "community" because I want a non-biased explanation, but let's say you're building a reusable module and that module requires 3+ dependent modules and removing 1 of them causes a breaking error not only in your app as a whole which uses this module, but the module itself.

From my understanding (which must be wrong) a loosely coupled modular system will not break by simply removing one module. The app should still run but without that "feature" / module and the module itself shouldn't causes everything to not run simply because a dependent module doesn't exist.

Is this wrong? If so, if modules are still dependent to the point of everything not working whats the difference between tight/loose coupling?

OwnerDisplayName: Denis Biondic


答:
If they are telling you to implement stored procedures and triggers - you have a major business process issue.

Your biggest challenge is to get users here to change how they think. They need to be providing you with the problem or requirement. For example, we need data moving from here to here.

It should be you who is implementing the solution with the least risk/most gain, and it is you who can do this in a manner which will help prevent future development issues.

Some control in the form of user sign-off or requirements, and then sign-off of the delivered development will also help. If the user has to take some responsibility/accountability for what they are asking for, they may think over it a bit more.


答:
You seem to be implying your choice is between a risky implementation of a business requirement or none at all.  It's rarely that black and white.  I have a hard time believing accountants are directly asking for stored procedures, but if they are, you need to give them what they mean instead of what they're asking for.  Find out what the business requirement is, then figure out the least risky way to implement it.

If your vendor isn't providing the hooks you need to safely implement the requirements your users want, then that problem is with the vendor, not your users.


答:
A manager recently announced that were were spending far too much time fixing bugs.

Above sounds very ignorant. Suggested reading for cases like that: Facts and Fallacies of Software Engineering by Robert L. Glass, particularly "Fact 43. Maintenance is a solution, not a problem."

Wikipedia article mentions 80% efforts spent on software maintenance.

my manager makes Dilbert's PHB look like a genius :)

Hm given above I'd also take some efforts in analyzing whether all the requests you do are bugs indeed.

In my experience it was way too often that requests for enhancements or new features were submitted as bugs. Good managers involve their programmers in finding out about that - bad managers, well, just keep complaining about too much time fixing bugs.


问:
Mobile Web Security Articles
I'm starting to introduce mobile web apps to my company but my not-so-techie boss is worried about web security issues on mobile devices.

I'm new in the mobile world but as a web developer I know the basics about web security (like the best practices listed in OWASP) but I don't know if there's anything else that could make my mobile web app vulnerable specifically for mobile web browsers.

Also, I need an internet article readable from not-so-techie bosses that could help me convince him how secure our mobile web app could be if I apply the common web security best practices.

Can you help me with this?

PS. I'm using Java as my backend and jQuery Mobile as my frontend.

答:
For blog posts, Google Online Security is perhaps a good place to start (link at the bottom). Also check out "Krebs On Security" - he's a journalist, not technical, so his standard of writing is excellent.

As I'm sure you know, being good at web security -mostly- lies in stuff like protecting against the basics and there is no substitute for having your software regularly audited and pen-tested by professionals. Preparing a rough and ready cost-benefit analysis for your boss might be useful in getting sign-off.

Krebs on Security: https://krebsonsecurity.com/

Google Online Security Blog: http://googleonlinesecurity.blogspot.com/

Title: Mobile Web Security Articles


问:
How should I handle multi-tasking in a WPF application?
In most of the multi-tasking CRM applications I've seen, MdiWindow is used to allow users to open multiple windows at the same time.

But MdiWindow doesn't seem to be commonly used in WPF. Looking through Codeplex, I only found one abandoned MdiWindow project.

In some of the WPF-based CRM applications I've seen, they create a dashboard and only let users work on one thing at a time.

What's the best way to handle multi-tasking in a WPF application? Is there a better alternative to MdiWindow in WPF?

答:
Usually the design I use works like a TabControl: there is a navigation area and a Content area

I think it's because I don't like cluttering my workspace with many windows for the same application. I would rather have a single application instance containing everything I am working on.

I also find it makes managing Views and Dialogs much easier with the MVVM design pattern. I'll usually have a ShellViewModel containing the currently opened views, a list of available views, and the currently active view.


问:
Is it legal/ethical to post production code?
This may sound silly or obvious but this is my case; I work at a company that recently implemented SAP and I was the responsible to generate/migrate the master data of the company which let me learn a lot from this system. SAP comes with its own language known as ABAP and since the system went live I've been learning and programming with it. Before ABAP I worked as a freelancer in other projects with VB6, VB.Net, C# and ASP.Net building a lot of stuff, here I've made some utilities that are been using daily, so I came with long experience in programming.

At first ABAP was difficult but eventually after long analysis, googling and trial and error I became the guy who makes basically all the development in SAP from reports, to user-exits, enhancements, BADIs, tables, dynpros, etc. Daily I learn more and more because of all the requests I receive which makes me investigate and code a lot everyday. It has become challenging and funny at the same time. You could be very productive in ABAP once you get into.

Ok, the question is - can I post how I resolved a certain thing in SAP? That implies that I'd publish production code. I feel doubtful about this.

答:
You should be very hesitant to do such a thing, and should certainly consult with management to make sure that, legality or ethics aside, it's something of which they approve.

On the other hand, illustrating a technique using a code structure you developed is perfectly ethical. Usually production code is not the clearest example of a technique anyway, since domain variables and extraneous function calls stand in the way of making your point as clearly as possible.


答:
I would say that it is clearly wrong to publish code you have written as part of your contract with your employer.  That code is owned by your employer and you probably don't have either the legal or the ethical right to publish it.

Publishing knowledge you've gained as part of your employment is a much greyer area.  Broadly I would suggest that;

If it's knowledge you've learnt for yourself, not relating to proprietary systems, then it's probably okay to write a code snippet from scratch and publish that.

If it's knowledge you could only have gained by working for your employer than you probably should not publish it.

If it's knowledge relating to proprietary company systems then you should not publish it.

Bottom line is that if you are concerned then talk to your management and get their, preferably written, consent before you do so.

Title: Is it legal/ethical to post production code?

Body:
This may sound silly or obvious but this is my case; I work at a company that recently implemented SAP and I was the responsible to generate/migrate the master data of the company which let me learn a lot from this system. SAP comes with its own language known as ABAP and since the system went live I've been learning and programming with it. Before ABAP I worked as a freelancer in other projects with VB6, VB.Net, C# and ASP.Net building a lot of stuff, here I've made some utilities that are been using daily, so I came with long experience in programming.

At first ABAP was difficult but eventually after long analysis, googling and trial and error I became the guy who makes basically all the development in SAP from reports, to user-exits, enhancements, BADIs, tables, dynpros, etc. Daily I learn more and more because of all the requests I receive which makes me investigate and code a lot everyday. It has become challenging and funny at the same time. You could be very productive in ABAP once you get into.

Ok, the question is - can I post how I resolved a certain thing in SAP? That implies that I'd publish production code. I feel doubtful about this.


答:
It depends on a lot of things, but if its just a short segment of code that anyone could reasonably expect to implement, then ethically I'd say its ok, you still may be violating copyright law though. Copyright laws are really grey and open to interpretation when it comes to code.

The thing you really need to watch for is parts of code that use a certain algorithm that may be patented or a trade secret, things that fall into this category should be fairly obvious though.

It should be obvious, but changing variable names and removing comments specific to your place of employment (TODOs) should be done if they use terms with special meaning to your company.


答:
As long as its not proprietary information or a proprietary problem being solved then it should be easy enough to change your production code to make a generic example of the problem being solved.  Be very careful however to cleanse the code of anything proprietary or identifiable.

I'm not saying to post production or proprietary code, I'm saying use that as a base to make a generic example to illustrate a solution to the problem posed.


问:
Mediator vs Observer?
Can someone provide me with a canonical answer on the differences between an Observer and a Mediator, and a summary of when you should use one pattern over the other?

I am unsure of what kind of situation would require an Observer and what kind would require a Mediator

答:
The Observer pattern is used when an action taken on one class (the observed class) needs to produce a reaction in another class (the observing class) but it is undesirable for the observed class to be coupled to the observing class.  This is a very common pattern.  The SAX XML parser may be a good example.  To use the SAX parser, a client implements the ContentHandler interface to "observe" the parser operation.  As the parser encounters elements of the XML document, it calls methods of ContentHandler.  The parser is able to invoke client code, but the parser is not coupled to the client code.

The Mediator pattern is an encapsulation of a pattern of usage of a set of objects.  Client code is only coupled to the mediator, instead of being coupled to multiple other classes.  It's similar to aggregation, except the lifetime of the encapsulated objects is independent of the lifetime of the mediator.

Title: Mediator vs Observer?


问:
Should source-code in textbooks and the like be translated?
A few weeks ago, my class was assigned to translate to Portuguese the book Real World Haskell. As I did the translation of the text and comments, I started to wonder if I should translate the code as well, as the instructor suggested. For example:

```data BookInfo = Book Int String [String]
              deriving Show```

would become

```data InfoLivro = Livro Int String [String]
               deriving Show```

Since I haven't read any software-related books in Portuguese, I don't know if that's a common practice, neither if it should be done this way. In the end, the code is a language mix (perhaps the example in Haskell is not a good one, since you can create synonyms quickly like type CadeiaDeCaracteres = String, but you get the point). So it doesn't really matter how hard you try, you'll have to rely on the reader previous experience with some sort of basic English words.

Knowing this, I really don't see the point in translating code, since we learn in the early days of our coding life it should be written in the universal language. Nevertheless, if the surrounding text (comments, for example, and text itself in a book) needs to be translated, what is possible and feasible in this matter? Can you provide me with some guidance of what to do?

答:
In my opinion, no. Most programmers are forced whether they want it or not, to learn english, and nowadays it is the lingua franca of the software world.

In my experience, however, books written by authors in one of the stronger languages, have a tendency to do that - so far I've seen the practice in books in german, french and russian (well, russian is a little different of a case, since they use different alphabet as well). It is a rule of thumb that it depends on the country's dependency on english.

The text is of course translated, the bigger comments also (one that describe the workings of a program in greater detail), then somewhat more rare, smaller comments and variable names. I've also seen the case where variable names were translated, but smaller comments were left in english. I believe the author however, in that particular case, was counting on his audience to have a working english knowledge.

Sorry if this didn't solve your dilemma, but there still isn't a consensus on this one :-/


答:
In a recursive function, it is often effective to carry the result from step to step, to make for a tail call optimization. To signalize to the user, that he needn't provide a parameter, it can be reasonable to name a parameter "result":

```<code>def removeOccurence [A] (slice: Seq[A], original: Seq[A]) = {
  @scala.annotation.tailrec
  def remove (leftOriginal: Seq[A], result: Seq[A]) : Seq[A] =
    trimStart (slice, leftOriginal) match {
      case (h :: tail) => remove (tail, h +: result)
      case (Nil)       => result.reverse
    }
    remove (original, Nil)
}
</code>```

But more often I use 'carry' and 'sofar', which I have seen in the wild, and which carry the idea even a bit better, in most cases.

A second reason is of course, if your topic suggest the word ''result'', for example if you do arithmetic evaluation. You might parse the formula, replace variables with values, and calculate a result in the end.

A third reason has already been stated, but I have a small deviation: You write a method which performs some job, let's say it evaluates a form of ''max''.

```<code>def max = {
  val result = somethingElseToDo
  if (foo) result else default
}
</code>```

Instead of calling the result ''result'', we could call it ''max'', but in some languages you can omit parenthesis when calling a method, so max would be a recursive call to the method itself.

In general, I would prefer a name which tells, what the result is. But if that name is already taken, maybe by more than one variable, attribut or method, because there is a GUI-field, a string representation, a numerical and one for the database, using another one increases the probability of confusion. In short methods of 3 to 7 lines, ''result'' shouldn't be a problem for a name.

Body:
Is it a good practice to call the variable a method returns with a variable name result?

For instance:

```<code>public Zorglub calculate() {
    Zorglub result = [...]
    [...]
    return result;
}
</code>```

Or should I name it by its type?

```<code>public Zorglub calculate() {
    Zorglub zorglub = [...]
    [...]
    return zorglub;
}
</code>```

I have seen both in the wild, if I need to choose one what reasons could make me prefer the former or latter (or any better name)?

I am mainly thinking about Java.

Body:
In a recursive function, it is often effective to carry the result from step to step, to make for a tail call optimization. To signalize to the user, that he needn't provide a parameter, it can be reasonable to name a parameter "result":

def removeOccurence [A] (slice: Seq[A], original: Seq[A]) = {
  @scala.annotation.tailrec
  def remove (leftOriginal: Seq[A], result: Seq[A]) : Seq[A] =
    trimStart (slice, leftOriginal) match {
      case (h :: tail) => remove (tail, h +: result)
      case (Nil)       => result.reverse
    }
    remove (original, Nil)
}

But more often I use 'carry' and 'sofar', which I have seen in the wild, and which carry the idea even a bit better, in most cases.

A second reason is of course, if your topic suggest the word ''result'', for example if you do arithmetic evaluation. You might parse the formula, replace variables with values, and calculate a result in the end.

A third reason has already been stated, but I have a small deviation: You write a method which performs some job, let's say it evaluates a form of ''max''.

def max = {
  val result = somethingElseToDo
  if (foo) result else default
}

Instead of calling the result ''result'', we could call it ''max'', but in some languages you can omit parenthesis when calling a method, so max would be a recursive call to the method itself.

In general, I would prefer a name which tells, what the result is. But if that name is already taken, maybe by more than one variable, attribut or method, because there is a GUI-field, a string representation, a numerical and one for the database, using another one increases the probability of confusion. In short methods of 3 to 7 lines, ''result'' shouldn't be a problem for a name.