答:
I posted an answer to a similar question here.

The bottom line is that you make time.

I'll demonstrate with an anecdote.

My sister is a novelist that writes purely in her spare time. She's got a husband and a son and she's published 4 books and a few short stories. On Mondays her husband and son (though he's 7 now, but she's been writing for a long time) know that it's her time to write. So mondays between 7 and 9 she writes, and they leave her alone.

Wednesdays, my brother-in-law plays hockey in a men's league.

Title: How do you find time to work on Open Source Projects?

Body:
A bit of background: I've got a small open source project that I've started on, a basic framework which provides an object oriented means of generating HTML code (since I don't really like HTML, and I do like PHP). It has some released source, and a few downloads, but primarily, the project is for me, with the Open Source portion just being a side benefit.

The original project which caused me to be able to develop on this project has mostly gone into hibernation for the time being, which means that all the development I get to sink into it at this point is personal time only. Unfortunately, I'm currently working toward my bachelor's degree, studying for certifications, and I have a three month old baby at home. In short, by the time I get around to "me time", I rarely feel like doing work, but rather usually feel like just chilling out.

So, if there's anyone else out there who feels like they're in a similar position, what strategies have you used to keep yourself motivated toward working on the project? I would really like to at least be able to work on this until I have 100% spec coverage, but I haven't committed source in months. Anyone out there who can help?


问:
About Open source program license
I am developing an open source program which for my school project. I have done some research on it, but there are still few questions. It is a school project, it is not any advance application and I am willing to share my work.

Is that mean if I release my program with license, people will afraid to change my code because it may result in law sue?

Can I claim my product as "open source" if I don't have license, I can define some rule of it (but without law protection)?

Do i have to apply for those license (e.g. GNU), I have to submit my product code or only fulfill in a form?

答:
If the school is contracting you to creating this application, then it is most likely not your call to be sharing the code. </p>

<p>I am assuming you are volunteering for this. A program CAN be open source as well as proprietary. There is no open-source registrar or anything like that. If you share the code, it is open source. Qt for example is open source. If you put code in a certain license like GNU and place a license file explaining the terms under which you are distributing the code, that is enough. </p>

ContentLicense: CC BY-SA 3.0

Title: About Open source program license

Body:
If the school is contracting you to creating this application, then it is most likely not your call to be sharing the code.

I am assuming you are volunteering for this. A program CAN be open source as well as proprietary. There is no open-source registrar or anything like that. If you share the code, it is open source. Qt for example is open source. If you put code in a certain license like GNU and place a license file explaining the terms under which you are distributing the code, that is enough.


答:
If you choose to use one of the GNU license, then their website has a short, readable explanation of what you need to do. I'd also recommend reading the FAQs as well.

As for your questions:

That all depends on what license you put on it! If you use an open license saying "Do what you like with this code" then they're not going to be afraid of being sued.

Why not? Upload the source to the web and tell people to help themselves. That's a form of open source.

Nothing as complicated. The guide I linked to goes into more details, but can be summed up as "the process involves adding two elements to each source file of your program".

Title: About Open source program license

Body:
I am developing an open source program which for my school project. I have done some research on it, but there are still few questions. It is a school project, it is not any advance application and I am willing to share my work.

Is that mean if I release my program with license, people will afraid to change my code because it may result in law sue?

Can I claim my product as "open source" if I don't have license, I can define some rule of it (but without law protection)?

Do i have to apply for those license (e.g. GNU), I have to submit my product code or only fulfill in a form?


问:
Storing translation data as JSON column
We're deciding on how to store translations of some descriptions of database items.

We could go the traditional way and keep a translations table (and a language table and an object_translation linking table) OR we thought it might be better to just have a Description column that contains JSON like the following:

```<code>{
     "EN": "This is the translation in English",
     "EE" : "See on kirjeldus eesti keeles"
}
</code>```

Are there any serious downsides as to why we shouldn't use this? (I haven't seen it being used anywhere else)

答:
The obvious downside is that if your database doesn't support query over JSON, and especially indexing over JSON, you may have lower performance performing operations other than "fetch this blob of translations" - especially "fetch only the "EE" translations", or "tell me what doesn't have an "EE" translation.

The key advantage of storing JSON is that you can serve it much faster: key lookup, read column, dump to browser.  No need to futz with encoding it to JSON on the fly - you get the same advantage that you do serving pre-compressed static content to clients rather than on-the-fly gzip compression.

You can also balance the two: use the structured model with the link table to preserve query capabilities, but store JSON data to minimize encoding and decoding costs when you send.

Ultimately, it depends on what queries are most and least common in your problem space.

(Oh, and don't forget to think about what happens if two languages get uploaded at the same time, if you pack everything into the one column.)

Title: Storing translation data as JSON column


答:
The first thing to do is to talk to the course professor, the department, or the university's legal department. Some universities have restrictions on what you can do with coursework. In some cases, you give up all rights to the work, meaning that you do not own it and you can not do anything with it. This varies by university, and sometimes even department. In addition to legal issues, if this is a common project, there might be academic dishonesty repercussions with releasing a project done for a course. Of course, only someone from the university can answer these questions.

Assuming that you are allowed to release your program, the next thing to do is to choose a license. If you release the code, you really should apply some license to it. This license would tell people what they can and can not do with the source code in terms of using, modifying, and redistributing (among other things). It also can release you from liabilities if the source code is used improperly and causes some kind of damage.

There are many questions here on Programmers about choosing the appropriate license, so I'm not going to go into all of your options. There are a lot out there. You should consider using one of the existing licenses rather than inventing your own. Existing licenses have been carefully written and (usually) reviewed by people with a legal background - these are things that are more likely to stand up when challenged.

Once you choose a license, you just make it obvious which one you have. Usually, this includes including a LICENSE file in your release that includes the full text of the licenses. Often, individual source files will also contain a line that identifies the copyright holder and the license under which the copyright holder has released the code.

Title: About Open source program license


问:
Jython and JRuby vs. Groovy (and Java)
I am very interested in Python for programming on the JVM, and I've worked in Java and Ruby (not JRuby) a lot, and to a certain extent in Groovy.

What are the limits to the Java-Jython and Java-JRuby integration right now? What about Groovy: are there any things that a Java class can do that a Groovy class cannot? And what about IDE integration (mostly Eclipse, but IntelliJ and Netbeans are also interesting)?

I'm not interested in whether Python, Ruby or Groovy is better/more-concise/whatever. I'm just interested in how well they are working in the JVM and tools (especially IDEs) right now. My main interest is not inside a web server, if that matters.

Simple examples of getting a HelloWorld which extends a custom Java class and implements a custom Java interface would be very useful to me.

答:
Regarding Groovy, a Groovy class can certainly do everything that a Java class can, since valid Java is (almost) always valid Groovy.

I've found that Eclipse and NetBeans aren't quite ready for prime-time when it comes to Groovy/Grails development.  But IntelliJ is really good, if you have the money.

ContentLicense: CC BY-SA 2.5

Title: Jython and JRuby vs. Groovy (and Java)


问:
Browser parsers vs Stand-alone parsers
Firefox/Chromium have well implemented(?) parsers. Then why are parsers like lxml and other such parsers being developed with so much effort put into it?

Aren't they re-inventing the wheel? Or are they solving a different problem? Can't parsers in browsers be made into standalone libraries?

答:
lxml is not a new parser, it's a Python binding for libxml2 and libxslt. Both libraries were originally build for Gnome, have been around for quite a while and are used by numerous projects, either directly or via language specific bindings like lxml.

Chrome uses both (check chrome://credits/) and Firefox uses Expat1 (check: about:license) which similarly to libxml is a standalone library. Both browsers use standalone open source libraries that are quite popular, so there isn't really much re-inventing the wheel going on here.

1 Thanks Wladimir Palant

Title: Browser parsers vs Stand-alone parsers


问:
people fork my project but don't fetch from upstream - what can I do?
Several people have forked my github repo but they have not fetched-merged from upstream. So my original repo has evolved significantly since the fork took place, and meanwhile these people are showing an old outdated version of my work, which kind of makes me look bad (e.g. what they're displaying is incomplete, contains bugs that I've fixed since then, etc.).

These people apparently don't understand what a fork is for; they just push the fork button (perhaps as a way of saying "this is cool") and then walk away. Ideally what I'd like is for them either to keep their fork updated from upstream or make a significant contribution or delete the fork. Is there anything I can do about this? (There isn't, is there? This is just the price of being open source, isn't it?)

答:
Is there anything I can do about this?

Make your repo private or take your code off GitHub.

This is just the price of being open source, isn't it?

Yes. The whole point of Open Source is that others are free to change it and/or redistribute it. Depending on the licence you might be able to enforce them to use a different name when distributing it (if they have modified it, if they haven't this doesn't apply). I'm not sure if forking is considered redistributing it though...

You might want to read the Open Source Definition and check out some of the licences.


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答: I like long compile times.  It gives me more time to work on my resume.</p>


问:
Do all functional languages use garbage collection?
Is there a functional language which allows to use stack semantics - automatic deterministic destruction at the end of the scope?</p>

答:
I have to say that the question is a bit ill-defined because it assumes that there is a standard collection of "functional languages".  Almost every programming language supports some amount of functional programming.  And, almost every programming language supports some amount of imperative programming.  Where does one draw the line to say which is a functional language and which is an imperative language, other than guided by cultural prejudices and popular dogma?

A better way to phrase the question would be, "is it possible to support functional programming in a stack allocated memory".  The answer is, as already mentioned, very difficult.  Functional programming style promotes the allocation of recursive data structures at will, which requires a heap memory (whether garbage collected or reference counted).  However, there is a pretty sophisticated compiler analysis technique called region-based memory analysis using which the compiler can divide the heap into large blocks that can be allocated and deallocated automatically, in a way similar to stack allocation.  The Wikipedia page lists various implementations of the technique, for both "functional" and "imperative" languages.


问:
Establish/meet deadlines when I am constantly working with unfamiliar platforms and frameworks
I work for a product development organization that is in online advertising. The assignments I receive are almost always on platforms or tools that I have never worked on before. At first it was android. Then node.js, then windows phone, then debian packaging, then python, hadoop, ganglia, reverse engineering, geo PostgreSQL, and the list goes on.

I am happy to be able to learn so much while on the job. The problem I keep running into is meeting deadlines. Often times it is not clear what is needed to be done to accomplish a certain task. I would need to set up the relevant SDK, run intobeginning issues, read online, pore through documentation, research online for every single item of work in that platform. Sometimes I am given deadlines, sometimes I create those deadlines.

I find it very hard to meet deadlines a lot of times. One becomes faster at doing something the second time around but I never work on some language or framework for longer than a week or two. And this is very stressful and painful to deal with. I get all the flak and public shaming that comes with missing deadlines. I suspect this cannot be normal. It cannot be possible to deliver 7 windows aphone apps not knowing a single thing about c# in a week. But I managed to do it one-day after the deadline.  All I have a lot of times is google search to guide me. Often there is little to no documentation on the tool I am customizing.

I sometimes get stuck on something sometimes for hours or even days.  This takes a toll on my health and I am no longer able to burn the midnight oil for every task. This causes a lot of mental anguish and depression.

In this situation, Am I correct in thinking any deadline I provide is a shot in the dark?

Is this normal? Does every single work item for you involve learning something completely new every time? I am not sure if it is fair to say I am a poor performer for not being able to meet deadlines on tasks involving a tool I don't know anything about. How do I handle this?

答: Yeah, this a perfect recipe for burnout. You have to make your supervisors realize the ridiculous situations they are constantly putting you in. If they're staunch and refuse to budge, it's time to move elsewhere.</p>


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

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

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

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

Unixen

| = pipe not vertical bar?

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

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

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

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"

答:
At a former job, we had a religious flamewar around the pronunciation of GIF.  I argued that the G should be a hard-G because it represents the word Graphics.  My colleagues argued that since the G is in front of an I, it should be a soft-G as in giraffe.  They further argued that the creator of the format pronounces with a soft-G so we should take that as the final proof.

So, at that job, I was the author of our Output Run-Time module, abbreviated ORT.  As the creator, I demanded that it be pronounced GIF with a hard-G.  Some people hated me.

Title: Pronunciation in programming?


答:
There are two approaches to take here. The first is to take the time it took you to do the last project that was "similar" to the new one. And double it to account for the cost of setting up/learning a new environment.

The second is to let them know that you need to specialize in order to excel. A jack of all trades is a master of none.

Title: Establish/meet deadlines when I am constantly working with unfamiliar platforms and frameworks

Body:
I work for a product development organization that is in online advertising. The assignments I receive are almost always on platforms or tools that I have never worked on before. At first it was android. Then node.js, then windows phone, then debian packaging, then python, hadoop, ganglia, reverse engineering, geo PostgreSQL, and the list goes on.

I am happy to be able to learn so much while on the job. The problem I keep running into is meeting deadlines. Often times it is not clear what is needed to be done to accomplish a certain task. I would need to set up the relevant SDK, run intobeginning issues, read online, pore through documentation, research online for every single item of work in that platform. Sometimes I am given deadlines, sometimes I create those deadlines.

I find it very hard to meet deadlines a lot of times. One becomes faster at doing something the second time around but I never work on some language or framework for longer than a week or two. And this is very stressful and painful to deal with. I get all the flak and public shaming that comes with missing deadlines. I suspect this cannot be normal. It cannot be possible to deliver 7 windows aphone apps not knowing a single thing about c# in a week. But I managed to do it one-day after the deadline.  All I have a lot of times is google search to guide me. Often there is little to no documentation on the tool I am customizing.

I sometimes get stuck on something sometimes for hours or even days.  This takes a toll on my health and I am no longer able to burn the midnight oil for every task. This causes a lot of mental anguish and depression.

In this situation, Am I correct in thinking any deadline I provide is a shot in the dark?

Is this normal? Does every single work item for you involve learning something completely new every time? I am not sure if it is fair to say I am a poor performer for not being able to meet deadlines on tasks involving a tool I don't know anything about. How do I handle this?


问:
What does mathematics have to do with programming?
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...

答:
Simple answer; Math makes you fast. Sure, you can google/se/wikipedia your coding problems away, but get enough math done and you won't need to. Believe it or not, the properly trained human brain is faster than google. Moreover the more math you know the faster you will be able to understand the results google/se/wiki gives you, and the less you'll need to drill down to understand what people tell you. In the process of solving your programming problems you'll end up learning math anyway but if you focus on math it will be a far more efficient process.

Your question is kind of like a rock musician asking why they would need formal musical training. Is it possible to be successful without it? Sure. Does it make you much more of a badass if you do go with it? Absolutely.

Slightly more complicated answer - When mathematicians and programmers use the word "solution" (for problems, that is, not equations - ie not "roots") - they mean pretty much the same thing. Learning to solve math problems helps you to learn to solve programming problems.

BTW - and no offense intended to anybody whatsoever - anybody who says s/he is a good programmer but s/he hates math is a Big Fat Liar. What happened was, they got turned off of formal math by a bad hs or college instructor and ever since then they feel like they "aren't good at math". Anybody without a learning disability (ie anybody capable of learning an OO language) is capable of everything up to and including Sophomore Calculus.


问:
What parts of Code Complete haven't stood the test of time?
I was looking at Code Complete on the shelf, thinking, "Outside of the Mythical Man Month, this may be one of the few mass market Software Engineering books to stand the test of time."  For this reason, I'm thinking of jumping in to reread it.

I'm curious - has anyone else given it a second look recently?  I so, did you see anything he got very wrong?

This isn't an attack, and not a request for a book review - I am more interested in which ideas have changed over the years.

And please - no comment about, "Demarco/Spewak/Zachman stood the test of time..." I am specifically interested in Code Complete because of the breadth of ground it covers, and breadth of impact it had in the field.

答:
Code Complete covers a lot of timeless concepts such as:

strong cohesion

loose coupling

good routine names

defensive programming

self-documenting code

software reviews

unit testing

which are certainly relevant today.

Some of the concepts championed in CC are now syntactically enforced in newer languages, for instance C# doesn't allow variable in sub-scopes to be defined in a manner that hides a super-scoped definition.

Other concepts, such as Hungarian notation for variable names have fallen by the wayside in mainstream programming (although anyone still working with the Win32 API will argue vehemently that they are alive and well).  Nevertheless, the real concept behind the variable naming convention is to convey necessary meaning and clarify code, concepts that I would argue are also timeless.

All told, from what I can recall (and a quick peek inside my venerable copy of CC), I would say it is certainly worth reviewing.

I don't think, however, that it rises to the truly timeless nature of The Mythical Man Month. MMM address issues of who is doing the work, how and why are they doing it; as well as the costs and complexity of (human) communications.  MMM addresses issues which are fundamental to everything we do.  CC, in comparison, focuses on practical and pragmatic issues of how we do it.  Put another way, if a project is behind schedule, and a manager decides to add 100 people to the team, writing comprehensible code will not really make a difference.

CC doesn't really address significant issues plaguing our industry; but it does provide a good foundation for striving for the best outcome in an often impossible situation.

I would certainly consider them both required reading for anyone who care about software development; and I would recommend re-reading MM whenever you need a refresher.  CC is worth rereading if you are leading a development team, setting group standards, or training newer developers; outside of that, I personally find that I long ago internalized the material in CC and practice it on a daily basis.

Hopes that helps.  They are certainly two of my favorites.


答:
First - make sure you know who made the commitment - if it's yours, it's your problem and you should meet it. If it's not yours, its not your problem. Tell whoever made the commitment on your behalf that you will do the best you can. Now the trick - don't make commitments you can't keep. Stick to your guns.

You are being bullied -whats the laws in your country around that?

A couple of useful phases I have used (sparingly, only when I have other options)

"You cannot negotiate estimates, what features do you want to drop?
What about quality?"

"I don't do death march."

"If you think x can be
done in y, You do it. I'll enjoy watching you fail."

"Where did that estimate/timeline come from? Well, get them to do it"

"Project management is like a spring, the more you compress it, the
bigger the mess when it slips, feeling lucky?"

"You do your job, let me do mine"

"I'd love to make that
commitment, and I understand that you need x by y and how important
it is to you. To make this work I need (fill in what will make the
biggest difference)"


答:
You are absolutely right in your feelings.  There's a lot of falseness going on right now around the following areas:

"Full Stack Engineer".  It's baloney. I don't know anyone who is excellent on the backend languages, excllent in the database and excellent on the front end.  People might be good at half a dozen languages and/or three different database systems but there's still gonna be a lot they are novices at.

"Jack of all trades, master of none"  senior folks understand this and learn that they need to choose areas to specialize in.

"10,000 hours".  A common reference to being really good ('expert) at something.  Compare that to the hours you're spending in each of these areas.  You might need to live to be 178 to get expert in them all.

So the above is not "the answer", it's agreement and more fodder for your cannon... because the answer is that you need to set up a meeting with management and let them know that these projects have been great, you've loved helping the company out in all these different areas.  But you are suffering.  It's affecting your health.  You're stressed.  You want to deliver a high quality on-time product, but these circumstances are making it insanely hard.
It's made you even question your future at the company.  If you're both good and highly valued it shouldn't be a problem.


答:
Is this normal?  Does every single work item for you involve learning something completely new every time?

No.

If you want to give better estimations, learn from the past.  Keep track of how long it takes you to ramp up on a new technology versus the actual implementation.  This can be difficult if you're doing both at the same time, but try to be cognizant of the difference.

Do your estimates based on a normal workday, minus normal interruptions.  Don't account for overtime in your estimate.  Leave that for helping deal with any issues that arise.  I like to use overtime to help bring in projects on time if there are setbacks.

Always leverage what you know, even if it's completely unfamiliar territory.  For example, knowing one programming language will help you in learning another.  Once you are exposed to different paradigms, you will be able to determine the closest relative technology to draw from.  For example, if you need to use C# and don't know it, you could draw on your knowledge of Java or C++ to get going.  It's not going to be a one-to-one and there are usually different methods of accomplishing what you need, but it's a good starting point.

So, in situations like this, it's best to estimate the implementation based on something you already know.  Add in some padding for fixing issues and dealing with the unknown (usually a small percentage of the total estimate).  On top of this, you add some additional time for research and learning to get up to speed on any new technology you will need to use.  This estimate can be affected by things like availability of documentation (like API documentation, blog posts, questions on these sites).

Now that that's out of the way, we get to the other matter: predetermined deadlines.  It's one thing to miss your own estimations as they are your responsibility, but it's quite another to be given a deadline that is unrealistic (which I'm guessing is happening in your case).  In this situation, it is best to still perform your own estimate to see if the deadline is feasible or not.  If it isn't, let your supervisor know as soon as possible what your estimated deadline is and why it is different.  If you can provide a breakdown of the various tasks and hours needed to complete each, it would help support your estimate.

If management is not receptive to your input, then it may be time to look elsewhere.  The more accurate your estimates are over time, the more likely that management will listen to you if your estimates differ from theirs.  This relies on management being reasonable and objective, of course.

One more thing - you didn't mention this, but if you are allowed vacation benefits, use them.  Don't let them go unused.  You won't be doing yourself or anyone you work for any favors if your health or focus deteriorates to the point where you aren't able to complete projects favorably.  If you aren't allowed to take vacations because a project is always due by x date and it conflicts with vacation, it is time to look elsewhere - especially with the way you're expected to fulfill these requirements.

I wish you good luck.


问:
Abstract base classes and copy construction, rules of thumb
Often times it's a good idea to have an abstract base class to isolate the interface of the object.

The problem is that copy construction, IMHO, is pretty much broken by default in C++, with copy constructors being generated by default.

So, what are the gotchas when you have an abstract base class and raw pointers in derived classes?

```<code>class IAbstract
{
    ~IAbstract() = 0;
}

class Derived : public IAbstract
{
    char *theProblem;
    ...
}

IAbstract *a1 = new Derived();
IAbstract a2 = *a1;//???
</code>```

And now do you cleanly disable copy construction for the whole hierarchy? Declare copy construction as private in IAbstract?

Are there any rules of three with abstract base classes?

答: You could, of course, just make it protected and empty, so that derived classes can choose. However, more generally, your code is forbidden anyway because it's impossible to instantiate IAbstract- because it has a pure virtual function. As such, this is generally a non-issue- your interface classes can't be instantiated and therefore can never be copied, and your more derived classes can ban or keep copying as they wish.


问:
What quality level in the commit history can/should I expect/enforce?
I worked as a lone developer for a long time. During this time, I developed a way of formulating and ordering commit messages: Refactor first, describe exactly the reason for the commit in the message, link to the issue tracker, ... There is even a script to create several sorts of change log (public, company-internal, developer) from the commit history.
This way I always know, when and why the code in the codebase changed to the state it is now.

With the advent of interactive rebase and commit reordering, I can easily make sure that history (and, thus, documentation) looks exactly the way I want it to be. Bad code doesn't even get into the history. So, every commit has its well-defined purpose.

It took me years to evolve this practice, which I consider a good one. (Is it?) However, applying this to someone else's code changes (i.e., rewriting the history of someone else's changes) is, for me, a painfully time-consuming task. I have tried this in order to identify unnecessary or even faulty changes. The total size of the patch in question is slightly too big to be reviewed as a single unit, and there are a few questionable code changes.

In fact, it turns out that I cannot afford to control the code base as a "dictator". It just costs too much time. So I'd like to lose some control while maintaining a good quality of the code. Currently, I just don't see how to achieve this.

"How clean" should the history of a project be? Which format and granularity for the commits should I require? Should I ask the developer to reformat history (e.g., to split a commit), even if it would require education on how to split a commit after the fact? Should I teach developers to work on feature branches? Can commit templates help? How frequently should the changes by the others be reviewed?

答:
It is generally easiest to avoid editing the history - It can be done even in a team environment, but it requires a lot of work for little benefit and introduces a risk of data loss.

You will have some commits that are incomplete and don't build, but that is ok as long as they are on a development branch. Add the feature documentation comment when you merge the development branch into master, which does contain only completed code.


答:
Copy construction on an abstract class should be made private in most cases, as well as assignment operator.

Abstract classes are, by definition, made to be a polymorphic type. So you don't know how much memory your instance is using, and so cannot copy or assign it safely. In practice, you risk slicing : https://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c

Polymorphic type, in C++, mustn't be manipulated by value. You manipulate them by reference or by pointer (or any smart pointer).

This is the reason why Java has made object manipulable by reference only, and why C# and D has the separation between classes and structs (the first one being polymorphic and reference type, the second one being non polymorphic and value type).

Title: Abstract base classes and copy construction, rules of thumb

Body:
Often times it's a good idea to have an abstract base class to isolate the interface of the object.

The problem is that copy construction, IMHO, is pretty much broken by default in C++, with copy constructors being generated by default.

So, what are the gotchas when you have an abstract base class and raw pointers in derived classes?

```<code>class IAbstract
{
    ~IAbstract() = 0;
}

class Derived : public IAbstract
{
    char *theProblem;
    ...
}

IAbstract *a1 = new Derived();
IAbstract a2 = *a1;//???
</code>```

And now do you cleanly disable copy construction for the whole hierarchy? Declare copy construction as private in IAbstract?

Are there any rules of three with abstract base classes?


答:
Is that mean if I release my program with license, people will afraid
  to change my code because it may result in law sue?

Depends on your license. But essentially, if you put a simple GNU GPL License, or something similar, it ensures that people are free to modify. There is no problem.

Can I claim my product as "open source" if I don't have license, I can
  define some rule of it (but without law protection)?

As long as people can get access to the source code you created either for use or modify, it IS Open source. Yes, there are no other exams you need to pass!

Do i have to apply for those license (e.g. GNU), I have to submit my
  product code or only fulfill in a form?

There is no registration stuff. Simple thing is apply LICENSE to your source and put it up on web somewhere or link with your email address.

BONUS:

So is that so complicated? What all things do i have to do?

Not Much really go through GNU GPL FAQ; essentially all you have to do is copy paste a LICENSE file in the source folder and put up copyright notice (a 2 liner) in source files.

Title: About Open source program license


答:
Overall, the book is still good.  However, I do have a few small issues with it:

Chapter 17 ("Unusual Control Structures") does mention guard statements as returning from a function early, but the examples given in Chapter 15 on "if" statements advise against guard statements.  (Called guard clauses/early returns in the book)

The example in section 14.2 appears to contradict itself.  It first gives an example of "bad" code, and how to make it "good".  It then states that, when grouping related statements together, either by data or by task similarity would be "good".  The "bad" example should then also be considered "good" - and, I think, much easier to read than the "good" example, because all the data is being calculated at the same rate - there's less state to hold in your head.

Chapter 23, Debugging, where print statements are villified in a bullet point.  While I agree that they shouldn't be the only tool, they are enormously helpful in reducing the range of code where the bug occurs.  Sprinkle a few throughout to see where the data suddenly isn't what you expect, gives a good starting point for debugging, depending on the code you're working with.

I have a vague memory of another involving function arguments, but can't find it at the moment.  It may have been another book.

Title: What parts of Code Complete haven't stood the test of time?

Body:
I was looking at Code Complete on the shelf, thinking, "Outside of the Mythical Man Month, this may be one of the few mass market Software Engineering books to stand the test of time."  For this reason, I'm thinking of jumping in to reread it.

I'm curious - has anyone else given it a second look recently?  I so, did you see anything he got very wrong?

This isn't an attack, and not a request for a book review - I am more interested in which ideas have changed over the years.

And please - no comment about, "Demarco/Spewak/Zachman stood the test of time..." I am specifically interested in Code Complete because of the breadth of ground it covers, and breadth of impact it had in the field.


问:
Training a company to use a DVCS coming from a CVCS mindset, is it as hard as one would think?
So, I'm preparing to consider the outcome of training a lot of people (>25) to use Mercurial coming from a centralized mindset. I've done it with individuals and had success with it, although the time invested in each one has been different and most of them have been both proactive and open to trying something new.

I was wondering if there was someone here with experience giving such training to a large group of people as I would like to find out what are the do's and don'ts... of course, this would be more oriented towards dealing with those resistant to change, and a don't I can come to think of is telling them to avoid cheat-sheets mapping commands, as Joel Spolsky suggests.

答: One item I one consider is to look at 'same name, different functionality' issues. One of these that I've experienced with a git(dvcs)-svn(cvs) paradigm is that branching is different.  In svn one tends to branch more, this workflow partly reflecting the fact that you can't "commit locally".  When svn folks move to git, they need to learn what branches mean in terms of workflow in git and how they are often used when folks are collaborators.  This has tripped up more than one person. </p>


问:
Good example of a properly unit tested PHP project?
In hopes of getting myself and my coworkers to adopt automated unit testing methods in future projects, I would like to see a proper example on how it's done. Simple introductionary lessons to unit testing only cover very basic examples and they don't seem to convince anyone of the benefits unit testing can offer. What are some open source projects written in PHP that come with an extensive array of unit tests that are done "properly", and can be used as an example of how testing should be done?</p>

答: Most PHP frameworks these days are unit tests, for a good example of the difference in tools, Zend Framework uses PHPUnit and CakePHP uses SimpleTest. Their repos should be enough to get you started or writing "proper" unit tests.</p>


问:
Is MongoDB the right choice in my case?
I'm going to build my first real project in Rails that consist in a web app made of 3 main parts:

The static part where no database is used

The User registration part which will require a database and I can use MySQL since each user's row will have the same fields

The "App" where users will be able to create, organize, edit... items in collections and share them with other users

There will be several item types and each one will have different options for example I may have "video" items with the following options:

id

user_id

collection_id

title

platform (if embedded)

url (if embedded)

file name (if hosted on my app)

file size (id hosted on my app)

and "map" items:

id

user_id

collection_id

title

platform (google maps, bing maps...)

location

url

map size

As you can while for users I may use MySQL for items the flexibility of MongoDB may be useful since each item may need different options then another item

Up to now I've always used PHP and MySQL (always on shared hosting for small projects) and scalability is a totally new word for me.

I have time to learn but I would like to be able to do something concrete in something like 1 month.

I've read a lot about MongoDB and NoSQL vs RDMS and MySQL and after trying it I have to say that I like how MongoDB works: no tables, no rows and its documents JSON like so:

In my situation what would you raccomend? why?

About scalability there may be problems with MongoDB? if yes when (in term of DB size) and may these problems slow down my app considerably?

Edit: how the app will work

Since many asked this is how I'd like the app to work:

A user sign up

He's logged in

He create his first collection iside which he can create infinite items

Items are of various type and each type need different data to be saved in the database and type of items may be added or modified

Users may create other collections and items inside it.

So we have CRUD for collections and items inside of them and each collection/item is referred to a specific user

The main problem with MySQL is that it hasn't a flexible schema, there is way to solve this (a workaround?)?

Thinking about NoSQL the only doubt I have is about join, for example given a certain colection I want to retrieve datas related to the User with id = user_id field in the collection

EDIT: Idea to keep using MySQL

Create a field in the "items" table with optional settings, each setting divided by a | or another symbol.

Then I will save somewhere a structure of each item optional settings, for example the "notes" item type need two optional settings "colour" and "strange_setting", when I get the data from MySQL i will split the field for optional settings into an array knowing that the first item in the array is for "colour" and so on.

What do you think? there are problem with that solution? do you have other ideas?

答:
We may not be able to help you until you tell us what you intend to do with the app. Relational databases are good for certain things, and NoSQL databases are good for others.

As someone once said to me here on SO:

the relational part of a relational DB is far more optimized than
  some other parts

It means you can use a relational database also if that seems to fit with your use cases. Don't just go ahead with MongoDB because of its flexibility/scalability. This is the first line about MongoDB on Wikipedia:

MongoDB (from "humongous") is an open source document-oriented NoSQL
  database system.

Do you really intend to use a document-oriented DB? If there is some graphiness in your use cases, then you may very well go for a graph database like Neo4j. Or you can very well use the best of both SQL and NoSQL together as some people do.

BTW, I also am doing a project in which I use best parts of both SQL and NoSQL.

EDIT:
I say once again:

Check out the Neo4j vs Hadoop section on this article. It says:

In principle, Hadoop and other Key-Value stores are mostly concerned
  with relatively flat data structures. That is, they are extremely
  fast and scalable regarding retrieval of simple objects, like values,
  documents or even objects.

Referring to the same article, do you really need a flat data structure for which you are going for MongoDB? This eventually depends upon your detailed use cases, how the step 3 and 4 is going to be performed.

Additionally, you may want to refer these questions:

https://stackoverflow.com/questions/2124274/mongodb-what-to-know-before-using

https://stackoverflow.com/questions/1476295/when-to-use-mongodb-or-other-document-oriented-database-systems

(Check out the top/selected answer of the second question for sure. You're in that dilemma that this might just solve.)

I guess these questions have all the info you wanted to know. In the end, it is you who will have to decide whether it is MongoDb or something else, we can just recommend. The only people who know your detailed use cases are you and your team.

EDIT AGAIN (for the MySQL part):
As I've understood it, you are planning on storing something in the db and separating them through a separator. This presents 2 problems:

You need to additionally handle any input that will have the separator.

The relational storage part of a relational database is far more optimized than the string matching part. I would not go for a scheme where I need to do string matching in a database to get some specific result. Again I am stressing:

the relational part of a relational DB is far more optimized than
  some other parts (e.g. string matching)

Do not use multivalued attributes. People generally dread them.

Title: Is MongoDB the right choice in my case?


答:
The most important thing is to have a clear idea of what the standard workflow will be - how you will use branches and what gets pushed to the central repository.

A DVCS can be used in many ways, from a centralized model with everyone working on a single branch to sharing changes between developers without having a central server at all. The command documentation reflects this so is quite confusing for new users.

If you have a clear workflow designed you can give the users a list of common tasks instead of a list of commands, and it can be as simple as what they are used to despite being entirely different.

If you are dealing with those who are truly resistant to change, you can use git-tfs or similar - that way you don't need to train anyone who hasn't seen how much better DVCS works for a specific project.

Title: Training a company to use a DVCS coming from a CVCS mindset, is it as hard as one would think?

Body:
So, I'm preparing to consider the outcome of training a lot of people (>25) to use Mercurial coming from a centralized mindset. I've done it with individuals and had success with it, although the time invested in each one has been different and most of them have been both proactive and open to trying something new.

I was wondering if there was someone here with experience giving such training to a large group of people as I would like to find out what are the do's and don'ts... of course, this would be more oriented towards dealing with those resistant to change, and a don't I can come to think of is telling them to avoid cheat-sheets mapping commands, as Joel Spolsky suggests.


问:
what is the difference between Soak testing and Stress testing?
Can anybody explain the difference about soak and stress testing? I googled about them and found that both are about to test the software beyond its limits. Is it right for both testing strategies?</p>

答:
According to the various answers found here and on Wikipedia, soak testing seems to be a test of normal sustained use for a long period of time. This is done to to ensure bugs or memory leaks do not appear after what is considered to be a relatively "normal" usage period.

Stress testing is also a form of reliability test that tests beyond normal usage of the application for a shorter time to see if it breaks or not. In that category you can typically find testing how the application behaves when a lot of concurrent users are connected and system resources start to lack (memory, processing time, bandwidth, etc.)


问:
Path forward into making Python web applications
I currently know a working knowledge of Python and some related libraries (including the included-with-Python SQLite) for the purpose of making desktop applications.

I would now like to start to make "web applications".  By this, I mean that whatever is on the desktop application will be done by visiting a website...so the web page will have all the same sorts of widgets found in desktop apps (buttons, pulldowns, textboxes, etc).

I am not interested in making just static web sites or online magazines or things like that.

All I know about anything web-related is the basics of HTML and CSS.  I also get the sense that I will have to learn Javascript and find a Javascript widget toolkit for the widgets.  I'm unclear on what else I will need.  I've heard a lot of good things about the Django web framework, but I'm not sure what the role of a "web framework" is in the mix here (and I got the sense that Django was used mostly to build things like online magazines, not web applications), though I get the sense I will need one to handle the basics of routing information through the web.

I'm also open to the idea of using a different programming language than Python, though I like it and would prefer to keep using it.  I'd like to start simple and make small toy apps just to get the basic ideas, and then build from there.

EDIT FOR SPECIFIC QUESTION:  What are the minimum tools/services will I need to get/learn to produce web apps (as defined above) using Python?

EDIT 2:  I'm removing references to SaaS.  Let's just call it a widget-using web app.

答:
Based upon the following two things:

...I've heard a lot of good things about the Django web framework...

...though I get the sense I will need one to handle the basics of routing
  information through the web...

I'd suggest that you go for a python microframework. Flask would be a good choice. Do not go for Django if you need a subset of its features and a microframework is giving you those features.

And regarding services/tools, you may need to use atleast these for your app if you want to do on your web app whatever a user can do on a desktop:

Templating engine (e.g. Jinja)

SQL/NoSQL Database (e.g. PostgreSQL)

Form validation package (e.g. WTForms)

Caching (e.g. memcached or redis)

(Stellar) Javascript for sure, HTML5 + CSS3 or jQuery to make your work easier


答:
I think the mindset rather is something like:

Uh, I think this sounds like a cool project I can hack on when I get
  the time, maybe I can even make a major contribution, let me just fork it for
  now...

And of cause that leaves a lot of stale forks around, but maybe sometime one of these forks will become a contribution.

Title: people fork my project but don't fetch from upstream - what can I do?

Body:
Several people have forked my github repo but they have not fetched-merged from upstream. So my original repo has evolved significantly since the fork took place, and meanwhile these people are showing an old outdated version of my work, which kind of makes me look bad (e.g. what they're displaying is incomplete, contains bugs that I've fixed since then, etc.).

These people apparently don't understand what a fork is for; they just push the fork button (perhaps as a way of saying "this is cool") and then walk away. Ideally what I'd like is for them either to keep their fork updated from upstream or make a significant contribution or delete the fork. Is there anything I can do about this? (There isn't, is there? This is just the price of being open source, isn't it?)


答:
I work as a Mercurial consultant and I've found that it's not too hard to explain DVCS to new users, provided that you don't confuse them. So what I do is:

Emphasize the core principles. The history model in Mercurial is actually very clean and simple. In particular, I find that branches are modeled better in Mercurial than in, say, Subversion. Talk with the users about how working together should work in an ideal world: I do a bit of work on my machine, you do a bit of work on your machine and we later reconcile (merge) our work. Then show them how Mercurial implements exactly this model.

Emphasize the centralized workflow. A lot of guides and tutorials put a lot of emphasis on the distributed aspect of DVCS — my experience is that this is not very important! Especially not in an organization where you already use a big centralized VCS. The important part is the new and improved workflows.

Emphasize simple use cases. Let the users get hands-on experience from playing with the tool. First they will commit and push/pull with a central server. Later you can guide them through a more structured scenario where they create a feature branch, make some commits, and merge it back.

We've made some training material that we call a Mercurial Kick-Start. I've used it several times and it normally has enough content for two or three days, depending on how much I talk.


问:
Is the 'Law of Demeter' applicable to public/API method signatures?
Given that changes to the API/public method signature should be minimal to prevent breaking those client codes that use these methods, I was wondering if the Law of Demeter is less applicable to these.

A simple example:

```<code>class Account() {
   double balance;
   public void debit(Transaction t) {
      balance -= t.getAmount();
   }
}
</code>```

Notice that the debit method passes the Transaction object rather than just double amount (the 'Law of Demeter', as I understand it, would say to just pass the required info, in this case just the amount, not the Transaction object...). The reason behind this, is because the method in the future might require some other Transaction properties aside from amount. From what I understand, this will prevent breaking the method signature by adding a new parameter in the future.

Does this make it a sensible choice then? Or am I missing something?

答:
If you're planning on expanding the Account class in the future, I would say this is a situation where making the Transaction object more general purpose would be a good bending of the rules of the Law.

For example:

```<code>public class Amount {

    public void process( Transaction t ) {
        ....
    }
}

public abstract class Transaction {

    public String getType();

}
</code>```

I think I'm kind of straying from the original question, but my point is that while you may be worried that you're straying from the Law of Demeter, the advantages of doing so outweigh the negatives.

Body:
If you're planning on expanding the Account class in the future, I would say this is a situation where making the Transaction object more general purpose would be a good bending of the rules of the Law.

For example:

public class Amount {

    public void process( Transaction t ) {
        ....
    }
}

public abstract class Transaction {

    public String getType();

}

I think I'm kind of straying from the original question, but my point is that while you may be worried that you're straying from the Law of Demeter, the advantages of doing so outweigh the negatives.


问:
Are there any free tools to measure web project's performance, security and other standards?
Are there any open-source tools to measure the standard of a web application project? I want to verify my project for:

Possible security leaks (SQL Injection etc.)

Performance

Stability (in high concurrent environment)

and other quality metrics.

答:
There are many tools, some of them are free.

For Performance testing you can use the YSlow browser plugin which gives you a good overview to start with. Apache JMeter would allow for far more tests with heavy load and if you install it on several machines could test for concurrency. It's scriptable, so you could write very complex user interactions. I haven't used it for some time now, but remember, that it allowed for a lot of options how to test your website.
Other alternatives are: Selenium, Watir, HtmlUnit, siege

WebPageTest works in it's free version similar to YSlow, but runs from several servers worldwide and has a few more settings. I don't know, what the payed variant offers, but maybe worth a look.

For SQL Injection there are some tools like NetSparker which can run tests. I didn't use this one by now, but it looks promising.

Exploit-Me is a set of tools for Firefox that can test against several vulnerabilities.


答:
But this doesn't break the Law of Demeter.

More formally, the Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects:

O itself

M's parameters

any objects created/instantiated within M

O's direct component objects

a global variable, accessible by O, in the scope of M

Wikipedia: Law of Demeter

Transaction is an argument to the debit method, so calling t.getAmount() is fine.

Edit: Misread that, you are saying the LoD would have you pass the amount of the transaction, not a Transaction object. If that is the case then yes, I think this is a good place to break it, knowing you will need more from the Transaction object in the future. Also, encapsulating primitives in domain level objects is another good programming practice.

Edit 2: Having read the might need more in the future, one could also see this as unnecessary gold plating. Providing a method that takes a double now (or better a Money class) is sufficient. If you do need a Transaction argument later it's not disastrous to provide a second signature taking a Transaction, but continue to support the original signature. It's not like you would be implementing two methods, one would call the other.

Title: Is the 'Law of Demeter' applicable to public/API method signatures?

Body:
Given that changes to the API/public method signature should be minimal to prevent breaking those client codes that use these methods, I was wondering if the Law of Demeter is less applicable to these.

A simple example:

```<code>class Account() {
   double balance;
   public void debit(Transaction t) {
      balance -= t.getAmount();
   }
}
</code>```

Notice that the debit method passes the Transaction object rather than just double amount (the 'Law of Demeter', as I understand it, would say to just pass the required info, in this case just the amount, not the Transaction object...). The reason behind this, is because the method in the future might require some other Transaction properties aside from amount. From what I understand, this will prevent breaking the method signature by adding a new parameter in the future.

Does this make it a sensible choice then? Or am I missing something?


问:
Should I be bothered if my LOC/day ratio is too high?
I'm currently working on an indie project, so I don't exactly have the luxury of throughout human testing or external code review — however, I don't see any difficult bugs in my current code (I fix them as I see them, and most of the time they're just wrong field names and such, things that you fix in a minute or two), and I test it after implementing any feature before pushing it. Lately my LOC number was about 400 a day (for the record, it's C#), and I'm not only implementing new systems, but also rewrite things I've already written and fix some bugs.

Should I be bothered? Is it the sign that I need to stop and review all the code I've been writing up to this date and refactor it?

答:
If you believe in beautiful functional code, then that should be your only measure

"Does it flow? does it look beautiful?"


答:
Not at all - some days you are fixing a hard to find bug and only change one line. Other days you're adding new code and write several thousand lines.

Daily LOC doesn't tell you anything except that the tasks for that day could be accomplished with 400 lines of code.

Title: Should I be bothered if my LOC/day ratio is too high?

Body:
I'm currently working on an indie project, so I don't exactly have the luxury of throughout human testing or external code review — however, I don't see any difficult bugs in my current code (I fix them as I see them, and most of the time they're just wrong field names and such, things that you fix in a minute or two), and I test it after implementing any feature before pushing it. Lately my LOC number was about 400 a day (for the record, it's C#), and I'm not only implementing new systems, but also rewrite things I've already written and fix some bugs.

Should I be bothered? Is it the sign that I need to stop and review all the code I've been writing up to this date and refactor it?


答:
You shouldn't be bothered with number of LOC you produce per day.

But you should be bothered :

if your code is not tested (if for example, you do not have unit tests)

if you start having trouble adding new features or changing implemented features (that means your refactoring wasn't proper)

if your experience is not big, and your code is not reviewed (extra pair of eyes is likely to spot problems)


答:
LOC is probably one of the most abused metrics, and as a result is probably one of the more useless measures of code quality, and an even more useless measurement of programming effort.

Yes, that's a bold statement for me to make, and no, I can't point you to studies proving my point.  However, I can state with hard earned experience that when you start worrying about how much code you've written, you're probably worrying about the wrong problems.

You first need to ask yourself what it is you are trying to measure or prove, and whether this proof is merely out of interest, or to support a wider quality improvement and where you need to use this information to get buy-in from your team/management to do something about it.

One of the things that I tend to use LOC for is a bit of a sanity check.  If I find myself writing a lot of code, I become more interested in LOC per method, or LOC per class, rather than LOC over all. These measurements might be indicators that you have further refactoring to do if you're feeling a little OCD about how well factored your code should be.  Very large classes might need to be refactored into a few smaller classes, and long multi-line methods might need to be broken down into several methods, other classes, or may even indicate some repetition that could be removed. Notice I used the word "might" several times there.

The reality is that LOC provides only a possible indicator, and no real guarantee that your code may need to change. The real question to ask is whether the code behaves as required and as expected. If so, then your next question is whether or not you will be able to maintain the code easily, and whether you will have the time either now or in the future to make changes to working code to reduce your maintenance overheads in the future.

Often, lots of code means that you will have more to maintain later, but sometimes even well-factored code can stretch out to hundreds of lines of code, and yes, you can sometimes find yourself writing hundreds of lines of code in a day. Experience however tells me that if I am sustaining an output of hundreds of lines of new code each day, that often there is a risk that much of the code has been inappropriately cut and paste from somewhere else, and that in itself may indicate problems with duplication and maintenance, but again that is no guarantee, so I tend to rely on what my experience and instincts tell me based on how the tasks at hand were completed.

The best way to avoid the dilemma posed in your question IMHO is to forget about LOC, and refactor ALL of the time.  Write your code test first, implement to fail, refactor to pass, then see what may be refactored there and then to improve the code.  You'll leave the task knowing that you've double-checked your work already, and you won't be so concerned about second-guessing yourself in the future.  Realistically speaking, if you use a test-first approach as I've described, any LOC/day measurement on your completed code will really mean you've written 3-5 times the measured amount, with that effort hidden successfully by your ongoing refactoring efforts.


答:
LOC is an 'official' measure of productivity, but arguments against its value could be lengthy (An ORM could generate 50,000 lines of code in 3 minutes, however, if the database design is wrong all that code may go to the bin).

I suggest you measure your progress by tracking %completed task vs time vs. % tasks planned to be completed. This is what counts. Customers pay for working code that provides business value not for the LOCs.

Some references about LOC

Against: LOC-Most meaningless measure

Neutral to some extent: Wiki-LOC

Pro (I disagree with most of it but, you can take a look): Diseconomies of Scale and Lines of Code


问:
Why no more macro languages?
In this answer to a previous question of mine about scripting languages suitability as shells, DigitalRoss identifies the difference between the macro languages and the "parsed typed" languages in terms of string treatment as the main reason that scripting languages are not suitable for shell purposes. Macro languages include nroff and m4 for example.

What are the design decisions (or compromises) needed to create a macro programming language? And why are most of the mainstream languages parsed rather than macro?

This very similar question (and the accepted answer) covers fairly well why the parsed typed languages, take C for example, suffer from the use of macros. I believe my question here covers different grounds:

Macro languages or those working on a textual level are not wholly failures. Arguably, they include bash, Tcl and other shell languages. And they work in a specific niche such as shells as explained in my links above. Even m4 had a fairly long time of success, and some of the web template languages can be regarded as macro languages.

It is quite possible that macros and parsed typing do not go well together and that is why macros "break" common languages. In the answer to the linked question, a macro like #define TWO 1+1 would have been covered by the common rules of the language rather than conflicting with those of the host language. And issues like "macros are not typed" and "code doesn't compile" are not relevant in the context of a language designed as untyped and interpreted with little concern for efficiency.

The question about the design decisions needed to create a macro language pertain to a hobby project which I am currently working on on designing a new shell. Taking the previous question in context would clarify the difference between adding macros to a parsed language and my objective.

I hope the clarification shows that the question linked doesn't cover this question, which is two parts:

If I want to create a macro language (for a shell or a web template, for example), what limitations and compromises (and guidelines, if exist) need to be done?

(Probably answerable by a link or reference) Why have no macro languages succeed in becoming mainstream except in particular niches? What makes typed languages successful in large programming, while "stringly-typed" languages succeed in shells and one-liner like environments?

答:
The linked questions identify a load of issues in current macro languages. If you're going to design a new language, you should address those those issues.

For instance, take the define TWO 1+1; TWO*TWO=3 example. You can make your language robust by not including a rule for 1+1*1+1; instead require arithmetic expressions to be explicitly parenthesized. That means 1+1*1+1 is a syntax error, and should be written as (1+1)*(1+1).

Title: Why no more macro languages?


答:
Some of these answers are missing the point, you are not using LOC as a measure of productivity (if you were then you wouldn't be worrying about being too 'productive'), what you are actually doing is worrying about your code quality because code is the enemy this is a good thing to worry about.

Unfortunately the only way to know about code quality is code review, as you are a one man team this will be tricky, even if you did stop to review your code (and you don't really want to stop, right?) reviewing your own code won't reveal as much as a peer reviewing your code. I'd suggest trying to get someone else to review at least some of your code so you can tell if your 400 LOC/day is churning out gibberish or not. Even an independent review of one days code will help here


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

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

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

答:
It isn't really possible to standardise how projects should be laid out, because "it depends".

If you introduce a standard structure, but some of it isn't relevant to the requirements being developed, you can end up with additional noise that you don't need. Similarly, if the standards need to work for a wide range of projects, they will need to incorporate too many disparate scenarios.

Our job as developers is to look for patterns and best practices and apply them to the task in hand. We use our experience and expertise to choose the right file system structure for the project we are working on.


问:
How I can hide dependencies from my Services?
Here's a service abstraction that I am working on :

```<code>public abstract class Service
{
public ILogger Logger{get;set;}

public IQueryManager QueryManager{get;set;}

public ICommandManager  CommandManager{get;set;}
}
</code>```

Then I have to call them in my class as usual :

```<code>Logger.Log("Something");

QueryManager.Query(new QueryObject()).Result;

etc.
</code>```

But I'd like to have some protected helper methods to make these sentences less verbose :

```<code>Log("Something");\\calls Logger.Log("Something")

Query(new QueryObject()); \\ returns QueryManager(new QueryObject()).Result
</code>```

Is there a way so that I can implement my dependencies so that they will be hidden from children of Service ? Is there an IoC container that allows me to use private properties to inject my dependencies ?

答:
Constructor injection should be preferred over property injection in most cases..</p>

```<code>public abstract class ServiceBase
{
    // Use constructor injection to get the dependencies, but they are not exposed to derived classes...
    protected ServiceBase(ILogger logger, IQueryManager queryManager, ICommandManager commandManager)
    {
        this.Logger         = logger;
        this.QueryManager   = queryManager;
        this.CommandManager = commandManager;
    }

    private readonly ILogger Logger;
    private readonly IQueryManager QueryManager;
    private readonly ICommandManager CommandManager;

    protected void Log(String message)
    {
        this.Logger.Log(message);
    }

    protected QueryResult Query(IQueryObject queryObject)
    {
        return this.QueryManager.Query(queryObject);
    }
}

public class MyService : ServiceBase
{
    // Dependencies must still be declared in the derived constructor, even though they are not exposed to this class...
    public MyService(ILogger logger, IQueryManager queryManager, ICommandManager commandManager)
        : base(logger, queryManager, commandManager)
    {
    }

    public void Foo()
    {
        Log("hello, is this foo");

        var result = Query(new QueryObejct());
    }
}
</code>```

Body:
Constructor injection should be preferred over property injection in most cases..

public abstract class ServiceBase
{
    // Use constructor injection to get the dependencies, but they are not exposed to derived classes...
    protected ServiceBase(ILogger logger, IQueryManager queryManager, ICommandManager commandManager)
    {
        this.Logger         = logger;
        this.QueryManager   = queryManager;
        this.CommandManager = commandManager;
    }

    private readonly ILogger Logger;
    private readonly IQueryManager QueryManager;
    private readonly ICommandManager CommandManager;

    protected void Log(String message)
    {
        this.Logger.Log(message);
    }

    protected QueryResult Query(IQueryObject queryObject)
    {
        return this.QueryManager.Query(queryObject);
    }
}

public class MyService : ServiceBase
{
    // Dependencies must still be declared in the derived constructor, even though they are not exposed to this class...
    public MyService(ILogger logger, IQueryManager queryManager, ICommandManager commandManager)
        : base(logger, queryManager, commandManager)
    {
    }

    public void Foo()
    {
        Log("hello, is this foo");

        var result = Query(new QueryObejct());
    }
}


问:
When not to use ORM and prefer stored procedures?
I am using PetaPoco micro-ORM. It is indeed very easy and secure to work with databases using ORM tools, but the only thing I hate is extra code. I used to put most of the code in the database itself and use all the RDBMS features like Stored Procedures, Triggers etc.,  which it is built to handle better.

I want to know when not to use ORM over Stored Procedures/Triggers and vice-versa.

答:
Trigger should be used as invariant of record or consist of vital business rules, IMHO.

The problems of orms:

You should set permissions per tables, not per "Action"( i mean SP)

To change the logic of your solution you need to change the code inside of your app and then redistribute it over network for clients


答:
ORMs(Object-relational mapping) are not mutually exclusive with Stored Procedures. Most ORMs can utilize stored procedures. Most ORMs generate Stored Procedures if you so choose. So it the issue is not either or.

ORMs may generate unacceptable SQL (in terms of performance) and you may sometimes want to override that SQL with hand-crafted SQL. One of the ways to accomplish this is by using SPs(stored procedures).

In DotNet, Don't use stored procedures if:

If you are not familiar with stored procedures (not your case, but included for completeness).

If you don't want to introduce a layer of complexity and versifying to your project.

You are creating an application that should work with different databases or that would have to be replicated across several database servers (this last restriction may apply for some databases only).

Note that triggers are not to be compared with ORMs. Triggers do functions that are better not be in your application code (such as logging or synchronizing data across databases).

Some people prefer the use of Stored Procedures over SQL in code for different reasons such as security (for example to prevent SQL injection) and for their claimed speed. However, this is somewhat debatable and needs detailed discussion.

If your ORM can't generate Stored Procedures, and you have to write a large system, then you need to weight of the extra hand coding based on your case.

Title: When not to use ORM and prefer stored procedures?

Body:
I am using PetaPoco micro-ORM. It is indeed very easy and secure to work with databases using ORM tools, but the only thing I hate is extra code. I used to put most of the code in the database itself and use all the RDBMS features like Stored Procedures, Triggers etc.,  which it is built to handle better.

I want to know when not to use ORM over Stored Procedures/Triggers and vice-versa.

ContentLicense: CC BY-SA 4.0


问:
How do I review my own code?
I'm working on a project solo and have to maintain my own code. Usually code review is done not by the code author, so the reviewer can look at the code with the fresh eyes — however, I don't have such luxury. What practices can I employ to more effectively review my own code?</p>

答:
Take a look into the Code Review Stack Exchange site. It is for sharing code from projects you are working on for peer review:

Code Review Stack Exchange is a question and answer site for seeking peer review of your code. We're working together to improve the skills of programmers worldwide by taking working code and making it better.

If you are looking for feedback on a specific working piece of code from your project in the following areas…

Best practices and design pattern usage

Security issues

Performance

Correctness in unanticipated cases

You can also use code static analysis tools to detect certain kind of problems, but they are going to produce false alarms in some cases, and can not suggest how to improve the design.

Title: How do I review my own code?


答:
ORMs often assume that the database exists to serve the ORM. But usually the database exists to serve the company, which might have hundreds and hundreds of apps written in multiple languages hitting it.

But it's only a case of "ORM vs. Stored Procedures" if you're using an ORM that can't call a stored procedure. Otherwise, it's a case of deciding where to code  the business logic.

Wherever you code the business logic, its job is to make sure the database changes from one consistent state to another consistent state regardless of which application makes the change. So you really only have two practical choices--code it once in the database, or code it once in an "impenetrable" data access layer.

Beware of the dbms command-line interface if you use an "impenetrable" DAL.


答:
First of all, make use of tools to check as much as you can. Tests (backed up with some reasonable code coverage) will give you some confidence of the correctness of the code. Static analysis tools can catch a lot of best practice things. There will always be issues that you need human eyes on to determine though and you will never do as good a job reviewing your own stuff as someone else, there are some things you can do to help however

check tests exist and pass (possibly have a target test coverage, though you may need to break this in certain cases, but you should be able to justify why)

check Static analysis passes (there will also be false negatives here but that is fine as long as you can justify why then its fine to suppress them)

maintain a check list of further things to check in review (ideally add this as new static analysis rules if possible) make sure you check anything the SA can't check, e.g., are comments still valid, are things named appropriately (naming things is of course, one of the 2 hard problems known to computer science)

if a fault is identified check if the cause is systemic and look at why it wasn't found in earlier tests or reviews

This of course is useful when you are reviewing others code as well

Title: How do I review my own code?

Body: I'm working on a project solo and have to maintain my own code. Usually code review is done not by the code author, so the reviewer can look at the code with the fresh eyes — however, I don't have such luxury. What practices can I employ to more effectively review my own code?</p>


答:
I agree whit jk-s opinion that single-person review is not as efficient as 2 person review. however you can try to make the best of it:

short term review (shortly after the code was produced)

I am using git as a local repository. Whenever I have finished a feature or fixed a bug I transfer the changes to the repository.

Before i check in I compare what I have changed in my code and rethink:

do variable/method/classnames still reflect what they are used for?

long term review (6 months after the code was produced)

I ask myself:

can I describe in one sentense what a class/method/variable does?

how easy is it to use a class in isolation (whitout the other classes) or write a unittest for?

Title: How do I review my own code?


答:
Simple query --> ORM

Complex query --> Stored Procedure


答:
Working solo means that unless you trust complete strangers to review code on your behalf, that you will need to look at the way you write your software in order to maintain code quality.

First and foremost, you should have a means to ensure that your code is matching requirements, and second that your code will be relatively easy to change if you decide later that you got something wrong. My suggestion would be to apply a Behaviour Driven Development approach for the following reasons:

BDD means writing code test first.  This ensures all of your code is covered by tests.

BDD is essentially TDD, but with a slightly different focus and "language". What this implies is that you continuously refactor your code as you are working on it, and use your tests to ensure your refactoring efforts continue to ensure that your code satisfies your product spec.

BDD language encourages tests to be written in the form of statements that essentially encode requirements as unit tests.

So the idea here, is that your continuous refactoring of code even after you get your tests to pass, means that you are effectively reviewing your own code and using your unit tests as the "extra pair of eyes" which make sure your code doesn't stray from the requirements that are encoded in the tests. Also, high test coverage based around requirements ensures you will be able to change your code in the future without failing the requirements.

The real issue for you will be whether or not you're able to spot potential issues in your code that will indicate a need to refactor.  There are several profiling tools on the market that can help you with this, as well as several other tools which are concerned with code quality metrics. These can often tell you many things that code reviews can miss, and are a must when developing projects on your own. In reality however, experience is the key, and once you are in the habit of being merciless in your refactoring, you will likely become much more critical of your own code.  If you haven't already, I'd suggest reading Martin Fowler's Refactoring book as a starting point, and looking for a good BDD API that you feel will work for you in whichever language you have chosen to work with.

Title: How do I review my own code?


答:
Are you also measuring the number of code-duplicates?

If the high output is because you have a lot of copy&paste in you code then you should worry.

Reason: in case that there was an error in your copy&paste-source it is hard and error-prone to fix all usages of the copy&paste


问:
How do I keep an eye on a remote freelancer?
I've been hiring several developers from different places around the world. It all goes well, but I see that some of them are abusing my polite overlooking too much lately.

They are all hired for a full-day. However, I see that after 5 hours in a day, not much has been done.

I am considering to develop a software that will take a screenshot of the computer screen every 1-5 minutes and upload it to my system. However, this is going to the extremes.

How do people usually manage remote developers?

答:
What you want is called a contract. The contract say what they have to deliver and when, and what you have to pay and when.

As simple as this. Everything else would be dramatically counter productive. It will break confidence between you and the freelancer. If you want to closely look at what people are doing, then consider hiring in your office.


答:
I would create an excel sheet with a break down of each feature.

The contractor should update this daily.

Each item should have a progression defined in terms of %.

When a feature is 100%, it should be ready for you to "sign off".

If an item does function as expected, then this item needs to be flagged and corrected.

Title: How do I keep an eye on a remote freelancer?

Body:
I've been hiring several developers from different places around the world. It all goes well, but I see that some of them are abusing my polite overlooking too much lately.

They are all hired for a full-day. However, I see that after 5 hours in a day, not much has been done.

I am considering to develop a software that will take a screenshot of the computer screen every 1-5 minutes and upload it to my system. However, this is going to the extremes.

How do people usually manage remote developers?


答:
Screenshots seems counter productive.  If it comes to that, you're in trouble.

The ideal is to have tangible milestones, and check their progress against them.  If you can't get your money's worth on the milestones based on the amount of time you have to pay to get them, find other help.  If you can't create the work at this level of detail, and don't know if you're getting ripped off, it might be inappropriate to source the work remotely.  You could introduce a system of competitive bidding for the work, but if you can't detail what's needed at a low level, can you tell what the code quality is?

In general outsourcing and remote work should be about buying results, not buying time.  Otherwise, as you've found out, the trust breaks down.


答:
The Personal Software Process technique for reviews might be useful, although it relies on having historical data about your work and quality of products.

You start with historical data about your work products, specifically the number and types of defects. There are various methods of classifying defects, such as this one from a PSP course. You can develop your own, but the idea is that you need to be able to tell what mistakes you are making along the way.

Once you know what mistakes you are making, you can develop a checklist that you can use during a review. This checklist would cover the top mistakes that you are making that you think can best be caught in a review (as opposed to using some other tool). Every time you review a work product, use the checklist and look for those mistakes or errors, document them, and fix them. Periodically revise this checklist from time to time to make sure you are focusing on real, relevant problems in your code.

I would also recommend using tool support when it makes sense. Static analysis tools can help find some defects, and some even support style checking to enforce consistency and good code style. Using an IDE with code completion and syntax highlighting can also help you prevent or detect some problems before you click "build". Unit tests can cover logic problems. And if your project is sufficiently large or complex, continuous integration can combine all of these into a regularly-run process and produce nice reports for you.

Title: How do I review my own code?


答:
Whenever I've been in the same situation as yourself, I've tried to solve the problem of "being too close to the code to objectively examine it" by using code review / metric tools.  It goes without saying that a tool cannot give the same value as an experienced reviewer, but you can still use them to pinpoint areas of bad design.

One tool that I've found fairly useful in this regard was SourceMonitor.  It's a bit simplistic, but it gives a good mid-level opinion of your code, such as the number of methods in a class, and the complexity of each method.  I've always felt that this type of information was as important (if not more important than) the enforcement of coding styles via tools like StyleCop, etc (which are important, but are often not the source of the largest problems).  Use these tools with the usual disclaimers:  know when to break a rule of thumb, and something that is all green in a code metric tool isn't automatically of good quality.

Title: How do I review my own code?


答: You hire honest programmers, and you (in consultation with them and possibly other honest programmers as a reality check) set reasonable goals in short time lines.  If they don't meet the goals, fire them.  If they do meet the goals, then it shouldn't matter to you if they play solitaire for 2 hours straight while they're clearing their minds and mulling over a problem.</p>


问:
How can I get involved with developer communities in my area?
I live in Manchester, UK, and while there are lots of developer communities (regular events, get togethers etc) in London, there are not many "up north".  I know of a few (NxtGenUg and ManchesterGeekNights) but there must be more than this.

What's the best ways of finding out about these?

How have people got involved with communities in there area?

答:
Get in touch with Manchester Uni or Manchester Met student's unions... they will have programmer's societies ran by the student's union. They welcome non-students and have regular meetups. Here is a list of societies

Also check out ManLug as there is bound to be coders there, and they may be able to point you in the right direction. Manchester also has a rich hacker community.


问:
How to avoid halting of the JVM due to a deadlock in java?
I have read many websites talking about how to avoid and how to design etc. I completely understand those strategies.

My question is based on the following preconditions:

You have a company with 1000's of developers.

There are different teams working on the same product but as modules.

New developers writing new code not knowing the overall system, please consider an Enterprise application.

High available software development where a downtime of 15 mins is considered as an SLA violation.

I could write few more preconditions but I thought these could be strong enough to support my question about why I might need a recovering strategy for a "Deadlock" in a software.

Please note that re-designing the modules whenever we find a deadlock is not realistic.

Now this being said.

Can someone take sometime to provide an input or brainstorm on an idea of how to resolve a deadlock if at all it happens, so that we can report it and move forward, instead of halting completely.

Run a deadlock detector that runs periodically to look for deadlocks in the system.

If a deadlock is detected, notify with an event to resolve the deadlock.

The deadlock event listener will then kick in and act upon the deadlocked threads.

For each thread identify the contention.

Write an intelligent algorithm that could either release the locks and kill the thread or release the locks and re-evaluate the thread.

In step 2 we handle the notification in multiple ways, out of which logging is one of the listener.

I know how to go about steps 1,2,6. Will need help with 3,4 and 5.

I know that Oracle RDBMS already has a deadlock detection and resolution strategy in place, I wonder if they would ever share their strategies in this thread :)

Can't add my comment as an answer so adding it as a comment here.

=================================================================

I completely understand the risk of killing the threads. I was 100% certain that I would get answers like this but I was also hoping that someone would suggest something new. I'll keep the thread open as there is no answer in here that I already do not know, thank you very much for trying though.

答:
Given arbitrary code that is deadlocked, there is no safe way to release locks/kill threads and resume processing.  Probably your best course is to detect and log deadlocks.

If you impose limitations on the software, such as all memory updates need to use something like clojure's software transactional memory, then it may be possible to avoid deadlocks altogether, or at least recover when they occure.  That is how database software can recover from deadlocks, all modifications are happening within a transaction, so if a deadlock is detected, one transaction can be rolled back, and the other can proceed.

Avoiding deadlocks does not have to be that difficult, make sure locks are acquired in order, don't do much work while holding locks, or try to structure your code using actors or SEDA.

OwnerDisplayName: Aravind Chennuru

OwnerDisplayName: sbridges


答:
I don't think you can do this in the general case - detecting arbitrary deadlocks/livelocks in a complex system is equivalent to the halting problem so you haven't got a hope of solving it. Recovery from such situations can also be arbitrarily complex, and it's almost impossible to return the system to a "safe" state. My overall advice would be to fix the underlying architectural issues rather than trying to paper over the problem with some flawed form of automatic deadlock/livelock detection and recovery.

Basically you are trying to solve the wrong problem - the deadlocks aren't the issue, your architecture and development approach is.

By the way, if you are concerned about clients with availability SLAs, then implementing an automated deadlock detection and resolution system is one of the worst things you can do, since this could potentially corrupt your client's data (the reason you have locks in the first place is to stop data getting corrupted by concurrent transactions!).

Think about how the conversation will so: "so let me get this straight - you implemented a deadlock resolution strategy which silently corrupts our data and pretends everything is ok so that you were able to hit your SLA target?" You could be in for a pretty big lawsuit if this happens, a missed SLA is peanuts in comparison....

FWIW, I think that lock-based programming is the wrong approach anyway for complex systems. Ideally you want to make everything stateless, but if you really need mutable state then a software transactional memory based approach is IMHO the right way to handle this. STMs used correctly can't deadlock since they don't require locks. This excellent video presentation describes Clojure's STM system which is an example of what is possible in this space.

Title: How to avoid halting of the JVM due to a deadlock in java?

Body:
I have read many websites talking about how to avoid and how to design etc. I completely understand those strategies.

My question is based on the following preconditions:

You have a company with 1000's of developers.

There are different teams working on the same product but as modules.

New developers writing new code not knowing the overall system, please consider an Enterprise application.

High available software development where a downtime of 15 mins is considered as an SLA violation.

I could write few more preconditions but I thought these could be strong enough to support my question about why I might need a recovering strategy for a "Deadlock" in a software.

Please note that re-designing the modules whenever we find a deadlock is not realistic.

Now this being said.

Can someone take sometime to provide an input or brainstorm on an idea of how to resolve a deadlock if at all it happens, so that we can report it and move forward, instead of halting completely.

Run a deadlock detector that runs periodically to look for deadlocks in the system.

If a deadlock is detected, notify with an event to resolve the deadlock.

The deadlock event listener will then kick in and act upon the deadlocked threads.

For each thread identify the contention.

Write an intelligent algorithm that could either release the locks and kill the thread or release the locks and re-evaluate the thread.

In step 2 we handle the notification in multiple ways, out of which logging is one of the listener.

I know how to go about steps 1,2,6. Will need help with 3,4 and 5.

I know that Oracle RDBMS already has a deadlock detection and resolution strategy in place, I wonder if they would ever share their strategies in this thread :)

Can't add my comment as an answer so adding it as a comment here.

=================================================================

I completely understand the risk of killing the threads. I was 100% certain that I would get answers like this but I was also hoping that someone would suggest something new. I'll keep the thread open as there is no answer in here that I already do not know, thank you very much for trying though.

OwnerDisplayName: mikera


答:
I've developed several totally different persons in my head.
One of them is not even a programmer!
We're chatting, discussing latest news and reviewing each other's code.

I strongly recommend my approach.

ps
He is not kidding.

Title: How do I review my own code?


答:
First, set your code aside for as long as practical. Work on something else, some other piece of code. Even after a day, you will be amazed at what you will find.

Second, document your code. Many programmers hate to document their code, but make yourself sit down and write out documentation, how to use the code and how it works. By looking at your code in a different way, you will find mistakes.

It has been said that true mastery of a subject is the ability to teach it to someone else. With documentation you are trying to teach someone else your code.

Title: How do I review my own code?


答:
In addition to the useful tools mentioned in other answers, I think modifying your mindset it useful when doing a code review.  It's silly, but I say to myself:  "I'm putting on my code review hat".  I do the same with QA.

Then it's important to limit yourself to that mindset.  You're either the reviewer or the reviewee, you can't be both at once.  So as a reviewer, I take objective notes to share with the reviewee.  I don't change the code while I'm reviewing it, that's not something a reviewer should do.

The formality feels a little absurd at times, but I find when working solo that I'm often pulled in a lot of directions.  So I may not necessarily close the review loop before something else comes up - that formality (and really, I'm talking rough notes in a wiki tool), is useful for making sure the review gets done.  Likewise with my QA hat on, I add tickets for bugs before I fix them.

Title: How do I review my own code?