答:
In addition to the other good answers so far...

If you're looking for ways to produce code faster, have you looked into developing a code generators for repetitive patterns of code? The idea is to write a program that produces more code to use in your main program.

Example: you need to write a series of simple CRUD queries for a large number of tables, each with a large number of columns. The details of these are given to you in an Excel spreadsheet, and to make things interesting, the requirements for these tables change now and then. One solution would be to write a macro for the spreadsheet that generates the CRUD queries and the code to execute them. This way you can generate queries for 1 or 10 or 100 tables with the same amount of effort (once the macro's written). When the requirements change and columns are added/removed/renamed, regenerating the queries is very easy. You might end up with more code (in terms of LOC) in the end, but since you don't have to manually maintain it (if there are special exceptions to these queries, they should not be generated, but tweaked by hand), it's not so bad.

This may not apply in all situations, but it's fairly generic and I've used this successfully in a few places. Sometimes writing a code generator in Java or C# makes more sense, depending on the situation.


问:
What do I need to learn to become a better web programmer?

Possible Duplicate:

  What should every programmer know about web development?

I'm 15 years old. I've been programming for 2 years. I suppose I am a good programmer (not designer).
I can use PHP(Good), Css(simple), and JQuery(not too bad).

What else can I learn related to web development (maybe system programming)?
Thanks for your suggestions..

答: The best way to become good at anything, wether it is programming, playing an instrument or a physical activity is to practice. Write lots of code. Try to learn as much as you can along the way. Read other peoples code as well as books and articles about programming. Try out the stuff that you learn. And never think you have learnt it all. There's always more to learn, and another field to master.</p>

ContentLicense: CC BY-SA 3.0


答:
Incidentally, I just recommended The Pragmatic Programmer: From Journeyman to Master in an answer to a different question, but it will do good to you too :-)

This book is what its title promises. It will show you what it takes to become a good programmer, and what are all the different areas, activities and skills involved in producing software. What is IMHO the most important is, it gives you the big picture, and teaches you the mindset to become a successful developer: one who is able to solve his clients' problems efficiently.

Title: What do I need to learn to become a better web programmer?

Body:
Possible Duplicate:

  What should every programmer know about web development?

I'm 15 years old. I've been programming for 2 years. I suppose I am a good programmer (not designer).
I can use PHP(Good), Css(simple), and JQuery(not too bad).

What else can I learn related to web development (maybe system programming)?
Thanks for your suggestions..


答:
In addition to plenty of reading and practice, make friends with others who have the same interest. Becoming part of a community of people all interested in doing the same thing will answer the question you're asking permanently.

But to answer your question more specifically, you should learn something about data persistence (databases, etc.). Try MySQL since you already have some PHP. The two go together like peas in a pod.


问:
Should we attempt to review all our code?
We're currently modifying out development process and I'm wondering if we should try to keep a 100% of our commits peer reviewed.

What is your experience regarding code reviews?

Do you tend to spend "a lot" of time on them (say 1/2 hours per day), or just skim over for 5/10 minutes max?

Do you have a fixed amount of time to spend per day/week/sprint/project?

Most importantly do you think that the target should be for 100% of the code to be peer reviewed or that 100% is not necessary?

答:
Code reviews may seem daunting, but they are a valuable tool when conducted properly. They will be your first line of defense against design and implementation mistakes. If you aren't conducting code reviews on every feature you put into place, you should start ASAP.

As for how much time to spend on peer reviews, a good practice is to leave 5-10% of your total estimated development time for conducting and responding to the code review.

We have a whitepaper on conducting effective code reviews that can help get you started on the right foot. It is a step by step guide and discusses common pitfalls you might face and how to resolve them. You can download it from our website.

OwnerDisplayName: Simeon

ContentLicense: CC BY-SA 4.0


问:
How to convince a teammate, who sees oneself as senior, to learn SVN conceptual basics?
To start with some background, I took up a new developer position this summer and ended up being the newest member on the team, yet with most experience under the belt.

So far I have managed to push sanity initiatives through easily enough because of low adoption costs (in terms of time and effort). However things have leveled up a bit.

One of my teammates, although experienced, does not really understand SVN. Naturally, blank areas on his mental map depicting oceans of SVN cause him to adopt rather strange usage patterns.

For example, he had declared a policy of "1 SVN commit per day per developer" because otherwise "the server would soon run out of disk space". When I explained him that SVN commits are deltas, not full copies, he responded with doubt and even today I'm not entirely sure if he understands what it means.

We also had a heated argument about whether to include Eclipse .project configuration in SVN. My teammate insisted we should, although it has caused numerous pointless conflicts. I was against keeping individual developer configuration files in SVN. Finally, it turned out that my teammate had a practice of re-checkouting the entire source tree after every commit to just make sure "code committed into repository works". That was the reason he was so adamant in keeping the project configuration in SVN - so it would be easy to re-import the project. When I explained that commit synchronizes working copy to remote byte-by-byte which makes re-checkout unnecessary, my teammate responded with doubt again and eventually waved the whole issue off as insignificant.

In my opinion, our team wastes time by resolving SVN conflicts in project configuration files which contain only developer-specific settings that need not be shared to SCM at all. All this mess because someone tailored the process around incorrect assumptions.

How can I convince a teammate, who sees oneself as senior, to get a better understanding of SVN basics?

答:
Start a brown bag initiative, once very few weeks someone holds a lunchtime talk about something they know about and presents it to the others.

You use this as excuse to present SVN in detail and maybe some of the thinking behind some of the alternatives.

A few weeks later someone else can have a go.


问:
Is web application startup time really that important?
Had a conversation with someone about adding some initialization code on application startup and he complained about that causing an increasing in the startup time. He couldn't really state a reason (gut feeling or something, don't know). This is not a heavy use application and starts in about a minute or so, we deploy a few times a year.

I remember reading such advice on questions on SO some time ago, people advising to initialize on startup instead on access of page with the "if you can afford the penalty" stamp on.

I've worked with web apps that started from 30 seconds to 4-5 minutes but once online they rocked.

So what am I missing? Unless it's a vital application like... I don't know... for the financial market, medical applications, space exploration etc, is it really that important the startup time?

P.S. I'm strictly referring to web apps, desktop apps are bound to start lightning fast.

答:
This question doesn't ask about any particular platform.  There are platforms on which startup time really is very important.

For instance, on Google App Engine; if your page isn't getting accessed (or rather, is getting accessed less frequently than another application on the same node), it will be unloaded occasionally.

Thus, if you're in the bottom 99% of site access frequency, then startup time is access time;  your application is being restarted at nearly every access.  if you are in the top 1%, then your application is getting started up on many nodes, and although many page accesses will return from an already started instance, some still won't, and so you'll have intermittent, long access times.

This same thing is true on many other hosting environments.  Leaks in third-party libraries, or even in your own code that have simply eluded discovery, might mean that the only reliable way to run your web service is to have it reload every so many requests (often between 100 to 10,000), and so the start up time is paid frequently.  Using this pattern is acceptable when an app is leaky, but starts up quickly; it's unworkable when the app takes more than a few seconds to start.


问:
Should I use Java applets or JavaScript/PHP to make my site more interactive?
I have a website that is about electronics. I want to make some functional calculators such as calculation for analog filters which will have to show lots of plots and stuff like that. This is a sample of what I am looking for and obviously it is only PHP and its graphic functions.

I want to have similar thing but much more interactive with realtime sliders and stuff like that.

What should I go for? Java Applets? or stick to JavaScript/PHP? I am asking this because I can do it with Java much faster (know it better than JavaScript and PHP). But I am afraid of browser incompatibility, security options for Applets and similar things. What is your suggestion?

答: Actionscript 3.0 with Adobe Flex is really recommended if you have a java background. Very easy to pick up if you are comfortable with object-oriented programming. You could build your backend in java and then have the frontend built in flash.</p>


问:
Any recommendations for setup/teardown of browser automation testing?
I have been doing some browser automation testing recently using Selenium (and Watin a bit too) and have reached a point where I am looking for recommendations on controlling the environment I'm testing.

For example, if I have a test that registers a new user on site (or similar database dependent task); how do people ensure that the test does not persist or at least is able to be repeated without always changing the test itself?

I'm seeking recommendations for ensuring my integration/acceptance tests using Selenium can be ran without having to worry about changing them or the environment manually.

答:
Run Selenium from a separate programming language's testing framework.

Guaranteeing the evironment is OK without manually doing any work is really hard to do if you're using the selenium recorder and playing back in their standard test language.  You'll need to export the code from the testrunner (or write it yourself) using a language like Java or C# where you have full access to Selenium and the Selenium Grid within the context of unit testing frameworks like NUnit and JUnit.

These testing frameworks using the flow of: Setup -> Test -> Tear Down.

This gives you the opportunity before the web test is run to add an item to the database so that your Selenium test, which runs directly after, will be guaranteed to have something to delete.  Similarly, the Tear Down could then delete the new user that you create.  The testing frameworks give you more power and access to be able to script things you definitely have to do running Selenium from the Selenium recorder/runner.


问:
Is this use of conditionals an anti-pattern?
I've seen this a lot in our legacy system at work - functions that go something like this:

bool todo = false;
if(cond1)
{
  ... // lots of code here
  if(cond2)
    todo = true;
  ... // some other code here
}

if(todo)
{
  ...
}
```

In other words, the function has two parts. The first part does some sort of processing (potentially containing loops, side effects, etc.), and along the way it might set the "todo" flag. The second part is only executed if the "todo" flag has been set.

It seems like a pretty ugly way to do things, and I think most of the cases that I've actually taken the time to understand, could be refactored to avoid using the flag. But is this an actual anti-pattern, a bad idea, or perfectly acceptable?

The first obvious refactorization would be to cut it into two methods. However, my question is more about whether there's ever a need (in a modern OO language) to create a local flag variable, potentially setting it in multiple places, and then using it later to decide whether to execute the next block of code.

答:
Many of the answers here would have trouble passing a complexity check, a few looked > 10.

I think this is the "anti-pattern" part of what you are looking at.  Find a tool that measures the cyclomatic complexity of your code--there are plugins for eclipse.  It's essentially a measurement of how hard your code is to test and involves the number and levels of code branches.

As a total guess at a possible solution, the layout of your code kind of makes me think in "Tasks", if this happens in a lot of places perhaps what you really want is a task-oriented architecture--each task being it's own object and in mid-task you have the ability to enqueue the next task by instantiating another task object and throwing it on the queue.  These can be amazingly simple to set up and they reduce the complexity of certain types of code significantly--but as I said this is a total stab in the dark.


问:
How much data should be required in a request to a webservice?
When recieving data from clients how much data that you provided to them should you require back from them?

For example when clients order a product from a webservice should they just need to provide a product code? The other alternative would be to require the product code product name and product price ect.

I have alway built webservices the former way with the minimum of data returned back to me, however I have just been consuming another web service that requires the vast majority of the data returned back to them. What are the advantages of the second way?

答:
Off the top of my head?

Requiring redundant information can reduce (though certianly not eliminate) bugs involving spurious or 'off-by-one' type errors.  Submitting an order with a product code and product description is less likely to be accidentally the wrong product code.

You can force the interaction to use your full interface.  Web scrapers will have to maintain session state to have enough information to run your service.  This means you can rate limit them more effectively, if that's an issue for you.

You don't have to look up anything; its all there in the request:  add_to_order(Product(**json.loads(request.data)))


问:
Am I using Factory and Impl classes properly?
In my 2d destruction derby simulator I have a CargoTruck class and CargoTruckImpl that implement an interface called Truck. CargoTruck has a reference to CargoTruckImpl which is returned through the CargoTruckImplFactory.

But then I decided to add to this chain by having CargoTruckImpl and CargoTruckMovementImpl use the interface called Movement. CargoTruckImpl has a reference to CargoTruckMovementImpl which is returned back to CargoTruck through the MovementImplFactory.

CargoTruck->CargoTruckImpl->CargoTruckMovmentImpl

FuelTruck->FuelTruckImpl->FuelTruckMovmentImpl

Is adding to the chain like this bad? Am I violating the Separation Principle or the Open-Closed Principle by using Factory classes this way? Is there a better way of doing this?

答:
What is MovementImplFactory doing for you here?  Abstract it and separate the instances into their domains.

This would have an AbstractMovementImplFactory being extended by CargoTruckMovementImplFactory and FireTrucImplkMovementFactory.

Then have your instances of the Trucks have references to the appropriate factories  For example, construct CargoTruckImpl to have a reference to CargoTruckMovementImplFactory.  When you need a movement for that truck, it can use its domain-specific factory to build it, and you've separated the movement logic from the truck logic.


问:
What are ways I can speed of development time when building applications?
I noticed that overtime with experience that the curve of learning shifts from trying to learn a language or technology (the way it works) to how to develop applications faster and with less code. I am very interested to see how other developers have minimized the time it takes to get applications to market.

I know for a fact that by learning just one thing it can save you a ton of time. For example I started learning lambda expressions and code that normally took 3 lines now only takes 1 and is alot faster to type.

Another angle is shortcuts and tools in an IDE itself. For instance I can't believe I didn't know how to remove unused using statements from my source code so I used to do it manually until I found out there was a tool in VS for removing them.

Are there any resources for learing faster ways of developing applications? Keyboard Shortcuts, tools, programs, references? Is there like a reference where one can learn these things? If not can you please share how you learned some of these tips?

NOTE: This question is geared towards .NET, C# and the Visual Studio IDE

答:
In addition to the answers posted:

0-Define requirements accurately to minimize re-work and major time consuming fixes, and consider the design-first approach.

1-Don't shoot yourself in the foot - Recognize your/your team's capabilities vs. requirements vs. time available before you commit to fancy features and focus on the core value of the application.

2-Use tools. There are very good tools to generate code and tools to help your end user generate reports if applicable.


问:
Should a developer argue against unnecessary or harmful features?
What is a good attitude from developers when discussing new features, and namely, non critical/questionable features?

Say you are developing some sort of Java like language, and the boss says: "We need pointers so that developers could fiddle with object memory directly!"

Should the developer shoot down the idea because it adds unimaginable complexity and security vulnerabilities, or should he do what's asked?

This may not be a good example, but what about things that are more in a gray area, like adding buttons that break workflow, or goes against internal structure of the program, etc.?

What is the optimal "can do" vs. "can't do" distribution for a regular programmer?

EDIT: The question is not about a bad boss :D

I was more interested how do people approach new problems that add a noticeable amount of problems while maybe being marginally useful.

Should the general attitude be:

yes we'll do it, screw the complexity

maybe

no, the general rework, and implications don't justify the change

What should be the reaction of a good developer?

答:
If you are in the position to understand the cons of doing it (complexity, lack of usability, etc.), then it is in everyone's best interest for you to explain it to the best of your ability. Often non-developers do not understand the problems of adding new features. It's easy for them because they don't have to do anything or even think about it.

However, if the powers that be decide that the new feature is going to be added, then you should do the best job possible. It's a challenge.

And, if the new feature is too stupid or the working environment too crappy, then it's time to find another job.


答: If you're already running in a servlet container and familiar with Java, check out the Google Web Toolkit. Your client code can be written in Java that gets compiled into browser-specific JS.</p>

Title: Should I use Java applets or JavaScript/PHP to make my site more interactive?

Body:
I have a website that is about electronics. I want to make some functional calculators such as calculation for analog filters which will have to show lots of plots and stuff like that. This is a sample of what I am looking for and obviously it is only PHP and its graphic functions.

I want to have similar thing but much more interactive with realtime sliders and stuff like that.

What should I go for? Java Applets? or stick to JavaScript/PHP? I am asking this because I can do it with Java much faster (know it better than JavaScript and PHP). But I am afraid of browser incompatibility, security options for Applets and similar things. What is your suggestion?


问:
Specifically for JS, CSS, HTML: what is the difference between optimization, compression, minification, tidying, concatenation?
When we talk about source code and the file which contains the code like CSS, HTML, JavaScript and we also talk about performance of a web site or application, what is the differences between these terms?

Optimization

Compression

Minification

Tidying

Concatenation

答:
Optimization - general term meaning any of the following:

Compression - fewer bytes through algorithmic means

Minification - fewer bytes by using shorter syntax with the same meaning

Tidying - removing code that doesn't do anything and removing redundant code

Concatenation - delivering all the data in one request rather than multiple requests


答:
It's great that you're applying some of the SOLID principles! However, I'd be a little suspicious about the number of Impl classes and Factory classes you're implementing (CargoTruck and CargoTruckImpl sound like the same class to me for example). It sounds like you might want to apply some DI principles here (or at least have something like Guice do some of this heavy lifting for you).

I always go back to Martin Fowler's article on DI when I start to worry about creating too many Factories etc, it might help clarify your thinking in this area.

Title: Am I using Factory and Impl classes properly?

Body:
In my 2d destruction derby simulator I have a CargoTruck class and CargoTruckImpl that implement an interface called Truck. CargoTruck has a reference to CargoTruckImpl which is returned through the CargoTruckImplFactory.

But then I decided to add to this chain by having CargoTruckImpl and CargoTruckMovementImpl use the interface called Movement. CargoTruckImpl has a reference to CargoTruckMovementImpl which is returned back to CargoTruck through the MovementImplFactory.

CargoTruck->CargoTruckImpl->CargoTruckMovmentImpl

FuelTruck->FuelTruckImpl->FuelTruckMovmentImpl

Is adding to the chain like this bad? Am I violating the Separation Principle or the Open-Closed Principle by using Factory classes this way? Is there a better way of doing this?


问:
Does anyone have suggestions for design or open source libraries specifically for a single page AJAX application?
I'm working on a major new version of a browser based application and I'm looking for comments/suggestions about the architecture/design.

It's a single page application using AJAX and client side templating to get new "pages".  I'm already using the Sammy Javascript library to handle bookmarking and forward/back buttons. I'm using JQuery, parts of JQueryUI, SlickGrid, and a little Dojo (mostly dojox/rpc/jsonrpc and it's dependencies) so far.

I'm communicating with the server using JSON RPC calls through a very thin web server layer that just forward the JSON strings to the business server, which has an API accessible in various ways, but the browser uses JSON RPC only.  Session state tracking happens in the business layer as part of the implementation of that API, though of course the RPC mechanism must give enough information to identify which session is calling it.

All that was context; the question I have is: does anybody know of any resources supporting this kind of design?  In particular I would be looking for open source Javascript libraries besides Sammy that support single page web applications.  Sammy expects you to use client side templating, and has some support for that plus several plugins for particular templating libraries, but doesn't support similar functionality for using AJAX to apply CSS style sheets (and remove or deactivate others) when you change screens and would have changed pages in a more traditional web application.

I'd also love to hear from anyone who has tried something similar.  Were you okay with one stylesheet for the whole application?  Did you have issues with memory leak issues from staying on one page for so long?

Also, any suggestions for a client side design?  Does MVP sound reasonable, with a model implemented in Javascript, presenter classes to implement events in an abstract way that's easier to unit test, and the view to handle the actual DOM stuff?  Some sort of application manager to track what pages are up, and that would clean up resources when a screen closes?

I haven't seen a lot of comprehensive references or libraries for the single page design, so anything people can tell me or refer me to would be appreciated.

Note that I have read Dev approaches to complex JavaScript UI's, which is a great question but not specific to single page complex Javascript UIs.

答:
Your approach is possible but have you considered the complexity with debugging and maintenance for a single page application?

A good alternative is the middle of the road approach via a portal design.  Please take a look at dropthings from Omar Al Zabir.  His portal is a single page application in the sense that everything appears to be rendered on one page.  However, the source of each portlet is from a different page.  This seperation greatly simplifies debugging and maintentance and provides the user with a single page style experience.


答:
The state machine pattern looks fine to me.
The anti patterns in there are "todo" (bad name) and "lots of code".</p>

Title: Is this use of conditionals an anti-pattern?

Body:
I've seen this a lot in our legacy system at work - functions that go something like this:

bool todo = false;
if(cond1)
{
  ... // lots of code here
  if(cond2)
    todo = true;
  ... // some other code here
}

if(todo)
{
  ...
}
```

In other words, the function has two parts. The first part does some sort of processing (potentially containing loops, side effects, etc.), and along the way it might set the "todo" flag. The second part is only executed if the "todo" flag has been set.

It seems like a pretty ugly way to do things, and I think most of the cases that I've actually taken the time to understand, could be refactored to avoid using the flag. But is this an actual anti-pattern, a bad idea, or perfectly acceptable?

The first obvious refactorization would be to cut it into two methods. However, my question is more about whether there's ever a need (in a modern OO language) to create a local flag variable, potentially setting it in multiple places, and then using it later to decide whether to execute the next block of code.


答: I'd suggest sticking to either javascript or Flash, or do the calculations server side in the language of your choice (which could be Java).  There's no reason to introduce a dependency on the client machine (ie, JVM) that isnt actually needed to do something similar to that example page you link to.  Fewer dependencies = less headaches.  Almost everyone has Flash installed, and every modern browser version can handle HTML Canvas.  But while most people will have Java installed, many wont.</p>


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答:
PC componenets:

High resolution and/or wide screen monitor having resolution at least 1680x1050, diagonally at least 19". Technology: LCD or higher, having response time < 10 ms. Good color reproduction and wide viewing angle are also important (thanks to Billy).

Processor should be Core 2 Duo or higher.

RAM should be 2 GB or higher.

Fast (>= 7200 RPM), large (>= 320 GB) hard disk. If possible, employ SSD.

A set of exotic keyboard and mouse, possibly wireless.

Other:

Large enough desk space.

Free beverages.

ContentLicense: CC BY-SA 2.5


问:
Can a small team enter .NET world while most of them are working on OpenSource languages?
We are a team of about 15 employees, in a non-IT enterprise. Today, we mainly develop websites, using PHP, MySQL, etc. We run a bit less than 100 linux servers on ourselves.

But today, we are confronted with a too-big-for-us-to-code project. We selected a great provider (yes, outsourcing), and now they ask us to choose between C++/Qt and .NET/WPF.

The app is highly graphical, and meant to be distributed on Windows systems. .NET is recommanded to us as easier to design and more lightweight.

But what about our team ? Can we handle, with our small number, both universes at the same time ?

responsibilites :

during the dev : design the app, review the code

after the dev : host servers, do maintenance and answer user calls

in the case we need a v2, we intend to call back the same provider

What do you think ?

EDIT

We finally chose C++/Qt. The reasons are :

the dev time has been tested to be somewhat equal

it suits us better from a management point of view

and it increases cross-platform portability

答:
In my experience (I was in a team that made a similar transition) there will be dificulties and frustrations, but you'll do fine, it all depends on the team's motivation to change.

Something that helped greatly was a one-week intensive training in .NET before starting the project.


问:
How do you version your files (Version Numbers)
I wonder how do you decide on the version number of your apps, do you really record down all changes made (for a change log)? Then how will you decide how to increment the version number. eg. +0.0.1 for each bug fix or something, +0.1 for each new feature release? or maybe you bundle many changes into +0.1 of your version number?</p>

答:
After reading a lot of articles/QAs/FAQs/books I become to think
that [MAJOR].[MINOR].[REV] is most useful versioning schema to
describe compatibility between project version (versioning schema
for developer, does not for marketing).

MAJOR changes is backward incompatible and require changing
project name, path to files, GUIDs, etc.

MINOR changes is backward compatible. Mark introduction of new
features.

REV for security/bug fixes. Backward and forward compatible.

This versioning schema inspired by libtool versioning semantics and by articles:

http://www106.pair.com/rhp/parallel.html

NOTE: I also recommend provide build/date/custom/quality as additional info (build
number, build date, customer name, release quality):

Hello app v2.6.34 for National bank, 2011-05-03, beta, build 23545

But this info is not versioning info!!

UPDATE For those who fill yourself as hipster - http://semver.org/ - like in libtool docs but shine as Web 2.0.


答:
Outsourcing it is fine, but you should have some of your own employees that also understand the system and how it works.

If your guys are all currently PHP guys then perhaps see if any of them are interested in some .NET training and get some for them.

Having something outsourced that none of your employees know anything about is a risky business.

Edit

Just to clarify, I don't mean that you should just have a few of your guys look through it when it's finished to learn how it all works, I mean you should have a few of your developers who are involved regularly with the project, who understand how it works as it progresses and who can be your "go between" between you (I'm presuming your the "manager") and the people you outsourced to. This means you should have developers learning .NET now.

The same people talking to the third party will help to build up a good working relationship and is also better than all of your developers bombarding them with questions.

Title: Can a small team enter .NET world while most of them are working on OpenSource languages?

Body:
We are a team of about 15 employees, in a non-IT enterprise. Today, we mainly develop websites, using PHP, MySQL, etc. We run a bit less than 100 linux servers on ourselves.

But today, we are confronted with a too-big-for-us-to-code project. We selected a great provider (yes, outsourcing), and now they ask us to choose between C++/Qt and .NET/WPF.

The app is highly graphical, and meant to be distributed on Windows systems. .NET is recommanded to us as easier to design and more lightweight.

But what about our team ? Can we handle, with our small number, both universes at the same time ?

responsibilites :

during the dev : design the app, review the code

after the dev : host servers, do maintenance and answer user calls

in the case we need a v2, we intend to call back the same provider

What do you think ?

EDIT

We finally chose C++/Qt. The reasons are :

the dev time has been tested to be somewhat equal

it suits us better from a management point of view

and it increases cross-platform portability


问:
How can I tactfully suggest improvements to others' badly designed code during review?
I'm a great believer in clean code and code craftsmanship, though I'm currently at a job where this isn't regarded as a top priority. I sometimes find myself in a situation where a peer's code is riddled with messy design and very little concern for future maintenance, though it's functional and contains little to no bugs.

How do you go about suggesting improvements in a code review when you believe there is so much that needs changing, and there's a deadline coming up? Keep in mind that suggesting the improvements be made after the deadline may mean they'll be de-prioritized altogether as new features and bug-fixes come in.

答:
I sometimes find myself in a situation where a peer's code is riddled
  with messy design and very little concern for future maintenance,
  though it's functional and contains little to no bugs.

This code is done. At a certain point, redesigns become too costly to justify. If the code is already functional with little to no bugs, then this will be an impossible sell. Suggest a few ways to clean this up in the future and move on. If/when the code breaks in the future, reassess the value of a redesign then. It may never break, which would be great. Either way, you are at the point where it makes sense to gamble that it will not break, since the cost will be the same now or later: drawn-out, terrible redesign.

What you need to do in the future is have tighter development iterations. If you had been able to review this code before all the work of ironing out bugs had been invested, it would have made sense to suggest a redesign. Towards the end, it never makes sense to do major refactoring unless the code is written in a fundamentally unmaintainable way and you know for certain that the code will need to be changed soon after release.

Given the choice between the two options (refactor or no refactor), think about which sounds like the smarter sell:

Hey boss, we were on schedule and had everything working, but now we
  are going to rebuild a lot of stuff so that we can add feature X in
  the future.

or

Hey boss, we are ready to release. If we ever have to add on feature
  X, it might take us a couple extra days.

If you said either one, your boss would likely say:

Who said anything about feature X?

The bottom line is that sometimes a bit of technical debt makes sense, if you were not able to correct certain flaws back when it was cheap (early iterations). Having quality code design has diminishing returns as you get closer to a completed feature and the deadline.


答:
A Training Plan

We're all expected to know everything about everything, new and old.  More often than not, we're expected to do so at our own time and expense.  Oh, sure, I was occasionally allowed to attend a conference, so long as it was 1.) free, and 2.) didn't take any time.

I find that one thing I'd love to have is a training allotment of not only money, but time.  A small investment (a week and a class fee) by the employer pays off not only in increased knowledge and productivity, but also morale, and I'd argue even loyalty.  Why go somewhere else if you are letting me grow as an engineer?

Title: Stuff every programmer needs while working

Body:
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed


问:
Simplifying Database Schema for Extensibility by non-expert Users

Possible Duplicate:

  Is it necessary to create a database with as few tables as possible

I've recently started to develop a database for a ~10 person office (it's an internship for me), and I've come up with a conceptual design I am quite happy with. My employers though, wish for me to simplify my design (less tables) because they wish to extend onto the database when I leave them and go back to school.

Two of them have some MSAccess experience, and they seem to know the term "database normalization", but none of them have a CS background. To accommodate this, I'm already going to build in MSAccess, which I do not have fond feelings for. I've explained that the conceptual ER diagram is not a table schema, and still needs to be translated into one and some of the relationships in the ERD might be one table with an entity, and simplifying the schema will lead to a "less normalized" database. The feeling I'm getting is that what they would like is for the database to just barely make it as 2NF, and would love it if it were 1NF.

Should I explain that views can be defined on the schema to make querying simpler? But I do not know how I can explain to them how to extend onto the design once I am gone without trying to teach them database theory, which they don't have time for. Or I could just make it less normalized - they're the ones paying for it and using it? I don't know.

答:
Build the client not only what they need, but in most cases you need to give them what they ask for as well; in this case, low normalization gives them both.  Not to mention, interns don't often have much room to argue.

So because of all this and the fact that you indicated, "non-expert users" need to maintain this product when you are long gone and this project is out of your hair...you should keep things simple.

Finally, normalization is not always preferable.  There are numerous articles debating the pro's and con's.


答: I'll go the other direction on this one: if your team has linux experience and familiarity, and you run your own servers, outsourcing to a .NET shop will be a disaster.  You won't have the experience to rein in the outsourcers when they get crazy, your linux and PHP intuitions will fail you in the Windows environment, you won't easily spot goofy .NET constructs, and you'll curse the fates that bind you to supporting two sets of servers, one Linux, one Windows.  If you hire some Windows folks to support that set of servers, the culture clashes and arguments will astonish you. </p>


答:
I personally prefer JavaScript/PHP to Java and think you should consider as this is more widely accepted. Java applets are not quite as popular.

Also a JavaScript solution will be faster and more responsive as users will not have to wait before they can use your calculator. Moreover there are a lot of javascript graphics libraries you can use: try rapheal.js


答:
When a spoonful of sugar helps the medicine go down, and what's wrong can be expressed succinctly - there aren't 20 things wrong - I'll lead in with a form that suggests that I have no stake, no ego invested in what I want to be heard.  Usually it's something like:

I wonder if it would be better to...

or

Does it make any sense to...

If the reasons are fairly obvious, I don't state them.  This gives other people a chance to assume some intellectual ownership of the suggestion, as in:

"Yes, that's a good idea, because < your obvious reason here >."

If the improvement is fairly obvious, but not so much as to make me look an idiot for not thinking of it, and the reason to do it reflects a value shared with the listener, then sometime I don't even suggest it, instead:

I wonder if there's a way to... < shared value statement here >

This is only for dealing with really touchy people - with most of my peers, I just let 'em have it!

Title: How can I tactfully suggest improvements to others' badly designed code during review?

Body:
I'm a great believer in clean code and code craftsmanship, though I'm currently at a job where this isn't regarded as a top priority. I sometimes find myself in a situation where a peer's code is riddled with messy design and very little concern for future maintenance, though it's functional and contains little to no bugs.

How do you go about suggesting improvements in a code review when you believe there is so much that needs changing, and there's a deadline coming up? Keep in mind that suggesting the improvements be made after the deadline may mean they'll be de-prioritized altogether as new features and bug-fixes come in.


答:
It is good that you know the concepts of Normalization and schema design. It is important to determine what is the system about? This affects your schema design greatly.

For example if the application is mostly about searching for information and reporting, then there is a type of schema called star schema which can be used. This is not a normalized data view but it helps reduce query complexity.

You can still have good schema by removing unnecessary look-up tables and place the data in files to be loaded by the application. This may cut your table by about 30%.

Your suggestion to create views over the existing schema is a great one also.

If you can determine the queries that will be required you could easily create the necessary views and the reports before you leave.

The last thing you should attempt is to teach users about database theory. Not only because it is usually a long way, but also because the can make mistakes and produce wrong results.

Most users want nothing but push a button. Some consider this too much to do :)

Title: Simplifying Database Schema for Extensibility by non-expert Users

Body:
Possible Duplicate:

  Is it necessary to create a database with as few tables as possible

I've recently started to develop a database for a ~10 person office (it's an internship for me), and I've come up with a conceptual design I am quite happy with. My employers though, wish for me to simplify my design (less tables) because they wish to extend onto the database when I leave them and go back to school.

Two of them have some MSAccess experience, and they seem to know the term "database normalization", but none of them have a CS background. To accommodate this, I'm already going to build in MSAccess, which I do not have fond feelings for. I've explained that the conceptual ER diagram is not a table schema, and still needs to be translated into one and some of the relationships in the ERD might be one table with an entity, and simplifying the schema will lead to a "less normalized" database. The feeling I'm getting is that what they would like is for the database to just barely make it as 2NF, and would love it if it were 1NF.

Should I explain that views can be defined on the schema to make querying simpler? But I do not know how I can explain to them how to extend onto the design once I am gone without trying to teach them database theory, which they don't have time for. Or I could just make it less normalized - they're the ones paying for it and using it? I don't know.


问:
Adapting to a team environment after developing alone for years
I have almost 5 years of experience as a web developer, and feel that I should be mid-level by now, but when I walk the walk I think I'm still pretty "junior" at it.

Here's what I think is the problem: For most of my career, I seldom had any real guidance by a more senior developer and zero experience with developer teams, so I sort of had to hack my way through a lot of solutions, and do everything cut-and-dried. In practice, there was no time to waste as the only guy responsible for writing or maintaining the code. Because of this, I have no formal knowledge of the actual software development process and eventually realized that coding is only a small part of the process.

I would greatly enjoy working with a developer team with solid experience, but I am afraid it would be a very bumpy ride trying to adjust with the knowledge base that is required for development processes. As a programmer who has flied solo most of his career, what can I do to prepare to "settle in" a job working with a larger team (at least 5) of seasoned pros?

Edit: To that end I haven't passed a lot of the technical tests given out by the "big shot" companies that thrive on their software and developers. By big I don't mean like Google, but reasonably successful in the geographic area.

答:
Be prepared to learn from your team members and realize that the way you have been doing things for the last several years may not be "up to snuff" with the rest of your team members. Code reviews will likely reveal this if they are a part of the development process.

Communication is also important, so if you haven't been doing so already, be prepared to document your code well, write external documentation, use detailed source control messages for your code changes and track issues/features/changes in issue (bug) tracking software. You need to allow your team members to see what you have done and understand why you have done it. Perhaps they will learn a thing or two from you in this manner.

Good luck!


答:
Can we handle, with our small number, both universes at the same time
  ?

Your team specifically?  That I dont know.

But many developers work in both worlds.  Its not that big a deal.  All thats really needed is a willingness to learn the new technology.  I think you'd be suprised how much can be learned in a couple of months working with the new technology.

I actually question the wisdom of outsourcing such an app if you are going to be the ones supporting it.  If they produce a piece of junk, and then up and dissappear, you're screwed.  A better approach might have been, if you needed extra resources, to bring contractors inhouse to help you develop it.


问:
Are there some good algorithms for implementing a Heap that minimizes fragmentation?
Right now I'm trying to create a Heap that requires 8-byte alignment, and was looking around online for some good methods that would minimize the amount of fragmentation. Less fragmentation is ideal, and even the ones that will slow down a lot are a consideration (but speed is also a sub-goal here)

Has anyone had any experience with Heaps who could let me know what to watch out for when going about this? Any input is appreciated

答: A coalescing heap will alleviate (but not avoid) fragmentation by coalescing adjacent free blocks.  Whenever you free a block, look at the next and previous blocks in your list.  If either (or possibly both) of them are free, then you can combine them to form one large block.  Some implementations defer the coalescing until allocation fails, at which point the allocator will walk the heap and look for adjacent free blocks to merge until it gets one large enough to satisfy the request.  This gives better average-case performance, but worst-case performance is much worse.  Merging blocks at deallocation time amortizes the cost over all deallocations, so there's not much variance between best-case and worst-case performance.</p>


答: My answer is: resharper, resharper, and... resharper :-) You could of course write some code snippets in Visual Studio or live templates for R# in order to minimize all repetitive tasks. Once you create a new code functionality, document it in Google docs, or your/company's wiki, because you may need it again in the future, and then you can just do a simple copy/paste work. Also make sure that you have a good knowledge of SOLID principles. Nothing can boost your productivity as much as good knowledge of design patterns and SOLID principles.</p>

Title: What are ways I can speed of development time when building applications?

Body:
I noticed that overtime with experience that the curve of learning shifts from trying to learn a language or technology (the way it works) to how to develop applications faster and with less code. I am very interested to see how other developers have minimized the time it takes to get applications to market.

I know for a fact that by learning just one thing it can save you a ton of time. For example I started learning lambda expressions and code that normally took 3 lines now only takes 1 and is alot faster to type.

Another angle is shortcuts and tools in an IDE itself. For instance I can't believe I didn't know how to remove unused using statements from my source code so I used to do it manually until I found out there was a tool in VS for removing them.

Are there any resources for learing faster ways of developing applications? Keyboard Shortcuts, tools, programs, references? Is there like a reference where one can learn these things? If not can you please share how you learned some of these tips?

NOTE: This question is geared towards .NET, C# and the Visual Studio IDE


问:
Schema/Code for respecting different schedules
We accept leads from lead providers. We only allow certain providers to post leads to us during certain days/times. Currently, we have 3 schedules, but we might add 1 or n more in the future:

Sunday @ 8AM - Friday @ 3PM -- all hours in between.

Monday - Friday from 8AM - 5 PM.

24 hours a day, every day.

In addition, we want to be able to one-off certain hours -- so, we would have told some of the lead providers, "I know you normally post 8 AM - 5 PM M-F, but Monday is a holiday, so don't post then."

The problem is that some lead providers are not setup to handle a schedule (or just ignore it if they want to sell us more leads). So, I now have to add this check into our system at the point in which we take in leads, and first check to see if that lead provider (they identify themselves in the XML they send) is allowed to post leads at this particular time.

I honestly don't know where to begin. Has anyone done this before? How did you handle it, and what is good/bad about your method?

答:
I would separate the data used to define the schedule from the generated schedule times - the logic to define a schedule will change a lot, probably, but the logic to tell if a given time falls in a schedule probably won't.  However, it's still reasonable to store only the definition of the schedule if you think you can encapsulate the logic to determine if a given time falls in a schedule.  If the check is mostly happening outside a DB this might not be too bad, but if you will be writing a lot of SQL that needs to know this, needs to use indexes, etc. then it's harder and you would be more likely to want generated schedule times.

For the generated tables, Tim Claason has a reasonable schema.  For the tables that create the schedule, they will pretty much record the options people entered on a data entry screen.  These may change - day of week, day of month, skip holidays, skip holidays but let people go the day after a holiday if they could have gone on a holiday - who knows what people will dream up?  So I would have some process that reads the definitions and blasts out the schedule start date/time - end date/time records for a lead provider for some date range out into the future.

This could be overkill if the rules are simple, but it sounds like they are reasonably complicated.


答:
You'll need to have the coding skills, but you also need to make interviewers comfortable with you willingness to get along with others. You need more than just wanting to be a better programmer.

Start analyzing the way you currently do things. Do you return to code and find what you wrote confusing and difficult to change? Are you repeating certain tasks over and over. Search SO sites or ask questions about how to do them better. You may not be able to inplement them. I currently program alone. I like agile development methods, but have had to adapt to my situation.

Don't just look for a team but find one that can/will teach you something. I prefer to ask questions about why things are done a certain way and get something beyond, "That's the way we've always done it." sort of answer. If everyone is going to get defensive, and not justify what they're doing, I don't feel I learn anything. Learning comes when you've discovered why you were right or wrong. Your mind has to be changed.

You may want to see where the team scores on The Joel Test.

Title: Adapting to a team environment after developing alone for years

Body:
I have almost 5 years of experience as a web developer, and feel that I should be mid-level by now, but when I walk the walk I think I'm still pretty "junior" at it.

Here's what I think is the problem: For most of my career, I seldom had any real guidance by a more senior developer and zero experience with developer teams, so I sort of had to hack my way through a lot of solutions, and do everything cut-and-dried. In practice, there was no time to waste as the only guy responsible for writing or maintaining the code. Because of this, I have no formal knowledge of the actual software development process and eventually realized that coding is only a small part of the process.

I would greatly enjoy working with a developer team with solid experience, but I am afraid it would be a very bumpy ride trying to adjust with the knowledge base that is required for development processes. As a programmer who has flied solo most of his career, what can I do to prepare to "settle in" a job working with a larger team (at least 5) of seasoned pros?

Edit: To that end I haven't passed a lot of the technical tests given out by the "big shot" companies that thrive on their software and developers. By big I don't mean like Google, but reasonably successful in the geographic area.


问:
Where can I find examples of functional specifications?
I am writing a functional specification for a software program (Mac OS X application to be exact). I want to improve this by looking at other (good) functional specifications, but I cannot find any.

Are there any (open-source) projects that have their specs publicly available so I can learn from them and improve my spec writing skills?

答: I suggest looking at the work of Karl Wiegers. His Process Impact site has a Goodies page that includes numerous sample documentation and documentation templates. I'd also highly suggest his books, Software Requirements and More About Software Requirements, which include more information about all aspects of requirements engineering and provide samples and examples.</p>


问:
Favoring Immutability in Database Design
One of the items in Joshua Bloch's Effective Java is the notion that classes should allow mutation of instances as little as possible, and preferably not at all.

Oftentimes, the data of an object is persisted to a database of some form. This has led me to thinking about the idea of immutability within a database, especially for those tables that represent a single entity within a larger system.

Something I have been experimenting with recently is the idea of trying to minimize the updates I do to table rows representing these objects, and trying to perform inserts instead as much as I can.

A concrete example of something I was experimenting with recently. If I know I might append a record with additional data later on, I'll create another table to represent that, sort of like the following two table definitions:

```<code>create table myObj (id integer, ...other_data... not null);
create table myObjSuppliment (id integer, myObjId integer, ...more_data... not null);
</code>```

It is hopefully obvious that these names are not verbatim, but just to demonstrate the idea.

Is this a reasonable approach to data persistence modeling? Is it worth trying to limit updates performed on a table, especially for filling in nulls for data that might not exist when the record is originally created? Are there times when an approach like this might cause severe pain later on?

答: Another possible reason for having an immutable database would be to support better parallel processing.  Updates happening out of order can mess up data permanently, so locking has to occur to prevent that, destroying parallel performance.  Lots of inserts of events can go in any order, and the state will at least be eventually right as long as all events are eventually processed.  However this is so hard to work with in practice compared to doing database updates that you would have to really need a lot of parallelism to consider doing things this way - I am not recommending it.


问:
Which popular object-oriented languages support readonly methods?
I thought that many object-oriented languages have a reserved keyword for methods which do not modify the state of an object. These methods often have names that start with get. AFAIK a "getter" is always related to a single object attribute and "accessor" is too general, so "readonly" may the right term for this kind of methods (?). To give an example:

```<code>object Timespan {
    attribute start
    attribute end

    // getter, not changing the state
    readonly method getStart    { return start }
    readonly method getEnd      { return end }

    // also not changing the state
    readonly method getDuration { return ( end - start ) }
}
</code>```

The compiler/interpreter should check that readonly methods have no side-effect by modifying object attributes. I wonder why this language feature is not more common - just naming a method getFoo does not ensure that it won't modify the object.

答: In C++ you can declare const member functions. Such methods can't modify object state ( not even potentially, i.e. they can't call non-const methods of the same object), and this is ensured by the compiler.


答:
Python:

```<code>@property
def foo():
    return self.__foo
</code>```

C#:

```<code>class Foo
{
    public int bar()
    {
        get
        {
            return 1;
        }
    }
}
</code>```

It's true that the Python example does not technically make things read-only, but "support" it is. A mechanism to communicate to other programmers that the method is read-only counts as support. And no, it does not simply have to be a trivial getter that only returns an instance field.

Title: Which popular object-oriented languages support readonly methods?

Body:
I thought that many object-oriented languages have a reserved keyword for methods which do not modify the state of an object. These methods often have names that start with get. AFAIK a "getter" is always related to a single object attribute and "accessor" is too general, so "readonly" may the right term for this kind of methods (?). To give an example:

```<code>object Timespan {
    attribute start
    attribute end

    // getter, not changing the state
    readonly method getStart    { return start }
    readonly method getEnd      { return end }

    // also not changing the state
    readonly method getDuration { return ( end - start ) }
}
</code>```

The compiler/interpreter should check that readonly methods have no side-effect by modifying object attributes. I wonder why this language feature is not more common - just naming a method getFoo does not ensure that it won't modify the object.

Body:
Python:

@property
def foo():
    return self.__foo

C#:

class Foo
{
    public int bar()
    {
        get
        {
            return 1;
        }
    }
}

It's true that the Python example does not technically make things read-only, but "support" it is. A mechanism to communicate to other programmers that the method is read-only counts as support. And no, it does not simply have to be a trivial getter that only returns an instance field.


答:
It may not look like a traditional software spec, but see:

https://www.relishapp.com/rspec

These are specs which also act as documentation and executable tests.

Note however, most successful is not created with a large detailed spec written up-front. The common alternative is an agile, iterative process.

Title: Where can I find examples of functional specifications?

Body:
I am writing a functional specification for a software program (Mac OS X application to be exact). I want to improve this by looking at other (good) functional specifications, but I cannot find any.

Are there any (open-source) projects that have their specs publicly available so I can learn from them and improve my spec writing skills?


答:
Given the constraints listed, I think that the best choice is C++/Qt.

C++ will do anything that C# will do, you'll have more access to 3rd party libraries, Qt itself is both cross-platform and available under LGPL if that fits your needs, your team would have better access to Qt than C#, the option would exist to provide for Linux & OS-X, etc.

Furthermore, even Microsoft has recently acknowledged that C#/.Net isn't all that they claimed it to be. Here's a talk by Herb Sutter that sheds some light on C++ for future development... http://channel9.msdn.com/posts/C-and-Beyond-2011-Herb-Sutter-Why-C

Honestly, the only place that I think C# would have a real advantage is if the developer can finish the C# version for a lot less $$$ than the C++ version, which is unlikely. Even so, if you're still thinking C#, you should also consider Java, because you still get most of the benefits that I've listed for C++/Qt.


问:
I can't remember programming 5 mins after learning?
I'm learning Java, and I found a great teacher. He explains everything perfectly. I understand it all. My problem, is that after learning a short section, for example "Nested If Statements" or "Many Methods and Instances", I can type it all great, but in 5 mins, after going on to a new section (when I'm comfortable with the last section) I forget the code to type for the last section. Any tips or techniques you guys use to remember code????

答: You have to simply start developing things, after doing some things a few time you will get to know how to do it in future projects. Its important that you just do it many times :)!</p>

OwnerDisplayName: Cole

OwnerDisplayName: Wesso


答:
The best way to learn how to code is to write code.  I have a saying "The more code I write, the more right I code."  Come up with a small sample application that you think will be helpful for you and code it.  Come back to http://www.stackoverflow.com if you have specific questions, and go to codereview.stackoverflow.com if you want others to look at your code and give you feedback.

Also read.  A lot.  Heres a list that'll get you started: https://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read

Title: I can't remember programming 5 mins after learning?

Body: I'm learning Java, and I found a great teacher. He explains everything perfectly. I understand it all. My problem, is that after learning a short section, for example "Nested If Statements" or "Many Methods and Instances", I can type it all great, but in 5 mins, after going on to a new section (when I'm comfortable with the last section) I forget the code to type for the last section. Any tips or techniques you guys use to remember code????

OwnerDisplayName: bittersweetryan


答: Practice, practice, read notes, practice, and practice.</p>


答:
Don't stress.  What you are talking about is "ephemeral".  These things (syntax, language quirks, etc.) will become natural through practice, and are constantly changing.

What is most important is that you learn to program.  The most important concepts will last throughout your career and will exercise your problem solving abilities, not your memory.  An IDE, Google, StackOverflow and practice can help you through the rest.


问:
Displaying and processing objects in a list?
I currently have code like this to display some objects that meet some criteria in a grid:

```<code>// simplified
void MyDialog::OnTimer()
{
    UpdateDisplay();
}

void MyDialog::UpdateDisplay()
{
    std::list<MyClass *> objects;
    someService_->GetObjectsMeetingCriteria(objects, sortField, sortDirection);

    for(std::list<MyClass *>::iterator it = objects.begin();
        it != objects.end() ; it ++)
    {
        AddObjectToGrid(*it);
    }

}
</code>```

This works fine.  Now the requirement has come in to process these objects when they meet some criteria.  The information on the objects can change quickly so it would be most desirable to check if an object meets criteria and then process it immediately and continue on in this fashion.

My question is how to best architect this to handle the display and processing.  I could simply add a method to process the object such as:

```<code>for(std::list<MyClass *>::iterator it = objects.begin();
    it != objects.end() ; it ++)
{
    ProcessObject(*it);
    AddObjectToGrid(*it);
}
</code>```

However ideally I'd check if an object meets the criteria immediately before processing it to ensure its acting on the most recent info. In this example, all the objects are checked to see if they match the criteria and then afterwards each one is processed.

Also I'm concerned this is coupling the processing code with the display code although I'm not sure how to separate them or if it's even necessary.  I could solve that like this:

```<code>void MyDialog::OnTimer()
{
    ProcessObjects();
    UpdateDisplay();
}
</code>```

But then I'm iterating over the list of objects twice, once to process and once to display.

Finally I could do something like:

```<code>// simplified
void MyDialog::OnTimer()
{
    ProcessAndDisplayObjects();
}

void MyDialog::ProcessAndDisplayObjects()
{
    std::list<MyClass *> objects;
    someService_->GetAll(objects, sortField, sortDirection);

    for(std::list<MyClass *>::iterator it = objects.begin();
        it != objects.end() ; it ++)
    {
        if(someService->MeetsCriteria(*it))
        {
          ProcessObject(*it);
          AddObjectToGrid(*it);
        }
    }
}
</code>```

Overall what's holding me up is I'm worried about coupling the display and processing code together and the code running efficiently because timely processing is critical.  How can I best structure this code?

答:
I'll describe the ideal first, then some good enoughs within the constraints you might have.  Ideally you want the processing code to be outside the dialog class, you want the processing to happen separately on a thread other than the gui thread, for the processing code to get notified when the data changes so that processing is needed, and then to notify the dialog to update the data rather than using a timer. (Timers have a problem of either being too granular or not granular enough, too much and they eat up cycles unnecessarily, not enough and the GUI is unresponsive.)

OK, so you probably aren't prepared to do separate threads and notifications, but it is still important to move the processing code outside the dialog. Your concern about coupling the two processes is well founded, even if it turns out to be a trivial issue for now, requirements and code change. This is your best approach for decoupling them, and it makes adding any of the other above features later much easier.  The important thing, even if the timer spawns both the processing and the update, is for the update to do as little as possible, i.e., call some function to get a value to put in the grid, and nothing else.  The processing should all be done by the time that starts. Assuming no other structural changes to your code, I'd go with something like:

```<code>OnTimer()
{
  if (!processor.IsReady())
    processor.process();
  UpdateDisplay()
}
</code>```

Later, if you want to spawn a new thread for the process() call, it is easy to do by calling processthread.start() or whatever instead of processor.process(); and returning, letting the next timer cycle pick up the data.  If you want to have a different way of launching the process routine (a notifier that the data has changed, or a second timer, or something), you can change the above to:

```<code>OnTimer()
{
  if (processor.IsReady())
    UpdateDisplay();
}
</code>```

Don't worry about iterating twice, unless the data set is really huge.  And if it is huge enough to worry about, all the more reason to look at doing it outside the GUI thread, because no matter how you factor it, it will cause your display to hiccup.  If your processor object is behind an interface, all the better, then you can refactor that later without affecting the dialog code. And you can add code in OnTimer() to check a flag to see if not only is the data processed, but has it changed since your last update, and skip it if not.

Body:
I'll describe the ideal first, then some good enoughs within the constraints you might have.  Ideally you want the processing code to be outside the dialog class, you want the processing to happen separately on a thread other than the gui thread, for the processing code to get notified when the data changes so that processing is needed, and then to notify the dialog to update the data rather than using a timer. (Timers have a problem of either being too granular or not granular enough, too much and they eat up cycles unnecessarily, not enough and the GUI is unresponsive.)

OK, so you probably aren't prepared to do separate threads and notifications, but it is still important to move the processing code outside the dialog. Your concern about coupling the two processes is well founded, even if it turns out to be a trivial issue for now, requirements and code change. This is your best approach for decoupling them, and it makes adding any of the other above features later much easier.  The important thing, even if the timer spawns both the processing and the update, is for the update to do as little as possible, i.e., call some function to get a value to put in the grid, and nothing else.  The processing should all be done by the time that starts. Assuming no other structural changes to your code, I'd go with something like:

OnTimer()
{
  if (!processor.IsReady())
    processor.process();
  UpdateDisplay()
}

Later, if you want to spawn a new thread for the process() call, it is easy to do by calling processthread.start() or whatever instead of processor.process(); and returning, letting the next timer cycle pick up the data.  If you want to have a different way of launching the process routine (a notifier that the data has changed, or a second timer, or something), you can change the above to:

OnTimer()
{
  if (processor.IsReady())
    UpdateDisplay();
}

Don't worry about iterating twice, unless the data set is really huge.  And if it is huge enough to worry about, all the more reason to look at doing it outside the GUI thread, because no matter how you factor it, it will cause your display to hiccup.  If your processor object is behind an interface, all the better, then you can refactor that later without affecting the dialog code. And you can add code in OnTimer() to check a flag to see if not only is the data processed, but has it changed since your last update, and skip it if not.


答: If you are just rote typing what the teacher shows, the knowledge will go in one ear and out the other.  Take the examples he gives, and change them a bit, play around.  If they're just exercises, it won't matter. By making even a simple change, like "I want to display the numbers sorted in reverse instead", or something, it forces you to understand the example instead of just copying it. Then take that after class and try to do more with it, extend it, incorporate it into something else. You'll find that your understanding goes up, and when understanding goes up, you don't have to remember as much. </p>


答:
It's like clothes in a closet.

Without something to hang them on, they will fall to the floor.

What you need to hang programming concepts on is one or more problems you're trying to solve.

Just typing stuff in, without having a problem you're trying to solve, is like throwing your clothes in the closet and expecting them to hang by themselves.


问:
How should I organize the words of a sentence for better outputs/maintenance and performance?
Having this sentence (consider many sentences in the future)

David Henderson Houston patented the first roll film for cameras in
  1881.

I can make questions like

1. Who patented the roll film?

2. When was the first roll film for cameras patented?

3. What did David Houston patent (in 1881)?

The answer will return some or all of the sentence above in a format of answering the who, when and what.

My question (and what I am trying to achieve) is to separate this sentence in such a way that I can save it in a DB, smartly and efficiently.

I thought of editing this sentence leaving only the main keywords/facts; let's say David Houston patented the roll film in 1881.

After this, I thought I have to organize the words. So a solution may be to create tables for nouns, verbs, adjectives... separating the sentence in the correct table. Every word will have its unique ID.

In the table answers, the answer will be saved in a form like 2,23,64,4 every ID is a word... and with some agorithm and sql magic (this is not my point now) it will return the David Houston patented the roll film in 1881 on the question who.

What do you think of my thinking of separating the sentences like I wrote above? What are your thoughts on how I should organize the words to access them through a database? Am I entirely off the correct path?

答:
I think before you consider a way to store it, you must decide on a consistent sentence structure.

With your current example (removing all prepositions)
David Houston patented the roll film in 1881.
All your sentences must follow this format:

Name | Action | Object | When

If this is the case then you can store data in just those 4 fields.  If you want to store answers as numbers then you would need a 5 tables, 1 for each Name, Action, Object, Date (each with 2 fields, an ID number and the description) and a 5th table to tie them all together like your | 2 | 23 | 64 | 4 | example.  If you have a lot of data this would be the best way to go, especially if David Houston also did hundreds or thousands other things that you would like to store.

Hope this helps.

OwnerDisplayName: kotsirokolos

OwnerDisplayName: Prediluted


答:
You could manually parse each sentence into its grammatical parts, as you would do in a sentence diagram.

Then you can make questions by removing one or more parts.

For example, you can remove the subject of the sentence, and replace it with "Who" or "What".

Or, you could remove the predicate, and ask: "What did (subject) do?"

Title: How should I organize the words of a sentence for better outputs/maintenance and performance?

Body:
Having this sentence (consider many sentences in the future)

David Henderson Houston patented the first roll film for cameras in
  1881.

I can make questions like

1. Who patented the roll film?

2. When was the first roll film for cameras patented?

3. What did David Houston patent (in 1881)?

The answer will return some or all of the sentence above in a format of answering the who, when and what.

My question (and what I am trying to achieve) is to separate this sentence in such a way that I can save it in a DB, smartly and efficiently.

I thought of editing this sentence leaving only the main keywords/facts; let's say David Houston patented the roll film in 1881.

After this, I thought I have to organize the words. So a solution may be to create tables for nouns, verbs, adjectives... separating the sentence in the correct table. Every word will have its unique ID.

In the table answers, the answer will be saved in a form like 2,23,64,4 every ID is a word... and with some agorithm and sql magic (this is not my point now) it will return the David Houston patented the roll film in 1881 on the question who.

What do you think of my thinking of separating the sentences like I wrote above? What are your thoughts on how I should organize the words to access them through a database? Am I entirely off the correct path?

OwnerDisplayName: mbeckish


答:
Depending on your learning style, it may be important for you to understand the motivation behind using certain constructs in your programs.  Many programming books are written so that they build these concepts upon each other chapter by chapter.  Try skimming ahead by one chapter while you're doing the exercises for the prior one.

This way, you can say, "okay, it makes sense to use an if statement in this case, but I know that in another scenario, it's more effective to use a switch statement."  That way, the concepts are linked in your mind, and you can always briefly check back for any syntax specifics that crop up (and those will definitely become second nature before long).

kylben's idea of extending yourself by modifying each assignment slightly is also a great way to keep on your toes with things.  You can also come up with "capstone" projects for every couple of chapters and challenge yourself to build something with everything you know so far.


答:
I couldn't agree more to what the other people have been saying here, programming is learned by doing. The more coding you do generally the more you learn. Having said that many other things are important to learn how to code right, for example never forget to read by looking at how other people learn, read on on new tools and technolgies and browse daily in Q&A such as programmers.com.

As for actually remembering what you learn, once you finished writing a bit of code then explain to yourself silently what you actually have done or explain to a fellow coder. By doing this I find that I remember much more clearly and it gives me the opportunity to reflect on what I have done. Also try to challenge yourself by coming up to alternate ways to write the code you've just written, better or worse. Play around with the problem you solved and think how you would need to change your code if the problem its intended to solve would change slightly.


问:
Is testing the easiest way to contribute to an Open Source Project?
I want to contribute to an open source project, but I don't know much about unit testing. I want to learn how to test and then practice my skills on an open source.

Will this also be acknowledged as a contribution.

I want to first get my name out there and then conc. on development.

答:
Other than writing tests, here are other works that are relatively easy to get started with while you're familiarizing yourself with the project:

triaging bugs

testing patches subitted on the bug tracker

preliminary patch review

writing docs

for smaller projects, packaging for package managers that they had not supported yet


答:
Since you're (at least apparently) using C++, I'd try to write the code to fit a little more closely with how the standard iterators and algorithms do. I'd start with a small facade to give your "grid" an iterator interface:

```<code>// warning: untested code.
struct grid_proxy {
    grid_proxy &operator=(MyClass const &item) {
        AddObjectToGrid(item);
        return *this;
    }
};

class grid_iterator : public std::iterator<std::output_iterator_tag, MyClass> {
public:
    operator*() { return grid_proxy(); }
    grid_iterator operator++() { return *this; }
    grid_iterator operator++(int) { return *this; }
};
</code>```

Then I'd write a small algorithm that probably should be in the library, but isn't: a transform_if:

```<code>template <class InputIterator, class OutputIterator, class UnaryOperation, class Predicate>
void transform_if(InputIterator start, InputIterator stop,
                  OutputIterator out,
                  UnaryOperation op,
                  Predicate pred)
{
    while (start != stop) {
        if (pred(*start))
            *out++ = op(*start);
        ++start;
    }
}
</code>```

With these, your overall operation becomes something like:

```<code>std::list<MyClass *> objects;
someService_->GetAll(objects, sortField, sortDirection);

transform_if(objects.begin(), objects.end(), grid_iterator(), MeetsCriteria());
</code>```

At the moment, I've assume that MeetsCriteria will be written as a functor rather than a member function. If you can use C++11 features, you might want to consider using a lambda instead.

In any case, this provides pretty fair de-coupling of most of the code. transform_if simply knows that it's writing to an iterator -- only the grid_iterator has any clue that AddObjectToGrid is involved. A different iterator can produce the output entirely differently.

Likewise, transform_if doesn't really care at all about the criteria or how it's determined, as long as it can be invoked like a function with the right signature.

While this does impose a little overhead in writing a conforming iterator type and such, it has a few advantages. The aforementioned decoupling is certainly handy. The fact that anybody who knows the C++ library reasonably well will know what's going on almost without a second thought is also a very good thing as a rule.

Title: Displaying and processing objects in a list?

Body:
I currently have code like this to display some objects that meet some criteria in a grid:

```<code>// simplified
void MyDialog::OnTimer()
{
    UpdateDisplay();
}

void MyDialog::UpdateDisplay()
{
    std::list<MyClass *> objects;
    someService_->GetObjectsMeetingCriteria(objects, sortField, sortDirection);

    for(std::list<MyClass *>::iterator it = objects.begin();
        it != objects.end() ; it ++)
    {
        AddObjectToGrid(*it);
    }

}
</code>```

This works fine.  Now the requirement has come in to process these objects when they meet some criteria.  The information on the objects can change quickly so it would be most desirable to check if an object meets criteria and then process it immediately and continue on in this fashion.

My question is how to best architect this to handle the display and processing.  I could simply add a method to process the object such as:

```<code>for(std::list<MyClass *>::iterator it = objects.begin();
    it != objects.end() ; it ++)
{
    ProcessObject(*it);
    AddObjectToGrid(*it);
}
</code>```

However ideally I'd check if an object meets the criteria immediately before processing it to ensure its acting on the most recent info. In this example, all the objects are checked to see if they match the criteria and then afterwards each one is processed.

Also I'm concerned this is coupling the processing code with the display code although I'm not sure how to separate them or if it's even necessary.  I could solve that like this:

```<code>void MyDialog::OnTimer()
{
    ProcessObjects();
    UpdateDisplay();
}
</code>```

But then I'm iterating over the list of objects twice, once to process and once to display.

Finally I could do something like:

```<code>// simplified
void MyDialog::OnTimer()
{
    ProcessAndDisplayObjects();
}

void MyDialog::ProcessAndDisplayObjects()
{
    std::list<MyClass *> objects;
    someService_->GetAll(objects, sortField, sortDirection);

    for(std::list<MyClass *>::iterator it = objects.begin();
        it != objects.end() ; it ++)
    {
        if(someService->MeetsCriteria(*it))
        {
          ProcessObject(*it);
          AddObjectToGrid(*it);
        }
    }
}
</code>```

Overall what's holding me up is I'm worried about coupling the display and processing code together and the code running efficiently because timely processing is critical.  How can I best structure this code?

Body:
Since you're (at least apparently) using C++, I'd try to write the code to fit a little more closely with how the standard iterators and algorithms do. I'd start with a small facade to give your "grid" an iterator interface:

// warning: untested code.
struct grid_proxy {
    grid_proxy &operator=(MyClass const &item) {
        AddObjectToGrid(item);
        return *this;
    }
};

class grid_iterator : public std::iterator<std::output_iterator_tag, MyClass> {
public:
    operator*() { return grid_proxy(); }
    grid_iterator operator++() { return *this; }
    grid_iterator operator++(int) { return *this; }
};

Then I'd write a small algorithm that probably should be in the library, but isn't: a transform_if:

template <class InputIterator, class OutputIterator, class UnaryOperation, class Predicate>
void transform_if(InputIterator start, InputIterator stop,
                  OutputIterator out,
                  UnaryOperation op,
                  Predicate pred)
{
    while (start != stop) {
        if (pred(*start))
            *out++ = op(*start);
        ++start;
    }
}

With these, your overall operation becomes something like:

std::list<MyClass *> objects;
someService_->GetAll(objects, sortField, sortDirection);

transform_if(objects.begin(), objects.end(), grid_iterator(), MeetsCriteria());

At the moment, I've assume that MeetsCriteria will be written as a functor rather than a member function. If you can use C++11 features, you might want to consider using a lambda instead.

In any case, this provides pretty fair de-coupling of most of the code. transform_if simply knows that it's writing to an iterator -- only the grid_iterator has any clue that AddObjectToGrid is involved. A different iterator can produce the output entirely differently.

Likewise, transform_if doesn't really care at all about the criteria or how it's determined, as long as it can be invoked like a function with the right signature.

While this does impose a little overhead in writing a conforming iterator type and such, it has a few advantages. The aforementioned decoupling is certainly handy. The fact that anybody who knows the C++ library reasonably well will know what's going on almost without a second thought is also a very good thing as a rule.


问:
How can I properly manage commits, prevent feature conflicts, and manage dependencies with a VCS?
It’s become an annoying factor of working with large teams: how do you manage checkins and prevent feature conflicts and manage dependencies with source control properly?

Currently at my workplace we use TFS 2008 and we're migrating to TFS 2010 in early December. Firstly any source control is better than none but what approach has anyone found useful to prevent multiple checkins and rollback all over source control history? Is a volatile trunk the best way to go or branch off when your implementing a new feature and once you're happy merge back into the trunk?

I'd really like to hear other people experiences and perhaps some best practices to managing source control.

答:
I've never used TFS 2008/2010 but from what I have read in various forums there are much negativity about using TFS for version control. This has made me stay clear from TFS from so far.

I'm currently using SVN and Git, I find them both good for small teams or single man team but wouldn't personally recommend SVN for a large team.

I've had my eyes on PlasticSCM for and will try to that in the near future.

I apologize for not answering your specific question, would have posted a comment if my privileges allowed me to.


答:
I think git makes all other source control software obsolete. Branching and merging are easy, and if there are problems, it gets contained, but a lot of problems get avoided by how it encourages very frequent commits, branching, and merging.  Each user gets a full copy of the repo (this can be pruned, but I work with a pretty huge code-base and it is not a problem), so there's something of an automatic backup.  Commits/push/pull are quick, and one of the most important things is that it breaks the coupling between file name and tracking. The file data, including the name and path, is a data blob that is referenced by a tree node, that is independent of paths.  This is not only safer, but certain kinds of "don't  ever do that" issues in something like SVN are not a problem. It can be used as a traditional hub configuration or peer to peer, and those uses can be mixed freely in the same setup. It's cryptographically secure against undocumented insertions. And it is very fast.

I find I use it at home now all the time, just to keep track of documents and sync them between computers, because its easier to commit and push to the file server than it is to back it up to the server or save it there.

The drawback is a bit of a steep learning curve, since it breaks all the rules that people are used to with source control, in subtle ways, but its a short steep learning curve.

Title: How can I properly manage commits, prevent feature conflicts, and manage dependencies with a VCS?

Body:
It’s become an annoying factor of working with large teams: how do you manage checkins and prevent feature conflicts and manage dependencies with source control properly?

Currently at my workplace we use TFS 2008 and we're migrating to TFS 2010 in early December. Firstly any source control is better than none but what approach has anyone found useful to prevent multiple checkins and rollback all over source control history? Is a volatile trunk the best way to go or branch off when your implementing a new feature and once you're happy merge back into the trunk?

I'd really like to hear other people experiences and perhaps some best practices to managing source control.


答:
I advocate one branch per feature as it allows great flexibility when deciding which features to ship & which to defer.

How well that works in your situation is dependent on how well your VCS handles branches and more importantly merging.  DVCS like Git & Mercurial make this a relatively trivial exercise.  SVN less so.  I've managed to avoid TFS though I have read a lot about it, mostly uncomplimentary I'm afraid.  If you're stuck with TFS do a small pilot release based on one feature per branch & see how well the merging goes for you.


答:
This bears a very close relationship with what are known as "Slowly Changing Dimensions" in the data warehousing world, and "Temporal" or "Bi-Temporal" tables in other domains.

The basic construct is:

Always use a generated surrogate key as the primary key.

The unique identifier of whatever you are describing becomes the "logical key".

Each row should have at least a "ValidFrom" timestamp and optionally a "ValidTo" timestamp and even more optionally a "Latest Version" flag.

On the "creation" of a logical entity you Insert a new row with a "Valid From"  of current timestamp. The optional ValidTo set to "forever" (9999-12-31 23:59:59) and Last Version to "True".

On a subsequent update of the logical entity. You at least insert a new row as above. You may also need to adjust the ValidTo on the previous version to "now() - 1 second" and the Latest Version to "False"

On logical deletion (this only works with the ValidTo timestamp!) you set the ValidTo flag in the current row to "now() -1 second".

The advantages of this scheme is that you can recreate the "state" of your logical entity at any point in time, you have a history of your entity over time and you minimize contention if your "logical entity" is heavily used.

The disadvantages are you store a lot more data, and you need to maintain more indexes (at the very least on Logical Key + ValidFrom + ValidTo). An index on Logical Key + Latest Version greatly speeds up most queries. It also complicates your SQL!

Whether this is worth doing unless you really need to maintain a history and have a requirement to recreate the state of your entities at a given point in time is up to you.

Title: Favoring Immutability in Database Design

Body:
One of the items in Joshua Bloch's Effective Java is the notion that classes should allow mutation of instances as little as possible, and preferably not at all.

Oftentimes, the data of an object is persisted to a database of some form. This has led me to thinking about the idea of immutability within a database, especially for those tables that represent a single entity within a larger system.

Something I have been experimenting with recently is the idea of trying to minimize the updates I do to table rows representing these objects, and trying to perform inserts instead as much as I can.

A concrete example of something I was experimenting with recently. If I know I might append a record with additional data later on, I'll create another table to represent that, sort of like the following two table definitions:

```<code>create table myObj (id integer, ...other_data... not null);
create table myObjSuppliment (id integer, myObjId integer, ...more_data... not null);
</code>```

It is hopefully obvious that these names are not verbatim, but just to demonstrate the idea.

Is this a reasonable approach to data persistence modeling? Is it worth trying to limit updates performed on a table, especially for filling in nulls for data that might not exist when the record is originally created? Are there times when an approach like this might cause severe pain later on?


问:
What is easier to do with web applications compared to native GUI applications?
I have the impression that more and more applications with a user interface use HTML+CSS+JavaScript client-side instead of a native GUI framework.

I wounder what are the most important driving forces for this? or in other words what are native GUI frameworks lacking to be competitive? e.g. is it easier to do some kind of things with HTML+CSS+JavaScript than with native GUI frameworks.

If we suppose the application is a client-server application where the client has a graphical user interface. What is the most important things that are easier to do in HTML+CSS+JavaScript than in the most popular native GUI frameworks?

答:
If it is pure UI + some data manupulation that can be done remotely, the web based application would suffice.
Native code comes into picture when you need to do some costly-operations or access some resources on the host (i.e) say you want to write an application like "wireShark"  to moniter your ethernet interface on your computer.

Now comes the combinations,

Pure web-based:
it is for light weight applications, that doesnot need much of processing on the host side. Pro's: easy deployment through servers, Con's: can't do much.

Pure native code:
Pro's: All powerful, Con's: deployment & maintenance headache.

The mix of Web-based + Native Code Plugin:
Pro's: This is interesting it is a mix of boath, a web-front-end & a native code backend.Yeah, a little easy to deploy & is powerful.
Cons: needs knowledge of both the sides, browser support will be a headache for the plugin development i.e, each browser(IE,FFX,Chrome) is special in a way.


问:
What's the difference between syntax and semantics?
I've always thought that referring to the syntax of a language was the same as referring to the semantics of a language. But I've been informed that apparently that's not the case. What's the difference?</p>

答:
Semantics describe the logical entities of a programming language and their interactions. Syntax defines how these are expressed in characters.

For example, the concept of pointer arithmetic is part of C's semantics; the way the + and - operators can be used to express pointer operations are part of its syntax.

Sometimes, two languages share part of their semantics, but the syntax differs wildly (e.g. C# and VB.NET - both use value types and reference types, but the characters you type to define them are different); in other cases, two languages are syntactically similar, but the semantics don't match up (consider Java vs. JavaScript, where the similarities often confuse beginners).


答:
Some of the Good practices that we really follow and helped us a lot:

1) Make sure you dont have a writable copy of the file in your local and you always check out to edit. (If at times you have to work local, then try to merge it in source control before EOD.)

2) Label your files periodically, after any small significant milestones.

3) Give good checkout or checkin comments. This will help when you review, sometimes you dont have to open and compare between versions.


答:
Firstly, a disclaimer. It is difficult to say what is the best way of managing your source, since we are not aware of how your team or teams work on a day to day basis.

Generally, it is better to work on the trunk. For each major release, branch it - so that bug fixes for the release version are on the branch which can be merged back into the trunk. All developers work on the trunk and commit code regularly (minimum once a day).

Merging new code in regularly minimises the pain of merging in large chunks of code in a massive integration phase. By spreading out the pain, you'll feel it less. The more often your team members commit the code, the less they'll have to merge - because they'll always be on the latest source.


答: Do not use any intellisense or autocomplete while learning (if you are using..). Try to type every syntax on your own and correct them on your own from the compiler results. Also dont do this while you are with your teacher. Practice when you are at home...</p>