答:
You appear to be suffering from what I consider to be a case of False Economy, and the longer you adhere to those things that don't work, the worse your problem will get.

Some Key Indicators:

What appears to be an unrealistic schedule.

I assume a poor understanding of sound development practices on the part of management.

I assume a lack of understanding or support from management.

Working 12 hours per day.

High levels of Stress.

Lack of sleep.

Anxiety.

Poor attention to design and code quality.

A lack of a unit testing safety net.

I want to know whether is it's feasible to write code that works when the project has a very tight schedule?

The short answer is yes.  The long answer is it's complex, and will require a massive change in perceptions on behalf of management and possibly the customer also, and a Herculean effort on your part... but I'll come back to all of this in a moment.

How can I write better code in the same amount of time?

Realistically, you can't if your assumption is that you can do anything that will save you time and still get a perfect result. You need to apply techniques that will increase the time it takes to implement your code because you would need to take time to focus on getting the detail right.  This takes time, and it is here where your false economies are hurting you the most. However, by doing things in a better way, you improve the quality of your code and that in turn will result in reducing the fragility of your system.  Again, I'll explain this further down.

How can I clear my mind and don't get worried about work when I go to sleep?

Anxiety causes a lack of sleep, and losing sleep creates anxiety.  This is a vicious circle if ever there was one, and if left unchecked will likely lead to anxiety's evil twin, Depression. Chronic loss of sleep, which I assume is likely combined with a lack of exercise and also likely poor nutritional habits, all is likely to result in Chronic Fatigue.  All of this is symptomatic of all of the problems that you are facing in your workplace, and the resulting problems you are likely to be facing in your home life.  This is where the greatest evidence of false economies lies, and it is probably the most serious problem that you need to deal with first.

I also welcome any suggestions.

I should first state that I am not a medical professional, an you really should seek advice from your doctor before you act on anything. I will note however that I have lived through the experiences you have described in your posting, and I know how difficult it is to deal with, and how important it is to do something about it. I've lived through the depression, anxiety, chronic fatigue, stresses, and all the other little nasties that accompany them, so I will offer you some advice based on these experiences:

Go to your doctor, and discuss your symptoms. Tell the doctor if you are tired, if you are feeling depressed or worried most of the time, if you get colds and flu often, and how you have been feeling physically. If your doctor is permitted, you are likely to be offered anti-anxiety or even anti-depression medication. Even if you feel reluctant to, leave pride at the door and take them as prescribed. They really do help, and allow you to find the strength to deal with everything that is to come.

Seek a good psychologist to discuss your problem as you know it, and who can help you to explore how you feel about it all, and to help you to develop strategies to deal with the problem.  Some of what you are asked to do may seem pointless, or a little wishy-washy. Do it anyway, because again, it really helps, particularly in teaching you specifically how to clear your mind.

Avoid sleeping tablets unless you really need them, as you can become dependent on them and make you sleep problems worse.  Personally I take them only when I am unable to get the sleep I need after a weekend, and that's usually when I have had a lazy and unfulfilled weekend.

Look into changing your diet.  Seriously cut out the caffeine as it only contributes to a heightened level of anxiety. Reduce your carbs, and balance your diet, and by that I mean eating more natural fruit and vegetables, reducing the amount of red meat you consume, and reducing fats and oils. Cut out the soft drinks, and limit yourself to a single cup of coffee per day if you find it impossible to give up. Diet is critical in helping you to combat the fatigue. Also, eat your last meal earlier so that you aren't going to bed on a full stomach.

Exercise every day. Get a strenuous workout at least once per week minimum, and walk or cycle for at least 30 minutes each day to the point of working up at least a light sweat. This will help to tire you physically which will help with your sleep, and with your fatigue.

Change your sleeping habits. Aim to wake up early for work, so you need to go to bed earlier than you may feel you want to. If you can't sleep, rest in a dimly lit room, and read something boring, and don't worry if you can't actually fall asleep right away.

Now that I've gone through all of the medically related stuff, let's look to what you can do about your work:

Someone suggested using the Pomadoro Technique. This is also known as time-boxing, and I think it's a good idea. You basically concentrate intensely for 20-25 minutes, then you take a little break. I suggest you get up and move around for about 3-5 minutes, and look into the distance to rest your eyes.  Try not to think about your tasks during that time. Get a drink, wander down to the bathroom, or simply move about in your office for a short spell.

Depending on your relationship with your boss, find a way to meet and discuss your concerns that the work schedule is impacting your health. Put it to him that you don't want to risk letting the customer of the company down, and that you'd like to try and develop a strategy that can ensure you can continue to get your work done, but that this means you need to make time to address your health concerns as well. Use this as a last resort however, as it would be better to explain the false economies that are at work here, such as:

Fatigued workers end up with a greatly reduced efficiency, whereas non-fatigued workers have the capacity to do more in a shorter span of time, and I would try to source some figures and studies that you can use to back you up.  With a good boss, you shouldn't even need this. The following articles may be of some use to you: article 1, article 2, article 3

Skipping testing and attention to some of the little details costs you later on. Look into the concept of Technical Debt as a starting point.

Try to reduce your working hours to 8 to 9 hours per day.

Book a vacation period, and get away for a while to somewhere quiet. Even if all you do is drive your car to the woods, and camp for a week.  Seriously, do nothing for a while in order to recharge your batteries.

In terms of actual programming related stuff:

Read the books Clean Code and Refactoring, and take the time to apply the techniques within.  These will help you to deal with the issue of code quality.  As I mentioned before, it will seem to make things take longer to do, however you will spend less time dealing with mess and problems that have resulted from how you may have worked previously.

Find tools that you can integrate into your development environment in order to aid you in your efforts to improve code quality.  For example, if you are developing in Visual Studio, using a combination of tools such as Resharper and NCrunch can contribute to massively increasing your overall efficiency if you use them religiously, and if you are already applying good techniques as described in the books I mentioned.

Write unit tests, and use a test-first approach.  This will seem to slow you down the most, however you will speed up your development overall when you have tests, as they can contribute to reduced debugging time, and give you the confidence to change tested code. Write your tests to satisfy requirements, and not to satisfy code.  This will focus your testing efforts constructively, which should minimize time expended on testing.

Most important of all, you need to manage expectations, starting with your own.  You are only human, and can only do so much at any given time.  You need to manage the expectations of your boss, and have your boss 9or yourself directly) manage the expectations of your customers.  This means seriously prioritizing the work you do.  Allocate time for new features, and time for bugs, and assume your deadlines will slip.  When dealing with the possibility of slipping delivery dates, promise only to deliver a set of critical features, and leave the rest of the features as "nice to have if possible". Next delivery date, you again go through this process, increasing the priorities of the prior delivery's "nice to haves", and so on. Build this into your development methodology as a minimum starting point, and then review after a couple of deliveries in order to see where you can tune your processes improve your efficiency. The greatest efficiencies will come from your life-style changes, however there are always little things you can do to streamline your work, like reducing overheads relating to documentation and communication between yourself and the end users.

Be proactive in all of this.  Show your boss that you can both work together to really improve matters, which will ultimately reflect well on both of you, and the company overall.

Also, don't make any drastic decisions now. Wait until you've dealt with your health and your workload, and see how you go for a while.  When your mind becomes clearer, and when you feel  you are in a better place, then will be the time to decide if it's worth staying or if it's time to move on. What I am basically saying is to deal with one problem at a time, and leave the rest to stew a little until they need your attention.

Title: How to code on a very tight schedule?

Body:
I'm working on a project that has very tight schedule. I don't have much time to code and test (even though I work more than 12 hours everyday, it's still delayed), and the result is very fragile. Its code is also very dilemma.

This program is used by all offices in our customer's company, which is located in many countries. I regularly get phone calls at midnight about errors from our user/tester or about them not knowing how to use some features.

After three years on this project, I feel very stressed and I can't sleep well because I'm very worried about errors and phone calls.

I have a few questions:

For three years, all the code I've written is just the perfect usage scenario code (so it break easily). It's poorly designed and doesn't have any unit tests. I have lots of problems because of this fact. Therefore, I want to know whether is it's feasible to write code that works when the project has a very tight schedule?

How can I write better code in the same amount of time?

How can I clear my mind and don't get worried about work when I go to sleep?


问:
Why are virtual machines required?
Instead of compiling the source code for the respective OS (on which it is targeted), you compile once and run everywhere.

For the sake of this question, I would call it VM (for example, both for Java and .NET). So this the execution of programs becomes something like

```<code> ------------       ----      ----
| Executable |  -> | VM | -> | OS |
 ------------       ----      ----
</code>```

It perfectly makes sense, the compiler remain generic for the respective VM. However, the implementation of VM may vary depending on the machine it is going to be installed i.e. (*nix, windows, mac) x (32 bit, 64 bit).

My question is, instead of writing VM for respective machines, why isn't the compiler is written for that specific machine? By this, instead of downloading respective VM you download the respective compiler and that compiler will take care of the machine-code+OS for that specific machine. End result, the execution of native code for any machine. Definitely, each source code would need compilation for that specific machine but now a days, the automated systems, scm builds can help us do this thing.

Do my reasons of being confused are right or I am missing some bits of technicalities here?

Edit:

PORTABILITY:

Yes, it is one reason but is portability a big issue in today's automated systems? how often do we have to worry about the fact that we don't have to compile it for other machines? Having a code compiled for native machine would give much better performance. Take Java for instance, you can't do low level programming on Windows and you have to choose JNI.

Take automated systems like TeamCity/Jenkins or others. We could have such an automated system setup where code submitted through version control would result in the executable.

答:
Like many concepts in computer science, the VM provides an abstraction layer.  You write your code against an 'interface' (byte code / intermediate language) and the abstraction layer (the VM) deals with the implementation details (compiling it for the target machine, and other tasks.)  The abstraction layer provides you with a set of services whose implementation details you no longer need concern yourself with.  In this case, you no longer need to worry about the specifics of the underlying hardware, given that the abstraction layer services (VM) are present.  The client benefits in a similar manner - they don't need to know the details about their platform, just that they can use the abstraction layer.

Of course, there are trade-offs with any abstraction.  You lose fine-grained control over the details on the other side of the abstraction, and have to rely upon that abstraction to employ a sensible implementation.  You need to consider the potential gains through use of an abstraction against the trade-offs. In certain applications the drawbacks may out weigh the benefits - you may need that high level of control for each and every platform.

Your proposal to use an automated system for compilations to different platforms is exactly what the .NET and Java abstraction layers already do.  One of the benefits of JIT compilation is that the compiler has specific details about the machine it is running upon.  This can introduce potential for optimizations that would otherwise not be possible when performing a release build on a developer's machine.

If you are concerned about run time slowdown due to native code generation and program execution occurring together, you have the option to generate the native code during installation rather than when the program is first executed.  .NET provides nGen for this purpose, which can perform native code generation at installation time rather than run time.  The CLR will then use the cached native code rather than performing JIT compilation.

ContentLicense: CC BY-SA 3.0

Title: Why are virtual machines required?


问:
Where does this concept of "favor composition over inheritance" come from?
In the last few months, the mantra "favor composition over inheritance" seems to have sprung up out of nowhere and become almost some sort of meme within the programming community.  And every time I see it, I'm a little bit mystified.  It's like someone said "favor drills over hammers."  In my experience, composition and inheritance are two different tools with different use cases, and treating them as if they were interchangeable and one was inherently superior to the other makes no sense.

Also, I never see a real explanation for why inheritance is bad and composition is good, which just makes me more suspicious.  Is it supposed to just be accepted on faith?  Liskov substitution and polymorphism have well-known, clear-cut benefits, and IMO comprise the entire point of using object-oriented programming, and no one ever explains why they should be discarded in favor of composition.

Does anyone know where this concept comes from, and what the rationale behind it is?

答:
Inheritance isn't inherently bad, and composition isn't inherently good. They are merely tools that an OO programmer can use to design software.

When you look at a class, is it doing more than it absolutely should (SRP)? Is it duplicating functionality unnecessarily (DRY), or is it overly interested in the properties or methods of other classes (Feature Envy)?. If the class is violating all of these concepts (and possibly more), is it attempting to be a God Class. These are a number of problems that can occur when designing software, none of which is necessarily an inheritance problem, but which can quickly create major headaches and brittle dependencies where polymorphism has also been applied.

The root of the problem likely to be less a lack of understanding about inheritance, and more one of either poor choice in terms of design, or perhaps not recognizing "code smells" relating to classes that are not adhering to the Single Responsibility Principle.  Polymorphism and Liskov Substitution need not be discarded in favour of composition. Polymorphism itself can be applied without relying on inheritance, these are all quite complimentary concepts. If applied thoughtfully. The trick is to aim to keep your code simple, and clean, and to not to succumb to being overly concerned about the number of classes that you need to create in order to create a robust system design.

In so far as the issue of favouring composition over inheritance, this is really just another case of the thoughtful application of the design elements that make the most sense in terms of the problem being solved. If you don't need to inherit behaviour, then you probably shouldn't as composition will help to avoid incompatibilities and major refactoring efforts later on. If on the other hand you find that you are repeating a lot of code such that all of the duplication is centred on a group of similar classes, then it may be that creating a common ancestor would help to reduce the number of identical calls and classes you might need to repeat between each class. Thus, you are favouring composition, yet you aren't assuming that inheritance is never applicable.

ContentLicense: CC BY-SA 2.5


问:
What do you suggest for cross platform apps, including web
I have always preferred cross platform development over most other concepts as long as I can remember. Which is one of the reason I never got into .Net. Currently, I use php/javascript/python as my primary languages of choice for web development. Which I also have been using at work.

But the need to learn c# has come up and one of the windows guys has been teaching me c#, so I am still very new. I have really liked the language. I have also been brainstorming on an app that I have been wanting to make for some time and have not determined the best way to build it. The main system will be online where users can log in and do everything. But I also want to make a desktop client that ties into and syncs the users content with the server (considering using couchdb for my particular use case for this app). They should be able to do everything the web app can. I would like to launch to linux, windows, and mac as well as make mobile versions.

In learning c#, my co-worked recommended I look at Mono, so I can use .Net as a cross platform system and even possibly use asp.net for the main site. So I am hoping to get some insight on where I could go. It seems as if I used .net with mono, I could reuse a lot of code for web and mobile using monodroid/monotouch.

But then how could this setup compare to using something like sencha touch for making a mobile version and node.js for the server side (am fairly proficient with JS and php already, I just need to learn c#/.net for work and would like to learn it more anyways). Or is there anything else I should consider?

I'm not really asking which method is better, I just want to know what options I have, which I could then make a calculated decision based on my needs and further research. Such as what features would the .net/mono route have that I would not in sencha/node.js, and vice versa (node.js is awesome at real time uset to user interaction, for example)

I am just looking for some insight and advice, and help woudl be greatly appreciated.

答:
I would not suggest taking the existance of Mono as implying that C# is a cross-platform development language. You can see my reasoning and answer to roughly the same question here: https://softwareengineering.stackexchange.com/a/20329/8068

Here's a link to the question as well:

Mono is frequently used to say "Yes, .NET is cross-platform". How valid is that claim?


答:
Disclaimer: I'm not an expert in .NET, by a long shot.

With Mono, you can run server-side / CLI C# code everywhere. Performance may differ, but for a client-side app this should not be an issue.

GUI code is not that portable, but must be relatively easy to port in simple cases. This does not allow for native look and feel, though; for that, you could consider platform-native toolkits.

Title: What do you suggest for cross platform apps, including web

Body:
I have always preferred cross platform development over most other concepts as long as I can remember. Which is one of the reason I never got into .Net. Currently, I use php/javascript/python as my primary languages of choice for web development. Which I also have been using at work.

But the need to learn c# has come up and one of the windows guys has been teaching me c#, so I am still very new. I have really liked the language. I have also been brainstorming on an app that I have been wanting to make for some time and have not determined the best way to build it. The main system will be online where users can log in and do everything. But I also want to make a desktop client that ties into and syncs the users content with the server (considering using couchdb for my particular use case for this app). They should be able to do everything the web app can. I would like to launch to linux, windows, and mac as well as make mobile versions.

In learning c#, my co-worked recommended I look at Mono, so I can use .Net as a cross platform system and even possibly use asp.net for the main site. So I am hoping to get some insight on where I could go. It seems as if I used .net with mono, I could reuse a lot of code for web and mobile using monodroid/monotouch.

But then how could this setup compare to using something like sencha touch for making a mobile version and node.js for the server side (am fairly proficient with JS and php already, I just need to learn c#/.net for work and would like to learn it more anyways). Or is there anything else I should consider?

I'm not really asking which method is better, I just want to know what options I have, which I could then make a calculated decision based on my needs and further research. Such as what features would the .net/mono route have that I would not in sencha/node.js, and vice versa (node.js is awesome at real time uset to user interaction, for example)

I am just looking for some insight and advice, and help woudl be greatly appreciated.


问:
How do you track bugs in your personal projects?
I'm trying to decide if I need to reassess my defect-tracking process for my home-grown projects.  For the last several years, I really just track defects using TODO tags in the code, and keeping track of them in a specific view (I use Eclipse, which has a decent tagging system).

Unfortunately, I'm starting to wonder if this system is unsustainable.  The defects I find are typically associated with a snippet of code I'm working on; bugs which are not immediately understood tend to be forgotten, or ignored.  I wrote an application for my wife which has had a severe defect for almost 9 months, and I keep forgetting to fix it.

What mechanism do you use to track defects in your personal projects?  Do you have a specific system, or a process for prioritizing and managing them?

答: I don't see the point in using formal bug tracking for small one-man projects.  Usually I just keep a (very short) mental list and fix the bugs as I become aware of them.  Of course this doesn't scale for large/multi-person projects, but the point is that it doesn't need to.</p>


问:
Should a new programmer focus on a single technology until he's proficient at it?
Ok, I've been teaching a buddy how to program for a while now. He's a very fast learner, and he's quite good at programming so far. However, he has one "issue" I keep trying to correct.

He jumps in and starts doing highlevel programming without learning some of the basics (He's created a full blown web application but still doesn't know pagination or session management).

This isn't the problem though. He keeps jumping around to new technology (Node.js, MongoDB, EC2, etc). I tried telling him that he should learn some of the basics about his RDMS of choice (MySQL) as he uses it everyday before investing a bunch of time into learning the basics of MongoDB (And probably moving to something new).

Am I the one in the wrong here, or should he try to focus on one thing at a time and get really good at it?

答:
Personally, if someone had to focus only on one technology, I'd say it should be C#/Java, used  along with SQL.

From this, I believe, you can adapt to any other technology.

But sticking to one technology could be limiting if a guy wants to step into the corporate environment.

Ideally, one object-orientated platform, one mobile platform, one web-platform and then very good knowledge of SQL (or any other db environment).

And basics first, otherwise he WILL get stuck later on!


问:
How to introduce your team to functional style of coding?
I have a situation where most people in my group come from an object oriented programming background with little to no understanding of functional programming. Not even basics like closures.

Any suggestions about what might be a good way to introduce them to functional coding style? A lot of coding that we do can be shortened if we do the functional way for our specific cases.

I have already given couple of presentations about functional and coding paradigms. Unfortunately we don't use a proper functional programming language like Haskell (basically legacy code is in C, C++, Java) so we have to do whatever is there with these.

答:
If functional programming is really going to make life much easier in your cases, then I suggest isolating one such case, and demonstrating equivalent implementations in both OO and functional languages to your colleagues.

If the difference in complexity is as wide as you say, then this should speak for itself.


答: I agree with you, its sometimes easy to get a superficial knowledge of a particular framework or technology or language, but to get a real understanding its best to get involved in a real world development through to completion, and maintain it - become someone who others come to for advice. Its preferable to become a jack of all trades, master of one rather than just a jack of all trades, master of none. Having said that, I wouldn't discourage him from learning new stuff because he obviously has a good level of enthusiasm.

Title: Should a new programmer focus on a single technology until he's proficient at it?

Body:
Ok, I've been teaching a buddy how to program for a while now. He's a very fast learner, and he's quite good at programming so far. However, he has one "issue" I keep trying to correct.

He jumps in and starts doing highlevel programming without learning some of the basics (He's created a full blown web application but still doesn't know pagination or session management).

This isn't the problem though. He keeps jumping around to new technology (Node.js, MongoDB, EC2, etc). I tried telling him that he should learn some of the basics about his RDMS of choice (MySQL) as he uses it everyday before investing a bunch of time into learning the basics of MongoDB (And probably moving to something new).

Am I the one in the wrong here, or should he try to focus on one thing at a time and get really good at it?


答:
Another major advantage of the VM/JIT approach is binary compatibility. For example, let's say you have an assembly/JAR/DLL that contains class A, and another assembly containing class B, which derives from class A. What happens if you change class A, e.g. you add a private member? Adding a private member shouldn't have any influence on class B at all, but if the assembly containing B was already compiled to native code, you would probably get weird bugs and hard-to-reproduce crashes, because the native code was compiled with the old memory layout of A, so it would e.g. reserve too little memory for A's variables, so A's members and the members B added would be mapped to the same memory locations.

If you're using a VM on the other hand, all these problems simply vanish, because when the code is compiled to native code, the layout of all classes is known.

Title: Why are virtual machines required?

Body:
Instead of compiling the source code for the respective OS (on which it is targeted), you compile once and run everywhere.

For the sake of this question, I would call it VM (for example, both for Java and .NET). So this the execution of programs becomes something like

```<code> ------------       ----      ----
| Executable |  -> | VM | -> | OS |
 ------------       ----      ----
</code>```

It perfectly makes sense, the compiler remain generic for the respective VM. However, the implementation of VM may vary depending on the machine it is going to be installed i.e. (*nix, windows, mac) x (32 bit, 64 bit).

My question is, instead of writing VM for respective machines, why isn't the compiler is written for that specific machine? By this, instead of downloading respective VM you download the respective compiler and that compiler will take care of the machine-code+OS for that specific machine. End result, the execution of native code for any machine. Definitely, each source code would need compilation for that specific machine but now a days, the automated systems, scm builds can help us do this thing.

Do my reasons of being confused are right or I am missing some bits of technicalities here?

Edit:

PORTABILITY:

Yes, it is one reason but is portability a big issue in today's automated systems? how often do we have to worry about the fact that we don't have to compile it for other machines? Having a code compiled for native machine would give much better performance. Take Java for instance, you can't do low level programming on Windows and you have to choose JNI.

Take automated systems like TeamCity/Jenkins or others. We could have such an automated system setup where code submitted through version control would result in the executable.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答: Personal favorite/pet peeve: IDE generated names that get comitted. If TextBox1 is a major and important variable in your system, you've got another thing coming come code review.</p>


答:
My question is, instead of writing VM for respective machines, why isn't the compiler written for that specific machine?

Let's imagine for a second that this is the way it works. I write a Java application, which I then compile - the compiler then generates an executable for every supported platform. I now have the following executables:

Solaris x64

Solaris x86

Solaris SPARC

Windows x86

Windows x64

Linux x86

Linux x64

MacOS

BSD

etc etc.

I then upload all of these to my website, and provide a download link to each one. I then submit all of these to download.com, tucows.com, sofpedia.com, submitting each one individually.

This seems like a major pain to me! When I update the software to version 1.1 I then need to repeat this process.

And what happens when a new platform emerges? Now my software isnt available for this platform, unless I update my developer software to support it, recompile, then re-release my software for this new platform.

And what about the user? They visit my site, and then have to select from a list exactly the right version of my software to use for their platform. Most users do not know whether they run x86 or x64, so they will probably end up downloading the wrong version and receiving some kind of error. What if they then switch from Windows to a Mac, they now need to go back and re-download my software.

All of this is a major pain, to both the developer and the user, and all of this can be avoided by just compiling to a bytecode then running through a VM, exactly as Java currently does.

If performance is almost identical to running native code, the question is not so much why not compile to native code, by rather why bother compiling to native code?

Title: Why are virtual machines required?


问:
How best do you represent a bi-directional sync in a REST api?
Assuming a system where there's a Web Application with a resource, and a reference to a remote application with another similar resource, how do you represent a bi-directional sync action which synchronizes the 'local' resource with the 'remote' resource?

Example:

I have an API that represents a todo list.

GET/POST/PUT/DELETE /todos/, etc.

That API can reference remote TODO services.

GET/POST/PUT/DELETE /todo_services/, etc.

I can manipulate todos from the remote service through my API as a proxy via

GET/POST/PUT/DELETE /todo_services/abc123/, etc.

I want the ability to do a bi-directional sync between a local set of todos and the remote set of TODOS.

In a rpc sort of way, one could do

POST /todo_services/abc123/sync/

But, in the "verbs are bad" idea, is there a better way to represent this action?

答:
Where and what are the resources?

REST is all about addressing resources in a stateless, discoverable manner. It does not have to be implemented over HTTP, nor does it have to rely on JSON or XML, although it is strongly recommended that a hypermedia data format is used (see the HATEOAS principle) since links and ids are desirable.

So, the question becomes: How does one think about synchronization in terms of resources?

What is bi-directional sync?**

Bi-directional sync is the process of updating the resources present on a graph of nodes so that, at the end of the process, all nodes have updated their resources in accordance with the rules governing those resources. Typically, this is understood to be that all nodes would have the latest version of the resources as present within the graph. In the simplest case the graph consists of two nodes: local and remote. Local initiates the sync.

So the key resource that needs to be addressed is a transaction log and, therefore, a sync process might look like this for the "items" collection under HTTP:

Step 1 - Local retrieves the transaction log

Local: GET /remotehost/items/transactions?earliest=2000-01-01T12:34:56.789Z

Remote: 200 OK with body containing transaction log containing fields similar to this.

itemId - a UUID to provide a shared primary key

updatedAt - timestamp to provide a co-ordinated point when the data was last updated (assuming that a revision history is not required)

fingerprint - a SHA1 hash of the contents of the data for rapid comparison if updateAt is a few seconds out

itemURI - a full URI to the item to allow retrieval later

Step 2 - Local compares the remote transaction log with its own

This is the application of the business rules of how to sync. Typically, the itemId will identify the local resource, then compare the fingerprint. If there is a difference then a comparison of updatedAt is made. If these are too close to call then a decision will need to be made to pull based on the other node (perhaps it is more important), or to push to the other node (this node is more important). If the remote resource is not present locally then a push entry is made (this contains the actual data for insert/update). Any local resources not present in the remote transaction log are assumed to be unchanged.

The pull requests are made against the remote node so that the data exists locally using the itemURI. They are not applied locally until later.

Step 3 - Push local sync transaction log to remote

Local: PUT /remotehost/items/transactions with body containing the local sync transaction log.

The remote node might process this synchronously (if it's small and quick) or asynchronously (think 202 ACCEPTED) if it's likely to incur a lot of overhead. Assuming a synchronous operation, then the outcome will be either 200 OK or 409 CONFLICT depending on the success or failure. In the case of a 409 CONFLICT, then the process has to be started again since there has been an optimistic locking failure at the remote node (someone changed the data during the sync). The remote updates are processed under their own application transaction.

Step 4 - Update locally

The data pulled in Step 2 is applied locally under an application transaction.

While the above is not perfect (there are several situations where local and remote may get into trouble and having remote pull data from local is probably more efficient than stuffing it into a big PUT) it does demonstrate how REST can be used during a bi-directional synchronization process.


问:
How should I refactor so that responsibility for a geocoding service is shared appropriately?
First, some background. I have an application that requires the use of several external geocoding providers which I don't control. It uses a central service layer inside the application to dispatch to the appropriate provider.

I have a number of classes that are arranged in this way:

GeocodingService: Responsible for dispatching a request to geocode something to an appropriate provider.

Has one public method, geocode, that accepts a GeocodingService::Request and returns a GeocodingService::Response.

Each response includes: the latitude of the geocoded query, the longitude of the geocoded query, and a list of address components for the address where the query was found (e.g., an address component for "123", one for "Main Street", one for "Paris", and so on).

GeocodingService::AddressComponent: A single segment of an address that contains the segment's name, its abbreviation, and its kinds. For example, France has a name of France, an abbreviation of FR, and is a country and a political segment.

AddressComponent is responsible for checking that the types an instance is set with are not outside the boundaries of certain tracked types.

Address: Domain model for addresses, containing both a preferred mailing address (a list of string lines) and a list of address components (a list of GeocodingService::AddressComponents).

My question is: where should AddressComponent live -- as a service class (like it does now), or with my other domain models?

If it lives in the service, then life is straightforward. But that seems wrong, because now a domain model has to depend on a service's definition of an address, and it seems like they should be independent.

If it lives as a full-fledged domain object, then doesn't that mean that the service is now coupled to a domain object? That also seems undesirable.

How do I resolve this impasse?

答:
Just because AddressComponents are inferred from external data provided by a service doesn't mean they aren't first class domain objects in your domain model.
Imagine you write another application in the same domain - wouldn't it be nice if you could reuse your domain layer without having to worry about Services ? I mean, the new application could get AddressComponent data from anywhere, its own database for instance. An AddressComponent wouldn't necessarily be linked to a Service.

So I'd choose option 2, and if you're concerned about your service instantiating a domain object, maybe you could introduce another object that does the creation - a Factory for instance.


答:
In the edit of your post, you question the usefulness of portability, wrt VMs.

In my professional life, portability has been the most important factor - My deployment platform is very rarely the same platform that I deploy on, and so I am able to develop & test on Windows, pass to my QA dept, who would test on Linux, and deploy to our production environment on Solaris.

This is not just some isolated and contrived example - this has pretty much been the bread-and-butter of my professional existence for probably the past 12 years of my multi-decade career. I'm sure there are many others with the same or similar experiences.

If we used different (cross-)compilers (on the same source code) to produce different binaries, then you could not feel confident of the quality of each binary, if they each were not tested on its own OS/Architecture.

The wonderful open source FreePascal Compiler project has a tag line of "write-once, compile anywhere" - while this is true, I would not expect to see any reputable software houses doing so, and releasing the applications without thorough testing on all platforms.

Title: Why are virtual machines required?


答:
There is more to portability than just being able to compile the code!

The behavior of a C program can be different on different platforms:

```<code>int  i;
char c[6];
int * p;

p = &c[2];
p = p + 1;
</code>```

It works without complaint on an IBM Power chip, but throws an exception on a SPARC chip.

OS, OS version, file system environment variables registry settings can all affect the way a compiled program will run.

A JVM pretty much guarantees the same behavior whatever the hardware and software environment.

Title: Why are virtual machines required?

Body:
There is more to portability than just being able to compile the code!

The behavior of a C program can be different on different platforms:

int  i;
char c[6];
int * p;

p = &c[2];
p = p + 1;

It works without complaint on an IBM Power chip, but throws an exception on a SPARC chip.

OS, OS version, file system environment variables registry settings can all affect the way a compiled program will run.

A JVM pretty much guarantees the same behavior whatever the hardware and software environment.

ContentLicense: CC BY-SA 4.0


问:
How important are UML diagrams for a successful project?
I'm in the middle of a project and I was asked to write UML diagrams (use cases,class diagram,etc). The project isn't very complex.

I was wondering if this be a waste of my time? Should I just be doing other fun stuff like writing code? And when is it not ok to build something without going through all of the conceptual phase? Is it all about complexity? And if so, how to measure it?

答:
One of the major gripes for me about UML diagrams as I've seen them used so far is that they mostly only tend to serve as "pretty pictures" on someone's wall or as a folded page in a binding somewhere and rarely serve as a baseline for a production code.

In this type of scenario - the UML diagrams (or whatever flavor of modelling language you use) are rarely useful in the long run, as they tend to suffer from loss of relevance as the time goes on and the project evolves. These initial drawings are mostly useless and incorrect in few year's time and having them around is mostly harmful.

That said, using modelling tools (not necessarily UML) is not entirely useless practice, if the models provide actual live and relevant input to the actual running code. If the model description is a useful artifact of the code, it should be treated as code:

Either by using it as a direct source of metadata for making dynamic decisions based on the modeled concepts, or using code generation to generate static code artifacts that get used in the actual working code.


问:
Use of pdb file in release build executables
This question is appropriate only for programs created on the windows platform.

If I build a release of my program with the /Zi option (create pdb file and store path to file in exe) then I don’t have to ship pdb file with release but we could retain for internal use.  The pdb file would be retained for our internal Quality Assurance use.  Then if a crash occurred, we have a system of printing the stack trace at the point of crash and this 'system' would have access to the exe symbols and we would get a nicely populated stack track in this file.

But there is a slight complication in that the final executable is created by a separate build dept in our company.  We developers can of course create a release build.

My query is that one of my colleagues is saying that the exe built by build team would be different from a release build created by us in development.  But I don’t understand why?  Is my colleague correct?  If so why?  And if so does this mean my plan for using pdb files with release builds is not possible?

答: Yes, you have to use the exact PDB file with the exact EXE file created together in the build. I don't have the details ready, but there are timestamps (and checksums?) in these files that will differ and prevent the whole thing from working properly.


答:
Easy: testing.

If the code works fine on the Virtual Machine you can be confident it will run on other hardware which has a proven to have a working VM.

If you compile for different platforms you have got a lot of testing to do, because every platform has its own quirks.

Title: Why are virtual machines required?


问:
Where should you put constants and why?
In our mostly large applications, we usually have a only few locations for "constants":

One class for GUI and internal contstants (Tab Page titles, Group Box titles, calculation factors, enumerations)

One class for database tables and columns (this part is generated code) plus readable names for them (manually assigned)

One class for application messages (logging, message boxes etc)

The constants are usually separated into different structs in those classes.
In our C++ applications, the constants are only defined in the .h file and the values are assigned in the .cpp file.

One of the advantages is that all strings etc are in one central place and everybody knows where to find them when something must be changed.

This is especially something project managers seem to like as people come and go and this way everybody can change such trivial things without having to dig into the application's structure.

Also, you can easily change the title of similar Group Boxes / Tab Pages etc at once.
Another aspect is that you can just print that class and give it to a non-programmer who can check if the captions are intuitive, and if messages to the user are too detailed or too confusing etc.

However, I see certain disadvantages:

Every single class is tightly coupled to the constants classes

Adding/Removing/Renaming/Moving a constant requires recompilation of at least 90% of the application (Note: Changing the value doesn't, at least for C++). In one of our C++ projects with 1500 classes, this means around 7 minutes of compilation time (using precompiled headers; without them it's around 50 minutes) plus around 10 minutes of linking against certain static libraries.

Building a speed optimized release through the Visual Studio Compiler takes up to 3 hours. I don't know if the huge amount of class relations is the source but it might as well be.

You get driven into temporarily hard-coding strings straight into code because you want to test something very quickly and don't want to wait 15 minutes just for that test (and probably every subsequent one). Everybody knows what happens to the "I will fix that later"-thoughts.

Reusing a class in another project isn't always that easy (mainly due to other tight couplings, but the constants handling doesn't make it easier.)

Where would you store constants like that? Also what arguments would you bring in order to convince your project manager that there are better concepts which also comply with the advantages listed above?

Feel free to give a C++-specific or independent answer.

PS: I know this question is kind of subjective but I honestly don't know of any better place than this site for this kind of question.

Update on this project

I have news on the compile time thing:

Following Caleb's and gbjbaanb's posts, I split my constants file into several other files when I had time. I also eventually split my project into several libraries which was now possible much easier. Compiling this in release mode showed that the auto-generated file which contains the database definitions (table, column names and more - more than 8000 symbols) and builds up certain hashes caused the huge compile times in release mode.

Deactivating MSVC's optimizer for the library which contains the DB constants now allowed us to reduce the total compile time of your Project (several applications) in release mode from up to 8 hours to less than one hour!

We have yet to find out why MSVC has such a hard time optimizing these files, but for now this change relieves a lot of pressure as we no longer have to rely on nightly builds only.

That fact - and other benefits, such as less tight coupling, better reuseability etc - also showed that spending time splitting up the "constants" wasn't such a bad idea after all ;-)

Update2

Since this question still receives some attention:

Here is what I've been doing in the past few years:

Put every constant, variable, etc exactly in the scope that is relevant for it: If you use a constant only in a single method, it is OK to define it in that method. If a single class is interested in it, leave it as a private implementation detail of that class. The same applies for the namespace, module, project, company scope. I also use the same pattern for helper functions and the like. (This may not apply 100% if you develop a public framework.)

Doing this increased reusability, testability and maintainability to a degree where you not only spend less time compiling (at least in C++), but also less time on bugfixing, which leaves you more time for actually developing new features. At the same time, developing these features will go faster since you can reuse more code more easily. This outweighs any advantage the central constants file might have by a magnitude.

Take a look at especially the Interface Segregation Principle and the Single Responsibility Principle if you want to know more.

If you agree, upvote Caleb's answer since this update is basically a more general take on what he said.

答:
Note: I am not a C++ developer... but here is my thought:
You need to consider following @jk's comment about the difference between using configuration files. In DotNet, there are resources file that is used to store such information. In Windows Forms, a resource file is maintained from VS for each form.

I don't see a value for a constant to be placed outside its scope of use unless it is a global constant that must be shared. As you mentioned this will be difficult to maintain during development at least. Also, you may get name clashes. Another thing is that it might be difficult to know who is using a given constant.

Now if you want non-programmer to review information then, for GUI, you capture the screen for them. If you want them to review data table entries, you could export the data to Excel or something similar.

If you still want to go with a centralized location approach and you want to place all your constants in one big file, each developer may use a shared file that is updated at the end of each interval to a central file. The data will come from individual files used in development. This can be easily automated or done manually. However, as I said it is probably a risk you don't have to take.

Title: Where should you put constants and why?


答:
You are oversimplifying this a lot, cross-platform is more than just compiling for a specific native instruction set. More common than not, the same C/C++ code cannot be just recompiled on different platforms because the API:s and libraries are different. For instance, GUI development is wildly different on Windows and Ubuntu Linux, socket communication is probably not identical on Unix and IBM z/OS, and so on.

So, to achieve your "write once, compile (and link) anywhere", you would have to create an abstraction layer of some sorts, where you create a common API for all OS-level services. Then you need to implement and distribute this for all platforms you want to support.

Also, while memory models are more and more similar today, there are still some differences between different platforms so you need to abstract memory allocation as well. Easiest here is maybe to create your own "virtual" memory manager on top of the native one.

While you're at it, file systems and access control (ACL) is handled pretty different between, say, Unix and Windows so you'll need to abstract those things as well. Maybe even create you own "File" wrapper for underlying implementations.

Then we have threading. Since Linux only has processes and Windows has threads, we need to abstract this somehow as well.

Well, at this point you have pretty much built a virtual machine. The point here is that while compiling some arbitrary code for different platforms is fairly easy, building working software of any complexity that can be run on any platform is far from trivial.

Title: Why are virtual machines required?


问:
Text comparison algorithm using java-diff-utils
One of the features in our project is to implement a comparison algorithm between two versions of text and provide a % change between the two versions. While I was researching, I came  across google java-diff-utils project.

Has anyone used this for comparing text using java-diff-utils ? Using this utility, I can get a list of "delta" which I assume I can use it for the % of difference between two versions of the text? Is this a correct way of doing this?

If you have done any text comparison algorithm using Java, could you give me some pointers?

答:
What does "the % of difference" mean?  If you start with a block of text and replace the characters in every other word with "q"s has it changed by 50%? If every other word is replaced with a single "q" has it changed by more than 50%? How much more?

I think the problem is too complex to have a single number as the answer.

This is normally handled with 3 numbers; inserted, deleted & replaced. But the definition of "replaced" can become problematic.


问:
Populate fields or return object
What is better to do in this type of scenario: populate fields or return an object?

The situation is like this: I'm doing calculations to find the prices (inc tax, ex tax, discounted etc) of a product. Is there any advice or are there any guidelines on how to handle a return value?

Populate fields:

```<code>public class ProductPrice
{
    public int BasePrice;
    public int IncTax;
    public int ExTax;
    // ...

    public void GetPricesForProduct(int ProductID)
    { /* Populate fields based on results */ }
}
</code>```

Return object:

```<code>public class PriceCalculator
{
    public ProductPrice GetPricesForProduct(int ProductID)
    { /* Populate object fields and return object */ }
}
public class ProductPrice
{
    public int BasePrice;
    public int IncTax;
    public int ExTax;
}
</code>```

I'm not sure I really like the first method, because the void return type doesn't make it clear what happens when the method executes. However, returning an object results in a class which has no functionality.

答:
You're right to prefer the second method.  The first method would easily clutter a class with members that would better be suited torwards an object which represents those values.

Better still, add a method to ProductPrice which performs the calculation and change "PriceCalculator" to "PriceFetcher" which simply gets the raw values and instantiates ProductPrice.

```<code>public class PriceFetcher
{
    public ProductPrice GetPricesForProduct(int ProductID)
    { /* Populate object fields and return object */ }
}
public class ProductPrice
{
    public int BasePrice;
    public int IncTax;
    public int ExTax;

    public float GetPrice()
    { /* Perform calculation on given data */ }
}
</code>```

This method has the added advantage that the object determines how the price is calculated and not the method which fetched the data, allowing you to do more complicated operations later with derived classes of ProductPrice and instantiate them using a factory in PriceFetcher.

Title: Populate fields or return object

Body:
You're right to prefer the second method.  The first method would easily clutter a class with members that would better be suited torwards an object which represents those values.

Better still, add a method to ProductPrice which performs the calculation and change "PriceCalculator" to "PriceFetcher" which simply gets the raw values and instantiates ProductPrice.

public class PriceFetcher
{
    public ProductPrice GetPricesForProduct(int ProductID)
    { /* Populate object fields and return object */ }
}
public class ProductPrice
{
    public int BasePrice;
    public int IncTax;
    public int ExTax;

    public float GetPrice()
    { /* Perform calculation on given data */ }
}

This method has the added advantage that the object determines how the price is calculated and not the method which fetched the data, allowing you to do more complicated operations later with derived classes of ProductPrice and instantiate them using a factory in PriceFetcher.


答:
The second approach appears better to me. It decouples price from product.

The class may not have any behavior at this time, but it may in the future. Even if it doesn't it doesn't mean it doesn't have a function - holding data that doesn't belong to the product class.

Title: Populate fields or return object

Body:
What is better to do in this type of scenario: populate fields or return an object?

The situation is like this: I'm doing calculations to find the prices (inc tax, ex tax, discounted etc) of a product. Is there any advice or are there any guidelines on how to handle a return value?

Populate fields:

```<code>public class ProductPrice
{
    public int BasePrice;
    public int IncTax;
    public int ExTax;
    // ...

    public void GetPricesForProduct(int ProductID)
    { /* Populate fields based on results */ }
}
</code>```

Return object:

```<code>public class PriceCalculator
{
    public ProductPrice GetPricesForProduct(int ProductID)
    { /* Populate object fields and return object */ }
}
public class ProductPrice
{
    public int BasePrice;
    public int IncTax;
    public int ExTax;
}
</code>```

I'm not sure I really like the first method, because the void return type doesn't make it clear what happens when the method executes. However, returning an object results in a class which has no functionality.


答: Well the use of void doesn't make sense as it conflicts with the name of the function.  If you have a something that is called get*** I expect that to return an object (or a primitive).  The second approach seems to be more correct as your PriceCalculator is really the main program (at least that is how it looks in this trivial example).  I would rename the function to GetPricesForProductById as that is what you are doing, not getting prices by a Product

Title: Populate fields or return object


答:
the second option (the factory model) is better (add the id to the returned object and make it immutable for completion but that is all I would change)

when you have a method named get* one expects it to return something but even calculatePricesForProduct lacks what it should be because you start from an different object and overwrite it with the new product. This type of mutable objects are a pain to safely work with (making a copy of it everywhere you need to use it) unless you planned out their use fully

Title: Populate fields or return object


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答:
I've done this:

```<code>rm -rf /bin
</code>```

(Actually, I didn't do exactly that. That would be dumb and inexcusable. I did it in a more subtle, roundabout way that resulted in essentially that command being executed.)

Needless to say, the Unix system was unusable after that point and had to be re-installed. I was a beginning sysadmin at the time and the senior guy overseeing me was understanding.

Some good came of the experience. I learned how to list directories without having any of the /bin commands to use.

```<code>echo *
</code>```

Title: Biggest mistake you've ever made

Body:
I've done this:

rm -rf /bin

(Actually, I didn't do exactly that. That would be dumb and inexcusable. I did it in a more subtle, roundabout way that resulted in essentially that command being executed.)

Needless to say, the Unix system was unusable after that point and had to be re-installed. I was a beginning sysadmin at the time and the senior guy overseeing me was understanding.

Some good came of the experience. I learned how to list directories without having any of the /bin commands to use.

echo *


问:
Architectural considerations for a new black box program
I see an emerging trend in "cloud" computing to move work load to a third-party server and get charged pennies for amount of work done in this way.  This could be anything from file hosting to user authentication.  So I thought about this for a bit and thought, why can't these services be offered in a peer-to-peer way rather than the traditional client-server way.

So my idea is to create (to the best of my abilities to describe it) a black box virtual machine.   Some program which hosts a web service on that computer which allows any other computer with this software to ask it to perform calculation of any kind, with the condition that the same can be asked from the host, with no financial "cost" of any kind.

Obviously, it would be a security risk without proper precautions, therefore the following must be observed:

This software has the power to refuse execution requests or halt execution at any time.

Parameters are passed which request certain access permissions, among which include but are not limited to:

Memory usage - How many megabytes are going to be at the program's
disposal.

Disk usage - How much disk space can be consumed.

Namespace - Context for this program, which determines if it'll have access to disk space written by other programs with this namespace.

CPU usage - Maximum % of the CPU which can be used during idle moments and non-idle moments.

"Disk" access is a black box with root "/" which is simulated, hiding actual disk contents.  When a program is executed, a folder is created with its name under "/prog/" and is given free reign to read and write in any folder (including folder of other programs, perhaps with a parameter which requests it explicitly).  Only other programs under the same namespace can see each other, but a program can be under multiple namespaces.

Some sort of analysis framework which statistically determine if porting multi-threaded jobs to other black box virtual machines is convenient and if so, will automatically attempt it.  However it won't ask any work from a computer with resource parameters higher than the resource parameters it itself provides other computers.  Meaning, you only get what you give in short.

If no limits are placed on certain types of resources, some sort of fail safe to ensure that the stability of the computer is not put at risk.

Some sort of powerful module system which allows people to write programs to work with this system.

These modules would have a friendly way to install themselves from installations on peer computers or alternatively a way to download and install itself from an internet site.

These modules would have to follow the same guidelines as a program executed on this sytem.

My question is, a) what if anything, exists already which does this to some extent and 2) what language, platform, operating system would you advise to build this program?

I was leaning towards Java, since a virtual machine has complete access to how its programs are run, hence I would only have to rework how files are read/written to the file system, however nothing is written in stone.  Any advice would be appreciated, even if it is advice which suggests this type of thing is not possible.  Also, if anyone has a good name for this program, I'm all ears.  :)

答:
The behavior of letting run a program on some "available" machine already exists and is known as "queuing system" such as the sun grid engine.

The input is a set of jobs you want to perform, and the engine will distribute them among the machines currently available, given the resource requirements, the priorities, etc.

So, what you would do is a kindof distributed queing engine with fault-tolerance if I get it right. Why not. Dunno if it already exists or not.


答:
I'd say simply that you want to split your huge constants class into many smaller files, one per form for example. This ensures you don't have such a huge dependency on the constants file, so adding or updating a string would not then require a total recompile. You can still store these files in a central location, but (eg) have 1 file with constants for each dialog, suitably named. Then you can only include those files in the relevant dialog files, which cuts down the recompilation massively.

I'd also suggest you use something like GNU GetText utilities to handle the strings, it's designed for translation, but works just as well for simply changing the text to something else. You could put them in a strings resource, but I find them to be more difficult to work with as they're keyed by ID, the GetText utils are keyed by an original string - makes things very easy to develop.

Title: Where should you put constants and why?

Body:
In our mostly large applications, we usually have a only few locations for "constants":

One class for GUI and internal contstants (Tab Page titles, Group Box titles, calculation factors, enumerations)

One class for database tables and columns (this part is generated code) plus readable names for them (manually assigned)

One class for application messages (logging, message boxes etc)

The constants are usually separated into different structs in those classes.
In our C++ applications, the constants are only defined in the .h file and the values are assigned in the .cpp file.

One of the advantages is that all strings etc are in one central place and everybody knows where to find them when something must be changed.

This is especially something project managers seem to like as people come and go and this way everybody can change such trivial things without having to dig into the application's structure.

Also, you can easily change the title of similar Group Boxes / Tab Pages etc at once.
Another aspect is that you can just print that class and give it to a non-programmer who can check if the captions are intuitive, and if messages to the user are too detailed or too confusing etc.

However, I see certain disadvantages:

Every single class is tightly coupled to the constants classes

Adding/Removing/Renaming/Moving a constant requires recompilation of at least 90% of the application (Note: Changing the value doesn't, at least for C++). In one of our C++ projects with 1500 classes, this means around 7 minutes of compilation time (using precompiled headers; without them it's around 50 minutes) plus around 10 minutes of linking against certain static libraries.

Building a speed optimized release through the Visual Studio Compiler takes up to 3 hours. I don't know if the huge amount of class relations is the source but it might as well be.

You get driven into temporarily hard-coding strings straight into code because you want to test something very quickly and don't want to wait 15 minutes just for that test (and probably every subsequent one). Everybody knows what happens to the "I will fix that later"-thoughts.

Reusing a class in another project isn't always that easy (mainly due to other tight couplings, but the constants handling doesn't make it easier.)

Where would you store constants like that? Also what arguments would you bring in order to convince your project manager that there are better concepts which also comply with the advantages listed above?

Feel free to give a C++-specific or independent answer.

PS: I know this question is kind of subjective but I honestly don't know of any better place than this site for this kind of question.

Update on this project

I have news on the compile time thing:

Following Caleb's and gbjbaanb's posts, I split my constants file into several other files when I had time. I also eventually split my project into several libraries which was now possible much easier. Compiling this in release mode showed that the auto-generated file which contains the database definitions (table, column names and more - more than 8000 symbols) and builds up certain hashes caused the huge compile times in release mode.

Deactivating MSVC's optimizer for the library which contains the DB constants now allowed us to reduce the total compile time of your Project (several applications) in release mode from up to 8 hours to less than one hour!

We have yet to find out why MSVC has such a hard time optimizing these files, but for now this change relieves a lot of pressure as we no longer have to rely on nightly builds only.

That fact - and other benefits, such as less tight coupling, better reuseability etc - also showed that spending time splitting up the "constants" wasn't such a bad idea after all ;-)

Update2

Since this question still receives some attention:

Here is what I've been doing in the past few years:

Put every constant, variable, etc exactly in the scope that is relevant for it: If you use a constant only in a single method, it is OK to define it in that method. If a single class is interested in it, leave it as a private implementation detail of that class. The same applies for the namespace, module, project, company scope. I also use the same pattern for helper functions and the like. (This may not apply 100% if you develop a public framework.)

Doing this increased reusability, testability and maintainability to a degree where you not only spend less time compiling (at least in C++), but also less time on bugfixing, which leaves you more time for actually developing new features. At the same time, developing these features will go faster since you can reuse more code more easily. This outweighs any advantage the central constants file might have by a magnitude.

Take a look at especially the Interface Segregation Principle and the Single Responsibility Principle if you want to know more.

If you agree, upvote Caleb's answer since this update is basically a more general take on what he said.


答: The second one is clearly better. Imagine you call GetPricesForProduct a second time with a different id before you have copied all fields. To me the first version is an anti-pattern. Never do that.

Title: Populate fields or return object


答:
I don't know why is PriceCalculator is a class on its own. The calculated price value is a property that logically belongs to ProductPrice class. The price calculation is not a utility or helper it is tightly dependent on the  ProductPrice and (should) be encapsulated in that class. Accordingly, PriceCalculator should be CaculateProductPrice() method inside ProductPrice class (or Product class). Another reason for that is you don't ever want to instantiate ProductPrice and PriceCalculator separately. In fact, you probably never need to create an object from PriceCalculator on its own.

Edit: Added the text (or Product class), since I am not fully aware of the properties and assications in and between Product and ProductPrice.

Title: Populate fields or return object


答:
I would suggest putting all of these constants into some sort of configuration file. For Java applications, we usually use .properties files, a simple text with each line formatted as "(key) = (value)". Example

```
MainPanel.Title = Welcome to our application
DB.table.users = TBL_USERS
logging.filename = application.log
```

You then load this file at runtime, populate a cache that lets you look up a key and get back a value. When you need a constant you then query the cache. You will still need to have your keys somewhere, and the cache will need to be globally accessible, but when you change the actual values of the constants, no recompile is necessary, it should be possible to just re-start the app (or if you really want to get fancy, have multiple .properties files and caches and give the application the ability to reload a cache at run-time).

For an implementation, I found this SO question: https://stackoverflow.com/questions/874052/properties-file-library-for-c-or-c (it was the first hit on a Google search - I haven't actually used this software myself).

Title: Where should you put constants and why?

Body:
I would suggest putting all of these constants into some sort of configuration file. For Java applications, we usually use .properties files, a simple text with each line formatted as "(key) = (value)". Example

MainPanel.Title = Welcome to our application
DB.table.users = TBL_USERS
logging.filename = application.log

You then load this file at runtime, populate a cache that lets you look up a key and get back a value. When you need a constant you then query the cache. You will still need to have your keys somewhere, and the cache will need to be globally accessible, but when you change the actual values of the constants, no recompile is necessary, it should be possible to just re-start the app (or if you really want to get fancy, have multiple .properties files and caches and give the application the ability to reload a cache at run-time).

For an implementation, I found this SO question: https://stackoverflow.com/questions/874052/properties-file-library-for-c-or-c (it was the first hit on a Google search - I haven't actually used this software myself).


问:
Are there guidelines on how many parameters a function should accept?
I've noticed a few functions I work with have 6 or more parameters, whereas in most libraries I use it is rare to find a function that takes more than 3.

Often a lot of these extra parameters are binary options to alter the function behaviour. I think that some of these umpteen-parametered functions should probably be refactored. Is there a guideline for what number is too many?

答:
One aspect that the other answers do not take up is performance.

If you are programming in a sufficiently low level language (C, C++, assembly) a large number of parameters can be quite detrimental to performance on some architectures, especially if the function is called a large amount of times.

When a function call is made in ARM for instance, the first four arguments are placed in registers r0 to r3 and remaining arguments have to be pushed onto the stack. Keeping the number of arguments below five can make quite a difference for critical functions.

For functions that are called extremely often, even the fact that the program has to set up the arguments before each call can affect performance (r0 to r3 may be overwritten by the called function and will have to be replaced before the next call) so in that regard zero arguments are best.

Update:

KjMag brings up the interesting topic of inlining. Inlining will in some ways mitigate this since it will allow the compiler to perform the same optimizations that you would be able to do if writing in pure assembly. In other words, the compiler can see which parameters and variables are used by the called function and can optimize register usage so that stack read/write is minimized.

There are some problems with inlining though.

Inlining causes the compiled binary to grow since the same code is duplicated in binary form if it is called from multiple places. This is detrimental when it comes to I-cache usage.

Compilers usually only allow inlining up to a certain level (3 steps IIRC?). Imagine calling an inlined function from an inlined function from an inlined function. Binary growth would explode if inline was treated as mandatory in all cases.

There are plenty of compilers that will either completely ignore inline or actually give you errors when they encounter it.


答:
I crashed a 100 000$ laser scanner.

The controller was storing positions as integer so I divided everything by 10000 to get the actual position in inches.

When the last digit was a 0, it was omitted so the Z axis was 10 times to far.

Hillarity ensued

Title: Biggest mistake you've ever made

Body:
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…


问:
Which architecture should I choose for this project?
I have a project. The server which based on a phone PCI-board is responsible for received phone calls from the customer and then redirect the phone calls to the operators.

I have decided to code the server using c++ programming language and qt framework because the PCI-board SDK's interface is c/c++ originated and for the sake of portability.

The server need to send the information of the the customer to the operator while ringing the operator and the ui interface of the operator client should be browser-based.

Now the key problem is how could the server notify the operator that there is a phone call for he/she.

One architecture I have considered is like this,

The operator browser client use ajax pooling the web server to check whether there is call to the client; the web server pooling the database server to check whether there is call;
the desktop server(c++) wait for the phone calls and set the information in the database.

The other operations such as hang up the phone call from the client, retransfer the phone call to the other operator also use this architecture.

Then, is there any way other than pooling the server(js code setInterval('getDail', 1000)) to decide whether there is a call to the operator?

Is this architecture feasible or should I use some terrific techniques that I do know such as web services,xml-rpc, soap???

The Caller center is for 8~300 operators and the operators do not seperate geographically.
Moreover, I have figured out that we need provide interface for customer programmer, so this thing is so called middleware? Then some new questions, how could we expose interface to customer, COM?

Thanks in advance.

答: If you haven't already, read about the architecture of Asterisk, an open source telephony applications platform. Your project seems similar: http://www.aosabook.org/en/asterisk.html</p>

OwnerDisplayName: Manoj


答:
Second Method (for all the reasons already given), and:

make PriceCalculator an interface; one day, you might need one for consumers, one for business customers, one for government customers, one for international customers (EU), one for international customers (outside the EU) etc., so you will implement different Calculators and use the one you need

make the fields in ProductPrice immutable; maybe it's best to make ProductPrice an interface with some getters (read-only attributes in C#); because you might want to reuse those objects, i.e. by caching them or even using a product price for more than one product (yes, the red mouse costs exactly as much as the green mouse, the yellow mouse and the blue mouse)

Title: Populate fields or return object


答:
I would like to recommend a gradual approach using Scala. And I would recommend starting with Scala's creator's book, "Programming in Scala, 2nd Edition". This book is FANTASTIC at slowly introducing one to (FP) Functional Programming using Scala. And in showing the move towards FP, it doesn't reject OO. In fact, it leverages it. I am making my second pass through it now.

Basically, Scala allows one to do Java/OO "without semicolons". And then one can try out a bit of FP without having to go whole hog. For example, in training myself to do FP, I typically will focus on referential transparency at the class method level, but let my methods have however many var-s, mutability and imperative-ness as is needed for me to do a first pass at an implementation. Then, I focus on slowly reworking each method to move it towards pure FP. And I also use the sister site to StackOverflow, CodeReview, to get help with my mental/thinking transition. Here's an example of a recent post I made doing this very thing.

Anyway, best of luck on your FP journey. :)

Title: How to introduce your team to functional style of coding?

Body:
I have a situation where most people in my group come from an object oriented programming background with little to no understanding of functional programming. Not even basics like closures.

Any suggestions about what might be a good way to introduce them to functional coding style? A lot of coding that we do can be shortened if we do the functional way for our specific cases.

I have already given couple of presentations about functional and coding paradigms. Unfortunately we don't use a proper functional programming language like Haskell (basically legacy code is in C, C++, Java) so we have to do whatever is there with these.


问:
Virtual Machines And Unit/Integration Testing Web Application
I am in the process of adding unit testing to a project I am working on at work and a suggestion came up that I should use VMs to populate the database with good data.  This was suggested as an alternative to what I usually do which is use yaml fixture file to load the data.  While I think that using a VM for the unit testing database might have some benefits, overall I do not see it as a great solution.

The first concern I have is the speed of running tests.  I don't know how long it would take to bring up and tear down a new VM instance based on a snapshot but my guess is that it would be longer to the data insertions that the yaml data fixture files do.  Unit tests should run as fast as possible because they should be executed at least once before any push to the version control repository and that can happen several times a day (even more when in bug fixing mode).

The next concern is having the data in a known state for all tests.  Sure, the first test that is executed on the VM's database is going to know what state the database is in however once a test modifies data, that could screw up the other tests.  With the yaml fixture data files, each test is guaranteed to know what state the database is in.

The last major concern is the complexity using a VM setup would probably entail (of course I could be wrong since I have never had a setup like this before).  Obviously we can't just run phpunit with using VMs in the setup.  First we would have to create a script that basically creates and deletes the VM.  This would have to either work on all OSes or we would have to force everyone to work in a VM environment (and running a VM within a VM seems like it is really going to be even slower).

The VM suggestion was to combat the issue of managing yaml fixture data files however to me it seem like managing yaml file would be the easier of the two options.

Has anyone ever worked in an environment where developers would use VMs for the database that unit testing (or integration testing or whatever you want to call it) required and was is successful?

答:
I was on a project for a large aerospace client. The application we were developing was designed to collect data from fleets using their engines worldwide. Because of the hardware requirements, we determined that it would be more cost effective to use virtualization rather than purchasing several discrete servers to host the system.

We purchased a twin set of healthy servers (4 quad core xeons 256GB ram) one for staging, the other for production. I configured the server to allow developers to self-provision their own development environments (whenever they wanted to wipe their database they just needed to click a button on the portal and it would be ready for them in a few minutes).

The unforeseen benefit of this setup was that we were able to just copy the staging VMs over to the production server and bada-bing bada-boom, we were live. That project was so successful, that it became a model for all of our future project work. And we also decided to virtualize our internal infrastructure.

So yes, it can work with the appropriate tools. We used Hyper-V and Microsoft System Center for Virtual Machine Management (SCVMM). There are similar tools available for VMWare (both first and third party) as well.


问:
How do we finish all our stories by the end of the sprint and not after and why is this important?
We are running 2 weeks sprints where the team will just barely finish development by the last day of the sprint but cards are not complete because testing is not finished.  The definition of done is really "when development is complete" rather than "when the stories are complete."  We have a 1 week delay between the last day of the sprint and the release date.  The team does finish the sprint by the release date but that seems like that isn't quite meeting the objective of scrum.  The team starts the next sprint the day after the previous sprint ends.

I see the following problems:

team is not using whole team testing

team is not too interested in pair programming or piling on one card at a time.

Maybe the stories are too large and we should break them down more so that we finish at a more steady pace throughout the sprint?

Any suggestions on how we get the team bought in to finishing the sprint by the end date? Or other ideas?

Why do we think it is important to finish by the last day? Why does it matter if the team is still finishing by the release date? (I have my own answers but am curious what others think here.)

答:
Where I used to work, we'd have a code freeze to allow time for testing in the sprint.  This also would give developers time to do refactoring and other minor tweaks while QA reviewed the work done to see what is and isn't ready for production as the refactoring work wouldn't be merged until after the release was tagged/branched.

I'd question how well does the team understand the idea of velocity where X points of story work are done in a sprint and not bleeding into another sprint with bug fixes or other work that would impact the next sprint's work.


答:
I'll be a little contrary, and say that the first method is better, IF you make this change:

Your GetPricesForProduct() function should be the CONSTRUCTOR for ProductPrice.

Because a ProductPrice object with no particular product doesn't MEAN anything; it's not properly initialized.

Title: Populate fields or return object


问:
XP, TDD or DDD - Which one should I learn first?
I want to learn XP, TDD and DDD to improve myself. My problem is I have general ideas of what they are but I don't know which one should I learn first, do I need to learn something before other?

Please suggest me which topic should I learn first, second and third.

答:
Focus on TDD.  XP and DDD are higher-level, management-type software development concepts, and you will be learning them as you go anyway.  TDD is a foundational concept.

To be effective at TDD, you will eventually need to know the others, and have a good grasp of software architectural principles.  It's impossible to "grow" a sound software architecture by simply doing "red, green, refactor;" you also need to know where you are going.


问:
Does one method overload an other, or are both methods "overloaded"
If I create this method

```<code>public void foo()
</code>```

And then I create an overloaded version like this

```<code>public void foo( string bar )
</code>```

Do we say that the second functions overloads the first, or are both methods equally "overloaded"?

This would imply (I think), that there is a base type function, that is being overloaded, by another function (somewhat like inheritance, but not really).

Assuming that one method can "overload another", would also imply terms like "overloader" and "overloadie", if that is a word at all. But that doesn't feel right at all, especially since you can have several overloads.

I got to this question when I wanted to write down the process of creating an overloaded method and I wanted the most correct way of writing it down.

Examples:

I am overloading foo

I am overloading foo with foo( string bar )

I am creating an overloaded method

I am making foo overloaded

So yeah, this kind of got me thinking, I am not sure what to make of it.
There are hundreds, if not thousands, of descriptions of function overloading online, but at a first glance I couldn't find any addressing this.

答: I would simply say foo is overloaded. There is certainly no master/slave or parent/child relationship going on here.


问:
Is it a good idea to put all assembly: WebResource in the same cs file?
I have a .NET library, with some WebControls.

These webControls have Embed Resources.

And we declare them like it, in all webcontrols for each cs file:

Something like this:

```<code> [assembly: WebResource("IO.Css.MyCSS.css", "text/css")]
    namespace MyNamespace.MyClass
    {
         [ParseChildren(true)]
         [PersistChildren(false)]
         [Designer(typeof(MyNamespace.MyClassDesigner))]
         public class QuickTip : Control, INamingContainer
         {
        //My code...
          }
    }
</code>```

Would it be a good idea to create a cs file and include all WebResource declarations there?

Example a cs file with just:

```<code>     [assembly: WebResource("IO.Css.MyCSS.css", "text/css")]
     [assembly: WebResource("IO.Image.MyImage.png", "image/png")]
//And many other WebResources of all WebControls of the Assembly
</code>```

答:
In general, this is not a good practice.  You want to be able to add or remove features in as few operations as possible, touching as few files as possible.  Ideally you want to be able to add a feature without modifying any existing files.

Think about reusing just one of these web controls in another application, and it becomes pretty clear.


答: I think that a good way to express this is to focus on the final result, not on changes made to the class over time. Thus, instead of saying "I overloaded 'foo' with 'foo(other parameters)'," you say "foo is an overloaded function, with 'foo()' and 'foo(other parameters).'"</p>

Title: Does one method overload an other, or are both methods "overloaded"

Body:
If I create this method

```<code>public void foo()
</code>```

And then I create an overloaded version like this

```<code>public void foo( string bar )
</code>```

Do we say that the second functions overloads the first, or are both methods equally "overloaded"?

This would imply (I think), that there is a base type function, that is being overloaded, by another function (somewhat like inheritance, but not really).

Assuming that one method can "overload another", would also imply terms like "overloader" and "overloadie", if that is a word at all. But that doesn't feel right at all, especially since you can have several overloads.

I got to this question when I wanted to write down the process of creating an overloaded method and I wanted the most correct way of writing it down.

Examples:

I am overloading foo

I am overloading foo with foo( string bar )

I am creating an overloaded method

I am making foo overloaded

So yeah, this kind of got me thinking, I am not sure what to make of it.
There are hundreds, if not thousands, of descriptions of function overloading online, but at a first glance I couldn't find any addressing this.


答:
When talking about overloads, the name of the function is overloaded, not the function itself. The functions overloading the name are "overloads" and overload the name, but not each other. In your example, "public void foo()" and "public void foo( string bar )" both overload the name "foo". Therefore, you cannot speak in terms of overloader and overloadee of one of the functions, because they have no direct relationship.

In your examples, you can say that you are overloading "foo" (the name) with "foo( string bar )" (the function), but you cannot say that you create an overloaded method, because methods are never overloaded. You can say that you create an overloading method. To formulate "making foo overloaded" is just a worse way of saying "overload foo".


答:
Constants that are specific to a class should go in that class's interface.

Constants that are really configuration options should be part of a configuration class. If you provide accessors for the configuration options in that class (and use them in place of the constants elsewhere), you won't have to recompile the whole world when you change a few options.

Constants that are shared between classes but which aren't meant to be configurable should be reasonably scoped -- try to break them out into files that have particular uses so that individual classes only include what they actually need. This again will help reduce compile times when you change some of those constants.

Title: Where should you put constants and why?


答:
I would say that TDD is the foundation. If you do nothing else, your code would be better off just from properly applying this practice. TDD is what allows Agile development (XP being one methodology) to work. Having good coverage from a unit test suite enables you to be fearless with changing/refactoring your code, because you know once something breaks, you'll have a red test to alert you.

Without TDD, adding new functionality or changing existing functionality becomes something like defusing a bomb. Even worse imagine that bomb didn't blow up right away but instead silently releases an odorless, colorless, gas that once you inhale it causes you to die six months later. That is what coding without test coverage is like. You might think you're fixing a bug or implementing a new feature but in reality, you might be adding a new bug that will exist undetected until all bloody hell breaks loose months down the road.

After that I would go with DDD. This will teach you techniques to create code that is more easily tested, making you even better at TDD.

With regard to Agile Development, the only way to really learn that is to be on a project where it is being implemented properly. XP and Scrum and the other methodologies have their specifics but there are general Agile tenets that will work well regardless of the approach.

Title: XP, TDD or DDD - Which one should I learn first?

Body:
I want to learn XP, TDD and DDD to improve myself. My problem is I have general ideas of what they are but I don't know which one should I learn first, do I need to learn something before other?

Please suggest me which topic should I learn first, second and third.