问:
Using prefix incremented loops in C#
Back when I started programming in college, a friend encouraged me to use the prefix incrementation operator ++i instead of the postfix i++, citing that there was a slight chance of better performance with no real chance of a downside. I realize this is true in C++, and it's become a general habit that I continue to do.

I'm led to believe that it makes little to no difference when used in a loop in C#, regardless of data type. Apparently the ++ operator can't be overridden. Nevertheless, I like the appearance more, and don't see a direct downside to it.

It did astonish a coworker just a moment ago though, he made the (fairly logical) assumption that my loop would terminate early as a result. He's a self-taught programmer, and apparently never came across the C++ convention. That made me question whether or not the equivalent behavior of pre- and post-fix increment and decrement operators in loops is well known enough.

Is it acceptable for me to continue using ++i in looping constructs because of style preference, even though it has no real performance benefit? Or is it likely to cause confusion amongst other programmers?

Note: This is assuming the ++i convention is used consistently throughout all code.

答:
It's true that i++ and ++i are different operations. They have the same side effect (modifying the stored value of i), but they yield different values, and as Karl Bielefeldt's answer points out an unoptimized implementation of i++ may have to store the previous value of i in a temporary.

But if you're using them in a context where the result is not used, there should be no difference at all.

For example, in a C-style for loop, the third expression in the loop header is evaluated only for its side effects; any value it yields is quietly discarded. These two loops:

```<code>for (i = 0; i < COUNT; i ++) {
    // ...
}

for (i = 0; i < COUNT; ++ i) {
    // ...
}
</code>```

have identical semantics, and if your compiler doesn't generate identical, or at least equivalent, code for both you should probably find a better compiler.

So in this context, the choice between i ++ and ++ i should be purely one of style. If you have a coding standard, follow it. If you don't, just be consistent.

If you're using either i ++ or ++ i in a context where the result is used, then performance isn't going to be a factor; use whichever one gives you the answer you need. Or consider whether your code might be cleaner if you rearrange it so you're not using the result of i ++ or ++ i.

Title: Using prefix incremented loops in C#

Body:
It's true that i++ and ++i are different operations. They have the same side effect (modifying the stored value of i), but they yield different values, and as Karl Bielefeldt's answer points out an unoptimized implementation of i++ may have to store the previous value of i in a temporary.

But if you're using them in a context where the result is not used, there should be no difference at all.

For example, in a C-style for loop, the third expression in the loop header is evaluated only for its side effects; any value it yields is quietly discarded. These two loops:

for (i = 0; i < COUNT; i ++) {
    // ...
}

for (i = 0; i < COUNT; ++ i) {
    // ...
}

have identical semantics, and if your compiler doesn't generate identical, or at least equivalent, code for both you should probably find a better compiler.

So in this context, the choice between i ++ and ++ i should be purely one of style. If you have a coding standard, follow it. If you don't, just be consistent.

If you're using either i ++ or ++ i in a context where the result is used, then performance isn't going to be a factor; use whichever one gives you the answer you need. Or consider whether your code might be cleaner if you rearrange it so you're not using the result of i ++ or ++ i.


问:
Besides macros, are there any other metaprogramming techniques?

Possible Duplicate:

  Programming languages with a Lisp-like syntax extension mechanism

I'm making a programming language, and, having spent some time in Lisp/Scheme, I feel that my language should be malleable.  Should I use macros, or is there something else I might/should use?  Is malleable syntax even a good idea?  Is it perhaps too powerful a concept?

In doing some research, I found fexprs.  I don't really understand what these are.  Help with that in an answer too please.

Is it possible to have a language with macros/something-of-a-similar-nature without having s-expressions?

答:
You might want to take a look at Ruby, which has a great deal of support for metaprogramming.  The book Eloquent Ruby covers the language well, with a significant amount of attention to metaprogramming in the later chapters.  There is also a book called Metaprogramming Ruby that is well-reviewed, but which I have not personally read yet.

Metaprogramming in Ruby is far more flexible (and powerful . . . and dangerous) than what is provided by .NET's Reflection libraries (since Guy Coder mentioned C# in his answer, I thought this comparison might be useful).  In Ruby, you can use hooks to dynamically select which mixin modules you want to add to a class at runtime, use "method_missing" for flexible error handling and delegation, use monkey patching to choose what code to add in dynamically, and get yourself into all kinds of awesomely amazing trouble writing self-modifying code.  This makes Ruby a very powerful language for, e.g., writing your own domain-specific language (DSL).

Note:  I used a lot of jargon in the second paragraph.  My hope is that this will provide people who are interested in more information with search terms for web searches, in case someone wants to know more but isn't ready to buy a book on the topic yet.

ContentLicense: CC BY-SA 3.0


问:
Reasons for Pair Programming
I've worked in a few shops where management has passed the idea of pair programming either to me or another manager/developer, and I can't get behind it at all.  From a developer stand-point I can't find a reason why moving to this coding style would be beneficial, nor as a manager of a small team have I seen any benefit.

I understand that it helps on basic syntax errors and can be helpful if you need to hash something out, but managers that are out of the programming loop seem to keep seeing it as a way of keeping their designers from going to Facebook or Reddit than as a design tool.

As someone close to the development floor that apparently can't quite understand from a book tossed my way or a wiki page on the subject... from a high level management position, what are the benefits of Pair Programming when dealing with Scrum or Agile environments?

答:
Less Errors in the final code (efficiency)

Not completely replacing code reviews but highly effective for getting things right early on. There is research out there that points in that direction.

Faster completion (effectiveness)

There is several research pointing this out. When it comes to complex features 2 heads are simply more effective. Experience in Pairing is a must for this.

(note: This is your salespitch for the manager: Financially a sane decision because you get more efficient trough lower number of bugs and more  effective by faster completion)

Teaching Juniors

You can add a junior directly to a more experienced programmer. If you have a group of absolute beginners, it's easy to stick around and let them, as pairs,  figure the basics out. Stick around and give advice. The concept is apparently very old and stems from craftsmanship.

Title: Reasons for Pair Programming


问:
How can I figure out if programming is right for me?
I have an IT background and was pretty confident until an opportunity came up at work to go into programming(C#). I have never programmed before this, and the software I am programming for is a program I have never used before (a 3D modeling software).

It has been 6 months since then and I feel like giving up. I didn't get much training... about 3 weeks of training spread out over the last 6 months.

I think I would be good at programming but this experience is making me rethink my decision. I'm not sure if it's just me, or if this frustration is normal.

How can I figure out if programming is right for me?

答:
I just thrown a book about C# away recently - since it has no value for me.

But I can confirm, frustration and bugs are considered as "normal".

While it's not a deadline sitting in the back of your neck - don't worry.

On the other hand - once it works like a charm it can be fun indeed.

When delivering extraordinary results - they might call you "Sir" :)

Regarding your question if it's the right job for you -
this depends, if you want to learn new things every day - whether or not.
Also, if you have the patience and the nuts to tackle problems.

I constantly apply TDD methodology - but this takes several years to learn.
Having a 3 weeks quick-starter course might bring you nowhere,
it's all about making mistakes and learning from them.

Everybody hates bugs and malfunction - but one can grow with them.
What I mean is, that making (or even provoking) errors is not necessarily a bad thing.

Probably the best tip I can give you is, to break things down into smaller milestones.

Because if the goals you've set are completely out of reach - this is what causes frustration.

I learned debugging on a Nintendo SNES - I was cheating like a hoe and got money from a console magazine for providing them with fresh cheats. Later on I got an Atari ST and learned to code Omikron Basic ... and I'm still here, currently self-employed as JS wizard :)

Your situation, as described, is rather "learning it the hard way"...
I'd also suggest learning it with way more basic applications than that.
A good language reference is all one needs, and maybe good examples.


问:
What is the relationship between the command line, the OS and the microprocessor?
I'm not totally clear on how using the command line differs from working through the OS' interface using an editor for example. Obviously the UI is different but I want to understand how the command line interacts with the kernel and microprocessor, and how this compares to how kernel interfaces with the OS' GUI. I know I'm missing several layers of abstraction but would be grateful for someone to explain this.</p>

答:
The command line is just another interface to the operating system.  It's more easily understood if you call it a command interpreter.  What it does is input commands in text form, parse them to determine their meaning, and make calls to the underlying OS based on the meaning.

It's not that different from what a graphical command interpreter does, such as Windows's "Explorer" shell.  It inputs commands from the keyboard and mouse, interprets them according to the UI rules to determine their meaning, and makes calls to the underlying OS based on the meaning.

For example, if I'm at the DOS prompt, and I type myProgram.exe, it will search the current directory and the path and, if it finds myProgram.exe, make a call to the OS function that launches a new process, spinning up an instance of the program.

The equivalent operation in the GUI would be to double-click on the icon for myProgram.exe, or a shortcut to it.  Since the exact location of the program is already known from the context, it doesn't have to search for the EXE; it just makes a call to the OS function that launches a new process, spinning up an instance of the program.

None of these things have much of anything to do with the microprocessor, except in the sense that everything runs on the CPU.  If you meant to ask if commands input by the command line talk directly to the CPU, the answer is no.  They're described in a human-readable language, and like any other human-readable command input to a computer, (such as programming languages,) they have to be parsed according to formally-specified grammar rules first.


问:
How to handle this unfortunately non hypothetical situation with end-users?
I work in a medium sized company but with a very small IT force.

Last year (2011), I wrote an application that is very popular with a large group of end-users.  We hit a deadline at the end of last year and some functionality (I will call funcA from now on) was not added into the application that was wanted at the very end.  So, this application has been running in live/production since the end of 2011, I might add without issue.

Yesterday, a whole group of end-users started complaining that funcA that was never in the application is no longer working.  Our priority at this company is that if an application is broken it must be fixed first prior to prioritized projects.

I have compared code and queries and there is no difference since 2011, which is proofA.  I then was able to get one of the end-users to admit that it never worked proofB, but since then that end-user has went back and said that it was working previously... I believe the horde of end-users has assimilated her.  I have also reviewed my notes for this project which has requirements and daily updates regarding the project which specifically states, "funcA not achieved due to time constraints", proofC.

I have spoken with many of them and I can see where they could be confused as they are very far from a programming background, but I also know they are intelligent enough to act in a group in order to bypass project prioritization orders in order to get functionality that they want to make their job easier.

The worst part is is that now group think is setting in and my boss and the head of IT is actually starting to believe them, even though there is no code or query changes.  As far as reviewing the state of the logic it is very cut and dry to the point of if 1 = 1, funcA will not work.

So, this is the end of the description of my scenario, but I am trying not to get severally dinged on my performance metrics due to this which would essentially have me moved to fixing a production problem that doesn't exist that will probably take over 1 month.

答:
This is not an issue that can be dealt with on facts - if you try, you will loose credibility.

First, accept that the software is "broken" - as it it does not do what the users want it to do. Now, accept that the users have a right to have the software do what they want it to do - thats what the software is therefore.  So what we have is defective software and an engineer refusing to fix it.....

As a result if the system you run to set priorities, these users cannot get their software fixed by going through the normal channels, so they are using side channels and escalating half truths higher up the food chain to try to out maneuver the system, in the mean time, making your KPI's look bad(your main concern should be the customers, not your KPI's) - Your KPI's are considered "collateral damage" if they like you, or a beneficial side effect if they don't. However, they do have some control over how much happens - best they like you.

So what is happening is the system is broken, and everyone is trying to manipulate things to get what they want. They want a feature, and you want to keep your spotless KPI's.

Unless you can fix the system or learn to play office politics real quick, game over:  you lose.

Note : None of this discussion involves Dead lines, bug vs feature discussions, who is paying etc. These are Facts - and facts do not matter (well, they sort of do, but they can be manipulated in so many ways....) in office politics.


答:
Quick Answer: most of the benefits and costs are posted in Wikipedia however, let's look at it from a bitdifferent angle.

I would like to mention specific cases of pair programming benefits that apply to agile/scrum development environment, taken from blog post:

The success or failure of software is dependent on its quality, and Pair Programming directly improves quality in numerous ways. When two developers work together design pattern quality improves as the pair develops short, simple, and easy to maintain code with fewer bugs. Bugs are a major quality concern in software development; with two sets of eyes writing the code, more mistakes are caught, thereby decreasing the cost of development. Bugs found late in the development process are often costly to fix. Finding software defects early prevents and helps deter difficult problems down the road. Complexity often arises in programming, and two minds working to solve a problem together can see more options and draw conclusions more quickly than one.

in Summary:

Promotes team communication

Promotes efficient application knowledge transfer

Promotes accountability on design approach

Results in better, easy to maintain code

Helps eliminate buggy code in its early stage

Increases team productivity since the team members will have undivided attention during coding

Improves communication and collaboration skills of the team members

Builds camaraderie at workplace

Makes work more fun

Title: Reasons for Pair Programming

Body:
I've worked in a few shops where management has passed the idea of pair programming either to me or another manager/developer, and I can't get behind it at all.  From a developer stand-point I can't find a reason why moving to this coding style would be beneficial, nor as a manager of a small team have I seen any benefit.

I understand that it helps on basic syntax errors and can be helpful if you need to hash something out, but managers that are out of the programming loop seem to keep seeing it as a way of keeping their designers from going to Facebook or Reddit than as a design tool.

As someone close to the development floor that apparently can't quite understand from a book tossed my way or a wiki page on the subject... from a high level management position, what are the benefits of Pair Programming when dealing with Scrum or Agile environments?

ContentLicense: CC BY-SA 4.0


答: In case of reality failure like this, the best thing is to move forward.  Instead of arguing about the past, talk about making it work and how easy or difficult that will be.  It doesn't really matter if the issue is fixing it or implementing for the first time.  If management wants A done before B make it so.</p>

Title: How to handle this unfortunately non hypothetical situation with end-users?

Body:
I work in a medium sized company but with a very small IT force.

Last year (2011), I wrote an application that is very popular with a large group of end-users.  We hit a deadline at the end of last year and some functionality (I will call funcA from now on) was not added into the application that was wanted at the very end.  So, this application has been running in live/production since the end of 2011, I might add without issue.

Yesterday, a whole group of end-users started complaining that funcA that was never in the application is no longer working.  Our priority at this company is that if an application is broken it must be fixed first prior to prioritized projects.

I have compared code and queries and there is no difference since 2011, which is proofA.  I then was able to get one of the end-users to admit that it never worked proofB, but since then that end-user has went back and said that it was working previously... I believe the horde of end-users has assimilated her.  I have also reviewed my notes for this project which has requirements and daily updates regarding the project which specifically states, "funcA not achieved due to time constraints", proofC.

I have spoken with many of them and I can see where they could be confused as they are very far from a programming background, but I also know they are intelligent enough to act in a group in order to bypass project prioritization orders in order to get functionality that they want to make their job easier.

The worst part is is that now group think is setting in and my boss and the head of IT is actually starting to believe them, even though there is no code or query changes.  As far as reviewing the state of the logic it is very cut and dry to the point of if 1 = 1, funcA will not work.

So, this is the end of the description of my scenario, but I am trying not to get severally dinged on my performance metrics due to this which would essentially have me moved to fixing a production problem that doesn't exist that will probably take over 1 month.


答:
Programming requires alot of drive, and dedication to get to the point where you know what you are doing and are exceptional at doing what you know.

For you to truly succeed, programming has to become a way of life; rather than a desired profession. It needs to grow into an obsession that starts at the resistor and extends to the entire network that comprises the internet.

Personally, I recommend you stick with it because I personally struggled alot too. I wasnt able to really start thinking like a programmer until about a year and a few months after I started studying computer science full time (often 12+ hours a day).

I spent the entire time just studying everything I could comprehend on the internet related to computers. I used the complexity of programming to make me even more stubborn and motivated everytime I was overwhelmed. I spent alot of time just reading other peoples code and manually typing it in myself. Whenever I found something I didnt understand, I looked it up. Everyday, diving deeper and deeper into my forced fascination and obsession. (I even started having programming dreams where I was communicating with programs via binary, Too deep! Lmao)

It wasnt always easy. I definitely felt like I wasnt cut out for it ALL THE TIME, but one day I was able to just jack-in and start coding like crazy. It just started to make more and more sense to me, with every line I imagined. It all started coming together to the point where I could go back and rewrite my code way more optimal and effcient only a few hours later.

After that I never doubted if I was capable of becoming a programmer. You have to really want it. There isnt many people who have the required dedication to overcome the tempest that is required to evolve into a computer scientist.

However, When you actually get to the point where you can build complicated software systems that was born from your creativity and ingenuity, the reward of accomplishment you feel far exceeds the struggle you had to go through to reach success.

Body:
I have an IT background and was pretty confident until an opportunity came up at work to go into programming(C#). I have never programmed before this, and the software I am programming for is a program I have never used before (a 3D modeling software).

It has been 6 months since then and I feel like giving up. I didn't get much training... about 3 weeks of training spread out over the last 6 months.

I think I would be good at programming but this experience is making me rethink my decision. I'm not sure if it's just me, or if this frustration is normal.

How can I figure out if programming is right for me?


问:
Learning Java with a simple project
As i remember the time when i was learning PHP, it was suggested to build a simple blog or a forum after reading the language fundamentals. I was told/read that this would cover everything that I would need to learn about PHP from a beginners book.
This advice was out there in a number of places, and after following and working with PHP it seems quite good advice. </p>

<p>Now, i am learning Java and reading the book "Thinking in Java" by Bruce Eckel. I wonder if there is any such set of similar, small projects that I could take up, that would cover all the essentials and most of what is covered in the book. </p>

答:
First of all , php and java are OOP. Since you are more familiar with php , you can try to transform your coding style in php as OOP0-ritten approach. That is, applying encapsulation and data abstraction by diving the programs into classes.

As for the learning, you have to make a clear objective purpose. If you are going to study Android later, you must have a clear mindset about the data structures and object references. Please trust me, I have been writing Android Applications and back-end applications using C# and java for more than one year.

If I were you,  I will start learning language C . It is because learning the essence of pass-by-value and pass-by-reference when learning pointers. Once you have make this clear and successfully apply them, learning java and php is no longer a problem , even for Android.

A couple of thing for writing  Android is that since you are going to implement a solution for your system using Android, you should handle the Android Activity life cycle and memory handling so that you can run the system smoothly and using the least amount of memory

Title: Learning Java with a simple project


问:
What are the pros and cons for having a dedicated T-SQL developer on your team?
Our T-SQL developer just gave his two weeks notice. We have been asked if our team of four developers would like an additional developer.

We are offered to do our own T-SQL / Entitiy Framework development or we could get another dedicated T-SQL developer.

What are the pros and cons with having a dedicated T-SQL developer on the team?

Which would you prefer and why?

答:
Short Answer:

That depends on the scope of the project and developers skill set.

Long Answer :

While acquiring such T-SQL or DBA specialists, you and your colleagues have to be trained up in the sense that they must have the mindsets and methodology to handle the SQL

It is because as the development grows for a long time, your SQL and exception-handling cases must increases and be more complicated.


问:
Programming vs Planning
Recently, I have been tasked with more high-level planning assignments due to the lead developer of my team leaving. I hate long-term planning.  My brain just doesn't naturally seem wired for it, and I am not interested enough in it to spend the time to learn it (it is hard enough to keep up with the programming side of the picture).

Can one still be a good programmer without being a high-level planner, too?

As a senior programmer, is one expected to be good at planning out the entire product and picking a date of completion?

答:
Planning and the Bungie-Boss

Dilbert has many strips about the bungie-boss.  Our challenges and expectations about planning may be both the cause and effect of leadership curn.  My experience at a Fortune 100 company was that in one year, everyone who started the year as a project lead exited.  Perhaps this was due to the planning problem.  Not sure if your former lead left for this reason, but when your role requires you make a plan with a commitment, if it does not come to pass, often, a deadline related exit is the result.

Organizational Context of Planning

If you are uncomfortable with planning, perhaps you are uncomfortable with being accountable for commitments made to marketing or other stakeholders before the problems to be solved are documented or understood.  This is a good instinct.

Planning is an important tool.  Don't neglect it.  Don't misunderstand it.

Planning is integrally linked to commitments, accountability, and negotiating power.  Agile planning has many merits.  You should know its techniques, as well as the techniques of planned methodologies.  Your organization may have its own approach and getting advice and working with someone who has survived leadership of many projects many be surprisingly helpful.

A Simple Planning Example - Must not be about software...

If a roofing company came to my house to bid on a replacement, if they bid too low, they may lose money on the job, but if they bid too high, they won't get the job at all.  Either way, they are out of business.  In your new role, if you bit too low, you will run the project until the accountability kicks in, then you will have problems.  If you estimate a project with enough padding to insure success by the deadline, they many just pick someone else to lead.  The kicker is that you are not like the roofer.  He can see how big the roof is, and has historical data about how long that size roof takes.

Becoming a Better Planner

You may wish to consider some kind of training.  In Agile methodologies, and most recent planned methodologies, estimation is a team wide activity.  Consequently, you should consider getting training for your team as well.

From experience, I can tell you it can be frustrating to get estimates from team members who will put it off, give you estimates they make in two minutes based on the task name without reference to a requirement or feature description or the existing code, or who insist that several of the tasks you list can be done in some fraction of a day even though past projects have spent weeks on similar issues.

There are various project manager training courses and certifications,  but I would watch for one that was independently accredited.  It might be worth a second thought before choosing to certify with approaches based on planned methodologies if you expect to work with Agile teams (or the other way around).

SLIM is a method invented by Putnam after working at GE and other companies on DoD projects in the 1970's.  SLIM is influential, and his company QSM offers a certification that seems to flow out of a tool that they make.  Depending on whether your company has adopted their tool, it might have either no value or high value.

Steve McConnell (author of Code Complete) also wrote a book about software estimation, and his company Construx teaches two classes for PDU credits that are accredited through the Project Management Institute.  I have his book, and if I wanted to learn about the topic via classroom training, I would probably pick Construx.  They also do Scrum training and administer various scrum assessments accredited through Scrum.org.

Another source that could provide great academic training about software project estimation, would be Barry Boehm's group at USC, based on their extensive work on COCOMO and COSYSMO constructive cost modeling which has been used at NASA and other large contractors to estimate very large projects.  I am not sure I am a true believer in COCOMO, but I like the empirical work they have done to correlate the effects of scale and cost drivers on schedule duration.

I also found a chapter from a textbook published by O'Reilly that briefly discusses major software estimation methods including Watts Humphreys PROBE and Kent Beck's planning game.  PROBE includes a notion that engineers track metrics on their own productivity, then apply them to their assign part on new projects.  Planning Game is very highly collaborative between developers and other stakeholders.

Title: Programming vs Planning


答:
To understand what the command line is you have to understand that in modern operating system, specifically monolithic-kernel OSes, like Linux, MacOSx and Windows. These type of operating systems can be described at the simplest abstraction as seperated into a core "kernel" that executes system critical programs the OS depends on (memory management, interupt handlers [IE: when you type a key, this is an example of a hardware interrupt the OS needs to be interrupted to address immediately], ect)  and a userland "shell" where your windows desktop and all your programs run in. (web browsing, games, ect)

The typical PC user never worries about what goes on in the kernel, because everything they interact with is done through the userland interface software. The OS depends on the kernel's executing software to be stable to function correctly, therefore the user is typically prevented entirely, or very restricted from directly interacting with the kernel.

Thus the command line allows you to execute small userland programs called tools. These tools provide an interface to call into the operating system via (who would have guessed) system calls. If you are writing a program, and you need a block of memory. C's malloc can be thought of as calling the kernel to ask if you can check out some unused memory for awhile. Then when you call Free on that memory, you are basically letting the OS know you are done with it and it can reuse that memory for other system threads that are concurrently executing (other programs that are doing work in the background, ect)

The kernel interacts with the CPU by laying out binary opcode instructions in memory so the CPU can be feed the next instruction it needs to execute every clock cycle. (2.5 ghz = ~2.5 million clock cycles a second. Which in a perfect theoretical world ~= 2.5 million instructions the CPU processes / sec.)

The way binary works, is each chip is designed in a very complex way where different patterns of 1s and 0s cause the chip to route the data to different places on the motherboard.

And thats a computer in a nutshell. (boom-boom tish)

Title: What is the relationship between the command line, the OS and the microprocessor?

Body: I'm not totally clear on how using the command line differs from working through the OS' interface using an editor for example. Obviously the UI is different but I want to understand how the command line interacts with the kernel and microprocessor, and how this compares to how kernel interfaces with the OS' GUI. I know I'm missing several layers of abstraction but would be grateful for someone to explain this.</p>


答:
Are you the only dev to have worked on this project? Sounds like you answered to someone while making the project. Where is that person in all of this? Where is the documentation for the project saying what was delivered?

There should be a document paper trail. A training doc showing how to use the application. A functional spec outlining what was developed. If a feature wasn't included, there should be documentation on that too. Someone should have had to sign off saying they accept that.

It shouldn't be your word against theirs, it should be all in the documentation.

If you don't have this documentation...then I'm afraid you are going to have to bite this one. Consider it a life lesson. At the end of the day, your users are your customers, and as the saying goes: the customer is always right. Draw up how to add this feature and how long it will take. Have a meeting and say something along the lines of 'Our records show that this feature was never implemented, but we can get it life in x weeks. Should we go a head?'

And for the love of all that is holy....get the documentation you need to show it was approved.


答:
I think the single most definite thing to ask yourself is "do you like to learn."

By this simple question you will know if programming is right for you with a decent probability. If you do not like learning, then no, you probably will not like programming. Programming is 5% about writing code, 10% about designing how your code should work, and 85% about learning how to write better code and make better designs. (and that doesn't change! I've been programming for 8+ years and still am constantly learning!)

Now of course, you can like learning and not like programming, but since you like learning then try making some programs! You can't give up at the initial learning curve though, especially with so many easy languages now. So get out there and write some code!

Title: How can I figure out if programming is right for me?


答:
Organizationally, I sense a problem.

There is a hierarchy that includes the head of IT and your boss.  If your organization is traditional (it doesn't sound like it is Agile), you are a resource and they are resource managers.  You have a full time job called software development.  If end users are directly requesting features, setting your priorities, and trying to manage your time, your managers are redundant.  They may be accountable to end users, but if they are doing their job, you are accountable to them and they need to shield you from going out of focused developer mode into defensive developer mode.

A few points to set the context of my answer:

Software developers are not time travelers, so the results need to be judged for what they are, not what they might have been.

If a feature was in a requirements specification, a schedule, and was prioritized above work that was completed, there may be a legitimate complaint.  Otherwise, what is the justification to hold you accountable?

Your punishment, if merited, needs to come from your chain of command.  Just as marketing and sales would not like it if product development scolded customers, most organizations have product managers to receive customer wrath (and praise) and convey it through channels.

Product managers can create extremely difficult relationships if they bask in the warmth of successful parts of projects, but only ever crack the whip when they face toward developers.

If you delivered functional product with a year worth of work, and it takes a month (or two) to add the desired feature, from what I have seen in our industry, your estimation was above average.

Solving the problem fairly and productively requires that people put the fingers of blame back in their pockets and make a go forward plan.

You will be able to do much better quality work with better motivation if you are appreciated instead of being the goat in a process that the head of IT should own.  It is the fair way and the productive way.  I hope you will be managed that way, and sometime in the future, I hope you will manage others that way.


答: The NetBeans IDE has a good selection of example projects, everything from basic Java (an anagram game) to web stuff (servlets, JSPs, JSF) to web services and more.  I often find it's easier to learn when I have a working project to play with, instead of wasting an hour or two hassling with the particular details of setting up a project for the first time.</p>

Title: Learning Java with a simple project

Body:
As i remember the time when i was learning PHP, it was suggested to build a simple blog or a forum after reading the language fundamentals. I was told/read that this would cover everything that I would need to learn about PHP from a beginners book.
This advice was out there in a number of places, and after following and working with PHP it seems quite good advice. </p>

<p>Now, i am learning Java and reading the book "Thinking in Java" by Bruce Eckel. I wonder if there is any such set of similar, small projects that I could take up, that would cover all the essentials and most of what is covered in the book. </p>


问:
Optimizing hash lookup & memory performance in Go
As an exercise, I'm implementing HashLife in Go.

In brief, HashLife works by memoizing nodes in a quadtree so that once a given node's value in the future has been calculated, it can just be looked up instead of being re-calculated. So eg. if you have a node at the 8x8 level, you remember it by its four children (each at the 2x2 level). So next time you see an 8x8 node, when you calculate the next generation, you first check if you've already seen a node with those same four children. This is extended up through all levels of the quadtree, which gives you some pretty amazing optimizations if eg. you're 10 levels above the leaves.

Unsurprisingly, it looks like the perfmance crux of this is the lookup of nodes by child-node values. Currently I have a hashmap of

```<code>{&upper_left_node,&upper_right_node,&lower_left_node,&lower_right_node} -> node
</code>```

So my lookup function is this:

```<code>func FindNode(ul, ur, ll, lr *Node) *Node {
        var node *Node
        var ok bool
        nc := NodeChildren{ul, ur, ll, lr}
        node, ok = NodeMap[nc]
        if ok {
                return node
        }
        node = &Node{ul, ur, ll, lr, 0, ul.Level + 1, nil}
        NodeMap[nc] = node
        return node
}
</code>```

What I'm trying to figure out is if the "nc := NodeChildren..." line causes a memory allocation each time the function is called. If it does, can I/should I move the declaration to the global scope and just modify the values each time this function is called? Or is there a more efficient way to do this?

Any advice/feedback would be welcome. (even coding style nits; this is literally the first thing I've written in Go so I'd love any feedback)

答:
What I'm trying to figure out is if the "nc := NodeChildren..." line causes a >memory allocation each time the function is called?

Yeah. Everytime you call the FindNode() function, nc := will be assigned to a new struct that lives in a new block of memory than the struct created from the previous function call. How this impacts performance depends on how many times you are calling that function (in a tight loop will create alot of garbage to take care of and require allocating memory everytime you reach 2x's the amount of memory during last allocation period. 2mb -> 4mb ->8mb->16mb, ect) Until the garbage collector runs those mbs can add up for objects that are no longer reachable.

If it does, can I/should I move the declaration to the global scope and just modify the values each time this function is called? Or is there a more efficient way to do this?

What I would do is create a slice to hold the Node pointers

```<code>var nc [4]*Node

func FindNode(ul, ur, ll, lr *Node) *Node {
        var node *Node
        var ok bool
        nc[0] = ul; nc[1] = ur
        nc[2] = ll; nc[3] = lr

        node, ok = NodeMap[nc] //change struct logic to slice logic
                               //i.e nc.ul -> nc[0], ect
        if ok {
                return node
        }
        node = &Node{ul, ur, ll, lr, 0, ul.Level + 1, nil}

        //why hash this with an index to a type that wont exist later?
        NodeMap[nc] = node
        return node
}
</code>```

Body:
What I'm trying to figure out is if the "nc := NodeChildren..." line causes a >memory allocation each time the function is called?

Yeah. Everytime you call the FindNode() function, nc := will be assigned to a new struct that lives in a new block of memory than the struct created from the previous function call. How this impacts performance depends on how many times you are calling that function (in a tight loop will create alot of garbage to take care of and require allocating memory everytime you reach 2x's the amount of memory during last allocation period. 2mb -> 4mb ->8mb->16mb, ect) Until the garbage collector runs those mbs can add up for objects that are no longer reachable.

If it does, can I/should I move the declaration to the global scope and just modify the values each time this function is called? Or is there a more efficient way to do this?

What I would do is create a slice to hold the Node pointers

var nc [4]*Node

func FindNode(ul, ur, ll, lr *Node) *Node {
        var node *Node
        var ok bool
        nc[0] = ul; nc[1] = ur
        nc[2] = ll; nc[3] = lr

        node, ok = NodeMap[nc] //change struct logic to slice logic
                               //i.e nc.ul -> nc[0], ect
        if ok {
                return node
        }
        node = &Node{ul, ur, ll, lr, 0, ul.Level + 1, nil}

        //why hash this with an index to a type that wont exist later?
        NodeMap[nc] = node
        return node
}


问:
Schema.org vs microformats
They both serve the same purpose: Providing a vocabulary for semantic markup. Schema is recognized and standardized… but the microformats standard is by an open community process.

Schema exploits microdata in documentation, while microformats go on classes. (Of note: microdata means that an element must be of a single itemtype, while microformats allow several classes to apply to the same element. I can markup xFolk+hAtom with classes, but not with microdata.)

Is this a black-and-white situation? Google says I can't use both "because it may confuse the parser".

What's the consensus on these?

答:
tl;dr, the three ways how to semantically annotate content in HTML5 documents:

Microdata and RDFa are syntaxes (extending HTML) for semantically marking up content, but they don‘t supply vocabularies.

Microformats is a convention (re-using what HTML provides) for semantically marking up content, and (solely!) supplies vocabularies for that purpose.

Schema.org is a collection of vocabularies (that can be used with various syntaxes, including Microdata and RDFa, but not Microformats), so this question should be: Microdata vs. Microformats? And why not invite RDFa to the party?

RDFa and Microdata are not the same, but conceptional similar. Microformats however differs strongly from both.

If your only aim would be to enhance the display of search results from search engines, it doesn’t matter which markup way you choose (as long as it is supported by the search engine). But "semantic markup", of course, allows much more: building the Semantic Web. Not without reason do Microformats relate to the term "lower-case semantic web", while RDFa relates to "upper-case Semantic Web" (Microdata is a newer syntax, but it would fit into the upper-case variant).

The main difference: extensibility. RDFa and Microdata use URIs, Microformats uses specific class names (for HTML’s class attribute) and link types (for HTML’s rel attribute). That means:

With Microformats you can only markup certain content if the Microformats community created and accepted an appropriate "vocabulary" (i.e., a Microformat).

With RDFa and Microdata you can create your own vocabulary if there doesn’t already exist an appropriate one (and there are many vocabularies).

Google says I can't use both "because it may confuse the parser".

I wouldn't let this stop me from implementing several markup ways. Also, Google kind of revoked this statement in a chat.

Update: On Google’s Structured Data documentation, it nowhere says they couldn’t handle different syntaxes on the same document. And their Testing Tool reports no errors if several syntaxes are used.

See also related questions on Stack Overflow:

microformats, rdf or microdata

The relationship between RDF, RDFa, Microformats and Microdata

RDF and microdata future

Microdata vs RDFa

Title: Schema.org vs microformats


问:
Questions to ask before someone leaves
Apart from the obvious questions relating to specific project work someone is working on are there any questions I should be asking a fellow dev who is leaving the company?

So far I am thinking about;

Locations of things on the server he uses that not maybe everyone does.

Credentials he has set up that we wouldn't have needed.

Client details he has not yet saved into our CRM system.

答: "Can I have your Aeron chair?"</p>

Title: Questions to ask before someone leaves

Body: "Can I have your Aeron chair?"

ContentLicense: CC BY-SA 2.5


答:
It's simple: do you enjoy doing it?  If you weren't being paid to do it, would you do it in your free time, for fun?  If the answer is no, then programming is probably not right for you.

That's not to say you couldn't learn to do it well enough to be gainfully employed doing it.  But if you don't love it, you'll never be great at it.  And, if you don't enjoy it, what's the point?

I started programming when I was 12 years old, and I did it because I wanted to.  I was 20 (and halfway through college) before it occurred to me that maybe I could do that for a living.  It was just a thing I did because I loved it.

I believe that most people that are great at something (anything) are so not because they have some innate skill, but because they have an unhealthy obsession for that thing.


问:
How secure (or insecure) is it to install Node packages globally?
Should I be concerned with security when installing Node packages globally? Why or why not?</p>

答:
I would be more concerned about scripts that run in the package.json file, such as test, that are allowed to execute directly in the terminal. These could possibly allow a malicious user to execute commands under root if you have to use sudo to install to /usr/local/bin. It's always best to inspect the package.json file of the module that you're downloading to make sure there isn't anything suspicious in it.

For example:

```<code>{
  [...snip...]

  "scripts": {
    "preinstall": "shutdown -t now"
  },

  [...snip...]
}
</code>```

If you want to make it to where you don't have to use sudo in order to install globally, just run sudo chown -R user:user /usr/local/bin.

You can view a NPM package's package.json file by using npm show <package>.

Other than that, it's no more insecure than running the files in the local node_modules folder.

Body:
I would be more concerned about scripts that run in the package.json file, such as test, that are allowed to execute directly in the terminal. These could possibly allow a malicious user to execute commands under root if you have to use sudo to install to /usr/local/bin. It's always best to inspect the package.json file of the module that you're downloading to make sure there isn't anything suspicious in it.

For example:

{
  [...snip...]

  "scripts": {
    "preinstall": "shutdown -t now"
  },

  [...snip...]
}

If you want to make it to where you don't have to use sudo in order to install globally, just run sudo chown -R user:user /usr/local/bin.

You can view a NPM package's package.json file by using npm show <package>.

Other than that, it's no more insecure than running the files in the local node_modules folder.


问:
How To Start Programming
I have taken a programming course 2 years ago but I haven't worked in  programming since then. I recently found a programmer job, but there is no programming team so for me to gain valuable experience from.

I am Programming by myself and making changes on a program already made by my Ex-colleague. I need to know what should I do to be on the right track for becoming a professional programmer without a team to take experience from. What are the good practices to improve and what are the bad ones?

I'm using VB.Net, ASP.Net and SQL.

答:
You need to first do code, and then code on different logic with different application, like web application and windows application.

You have to be clear with your logic.  Alternatively, you can get sample code from the internet or other Stack Exchange sites, for example Stack Overflow.

Just practice your coding. Experience can make you perfect.

Title: How To Start Programming


答:
I experienced the exact same thing around 6 or 7 months ago. You will certainly remember the things you learnt 2 years ago very quickly as you do more and more work.

My best advice for you, based on my own experience is to get your hands on a copy of the following books:

The Pragmatic Programmer: From Journeyman to Master
by Andrew Hunt and David Thomas

Pragmatic Thinking and Learning: Refactor Your Wetware
by Andy Hunt

Primarily the first one.

You would learn all that can be learned from those books as time goes by and you make a lot of the mistakes it points out, I just wish in hindsight that I had brushed over each of these books to avoid a lot of unnecessary pain that comes with encountering the issues yourself.

Other than that be active in your learning and ensure you are asking why something works, don't just accept that it works.

Title: How To Start Programming

Body:
I have taken a programming course 2 years ago but I haven't worked in  programming since then. I recently found a programmer job, but there is no programming team so for me to gain valuable experience from.

I am Programming by myself and making changes on a program already made by my Ex-colleague. I need to know what should I do to be on the right track for becoming a professional programmer without a team to take experience from. What are the good practices to improve and what are the bad ones?

I'm using VB.Net, ASP.Net and SQL.


答:
I was a naive programmer 1.5 year ago. TO be able to learn programming (in situations when you are not already a programming background) you first need to build some confidence in programming.

Concentrate on one programming language initially

Try to grasp the generic concepts form it like (not in order)

Compilation process

runtime

Memory management

Message passing

methods invocations

nature of variables, etc
that are applicable almost all programming language

Then focus the building of your logic in context of the programming language.

Its not always that what you plan you can (or should) program.

go for the best approach no matter what (no compromise while learning)

Read some good code.

listen to music

I am posting some URLs that you can use to get an idea

Udacity

http://codeacademy.com/

Khan Academy

projecteuler

Learn Street(Specially for Python, Ruby and JS)

Title: How To Start Programming


问:
Why to say, my function is of IFly type rather than saying it's Airplane type
Say, I have two classes:

Airplane and Bird, both of them fly. Both implement the interface IFly. IFly declares a function StartFlying(). Thus both Airplane and Bird have to define the function, and use it as per their requirement.

Now when I make a manual for class reference, what should I write for the function StartFlying?

1) StartFlying is a function of type IFly .

2) StartFlying is a function of type Airplane

3) StartFlying is a function of type Bird.

My opinion is 2 and 3 are more informative. But what i see is that class references use the 1st one. They say what interface the function is declared in. Problem is, I really don't get any usable information from knowing StartFlying is IFly type. However, knowing that StartFlying is a function inside Airplane and Bird, is more informative, as I can decide which instance (Airplane or Bird ) to use.

Any lights on this: how saying StartFlying is a function of type IFly, can help a programmer understanding how to use the function?

答:
Say StartFlying() is a method/function in IFly. The documentation should include:

How to find IFly, such as the namespace (.net or Java)/header file (e.g. C++) and file (such as an assembly in .Net or JAR file in Java).

Specify what the caller needs to supply, such as arguments to the method and their allowable values,

What the implementer needs to do, such as changes to other properties or return values.

Error handling, such as what exceptions thrown and under what conditions.

Security requirements. For example, does the user need to be a member of the Pilots group?

Links to similar interfaces (e.g. IWalk, IRun)

Link to an example or overview

You may want to include links or references to classes that implement IFly, such as Bird and Aeroplane but this may be manual and, therefore, prone to omissions or copy and paste errors.

Why describe StartFlying() in IFly in than Bird or Aeroplane? StartFlying() has been abstracted into an interface to standardize access similar functionality across disparate classes. This means other classes may implement it in the future beyond Bird and Aeroplane, both inside your library and outside.

Reference the documentation for IFly in the documentation for Bird and Aeroplane as well but these should also include implementation specific details. Aeroplane, for example, may require IsFueled() to be true, and including this in IFly would be confusing.


问:
What is the Reluctant ideas at Extreme Programming (XP)
Regarding Software Engineering, there are several obstacles for Extreme Programming, one of them is reluctant ideas. Not to accepting certain kind of idea.

What is the exact meaning of the term "reluctant ideas"

答:
Well.... asking to explain one aspect of XP without having to explain the rest is kind of difficult. Therefor I would like to start with a short reference about some core parts of XP. XP carries values, here to mention are communication, feedback, and courage. If you are communicating with others from your team and you'r all suggesting solutions (Feedback)... especially if your know-how levels differ ... you sometimes have a situation where a certain "idea"/"solution" for the xyz-problem is based on false assumptions or based on missing know-how.

Those who miss the know-how to see another solution will always come back to the xyz-solution for the xyz-problem. Those "ideas" are called "reluctant". If you look up the term all by itself, you get some definitions:

relecutant
adjective
 1. unwilling; disinclined: a reluctant candidate.
 2. struggling in opposition.

Can be confused:
 1. reluctant, reticent;
 2. reticent, reluctant.

Synonyms
1. Reluctant, loath, averse  describe disinclination toward something. Reluctant  implies some sort of mental struggle, as between disinclination and sense of duty: reluctant to expel students. Loath  describes extreme disinclination: loath to part from a friend. Averse,  used with to  and a noun or a gerund, describes a long-held dislike or unwillingness, though not a particularly strong feeling: averse to an idea; averse to getting up early.

From my point of view the "reluctant ideas" are those who are more like a tradition in the sense of "We have always done it like that" than based on experience or know-how. It takes courage on all sides to identify and to get rid off "reluctant ideas".

One example that shoots to my head right now:

"Why should I use a Version Control System?, I have always had my IDE
  safe my project right into the remote file system on the server and do
  backups locally. Using a VCS would only slow me down!"

(xyz-solution for xyz-problem, but obviously a bit confused)

The "reluctant idea" would be that you are faster (e.g. better coder) by circumventing a VCS. People who never ever used a VCS will often come up with this idea, where as those who use a VCS on a daily basis know (know-how) why using a VCS is the way to go.

XP or eXtreme Programming, like I said in the beginning, carries values. See:
http://www.extremeprogramming.org/values.html

If you take these values seriously your duty is to help yourself and others in your team to battle reluctant ideas. And that is most definitively an obstacle :-).


答:
I think your confusion comes from the fact that you named your interface IFly. Any recent programming book recommends to not name your interfaces with I in front. Give your interface a proper name.

In your particular example it would be a little bit harder to do this, but let's take this situation:

Interface is: FlyingObject

Implementation1: Airplane implements FlyingObject

Implementation2: Helicopter implements FlyingObject

Implementation3: UFO implements FlyingObject

If you do this and you try to write a documentation for it, it will be quite clear what StartFlying on FlyingObject means.

In some extreme cases, when it's impossible to find the proper abstraction, you may name your interface with a concrete name like Foo and than the implementation FooImplementation or FooImpl.

UPDATE: Of course it always depends on what you are documenting and how. If you document your business logic, you can simply say that any FlyingObject has a startFlying() method. Your business logic will not create those objects, so you don't care what are they exactly. In fact, this makes things much more clearer once you document that your business logic can use any object that has the startFlying() method and you connect that knowledge to the interface. You don't care who creates the Airplane or Helicopter. All you know and document from the point of view of the business logic is that you can start flying if you have an object capable doing so.

On the other hand if you document your factories or whatever logic you have that decides what type of flying object to create, there you can document something like 'Airplane, Helicopter, etc. must implement FlyingObject, otherwise they can't take you to Japan'.

I hope this update clarifies all the question you were asking.

Title: Why to say, my function is of IFly type rather than saying it's Airplane type

Body:
Say, I have two classes:

Airplane and Bird, both of them fly. Both implement the interface IFly. IFly declares a function StartFlying(). Thus both Airplane and Bird have to define the function, and use it as per their requirement.

Now when I make a manual for class reference, what should I write for the function StartFlying?

1) StartFlying is a function of type IFly .

2) StartFlying is a function of type Airplane

3) StartFlying is a function of type Bird.

My opinion is 2 and 3 are more informative. But what i see is that class references use the 1st one. They say what interface the function is declared in. Problem is, I really don't get any usable information from knowing StartFlying is IFly type. However, knowing that StartFlying is a function inside Airplane and Bird, is more informative, as I can decide which instance (Airplane or Bird ) to use.

Any lights on this: how saying StartFlying is a function of type IFly, can help a programmer understanding how to use the function?


问:
When should I start learning a PHP Framework
I'm a beginner programmer

I have been learning PHP for a while, though not consistently. But for the past few months (say 3 months) I have been a bit consistent in my learning, largely because of a project a friend ask me to do for him since he knew I was into web design. Though I struggled to complete the tiny project for him after about 3 weeks, because I got stuck some times and I have to look up tutorials/references relating to the problem I was trying to solve, but I feel fulfilled been able to accomplish a project and along the way grab most of PHP basics.

My interest in Web development has grew higher since completing that project and I have been trying to learn PHP/MySQL as fast as I could, because the same friend want me to do something else for him, which to me is way beyond the basics I know. Though I don't charge him anything, but it gives me a sense of fulfillment.

I want to learn a framework, because I heard it can make you accomplish more as a web developer and makes life much easier.

Can I learn a framework without having OOP knowledge?
I know how to create and use functions, though I don't use it much

I know my question is not straight forward, but I know you will understand were I'm coming from and advice me appropriately. I wish to become a professional Web Developer.

I really need your professional advice.

答:
I've been through a similar thing myself, learning PHP in my spare time as an exercise with an eye to helping a friend who runs an online game.

I found that the differences between PHP and my "work" language (Delphi) meant I was better off starting with the absolute basics of PHP and it's syntax, without any framework or OOP to get in the way. There's also a huge amount of online help (particularly the php.net website) which doesn't use a framework or OOP.

While this online code can be of varying quality, it can still help a beginner to get off the ground and start producing working code, which encourages me more than anything else to keep going and improve.

Once I got past this stage, I started looking at using OOP in PHP and rapidly progressed to a framework (codeigniter) on my friend's recommendation.

So, YES! Every PHP programmer should seek to learn OOP and a framework, but only once they've got to grips with straight, rough'n'ready procedural code (even if it's inline).

It's about learning in stages so you don't bite off too much at once, you should seek to progress as rapidly as possible and be wary about bad programming habits (which are everywhere in PHP), just keep learning and improving, that's what I'm still doing!


问:
How to deal with almost the same enums?
I need to define enums in several classes. The majority of fields are the same in all of the enums. But one has one or two more fields, another has fewer fields. Now I wonder what is the best way to deal with this?

Create separate enums

```<code>public enum Foo {field1, field2, field5 };
public enum Bar {field1, field2, field3, field4 };
</code>```

or use a general enum for them all

```<code>public enum FooBar {field1, field2, field3, field4 , field5};
</code>```

The enumerations contain the list of actions available for each class.

Update : sorry if the question was not clear enough . I want to use these enums as parameters in classes methods . for example classOne has a method as below :

```<code>public void DoSomeThing(Foo action,object moreData)
{
    // operation desired
}
</code>```

here I want action to be limited to Insert , Update and Delete

while in classTwo :

```<code>public void DoSomeThingElse(Foo action)
{
    // operation desired
}
</code>```

I want to limit action availabe to Insert and Select

答:
Conceptually, are enums talking about the same concept or thing or are they just related? For example, I might have a Direction enum and a Gears enum. Both may have a Reverse value but they mean very different things. In general, only merge concepts if they are the same. Otherwise you are making an assumption.

That said, from your comment above, it sounds like they are talking about the same concept (insert, update and delete) so I would merge them.

Also, if interop is a concern or they are similar, consider assigning the enum values fixed values, e.g. 1 for insert, 2 for delete and so on. It will make conversion and compatibility easier.

OwnerDisplayName: reza

Title: How to deal with almost the same enums?


答:
You should use a different approach.

Create an enumeration which contains all available actions (insert, update, delete, etc.).
So you can add a new (static) field to each class _ a list of items of that enumeration _ to represent the list of valid actions.

It makes no sense to have a separate enumeration for each class _ the enumerations semantically represent values of the same kind.

For example, you have an enumeration:

```<code>public enum ACTIONS { insert = 1, update = 2, delete = 3 }
</code>```

In you class you would use it like this:

```<code>public class MyClass
{
    public static ACTIONS[] Actions = { ACTIONS.insert, ACTIONS.delete };
}
</code>```

Title: How to deal with almost the same enums?

Body:
I need to define enums in several classes. The majority of fields are the same in all of the enums. But one has one or two more fields, another has fewer fields. Now I wonder what is the best way to deal with this?

Create separate enums

```<code>public enum Foo {field1, field2, field5 };
public enum Bar {field1, field2, field3, field4 };
</code>```

or use a general enum for them all

```<code>public enum FooBar {field1, field2, field3, field4 , field5};
</code>```

The enumerations contain the list of actions available for each class.

Update : sorry if the question was not clear enough . I want to use these enums as parameters in classes methods . for example classOne has a method as below :

```<code>public void DoSomeThing(Foo action,object moreData)
{
    // operation desired
}
</code>```

here I want action to be limited to Insert , Update and Delete

while in classTwo :

```<code>public void DoSomeThingElse(Foo action)
{
    // operation desired
}
</code>```

I want to limit action availabe to Insert and Select

Body:
You should use a different approach.

Create an enumeration which contains all available actions (insert, update, delete, etc.).
So you can add a new (static) field to each class _ a list of items of that enumeration _ to represent the list of valid actions.

It makes no sense to have a separate enumeration for each class _ the enumerations semantically represent values of the same kind.

For example, you have an enumeration:

public enum ACTIONS { insert = 1, update = 2, delete = 3 }

In you class you would use it like this:

public class MyClass
{
    public static ACTIONS[] Actions = { ACTIONS.insert, ACTIONS.delete };
}


问:
Getting non-programmers to understand the development process
When starting a project for a company that's not primarily a programming company, one of the expectations is that there's a finished product at the end free of all bugs and does everything needed right away. However, that's rarely the case.

What are some ways to manage expectations and explain to non-programmers how software development differs from other types of product development?

答:
You might compare it to something they can see and if possible, use everyday.

For example, the automobile.  Cars started as much less refined and reliable devices than we have today.  While cars have been made for over 100 years, but software probably about half that long.  Cars are available with significant customization, some included in the price (like choice of color), others like engine size, transmission type, wheel/tire, trim level are significant cost drivers.

There are many feature, quality, and cost drivers for cars, and for software.  Then you can discuss how software technology, availability of expertise, maybe even where it is built will make a big difference.  Appropriately development cycles (for example, yearly models with small changes, body/engine/platform changes about every three years) are driven by a combination of customer needs and a complex design process.  Some products start small and dumpy looking (think of the Honda Accord), but get improved every year until they are top rated.

Cars have recalls (often way more costly than software upgrades) and incremental improvements in the form of running changes to their parts lists (think bug fixes), and often they need long term support (think backward/forward compatibility).  Much of the cost of your car comes after you drive it home.  Much of the software cost comes after the initial product release as you update and upgrade customers.

In some cases, you can reference well known products that include software or other software products.  For example, phones have a release cycle and updates and methods of adding functionality after the initial sale to build more revenue.  Phones are a great illustration of forward / backward compatibility.  Too much, and people won't dump the old one to buy a new one.  Too little, and customers get desperate to have a phone they won't hate before its contract is up.

Products like Windows, Microsoft Office, web browsers, and web pages are all software that can be used in discussions.  They have been updated on annual or three year cycles, but may have automatic updates more frequently.  They have bugs and security holes that affect customers to varied degrees, but are a part of the landscape despite our best efforts.  Customers can get fixes free, but generally pay for enhancements, often as a bundle, sometimes as an individual module or via an licence key.

Industry leaders like Microsoft, Apple, Google, and Amazon all deliver relatively inexpensive customers to users.  But they have huge expenses that enabled those products.  Their experience shows that software is expensive, but valuable and profitable.  They often compromise between quality, having all the features they want, and getting into markets when the timing is right.  Not every product they make is a success, and they sometimes turn dogs into winners by renaming, improved marketing and sales, or cutting their losses and using what they learned in later products.


问:
How can I  really master a programming language?
I know that learning a language, you can simply buy a book, follow the examples, and whenever possible try the exercises. But what I'm really looking is how to master the language once you've learned it.

Now I know that experience is one major factor, but what about learning the internals of the language, what is the underlying structure, etc.

There are articles out there saying read this book, read that book, make this game and that game.
But to me this doesn't mean to master a language. I want to be able to read other people's code and understand it, no matter how hard that is. To understand when to use a function and when another, etc etc.

The list could go on and on but I believe I've made the point. :)

And finally, take whatever language as an example if needed, though best would be if C was taken as an example.

答:
On the high level side of the problem, learn about architecture: how to organize your projects, what's its structure. Don't just let them grow randomly.

On the middle level, learn different techniques and paradigms. The more diverse tools you have in your repertoire, the more power to you. If you only have studied java, python and ruby, you've been exposed just to a very little portion of the programming space. Learn imperative and functional programming, learn prolog and J. The idea is not to "master" hundred languages, but to learn about different ways of solving the same problems.

On the low level side of the problem, one thing that could be help you to be a better programmer (in fact better at whatever you do) is to have a good mental model of the platform. For example, you can learn how C control structures work and know the most common libraries, but if you don't have a mental model of how pointers and memory work, then you'll have troubles with moderately complex expressions.


问:
Is throwing an exception from a property bad form?
I've always been of the mindset that properties (ie, their set/get operations) should be fast/immediate and failure-free. You should never have to try/catch around getting or setting a property.

But I'm looking at some ways to apply role-based security on the properties of some objects. For instance an Employee.Salary property. Some of the solutions I've run across that others have tried (one in particular is the AOP example here) involve throwing an exception if the accessor doesn't have the right permissions - but this goes against a personal rule that I've had for a long time now.

So I ask: am I wrong? Have things changed? Has it been accepted that properties should be able to throw exceptions?

答:
AFAIK, this guidance primarily comes from the thought process that properties may end up used at design time. (E.g. the Text property on a TextBox) If the property tosses an exception when a designer's trying to access it, VS isn't going to have a good day. You will get a bunch of errors just trying to use the designer and for the UI designers, they won't render. It also applies to debug time as well, although what you'll see in an exception scenario is just "xxx Exception" and it won't clobber VS IIRC.

For POCOs, it won't really do any harm, but I still shy away from doing it myself. I figure people will want to access properties more frequently, so they should normally be low cost. Properties shouldn't do the work of methods, they should just get/set some info and be done with it as a general rule.


答:
The enumerations contain the list of actions available for each class.

Why are you trying to use enums to solve your problem. I would create interface to cover all common behavior (actions) of my classes instead. You may create one ICommon interface which will contain all your common behaviors for the class to support your design and class behaviors.

There are very good posts on this topic like Designing C# Software With Interfaces or you may also reference Wikipedia for common information - The concept of class interface.

Title: How to deal with almost the same enums?


问:
conventions for friend methods in Perl
Perl doesn't support a friend relationship between objects, nor does it support private or protected methods. What is usually done for private methods is to prefix the name with an underscore. I occasionally have methods that I think of as friend methods. Meaning that I expect them to be used by a specific object, or an object with a specific responsibility, but I'm not sure if I should make that method public (meaning foo ) or private ( _foo ) or if there's a better convention? is there a convention for friend methods?

答:
If you really want to have Friend semantics you could do something like this:

```<code>package A;

use Data::Dumper;

sub _friend
{
   die "you are no friend of mine" unless caller(0)->isa(__PACKAGE__);
   my $self = shift;
   "friend";
}

package B;

use base 'A';

sub new
{
   bless {}, shift;
}

sub test_friend
{
shift->_friend;
}

package main;

$bob = new B;

print $bob->test_friend, "\n";

print $bob->_friend, "\n";
</code>```

I named the method with an underscore so that Test::Pod will will not complain that it is not documented.

Title: conventions for friend methods in Perl

Body:
If you really want to have Friend semantics you could do something like this:

package A;

use Data::Dumper;

sub _friend
{
   die "you are no friend of mine" unless caller(0)->isa(__PACKAGE__);
   my $self = shift;
   "friend";
}

package B;

use base 'A';

sub new
{
   bless {}, shift;
}

sub test_friend
{
shift->_friend;
}

package main;

$bob = new B;

print $bob->test_friend, "\n";

print $bob->_friend, "\n";

I named the method with an underscore so that Test::Pod will will not complain that it is not documented.


问:
A testing feedback/report tool?
I'm thinking of developing a pluggable test and assessment module. This tool will be used especially for desktop application projects to report and log errors, bugs, missing features and suggestions from testers.

The tool will be plugged to the application by putting a small icon to the application itself. When pressed the tool will be visible where user can create entries about the application.

Is there already a tool like that? I am not speaking about UI testing btw.

For example, this tool might have a form consisting of

Page name

Environment information

Entry type (can be bug, feature request, suggestion)

Message

User Info (name, contact etc)

Date

I think such a tool can greatly help testers prepare reports. Developers can understand the issue better and track all the reports.

答:
We have something similar built into our desktop products.

For logging errors/exceptions we use Eurekalog, which compiles into your exe file and can email you a stack trace and the exception type and message (among many other details). Highly recommended (or something similar depending on your language and development environment).

For feature suggestions we designed our own simple screen with similar fields to those you gave in your example and then email ourselves when the user clicks send.

Title: A testing feedback/report tool?


问:
Developing a search algorithm
I want to create a basic search engine, and I want you to give me some ideas how to filter out the best results for my visitors.

I have three fields regarding a product the user can search in:

Title

Category

Description

I came up with these ideas and I ask you to either competently criticize them or add to them.

If the search term occurs in all three fields it should be among the first results.

If it is in two of the fields it is below the results of 1.

Combine the amount of occurences and output a value in per cent. For instance if in all fields together the term clock appeared 50 times and in all fields together there are 200 words, then the per cent value is 50/200*100 = 25%. Another product entry amounts to say 20% so product one having 25% is listed before product two having 20%.

答:
Actually you're more looking to find a "result ordering" rather than a search algorithm.

Anyway, I would grade the results using a points mechanism. This makes it easier to handle, easier to maintain and to enhance if you wish to. Moreover, it also helps you handling the case of multiple keywords search. This is how it works:

For each keyword the user gave:

give a points for the appearance in the title

give b points for the appearance in the category

give c points by occurrence in the description.

Sum the total amount of points for each keyword.

Order the list of items by points, from highest to lowest.

By playing with the parameter a, b and c you will change the resulting order. You can then fine-tune your algorithm either by allowing the user to change his preference (and updating the parameters in the background) or you can yourself make your own test and determine which parameters are the best.

Title: Developing a search algorithm


问:
What corners have have you cut at work?
Have you ever let your coding standards slip to meet deadlines or save time?

I'll start with a trivial example:

We came up with a coding standard at work around which brackets/formatting to use and so on. I ignore it and use the auto-format tool in netbeans.

答: There are many times that I let comments slip, and then when I get more time put them in.  It's actually a benefit since in refiguring out what I did, it gives me a better perspective on it, and sometimes I come up with better ways to do the job.</p>

Title: What corners have have you cut at work?


问:
Function calls to calls in windows api
When programming in Windows, how does Windows communicate with the programs that run on it?

When you incorporate a function call which is in another memory location on the disk or memory (not a function you yourself wrote and is included in the compilation), especially the Windows API, how does the compiler know where the function is located so when the program is run it can call that function?

For example, a very simple program that displays a window which reads hello world.
You would have to call Windows API functions to achieve such features as creating the window, its size, colors and so on...

So basically what I am struggling to grasp is how the programs I write communicate with the platform, framework they are run on(generally windows for Windows API).

答:
All those windows API functions you mentioned, as well as many other functions from different APIs out there available to you that you didn't write, are contained in external library files. A library is a collection of executable code, but it doesn't have a main function so it is intended to only be called by other programs that do start with main().

In order for you to use a library, in your c/c++ project, you must go to linker settings and add a .lib file reference.  For example a lot of windows API is defined in OLE32.lib, user32.lib and kernel32.lib.

Libraries come in two flavors, they can either be static or dynamic. In static libraries all the code will be in the .lib file itself. With dynamic libraries, you will have a pair of .lib  and .dll files. DLLs (as in OLE32.dll, user32.dll, kernel32.dll) contain the actual code but .lib is still needed in order to provide your executable with function addresses (which will get loaded into memory during execution) to call.

If you followed all that so far, there's one more piece of information missing. When a DLL gets loaded into your program's memory, at different times it will get loaded into different locations, so how does linker hard code the function address to call?  To achieve this, there's a layer of indirection present.  Linker hard codes addresses to a Branch (or Jump) Table, which is an array of function pointers to actual library functions. When a DLL is loaded into the process, Windows will update that "jump table" with actual addresses of where the DLL was loaded that specific time. This way your code never has to change and can always use the same function pointer, but in reality it points to a place in memory that is filled with JMP (assembly jump instructions) which then move the execution into the right library.

The interesting part is that at least 3/4th of c/c++ developers never heard about the jump table and really do not care. This is low-level stuff that is taken care of by windows and for the most part transparent to people.

As you are still a beginner I would recommend for you to stick to c (better yet c++) and just learn to be very comfortable in writing applications and using various APIs. Then take a look at Windows Internals. Very good book, but don't get discouraged if you start reading it and there are too many things you can't understand. When I first picked up a Inside COM book, it took me 3 attempts of trying to read it before I was actually able to grasp what it was actually talking about. First 2 times I simply didn't have enough background knowledge to understand that book.

Title: Function calls to calls in windows api


问:
python factory function best practices
Suppose I have a file foo.py containing a class Foo:

```<code>class Foo(object):
   def __init__(self, data):
      ...
</code>```

Now I want to add a function that creates a Foo object in a certain way from raw source data. Should I put it as a static method in Foo or as another separate function?

```<code>class Foo(object):
   def __init__(self, data):
      ...
# option 1:
   @staticmethod
   def fromSourceData(sourceData):
      return Foo(processData(sourceData))

# option 2:
def makeFoo(sourceData):
   return Foo(processData(sourceData))
</code>```

I don't know whether it's more important to be convenient for users:

```<code>foo1 = foo.makeFoo(sourceData)
</code>```

or whether it's more important to maintain clear coupling between the method and the class:

```<code>foo1 = foo.Foo.fromSourceData(sourceData)
</code>```

答:
The choice should between a factory function and a third option instead; the class method:

```<code>class Foo(object):
   def __init__(self, data):
      ...

   @classmethod
   def fromSourceData(klass, sourceData):
      return klass(processData(sourceData))
</code>```

Classmethod factories have the added advantage that they are inheritable. You can now create a subclass of Foo, and the inherited factory method would then produce instances of that subclass.

With a choice between a function and a class method, I'd choose the class method. It documents quite clearly what kind of object the factory is going to produce, without having to make this explicit in the function name. This becomes much clearer when you not only have multiple factory methods, but also multiple classes.

Compare the following two alternatives:

```<code>foo.Foo.fromFrobnar(...)
foo.Foo.fromSpamNEggs(...)
foo.Foo.someComputedVersion()
foo.Bar.fromFrobnar(...)
foo.Bar.someComputedVersion()
</code>```

vs.

```<code>foo.createFooFromFrobnar()
foo.createFooFromSpamNEggs()
foo.createSomeComputedVersionFoo()
foo.createBarFromFrobnar()
foo.createSomeComputedVersionBar()
</code>```

Even better, your end-user could import just the Foo class and use it for the various ways you can create it, as you have all the factory methods in one place:

```<code>from foo import Foo
Foo()
Foo.fromFrobnar(...)
Foo.fromSpamNEggs(...)
Foo.someComputedVersion()
</code>```

The stdlib datetime module uses class method factories extensively, and it's API is much the clearer for it.

Title: python factory function best practices

Body:
The choice should between a factory function and a third option instead; the class method:

class Foo(object):
   def __init__(self, data):
      ...

   @classmethod
   def fromSourceData(klass, sourceData):
      return klass(processData(sourceData))

Classmethod factories have the added advantage that they are inheritable. You can now create a subclass of Foo, and the inherited factory method would then produce instances of that subclass.

With a choice between a function and a class method, I'd choose the class method. It documents quite clearly what kind of object the factory is going to produce, without having to make this explicit in the function name. This becomes much clearer when you not only have multiple factory methods, but also multiple classes.

Compare the following two alternatives:

foo.Foo.fromFrobnar(...)
foo.Foo.fromSpamNEggs(...)
foo.Foo.someComputedVersion()
foo.Bar.fromFrobnar(...)
foo.Bar.someComputedVersion()

vs.

foo.createFooFromFrobnar()
foo.createFooFromSpamNEggs()
foo.createSomeComputedVersionFoo()
foo.createBarFromFrobnar()
foo.createSomeComputedVersionBar()

Even better, your end-user could import just the Foo class and use it for the various ways you can create it, as you have all the factory methods in one place:

from foo import Foo
Foo()
Foo.fromFrobnar(...)
Foo.fromSpamNEggs(...)
Foo.someComputedVersion()

The stdlib datetime module uses class method factories extensively, and it's API is much the clearer for it.


问:
Visual Studio 2012 - Express vs Professional
I'm having trouble finding a feature comparison between Visual Studio 2012 Express Edition and the professional edition. I'm using the trial Professional version at the moment, but it'll run out soon, so I need to make a decision whether to purchase the full version.

Obviously, I can just try both initially and see if the Express edition is suitable, but the problem is that there are that many features in Visual Studio, there might be a really useful feature that was missing in the standard edition that I didn't even know existed! Or I didn't spot it was missing until later down the line. I could really do with a feature comparison list like the one for all non-Express editions here. It's a shame that page doesn't include the Express edition.

答:
Short answer: Your link is good, but you are looking in the wrong place.

A good reference to compare Express with Standard is Comparing Visual Studio and Visual Studio Express 2012 for Web edition.

In general, the Express edition is lacking all design tools that you may need for architecture.

In prior VS Express versions, there was also lack of the NuGet support, and all the add-ons that you may get from Tools tab.

Also as mentioned, in order to develop a web-application and a Windows mobile application, you have to install two different versions of the Express edition, while it is not the case with other versions.


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答:
If it is the very end of the interview, a classic question is "what are our next steps?" You want to know whether to expect another interview or if they're going straight to a decision, and also roughly when. This is the note on which the conversation ends, so save it for last.

Before that, don't worry too much about questions that "show you care" and "are eager". As an interviewer, I make note of many things, but what I was asked is rarely specifically important. Ask what you want to know. If you really have no questions, say "I had a number of things I wanted to find out about, but you've covered all of them, thank you!" and then ask what the next steps are if you feel the interview is wrapping up. (Don't ask it if 10 minutes into a one hour interview you are asked "but before I go into detail on that, is there anything you wanted to ask?")


答:
The biggest difference is that Express editions do not support plugins (No ReSharper, no add-ons).  Additionally, the non-express versions are all combined, meaning you don't have to switch back and forth to get features from individual express versions if you have a project that crosses web, desktop, etc.

UPDATE 8/6/2015 - If you're looking for a free edition of Visual Studio today, you will most likely be using the Visual Studio Community Edition, which is very different from the Express edtions (better).  Community Edition is essentially Professional Edition, but free for Individuals, and DOES support plugins!

Title: Visual Studio 2012 - Express vs Professional

Body:
I'm having trouble finding a feature comparison between Visual Studio 2012 Express Edition and the professional edition. I'm using the trial Professional version at the moment, but it'll run out soon, so I need to make a decision whether to purchase the full version.

Obviously, I can just try both initially and see if the Express edition is suitable, but the problem is that there are that many features in Visual Studio, there might be a really useful feature that was missing in the standard edition that I didn't even know existed! Or I didn't spot it was missing until later down the line. I could really do with a feature comparison list like the one for all non-Express editions here. It's a shame that page doesn't include the Express edition.


问:
How to create distinct set from other sets?
While solving the problems on Techgig.com, I got struck with one of the problems. The problem is like this:

A company organizes two trips for their employees in a year. They want to know whether all the employees can be sent on the trip or not. The condition is that no employee can go on both the trips. Also to determine which employees can go together the constraint is that the employees who have worked together in past won't be in the same group. Examples of the problem:

Suppose the work history is given as follows: {(1,2),(2,3),(3,4)}; then it is possible to accommodate all the four employees in two trips (one trip consisting of employees 1& 3 and the other having employees 2 & 4). Neither of the two employees in the same trip have worked together in past.

Suppose the work history is given as {(1,2),(1,3),(2,3)} then there is no possible way to have two trips satisfying the company rule and accommodating all the employees.

Can anyone tell me how to proceed on this problem?

答:
This problem can be reduced to a bipartite graph problem.

Bipartite Graphs

If the vertices of a graph can be divided into two groups, such that

there exists no edge between any two vertices in the same group

(for every node, there is an edge that connects it to a vertex of the other group)

Abstracting away

We notice that

the people will be partitioned into two groups

only people in different groups share some kind of relationship with each other

Knowing that an (undirected) graph is simply a visualization of a (symmetric) relation, and a partitioning of its objects (i.e. persons) into two groups, and all edges connect vertices from different groups, we can see that this in fact qualifies as a bipartite graph, if such a partitioning is indeed possible.

We conclude that we must only determine, if it is a (relaxed) bipartite graph. Relaxed, because in the proper definition, every vertex must have at least one edge, but the problem does not specify whether that is the case. This is why (2) is in parentheses.

Detecting a bipartite graph

This can be done with either a breadth-first-search (BFS) of a depth-first-search (DFS) algorithm.

We can place the first vertex into group #1. (It does not matter which)

Having done that, it is clear that all its neighbors must be placed in group #2, since neighbors are those, that have have worked with the first person. Thus, they may not be in the group #1.

Similarly, we place all the neighbors' neighbors into group #1

Continuing the same way, we assign the nodes to the two different groups.

However, in case a bipartite graph cannot be formed, we have to stumble across a node when trying to assign it to group X, that was already assigned to a group, but not group X. In that case, it is impossible to form two groups of employees where nobody has worked with each other before.

DFS/BFS modification

Upon discovering a neighboring node, we place it in the opposite group of the currently active node, if it has not been assigned one yet.

In case it has already been assigned to the same node, we know it's impossible to form a bipartite graph.

Otherwise, it has already placed into a group conforming rule (1) of a bipartite graph.

Dealing with rule (2)

In case rule (2) is not in effect, i.e. the graph has more than one connected components, DFS/BFS will terminate before having assigned all nodes to a group.

In that case, the algorithm is simply run again on a yet unassigned node, until no such nodes are left.

Getting all solutions

In case rule(2) is not in effect, there exist more than just two solutions. For a graph with c connected components, (i.e. the DFS/BFS algorithm was run c times), there are 2c solutions.

For that, we need to differentiate between the two groups created by each invocation of the BFS/DFS algorithm: gc,1 and gc,2 for run c.

After having run the algorithm c times, we distribute the c pairs to two groups, in which the employees are being separated, freely.


问:
Is Web application a Web service?
According to W3C:

Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format

Web application conforms to this definition. Its interface is HTTP.

So can web application be called web service?

答:
Quick Answer: NO, even-though they are both applications with different purpose.

Longer Answer: A web application is generally used to build websites which have UI (web pages, views, some presentation layer).

A web service is an application that provides services to consumers (web applications, thick clients, other services, mobile apps, etc.).  Those services may provide data, perform some calculation or just about anything other than providing a UI. Thus, it will have a clearly-defined API which consists of providing responses to HTTP GET and POST requests made by a remote application. Now, this doesn't mean you can't access a web service from your browser, but it means that the application won't necessarily have a GUI user interface. For example: receive all results of GET and POST requests as strings of XML/JSON, which requires a client-side parser.

Title: Is Web application a Web service?


答: The key concept is that it's all the same stuff, all the way down.  Just as you call functions to do things, those functions call system functions, which call others until at the very lowest level, there are bits connected to the outside world, where hardware like networks, keyboards and screens makes things happen.</p>

Title: Function calls to calls in windows api

Body:
When programming in Windows, how does Windows communicate with the programs that run on it?

When you incorporate a function call which is in another memory location on the disk or memory (not a function you yourself wrote and is included in the compilation), especially the Windows API, how does the compiler know where the function is located so when the program is run it can call that function?

For example, a very simple program that displays a window which reads hello world.
You would have to call Windows API functions to achieve such features as creating the window, its size, colors and so on...

So basically what I am struggling to grasp is how the programs I write communicate with the platform, framework they are run on(generally windows for Windows API).


答: I know this is generally a big no-no in books on effective programming, but I often flip the bozo bit on some people. Didn't have negative effects so far.</p>

Title: What corners have have you cut at work?

Body:
Have you ever let your coding standards slip to meet deadlines or save time?

I'll start with a trivial example:

We came up with a coding standard at work around which brackets/formatting to use and so on. I ignore it and use the auto-format tool in netbeans.