问:
How many tiers should my models have in a DB driven web app?
In my experience, the "Model" in MVC is often not really a single layer. I would regularly have "backend" models and "frontend" models, where the backend ones would have properties that I want to hide from the UI code, and the frontend ones have derived or composite properties which are more meaningful in the context of the UI.

Recently, I have started to introduce a third layer in between when database normalization created tables that did not really match the conceptual domain objects anymore. In those projects I have model classes that are equivalent with the DB structure, these become components of objects that represent the domain model, and finally these are filtered and amended for displaying information to the user.

Are there patterns or guidelines for how, when and why to organize the data model across application layers?

答:
Your keywords are "Rich domain model" and you should be aware of anemic domain model antipattern.

In my (Java) applications I have these layers:

Business objects (database object + bahaviour related to the data), transparently mapped to DB via Hibernate, injected with service dependencies using Spring anotation @Configurable - because they contain dependencies, it is possible to have data + operation at one place - embracing OO design (notice the difference when using anemic model, which has data in one layer, and operations in another (this approach is procedural and destroys polymorphism and inheritance)).

Data access objects - Encapsulate communication with DB, this layer can be easily exchanged, if I decide to change DB access implementation (for example from JPA to JDBC or maybe object DB)

Service layer - contains actions, which do not operate over business objects (hashich and crypto services) and services, that operate over a set of business objects, hence a single BO could not have this responsibility.

Service facade - The true service layer as it is known from the similarly named pattern. Encapsulates the application, provides API for calls from the outter world (only those operations, which are relevant for callers, no inner issues). Security and transaction handling is done here. As well as transformation of inner data into data transfer objects.

Data transfer objects - Simple wrappers, which just contain data to be transported to the world outside your application. You cannot use your BO, because they have methods, which cannot be called outside without context, and worse - they contain private data. Just image, if it is wise to send UserBO to outter world, when it contains hashed password and the salt. Also DTO may differ from BO - they may have different granularity.

Some view layer - I use JavaServerFaces. But with this implementation, it really does not matter, it would be the same, if there were web services, REST or even binary API.

And one more link for another good article by Alistair Cockburn - Hexagonal architecture/Ports and adapters.


问:
Moving from one man project to team project in the future. What should I be doing now in preparation and what can wait?
To elaborate I am interested in knowing what people think you need to put in place while still a one man project (team source control, documentation, builds etc) and what things don't need to be done until that point when the second person comes onto the project.

Anyone with any experience of moving through this scenario, their insights will be appreciated.

答:
I will talk from the experience, but keep in mind that everyone is different. These things are not universal.

One thing is to let it go personally. This project is something you lived with and lived in for 18 months - you would naturally want every change to be like you would do it. Give a buffer for a colleague to make mistakes, to learn. Create a room for them to be useful. And keep in mind it might not happen right away. Also it would be great if there is something, a part of the code they can feel they succeed in improving or creating, that feels like success in a short period of time. Patience and tolerance has a good pay off rate here. Do not try to micromanage, and if you want to criticize, to say "you are wrong", make sure you have a merit, you can prove it, it is not a "religious" fight.

Another key issue is to find the right person for you. Ideally it is better to find someone smarter than yourself. It is subjective and relative, but if you feel a person has some knowledge and skills you don't have, it is for the best. It will be a mutually rewarding collaboration.

There are two ways it can go - the colleague will be a drag, and you will end up redoing what he or she did, or the skills of two of you will multiply, not just add up, and you will really appreciate working together.

On a topic of "clean, fast, reusable code" - I suggest on an interview, ask to write a small micro-kernel/service manager and/or job executor. See how pluggable components are specified and configured. Doesn't have to be finished, it is a thought that counts. And also you will quickly learn people who know well how to do it will want decent money ;-) Good luck!

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Alex Pakka

ContentLicense: CC BY-SA 2.5


答:
Here are some thoughts, partly based on personal experience:

Document your project. Design specifications, diagrams, manuals and comments will help the new employee get up to speed. Explaining a complex system only verbally can prove slow and frustrating. Documentation is frequently neglected in one-man projects. Make sure yours is an exception.

At first, concentrate on API-/core-level code yourself, while giving the new employee some "application layer" work or bug fixing to gradually familiarize them with the code. Generally, start out with easier, yet meaningful and thus rewarding tasks.

Communication is important. Be responsive to the new employee's questions, comments and ideas. Explain why you think an idea is not good if you do. A fresh pair of eyes can spot room for improvement surprisingly well. If your new employee is a decent one, he can peer review your code and eventually participate in architectural decisions. Discuss, bounce ideas off each other. That is one of the greatest benefits of having a co-worker on your project.

Define responsibilities clearly, once you know what kind of tasks your new team member is up to. Establish documentation practices and coding conventions to keep things smooth.

Use a revision control system. Maintain a logical source file layout and build discipline.

As for the interview - I'm not a big fan of artificial coding tests or trick questions, unless you wish to try the candidate's stress-enduring ability. Even the smartest of problem solvers can lock up in such a situation. The qualities you'll be looking for, among others are: honesty, professional capability, technological knowledge/insight, enthusiasm and mutual compatibility. Work atmosphere can mean a great deal; it is inadvisable to pick a teammate you don't like. Place your questions right and do some informal discussion to get a good picture of your candidate. Good luck!

Title: Moving from one man project to team project in the future. What should I be doing now in preparation and what can wait?

Body:
To elaborate I am interested in knowing what people think you need to put in place while still a one man project (team source control, documentation, builds etc) and what things don't need to be done until that point when the second person comes onto the project.

Anyone with any experience of moving through this scenario, their insights will be appreciated.

OwnerDisplayName: mizo


答:
Tools and methodology

What is needed to collaborate successfully and to be productive?

Identify parts/components of your project: Distinguishing clearly between different parts (database, data access layer, web site, service, API, test projects, build scripts, ...) and environments (dev, staging, production), and naming them consistently has an impact on your oral and written communication (documentation, project names, ...)

Use a source code management system (just in case you don't yet). Think about how to use branching with your project and setup.

Automate your builds - make it as easy as possible to set up an environment from your source repository.

Test projects are a must on big projects, at least for the more complex projects.

Use staging environment(s) where your project is ready to be used. Also, create and maintain sample data for an automated staging setup.

Use a bug tracking system which can help prioritizing and planning the development, and also serves as a memory for past bugs and how they were resolved.

Document each part of your project, some more than others. I personally like: Overview - Architecture - Dependencies - Configuration - Common problems (from here). Sometimes less is more - in order to not let your documentation get outdated, it's better to be concise and let documentation become a part of your everyday activity.

Management / teamwork

... or anything else on the interpersonal level

Define your expectations of the other developer. Be reasonable, nobody's likely to bring in the same involvement and passion as you do - at least not right from the start. Communicate what you expect and what not, define your and the other one's responsibilities. Not everybody is an engineer, architect, developer, dba and sysadmin, but if that's what you're looking for, choose the right person or you will be disappointed.

At first, define tasks precisely, and review and discuss the results. Gradually, start less and less micro-managing. The idea is to build up trust and to increase responsibility.

Plan your project, set goals for your project and for your team for the next year. Write it down and check it later, this will give perspective. Those goals may or  may not be communicated to others (as long as they are goals you need to achieve, not others), it can simply be your own checklist.

Take a day to prepare and plan the first month (or two/three months) of your new developer. I find it extremely motivating when working with well prepared people. Nobody should get the impression that his/her time is wasted.

Let go. It's your baby, it should become somebody else's, too. Allow the other one to become an expert better than you, at least in some parts of the project. This means actually you succeeded.

Listen - if you hired her, she's got something to say. Be ready to learn.

Be ready to share your knowledge and experience (and therefore time - be patient).

Mistakes will be made, it's how they're handled and what everybody's learning about them what counts.

Allow time to learn and experiment

Book references

I'll list some of the commonly mentioned books that I've actually read and I think are worth reading, for a more detailed description or for more books you may want to check out some of the questions on SO asking exactly for that, like this or this question.

Those books really are worth reading in respect to teams, organizations, and programming projects:

Peopleware

Mythical Man Month

Software Estimation, Demystifying the Black Art

None of those are practical guides of how to implement methodology X (except Software estimation, this books helps you choose an appropriate estimation process). Of course, books more focused on programming itself like Code Complete are also very enriching.

OwnerDisplayName: marapet


答:
Technology

If you are bringing in someone else as a developer there are three key things I'd recommend having up and running before they start.

Source control

Issue tracking

Continuous integration

If these three things are up and running properly you'll eliminate about 75% of the common problem that occur when you bring on a new team member. The point of these pieces of technology is to take a lot of what is happening only in your head and get it out where your team member can interact with it.

Source control makes sure you are both working on the same thing.  Issue tracking helps you both keep track of what needs to be done and will make it easier for you to know what they are working on and accomplishing. Continuous integration and testing  will help make sure that you have a repeatable build process and that new improvements aren't breaking other parts of the code.

Pragmatic Programmer has some pretty good books on this. Here are a few I'd recommend. They have other similar titles based on what programming language you are using or what version control you want to use:

http://www.pragprog.com/titles/tpp/the-pragmatic-programmer
http://www.pragprog.com/titles/tsgit/pragmatic-version-control-using-git
http://www.pragprog.com/titles/auto/pragmatic-project-automation

Personal

Often times the difficulties you will face are less on the technical side of things and more on the learning to let go side.  It can be hard to give someone else control over aspects of the project--particularly if you are use to doing it all yourself and making every single decision. You will save yourself some grief if you can find an area where you can have the new person work with a reasonable amount of freedom at the beginning so you can develop a foundation of trust. If you hire a good person, the main thing you'll probably be learning is how to trust the other person to do good work even if all of their individual decisions aren't the same as what you would have made.

You want to give your new hire the freedom to solve problems in the way that works for them while keeping safeguards in place so you can catch problems early on.

OwnerDisplayName: Mark


问:
How and where do I publish my open standard?
I have been writing an open standard for a protocol I am developing. As far as writing concerns I have it under control. But the main question is where can I publish such document. I have been searching on the internet and didn't find such site where I could upload a TXT or PDF file. I have no intention of keeping secrets and I would like people to read this and if possible make protocol better.</p>

答:
It used to be, and I hope still is, that anybody can publish anything as a Request for Comments (RFC) draft document at the Internet Engineering Task Force (IETF). This is the perfect place to publish your new protocol:

http://www.ietf.org/contact-the-ietf.html

It exists entirely so that new protocols and proposed standards can be published, widely read, discussed, shot at, shot down, insulted, praised, and generally worked over and, perhaps, finally adopted.

You will look like and feel like Saint Sebastian for a time but that's  how all candidate protocols are handled.

OwnerDisplayName: Mitja Felicijan

OwnerDisplayName: Pete Wilson


问:
Why is trailing whitespace a big deal?
Trailing whitespace is enough of a problem for programmers that editors like Emacs have special functions that highlight it or get rid of it automatically, and many coding standards require you to eliminate all instances of it. I'm not entirely sure why though. I can think of one practical reason of avoiding unnecessary whitespace, and it is that if people are not careful about avoiding it, then they might change it in between commits, and then we get diffs polluted with seemingly unchanged lines, just because someone removed or added a space.

This already sounds like a pretty good reason to avoid it, but I do want to see if there's more to it than that. So, why is trailing whitespace such a big deal?

答:
A lot of these answers almost touch on the reason it's bad for me, but basically:  It "breaks" text editors.  My experience is with vim.

Vim is designed so that common actions map to letters so cleanly that you don't even have to think about what letter or key combination to hit.  Various hotkeys allow the cursor to jump around the text so quickly that it takes only a couple keystrokes to get it to wherever you want.  Even things like folding blocks of code is fast, since you can hit END or $ to jump to the end of the line, where the cursor should overlap { or } or ( or ) or something - there's no need to break your thought flow to get an idea onto the screen.

But then comes along some trailing whitespace, and the cursor's movements are no longer predictable.  Your typing process is being interrupted because something you can't see is affecting where the cursor goes, so you have to break your train of thought to send it where it should be.

Ever notice how annoyed people get when they're really focused on a task and someone interrupts them?  Yeah, finding trailing whitespace when it's least expected is exactly like that.

As a sidenote, I've also noticed that people who don't care about trailing whitespace are the ones who use the mouse for navigation, and tend to be slower typists because of it...

Title: Why is trailing whitespace a big deal?


问:
See number of SVN Checkins per folder
I have a very large SVN repository (working copy of several gb) that has just reached its 20,000th checkin. As a bit of an interesting statistic for our team (and to partly celebrate our 20,000th checkin) I'd like to make a graph showing which folders in the repository have had the most checkins.

Is there any way to do this? We mostly use integrated SVN clients in our IDE and Tortoise SVN, but I'm willing to get other tools for this one-off thing.

答:
Run

svn log <directory> | grep '^r' | wc -l

To run this for every single folder inside a working copy and get a CSV as the output:

find <directory> ( ! -regex './..' ) -type d -exec /bin/bash -v
  -c "echo -n \"{},\";svn log \"{}\"|grep '^r'| wc -l" > ./SVNLog.txt \;

Title: See number of SVN Checkins per folder


问:
What's the best way to acknowledge many FOSS sources in a single project?
I have a project which uses a large number of LGPL, Artistic and other open-source licensed libraries. What's the canonical (i.e. the "standard") way of acknowledging multiple sources in a single project download?

Also, some of the sources I've used are from sites where using the code is okay, but publishing the source isn't. What's the usual manner of attribution in that case, and the usual manner of making the source available in an open-source project?

答:
Disclaimer:

If you want a real advice, you probably have to ask a lawyer (which I'm not).

This is how I do it, but I didn't consult a lawyer either.

To everybody who reads this: feel free to tell me what I'm doing wrong :-)

What I do:

I always put an "Acknowledgements" section in the readme file of my OSS projects:

```<code>### Acknowledgements

MyCoolTool makes use of the following open source projects:

 - [Json.NET](http://json.codeplex.com/)
 - [Mercurial.Net](http://mercurialnet.codeplex.com/)
 - [MSBuild Community Tasks](http://msbuildtasks.tigris.org/)
 - [WiX](http://wix.codeplex.com/)
</code>```

(it's in Markdown, because Github/Bitbucket display that nicely formatted on the project's main page - this is an actual example from on of my projects on Bitbucket)

Plus, I check in the license files together with the libraries.

I'm not sure if this is really necessary - but most of the licenses say something like "you must distribute the binaries together with this license".

When I started worrying about licensing stuff (what license do I use for my own code? Do the licenses of the OSS projects that I want to use comply with my license?), I looked at a lot of other OSS projects to see how other people do this.

Well, most of the OSS projects I looked at just had the libraries of their dependencies in source control, but not the license files.

Even better, lots of projects have a "you must distribute this license with the binaries" license, but still they don't even distribute their own license file with their own official binary download! :-)

OwnerDisplayName: boost

Body:
Disclaimer:

If you want a real advice, you probably have to ask a lawyer (which I'm not).

This is how I do it, but I didn't consult a lawyer either.

To everybody who reads this: feel free to tell me what I'm doing wrong :-)

What I do:

I always put an "Acknowledgements" section in the readme file of my OSS projects:

### Acknowledgements

MyCoolTool makes use of the following open source projects:

 - [Json.NET](http://json.codeplex.com/)
 - [Mercurial.Net](http://mercurialnet.codeplex.com/)
 - [MSBuild Community Tasks](http://msbuildtasks.tigris.org/)
 - [WiX](http://wix.codeplex.com/)

(it's in Markdown, because Github/Bitbucket display that nicely formatted on the project's main page - this is an actual example from on of my projects on Bitbucket)

Plus, I check in the license files together with the libraries.

I'm not sure if this is really necessary - but most of the licenses say something like "you must distribute the binaries together with this license".

When I started worrying about licensing stuff (what license do I use for my own code? Do the licenses of the OSS projects that I want to use comply with my license?), I looked at a lot of other OSS projects to see how other people do this.

Well, most of the OSS projects I looked at just had the libraries of their dependencies in source control, but not the license files.

Even better, lots of projects have a "you must distribute this license with the binaries" license, but still they don't even distribute their own license file with their own official binary download! :-)


问:
How do you avoid name similarities between your classes and the native ones?
I just ran into an "interesting problem", which I would like your opinion about:

I am developing a system and for many reasons (meaning: abstraction, technology independence, etc) we create our own types for exchanging information.

For instance: if there is a method which is called SendEmail and is invoked by the business logic, it way have a parameter of type OurCompany.EMailMessage, which is an object which is completely technology independent and contains only "business relevant data" (for instance, no information abut head encoding).

Inside the SendEmail function, we get this information from our EMailMEssage object and create a MailMessage (this one is technolgy specific) object so it can be sent over the network.

As you can already notice, our class has a very similar name to the "native" language class. The problem is: this is exactly what they are, email messages, so it is hard to find another meaningful name for them.

Do you have this problem often? How do you manage it?

Edit: @mgkrebbs just commented about using fully qualified names. This is our current approach, but a little bit too verbose, IMHO. I would like something cleaner, if possible.

答:
What language are you using?  The answer is language-specific.  In general the answer is 'use namespaces'.  I would almost never mangle the type name to avoid a conflict with some external namespace.

In a single Java application it is quite common to have the same class name (e.g. "Date") defined in half a dozen namespaces.  If one class needs to use two separate Date classes, then one of the Date classes has to be fully qualified everywhere it appears, as Java does not support type aliases.  In C++ life is easier; you can just rename one of them with a typedef.


答:
In node.js I generally use a only three layers.

Data layer:

A simple layer that talks directly to the datasource. It's only job is efficiently extracting data from the source and writing to it. The datasource can be anything, a TCP endpoint, a HTTP endpoint, a database, a filesystem, etc.

Domain layer:

The domain object layer. This is similar to your "M" in MVC. It's an object representation of a domain object. It has methods for construction, manipulation, validation and other logic.

Note that a single domain object can talk to several different objects from the data layer and that several views can transform a domain object.

View layer:

The view takes a domain object and transforms in an easily printable way. For example, in the view layer I would convert a timestamp to a human readable string or do my i18n language conversion.

It also does any other view logic. Generally you have multiple view objects for a single domain object.

And of course it also converts data from the domain object into a format you want, whether it's binary, xml, json, html, some arbitary TCP protocol, plain text, csv, etc.

IO Layer

You generally also need some form of IO layer that talks to the other layers.

i.e. the IO layer

unpacks input

calls the correct domain object from either data or a domain object instance

passes the data/domain instance through the view layer

pipes the raw information returned from the view layer (html/json/binary/...) down the output

Multiple applications

Now a single application has these three layers. If I had a dynamic website then I would have these three layers on the server and these three layers on the client.

If I had my own unique data source to talk to then that remote data source would also use these three layers, it would have it's own domain objects, it's own data layer on it's own data sources and it's own view layer which other services talk to when they use me as a data source.

Pretty picture

Image Source

Title: How many tiers should my models have in a DB driven web app?

Body:
In my experience, the "Model" in MVC is often not really a single layer. I would regularly have "backend" models and "frontend" models, where the backend ones would have properties that I want to hide from the UI code, and the frontend ones have derived or composite properties which are more meaningful in the context of the UI.

Recently, I have started to introduce a third layer in between when database normalization created tables that did not really match the conceptual domain objects anymore. In those projects I have model classes that are equivalent with the DB structure, these become components of objects that represent the domain model, and finally these are filtered and amended for displaying information to the user.

Are there patterns or guidelines for how, when and why to organize the data model across application layers?


问:
How much C/C++ knowledge is needed for Objective-C/iPhone development?
First, a little background. I'm a .Net developer (C#) and have over 5 years experience in both web development and desktop applications. I've been wanting to look into iPhone development for some time now, but for one reason or another always got side tracked. I finally have a potential project on the horizon, and I'm now going full steam ahead learning this stuff.

My question is this: I haven't done any C/C++ programming since my schooling days, I've been living in managed land ever since. How much knowledge if any is needed to be successful as an iOS developer? Obviously memory management is something that I'll have to be conscious about (although with iOS 5 there seems to be something called ARC which should make my life easier), but what else? I'm not just talking about the C API (for example, in order to get the sin of a number, I call the sin() function), that's what Google is for. I'm talking about fundamental C/C++ idioms that the average C# developer is unaware of.

答:
Depends.

A programming language subset (sometimes called "the good parts") usually works fine if your goals don't push the limits of that subset.

If you want to do simple UI stuff (the stuff you could do in a web app), stick with Cocoa and Foundation data types, and you write bug-free code, you could probably get by knowing very little of the C underneath Objective C.

However, if you want to do iOS audio, video, image (etc.) processing or analysis, the APIs and reference example code you will likely be working with are mostly in C, and are C idiomatic.

But Objective C is a strict superset of C, so the typos and bugs can manifest themselves at any level of the language environment.  If your code has bugs, then you may need to know stuff in depth at the C pointer, data type, and heap level to analyze a crash and debug it.  Objective C is not "managed" and thus one can create a gnarled mess in memory either or purpose or as a complete accident.


问:
Should security restrictions cause a service to return null or throw an exception?
I'm in a bit of a disagreement with a more experienced developer on this issue, and wondering what others think about it; our environment is Java, EJB 3, services, etc.

The code I wrote calls a service to get things and to create things. The problem I ran into was that I got null pointer exceptions that didn't make sense. For example, when I ask the service to create an object, I get null back; when I try to look up an object with a known valid ID, I get null back. I spent some time trying to figure out what was wrong in my code; since I'm less experienced I usually assume I've done something wrong, but it turns out the reason for the null returns was security. If the user principal using my service didn't have the right permissions for the target service, then it simply returns null. Most other services here aren't documented very well either, so apparently this is just something you have to know.

This is rather confusing as a developer writing code that interacts with the service. It would make much more sense to me if the service thew an exception that would tell me that the user didn't have the proper permissions to load this thing or to create that thing; I would then immediately know why my service wasn't working as expected.

The more experienced developer who wrote the service argued that asking for the data is not an error condition, and that exceptions should only be thrown in an error condition, not when the user doesn't have access to the data. This data is often looked up in a GUI, and for those users without the right permissions, these things simply "do not exist". So, in short: asking is not wrong, hence no exception. Get methods return null because to those users those things "don't exist". Create methods return null when the user wasn't allowed to create that thing.

Is this normal and/or good practice? I prefer using exceptions because I find it much easier to know what's going on. So I would for example also prefer to throw a NotFoundException if you asked for an object with an invalid ID, rather than returning null.

答:
I think return null is unfriendly, when the client invoke this method and return null, the client do not know what happened and why it returned null.
So we should be throw execption which is make sense and provide a documentation to descrip this execption.</p>


问:
Is it correct to refer to OSGi as a Dependency Injection mechanism?
I read the Wikipedia articles on both, and both are not mentioned together. Also, the purpose of OSGi is not Dependency Injection. Yet, what an OSGi container like Felix does matches the description for DI.</p>

答:
OSGi is conceptually related to Dependency Injection, both are about separation of concerns. A form of Dependency Injection can be achieved in OSGi via its Declarative Services specification, as explained in:

Neil Bartlett's Getting Started with OSGi: Declarative Services and Dependencies*,

Kai Tödter's blog post Eclipse 4.0: Dependency Injection and OSGi Declarative Services,

and this OSGi DevCon Europe presentation.

You can also achieve DI in OSGi via peaberry, an extension library for Google-Guice that supports dependency injection of dynamic services and provides OSGi integration out of the box.

* Worth noting that the article is part of a series listed in OSGi Alliance's basic education on OSGi technology page.


问:
What do I need to develop a PHP extension in lampp?
Actually I'm dealing with a trouble in my system, I have to delivery the system to clients and it was built in PHP, JS, ShellScript and SQL.

I would like to encrypt the code or obfuscate it from eyes of others! Then someone from the community told me about building my own PHP extension, it sounds to me as a great idea, since it will not be with the main code of the system.

But I have a problem doing this way, if a programmer get in the extensions and find it, all the hard work has gone. Then I'm here to ask again about this matter.

What is the best way to hide my Business Logic from third parties?

I know that there are stuff like IonCube, Zend Guard, and many others. But I'm looking something that I can build myself.

Is PHP extension the right way to follow? Or some Half SaaS system, with dependencies (Business Logic) in a remote server?

About the environment

OS: Kernel Linux 2.6.37.1-1.2 -
LAMPP (Apache 2.2, MySQL 5.5  PHP 5.3.8)

In php generally the extension is located at /php/ext/ but in lampp I have no idea where it is, I just found a folder /opt/lampp/lib/php/extensions/ is that right place?

答:
What you are trying to do is commonly known as security through obscurity, and it's generally not a good idea. You can transform parts of your PHP code to PHP extensions* if you want, but your primary motivation should be efficiency not security, as every compiled piece of code can get reversed engineered with a decompiler. As Claude Shannon put it best: The enemy knows the system.

But if you really want to go through with this, one of the most efficient ways to do it is Facebook's HipHop:

HipHop transforms your PHP source code into highly optimized C++ and then compiles it with g++ to build binary files. You keep coding in simpler PHP, then HipHop executes your source code in a semantically equivalent manner and sacrifices some rarely used features – such as eval() – in exchange for improved performance.

Zend Guard is indeed marketed as a tool to protect your code from privy eyes:

Zend Guard (formerly Zend Encoder) protects your applications from reverse engineering and unauthorized customization by providing encoding and obfuscation.  It further protects from unlicensed use and redistribution by providing comprehensive licensing support.  This combined functionality makes software distribution worry free.

but that's just sales speak, Zend Guard encoding is easily broken as is IonCube's.

Granted, if you rewrite your code as extensions, or transform and compile it with HipHop, or encode and obfuscate it with Zend Guard, you are adding an extra layer of security, a very thin layer, that will probably discourage novice developers. If you really want to protect your intellectual property, you should approach this legally: Consult a lawyer and sign a contract with your clients before submitting the code.

You could of course have some of the dependencies on saas mode, provided that this won't affect the performance and efficiency of your final product. If you're doing it just for security, your doing it wrong.

* Writing extensions is quite a complex thing to do, and there's less than little documentation for it out there. A good place to start is Extension Writing Part I: Introduction to PHP and Zend, in Zend's DevZone. Just a hint: You'll need to be fluent in C and familiar with PHP's source code.


问:
Reading source code to learn
As you develop as a programmer, software developer, or coder, IMHO, you begin to see different (best or worst) practices, different algorithms, and "more than one way to do it". Seeing this code can be a great learning experience for you, even though you did not write the code. But is doing this only going to confuse you?

For example, let's say you have a library in any language that was created by a colleague, and you have been using it for a while. You decide to look at the actual source code, regardless of how extensive it is, and get a better look at how this library is written. For the sake of example, the function you use most often from this library is the max function, which finds the largest of two numbers. But this function is a lot more complicated than it needs to be. The way it is written is confusing the heck out of you, and you don't know how this works.

Will this make you a better programmer, because you realize how complicated it is for such a simple function, or will it make you a worse coder because you feel less confidant?

So my question, in general, is does reading source code make you a better programmer and if so how? If not why do people still do it?.

答:
Although it will contribute I don't believe just reading code is the main reason for becoming a better programmer.  If it was then I would be a super programmer by now with all the code I've read over the years (o I can only dream).

I think it's a combination of trying to understand the code you are reading and hence in the process determining if that code is a good/bad solution.

In the process of coming to this decision you tend to do things like:

Query the original developer on their purpose when writing said code

Read articles of other developers on whether parts of the code is good programming practice

Decide if you understood the code from one scan through.  Often if so then that is a good starting point for knowing you are reading good code.

Try to figure out a better way of doing a piece of code in the language you are developing in.

Putting these elements together will help you on the way to becoming a better programmer.

So in summary.  The reading of the code is the means.  The methodology with which you go about processing/analyzing that code is what will help you become better at programming.

Why do people do it?  Because you have to learn from somewhere and reading your peer's code gives you one avenue by which to achieve what most programmers desire.  That being an elegant/clean/extensible solution that they can sit back at the end of the day with a nice cold beer and say job done!

Title: Reading source code to learn


问:
Architecture Question
I am writing a rules/eligibility Module.
I have 2 sets of data, one is the customer data and the other is the customer products data.
Customer data to Customer products data is one to many.

Now I have to go through a set of Eligibility rules for each of this Customer product data.
For each customer products data, I can say the customer is eligible for that product or decline the eligibility and should move on to the next product record.

So in all the rules, I need to have access to customer and customer product data(the particular record that the rules are being executed against).
Since all the rules can either approve a product or decline a product, I created an interface with those 2 methods and is implementing the this interface for all the rules.
I am passing the Customer data and one product data for all the rules (because rules should be executed on each row of customer product data). An Ideal situation would be having the customer and customer product data available for the rule instead of passing them to each rule.

What is the best way of doing this in-terms of architecture?

Edit: Here is what I am doing

```<code>public class CustomerContract
{
    public DateTime StartDate { get; set; }
    public DateTime endDate { get; set; }
    //Other Contract related details

}
public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string state { get; set; }
}

public class CustomerInfo
{
    public CustomerInfo(int CustomerID)
    {
        Customer = new Customer();// Get Customer from DB
        AppliedProducts = new List<CustomerProduct>();// Get the customer products by customerID
        CurrentContract = new CustomerContract();//Get the contract by CustomerID, State
        declineReasons = new List<int>();// just intailizing. the decline codes are added by rules.
    }

    public CustomerContract CurrentContract { get; set; }
    public IList<CustomerProduct> AppliedProducts { get; set; }
    public IList<int> declineReasons { get; set; }
    public Customer Customer { get; set; }
}

public class CustomerProduct
{
    public decimal AmountCharged { get; set; }
    public int DeclineReasonID { get; set; }
    public int Product { get; set; }
    public decimal DiscountApplicable { get; set; }
    public decimal AmountQuoted { get; set; }
    public decimal Tax { get; set; }
}

public interface IRule
{
    // Since we need to have access to contracts when deciding the eligibility
    CustomerProduct ExecuteRule(CustomerProduct currentproduct, CustomerInfo customerInfo);

    //when denied,
    CustomerProduct DenyProduct(CustomerProduct currentProduct);
}

public class EligibityEngine
{
    List<IRule>  rules = new List<IRule>();
    private CustomerInfo c;

    public EligibityEngine(int CustomerID)
    {
        c = new CustomerInfo(CustomerID);
        LoadRules();
        foreach (var customerProduct in c.AppliedProducts)
        {
            ExecuteRules(customerProduct);
        }
    }

    private void ExecuteRules(CustomerProduct currentProductItem)
    {
        foreach (var rule in rules)
        {
            currentProductItem = rule.ExecuteRule(currentProductItem, c);
        }
    }

    private void LoadRules()
    {
        // add all the IRule types here
        //rules.Add();
    }
}
</code>```

When I execute the rule, I have pass the customer Product data and customer data. I have to pass the result of one rule execution to the other. In the above pattern, if the rule changes data in customerInfo class, it is not save unless it is passes as ref.

My question is I want the all rules to have access to this data with out passing them in. So I need not worry about capturing the out put of the rule.

I want the executeRule method to void.

答:
I'm not sure whether this answer will help but I give it a shot anyways.

Based on my understanding of what you are saying, here is my suggestion:

You already have a module that provides access to the customer data and you have module that provides access to the customer product data. For each of these modules define one (or more) interfaces to access the data that will be used by at least one rule.

Then create an 'IRuleContext' interface that has methods to obtain the interfaces for accessing customer data and customer product data.

Write a module "Rules" such that each rule takes a parameter of type 'IRuleContext'. For example you could have an abstract base class 'EligibilityRules' with an abstract method of 'bool AppliesTo(IRuleContext)'. Then you could implement a number concrete rules with each of them using a different algorithm to determine eligibility.

Instead of modules you could also have services, components, classes, etc. This is dependent on what technology you are using. Also make sure that your choices meet your requirements, for example a web service may not an option in your scenario.

Title: Architecture Question


问:
What language should I use for making a cross platform library?
I want to build a SyncML parsing library (no UI) which should be able to build up messages based on information provided by the host application, fed in by the library's methods. Also, the library should to be able to do callbacks to methods in the host application.

I want to be able to compile this and have it available on as many platforms as possible: Windows, Windows Phone 7 OS, OSX, iOS, Linux, Android, BlackBerry. Basically as many platforms as possible.

The priority is to have this available on mobile devices.

Questions:

What setup should I use? (programming languages, compilers, IDE etc.)

How would I compile this library for these different platforms and how would I connect to it?

Any other info? e.g. articles that cover the subject of cross-platform development?

I haven't done this sort of a cross-platform project before, so any available information to put me in the right direction would be welcomed.

Myself, I have a background in C#/.NET and Objective-C.

答:
Using the Java platform / JVM would be the obvious choice - it has the widest cross-platform coverage of any language, and if you have a C#/.Net background the concepts will be very familiar.

Note that you don't have to use Java language to gain the benefits of the Java platform - in fact nowadays, if starting a project from scratch I'd probably recomemnd one of the following:

Scala - if you want a powerful, statically typed, multi-paradigm langauge with great performance on the JVM. Could suit you if you have a C# background.

Clojure - if you prefer functional programming, like dynamic languages and enjoy living on the cutting edge. Clojure has truly excellent concurrency capabilities which may be appealing - the linked video is well worth watching for some deep insights.

Groovy - if you want a simple-but-effective dynamic object oriented scripting language that will feel very familiar to C#/Java developers.

All these languages get all the benefits of being on the JVM (fantastic JIT compiler, very effective garbage collection, a huge set of libraries) but are much more productive languages to work in.

By the way, there's already an open source SyncML library available in Java called Funambol. Not sure of the extent to which this is useful directly to you but it's an example of the fact that there is usually an open source Java library for pretty much anything.......

Thoughts on other options:

C/C++ can certainly work cross-platform, but it requires a recompile (and subsequent testing) into native code for each platform. With JVM languages that isn't necessary as the compiled bytecode itself is portable. Unless you absolutely need C/C++ for performance or access to raw hardware features, I think it is a headache you should avoid.

C# in the form of Mono could work (witness the success of Unity as a cross-platform library for example), but it's nowhere the JVM ecosystem in terms of maturity, library availability or even raw performance. Also it's never going to be 100% compatible with Microsoft .Net since .Net has windows-specific features which are a nightmare for portability. Still, worth considering if you are determined to stick with C#.

Javascript might be an outside option if you are interested in using the library on both the client and server side.


问:
How can I share my python scripts with my less python-savvy business person partner?
I'm taking financial mathematics as an elective, and I'm working with real life finance industry worker type people. It's actually kind of fun. When I pulled out a macbook at one of our meetings, I had four lifelong windows users look at me like I had three heads.

Anyway, I'm helping with design and simulation of our trading strategy, and I wrote a little thing using matplotlib to visualize historical stock data. However, these guys don't know how to use git, or install python, or deal with path-related package management things. I need to be able to send my scripts to them to use, and I need to do it with absolutely minimal effort on their part.

I was thinking something on the lines of py2exe, but I'd like to hear some advice before I go ahead.

答:
For windows there are complete distributions available as an installable ".exe" from python.org and an even more complete distribution from "ActiveState".

Although they are enormous the installation pretty much windows standard: download the file, double click on the .exe and agree to everything that pops up.

An alternative would be to wrap your script in "cherryPy" or similar web server and let them access your application via http.


问:
How to develop complex applications
I want to know the approach in developing big complex application regardless of which programming language to use. I want to know how developers make such big applications such as internet banking, API's and big database management application. How should one approach to make  such applications. I have only 1 year programming experience so far and I work as a freelancer so when I saw such applications lots of questions came in my mind. How to understand the basic need of information technology. What actually it is? How it can be useful for common people of small towns. I want everyone to make use of technology no matter they are educated or not, rich or not. Please post some suggestions.</p>

答:
There are different kind of complexity, usually two types, a complexity caused by the addition of stuff that doesn't strictly belongs to our purpose or the nature of what are you doing ( like when you add some lines of code later on just to add some functionality that you didn't have planned to give to your app ), and what is usually called "the complexity of engineering" that means that the system that you have to design probably requires a lots of elements and many connections between those just to run.

The thing is that you can't really face this kind of problems without a solid base that only a college degree can give to you. We are talking about an intensive use of the math, basic and high level notions about both the hardware and the software.

What you can easily understand is the use of some good companion like the UML language that is really useful and powerfull especially during the design process, without talking about any specific languages you just can have a big picture in front of you. Other good things are the versioning systems like Mercurial and Git that are especially used when you are working in team with other people, you can also browse every IDE is made for your language and decide what is the most appropriate for your needs.

But this are only tips, you have to build your know-how reading some books and applying something in the real world, a good book for a start can be one about algorithms and data structure.

A good language to start from is Java, a good Java project with a good design can be Android with its own system classes; try to learn Java and analyze the design of this big project in UML to begin to understand what it's like to design a very big project and what you have to care about. The design it's all about how different languages can have the same business logic and what the user is allowed to know and do, and with some languages you also have to care about some performance issues but this is something that you can learn in a college not on the internet.

Title: How to develop complex applications


答:
What you're talking about are the concepts of Software Engineering. It's difficult to really condense all you need to know into a single SO comment, when there are series of books written on the subject and it is indeed a field of its own. Here's some books you can look into to get you started, and coupled with your education should set you on the right path:

Code Complete: A Practical Handbook of Software Construction

The Pragmatic Programmer: From Journeyman to Master

Design Patterns: Elements of Reusable Object-Oriented Software

Refactoring: Improving the Design of Existing Code

Title: How to develop complex applications

Body: I want to know the approach in developing big complex application regardless of which programming language to use. I want to know how developers make such big applications such as internet banking, API's and big database management application. How should one approach to make  such applications. I have only 1 year programming experience so far and I work as a freelancer so when I saw such applications lots of questions came in my mind. How to understand the basic need of information technology. What actually it is? How it can be useful for common people of small towns. I want everyone to make use of technology no matter they are educated or not, rich or not. Please post some suggestions.</p>


答:
In one word: Modularity.

You build large software systems by composing them from smaller building blocks.  You do that by using techniques such as Object Orientation.  Each object is a complete, testable software unit in its own right.  When combined, each of these objects communicates messages between itself and other objects, creating a complete, coherent system.

Getting good at this takes awhile, because you have to figure out what each object is responsible for, and how it fits in with the rest of the system.

Think about how a car is built.  A car is a system, composed of smaller subsystems like the engine, the electrical and fuel systems.  The engine, in turn, is built up from components like the pistons, crankshaft and valves, and it is supported by an ignition system, a cooling system and a lubrication system.  The ignition system has spark plugs, wires, a coil, etc.  While the entire system is enormously complex, nothing is particularly difficult to understand if you look at its components, and how they work together.

Software works the same way.  You have methods, variables and keywords inside classes.  You instantiate objects from these classes.  You have objects that are factories that can create other objects, objects that manipulate collections of other objects, object that act as proxies, and so forth.

You learn how to build these larger systems by learning how to write smaller programs (or smaller parts of larger systems) first, and then combining those smaller parts into larger systems.

Title: How to develop complex applications


答:
This is a very wide question, with no one ready-made answer. I'll try to answer nonetheless, but my answer will be as vague as the question. I'll assume nonetheless that you are asking about how to build a large app on your own or with a colleague. Large teams are something totally different.

Careful Planning: List everything the app needs to do, trim the unneeded. Then trim gain. Keep trimming. Also, list all the tasks you have to do and break them in sub-tasks

Plan everything in different sections. I do it in this order:

I list all the main "objects" of my app. For example, books, pages, authors, users, with their properties, relations, and actions

I do the database design

I design the roles of the users, implement this in my "objects" sheet and my "database design" sheet

I describe all the main classes I will need, in quick pseudo-code

I wireframe the design (quick sketches)

I create a quick mockup with as little code as possible, as functional as possible

If you are on your own, you will want to keep the whole process loose and sketchy. Allow for changes, specially early on. You will NOT think of everything, so leave room for all the things unplanned that you will stumble on on the way.

To that effect, create you app in a modular way, with components as decoupled as possible. This makes it easier to maintain, debug, and test. I learned this the hard way as I was creating a monolithic framework, stopped working on it for a few weeks, then was totally lost in my own code. So think "plugins"

Begin with the bare essential, test, let your friends use it, see what's needed, analyze, dig out the few essential features, implement. Rinse and repeat.

Read getting real by 32 signals.

Have some sort of version control. I personally like mercurial, but whatever is fine. Just have one.

Test different languages, don't get stuck on one. Pick one functional, one object-oriented language, you will learn from each.

Stick to a language until you master it completely (contradictory yeah I know). When you will want to create mockups, begin with this language, at least you will be able to work fast.

Above all, read, read, read, and apply, apply, apply, create your own stuff and push forward for more optimized code, better standards, and whatever the language you choose, try to push it to the max. And don't listen to the "don't reinvent the wheel" thing. DO reinvent the wheel, just not when you are working for a client. If you are on a professional project, use whatever you can to make it work. But on your personal projects, build everything from the ground up. Then look up the source of similar projects and see how they did it.

Then throw everything away because what you did is most likely going to be crap the first 100 times. Rinse and repeat.

Practice makes somewhat better, after a few years (2 to 4), you should be able to manage even a very large project by yourself. But you have to be wanting to do it from day one. If you only try to build little stuff for 4 years, you won't get there.

Try to manage to have a life beside all that, because fresh air, friends and going out make it all better.

Title: How to develop complex applications


答:
First of all you should Ignore Coding until you fully understand the Requirements.

The phases of software development

Requirement Analysis : is the very first phase of project development and the most important one. You need to write down what is the requirement of the client, the users and the project itself. Take as much time as you want before proceeding to the later stages. Because if this phase is misunderstood, you might need to run back and from between phases

Design & Architecture : This is the phase where you put your requirements at work. Draw sketches of application flow, pen down the algorithms for carrying out functions. Make a nice wireframe or outlining as to how the application will look. In short consider how every requirement will be met and foreseen. Also, a good designer or architect will take into account the future expansion so you should consider that too

Coding : The part where the results can be seen. Choose any language you are comfortable with and start coding. Coding is not the hardest part and need not take as much time as Analysis or designing but this is the part you, your users and clients are concerned with. Write code as neat as possible applying different coding practices and make sure your leave less spots for the testing phase to clean up

Testing : Last but not the least important phase. Testing mostly takes more time than coding because you test your code against all circumstance ranging from user input to load performance. A thorough testing will always lead to a better product

Title: How to develop complex applications


答:
Besides the obvious problem that it breaks parsing in certain cases?  As another poster has noted it can cause subtle and difficult to trace errors.  Whitespace is not always insignificant.  In some cases, trailing whitespace can significantly change the meaning of a line of code or data.

In most cases whitespace is there to format the code for human readers. Trailing whitespace may indicate several things including:

An incomplete statement;

A missing comment;

A mistaken edit; or

Sloppy editing.

Two of these may result in incorrect funtioning, and another may make it more difficult to comprehend the code.

Title: Why is trailing whitespace a big deal?

Body:
Trailing whitespace is enough of a problem for programmers that editors like Emacs have special functions that highlight it or get rid of it automatically, and many coding standards require you to eliminate all instances of it. I'm not entirely sure why though. I can think of one practical reason of avoiding unnecessary whitespace, and it is that if people are not careful about avoiding it, then they might change it in between commits, and then we get diffs polluted with seemingly unchanged lines, just because someone removed or added a space.

This already sounds like a pretty good reason to avoid it, but I do want to see if there's more to it than that. So, why is trailing whitespace such a big deal?


答:
Your question is a big question include many aspect.
But I think the first you should be understand good and bad which each language and what`s situation best of this language using.
And then according to business requirement to decide which language you could use.
And next you should be understand this language about detail.</p>

Title: How to develop complex applications


问:
Can I use a JQuery plugin under the CC BY-SA 3.0 license in a commercial webapp?
if a JQuery plugin is released under the CC BY-SA 3.0 license, can it be used as part of a closed source commercial web application which is not redistributed, just accessible on the web?</p>

答:
The license says:

Notice — For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page.

So just make a link to the website and you'll be fine.

OwnerDisplayName: Jan Dragsbaek


问:
How do you proactively guard against errors of omission?
I'll preface this with I don't know if anyone else who's been programming as long as I have actually has this problem, but at the very least, the answer might help someone with less xp.

I just stared at this code for 5 minutes, thinking I was losing my mind that it didn't work:

```<code>    var usedNames = new HashSet<string>();
    Func<string, string> l = (s) =>
        {
            for (int i = 0; ; i++)
            {
                var next = (s + i).TrimEnd('0');
                if (!usedNames.Contains(next))
                {
                    return next;
                }
            }
        };
</code>```

Finally I noticed I forgot to add the used name to the hash set.

Similarly, I've spent minutes upon minutes over omitting context.SaveChanges().

I think I get so distracted by the details that I'm thinking about that some really small details become invisible to me - it's almost at the level of mental block.

Are there tactics to prevent this?

update: a side effect of asking this was fixing the error it would have for i > 9 (Thanks!)

```<code>    var usedNames = new HashSet<string>();
    Func<string, string> name = (s) =>
        {
            string result = s;
            if(usedNames.Contains(s))
                for (int i = 1; ; result = s + i++)
                    if (!usedNames.Contains(result))
                        break;
            usedNames.Add(result);
            return result;
        };
</code>```

答:
Experience is the best defense here.

Over time, you should become more adept at spotting these omissions from the observed behavior.

(You should also become more adept at not making them in the first place)

Stepping through the code line-by-line in the debugger should also highlight what's missing.

OwnerDisplayName: Gabriel

OwnerDisplayName: SLaks


答:
I personally find it helpful to describe my methods in comments before writing the implementation code.
That way, if I forget something, or if someone else picks it up in two weeks time, they will know what was 'supposed' to happen and should be able to implement it themselves without needing to some and ask me!

E.g

```<code>MyMethod() {
    //setup vars

    //perform complex function

    //set flag for something or other

    //save changes
}
</code>```

It won't prevent the 'I've made an error in the algorithm' type issues, unless you really go low level with the commenting, but it should prevent the 'forgotten to save changes' type errors.

Title: How do you proactively guard against errors of omission?

Body:
I'll preface this with I don't know if anyone else who's been programming as long as I have actually has this problem, but at the very least, the answer might help someone with less xp.

I just stared at this code for 5 minutes, thinking I was losing my mind that it didn't work:

```<code>    var usedNames = new HashSet<string>();
    Func<string, string> l = (s) =>
        {
            for (int i = 0; ; i++)
            {
                var next = (s + i).TrimEnd('0');
                if (!usedNames.Contains(next))
                {
                    return next;
                }
            }
        };
</code>```

Finally I noticed I forgot to add the used name to the hash set.

Similarly, I've spent minutes upon minutes over omitting context.SaveChanges().

I think I get so distracted by the details that I'm thinking about that some really small details become invisible to me - it's almost at the level of mental block.

Are there tactics to prevent this?

update: a side effect of asking this was fixing the error it would have for i > 9 (Thanks!)

```<code>    var usedNames = new HashSet<string>();
    Func<string, string> name = (s) =>
        {
            string result = s;
            if(usedNames.Contains(s))
                for (int i = 1; ; result = s + i++)
                    if (!usedNames.Contains(result))
                        break;
            usedNames.Add(result);
            return result;
        };
</code>```

Body:
I personally find it helpful to describe my methods in comments before writing the implementation code.
That way, if I forget something, or if someone else picks it up in two weeks time, they will know what was 'supposed' to happen and should be able to implement it themselves without needing to some and ask me!

E.g

MyMethod() {
    //setup vars

    //perform complex function

    //set flag for something or other

    //save changes
}

It won't prevent the 'I've made an error in the algorithm' type issues, unless you really go low level with the commenting, but it should prevent the 'forgotten to save changes' type errors.

OwnerDisplayName: dougajmcdonald


答: You could ask someone else to look over your code.</p>

OwnerDisplayName: BenH


答:
A unit test likely would've / should've  caught this omission.

```<code>Assert.AreEqual("NEXT", obj.GetNextName("NEXT"));
Assert.AreEqual("NEXT1", obj.GetNextName("NEXT"));
</code>```

It would also catch the likely bug you'll have when i = 10.

```<code>...
Assert.AreEqual("NEXT9", obj.GetNextName("NEXT"));
/* your TrimEnd call could be a bug */
Assert.AreEqual("NEXT10", obj.GetNextName("NEXT"));
</code>```

Test-driven development is proactive by its definition.  In your example, you would immediately see that it wasn't working as designed and you would get feedback as to what it was returning.

Body:
A unit test likely would've / should've  caught this omission.

Assert.AreEqual("NEXT", obj.GetNextName("NEXT"));
Assert.AreEqual("NEXT1", obj.GetNextName("NEXT"));

It would also catch the likely bug you'll have when i = 10.

...
Assert.AreEqual("NEXT9", obj.GetNextName("NEXT"));
/* your TrimEnd call could be a bug */
Assert.AreEqual("NEXT10", obj.GetNextName("NEXT"));

Test-driven development is proactive by its definition.  In your example, you would immediately see that it wasn't working as designed and you would get feedback as to what it was returning.

OwnerDisplayName: Austin Salonen


问:
When to do code reviews when doing continuous integration?
We are trying to switch to a continuous integration environment but are not sure when to do code reviews. From what I've read of continuous integration, we should be attempting to check in code as often as multiple times a day.  I assume, this even means for features that are not yet complete.

So the question is, when do we do the code reviews?

We can't do it before we check in the code, because that would slow down the process where we will not be able to do daily checkins, let alone multiple checkins per day.

Also, if the code we are checking in merely compiles but is not feature complete, doing a code review then is pointless, as most code reviews are best done as the feature is finalized.  Does this mean we should do code reviews when a feature is completed, but that unreviewed code will get into the repository?

答:
IMO, you should review code before it gets published to mainline so that mainline only ever has the highest quality code.

OTOH, a good point could be made that 'why bother reviewing if the CI test automation hasn't run on it?', so perhaps the best would be to give developers each a private branch that the CI server will build and test for them.  That way they first commit and push there, then once it passes get it reviewed, then merge to mainline (where it will get another run through the CI server).

You should definitely review non feature-complete code to make sure that scaffolding for future features is in place, or at least that there's nothing being put in that would prevent said future features from being implemented.

Also, note that code reviews don't have to be slow, or synchronous - a tool like gerrit or reviewboard or the like can make them asynchronous and fairly painless.

(Full disclosure: I used to work for SmartBear, makers of Code Collaborator, a code review tool)

OwnerDisplayName: SpecialEd

OwnerDisplayName: pjz

ContentLicense: CC BY-SA 4.0


问:
Calculation of Milestones/Task list
My project manager assigned me a task to estimate the development time for an iPad application. Lets assume that I gave estimation of 15 working days. He thought that the number of days where too many and client needed the changes to the application urgently (as in most of cases).

So, he told me: "I am going to assign two developer including you and as per my understandings and experience it won't take more than seven working days."

Clarifications

I was given the task of estimating development time for an individual. How could I be sure that 2 developers are going to finish it within 7 days? (I am new to team & I hardly know the others abilities)

Questions

Why do most of project managers / team leaders have understandings like:

If one developer requires N days,

Then two developers would require N/2 days,

Do they think something like developer = s/w production machines?

Should a team member (developer, not team lead or any higher post) estimate other developers work?

I didn't deny anything in the meeting and didn't said, but what should be the appropriate answer to convince them that N/2 formula that they follow is not correct?

答:
This is a standard estimation trap most people get into when higher authorities are do not have deeper insight into the problem. The crux of the problem is not estimate. Not even details, but typically it all boils down to perceptions (or in some case, competitive quotes that marketing guys needs to match).

Most project managers tend to pad estimates; and most people who manages PMs, knows this, and a vicious circle or the bargaining for estimates goes on. I haven't seen a PM who would won such a bargain!

In general, when you think that it is difficult to win over estimate arguments, it is time to implement Agile or iterative. In a nutshell, try to do most important thing first and invite the customer (or reps) to validate.

As a general rule, i would try to convince them with only a first firm release what everyone confirms as most important and a few milestone after that - many a times on the ground that balance depends on the understanding till this point. The more iterative you get, the better is the visibility of the project and people tend to appreciate the problems at hand better.

Second, Identify key risk areas earlier. Identify which are the key goals and milestones which has pivotal role in making project success or failure. And ensure what is the minimum time you can take to get there. Be clear and appraise anyone when potential issues (specifically requirements being still open ended) in the light of which the worst case best case ratio can still swing a lot. Identify and highlight key technology challenges. One might don't know or may be assuming that things might be easy to do.

Last, but important: Avoid getting more resources to reduce time lines.

Read this

1. article How to Deliver Quality Applications On Time and Within Budget and

2. book Rapid Development.

The essential teachings is that while most people demand fast schedule, they really need (and want) a reliable schedule. Bringing predictable, stable and more visible way of managing project brings all the desired confidence with which the why part of estimates becomes broadly more acceptable.

Over time, when people trust you more, you will see that estimation traps slowly goes away.

Title: Calculation of Milestones/Task list


答:
Only really experienced developers are able to estimate properly. The reason is that the repetitive comparison between his estimations and what really happened (errors) teach him intuitively to increase his abilities.

Very few experienced developers or managers are able to estimate for others. Estimating for a whole team is even more complicated, and I personally believe it's impossible without proper tools.

That's why collective estimation such as planning poker coupled to velocity tracking is the way to go.

Planning Poker helps team avoid being affected by cognitive bias (thoughts being influenced by beliefs, environment, etc), while velocity tracking, later used in planning helps the manager to convert subjective estimations to realistic estimations.

Title: Calculation of Milestones/Task list

Body:
My project manager assigned me a task to estimate the development time for an iPad application. Lets assume that I gave estimation of 15 working days. He thought that the number of days where too many and client needed the changes to the application urgently (as in most of cases).

So, he told me: "I am going to assign two developer including you and as per my understandings and experience it won't take more than seven working days."

Clarifications

I was given the task of estimating development time for an individual. How could I be sure that 2 developers are going to finish it within 7 days? (I am new to team & I hardly know the others abilities)

Questions

Why do most of project managers / team leaders have understandings like:

If one developer requires N days,

Then two developers would require N/2 days,

Do they think something like developer = s/w production machines?

Should a team member (developer, not team lead or any higher post) estimate other developers work?

I didn't deny anything in the meeting and didn't said, but what should be the appropriate answer to convince them that N/2 formula that they follow is not correct?


答:
I don't know if it is the best way to do it... but I'll explain how we do it. One or more developers work on a given branch and commit their code as often as they can in order to avoid wasting time on a merge that would not have happened otherwise. Only when the code is ready is it committed into the head. Now that's for the commits and branch/head thing.

As for the code review, we use Sonar as our continuous integration tool (and Maven/Jenkins for interacting with Sonar) for providing us with fresh test results, code coverage, and automatic code review every morning (builds are done nightly) so that we developers can spend a maximum of one hour every morning to fix their problems/code smells. Each developer takes responsibility (being proud too!) for the feature he is writing. Now, that's automatic code review, which is great to find potential technical/architectural problems, but what is more important is to test if these new implemented features are doing what the business wants them to do, properly.

And for that, there are two things: integration tests and peer code review. Integration tests help in being reasonably confident that the new code does not break the existing code. As for the peer code review, we do it on Friday afternoons, which is a bit more relaxed time to do that :-) Each developer is assigned to a branch he does not work on, takes some time to read the requirements of the new feature first, and then checks what has been done. His most important job is to make sure that the new code works as expected given the requirements, does not break our own "rules" (use this object for that, and not that one), is easy to read, and that it allows for easy extension.

So we have two code reviews, one automatic and one "human" and we try to avoid committing unreviewed code into the HEAD branch. Now... It does happen sometimes for various reasons, we're far from perfect, but we try to keep a fair balance between quality and cost (time!)

@pjz provides a good answer too, and he mentions code review tools. I've never used any, so I can't say anything about that... although I have been tempted in the past to work with Crucible since we're already using JIRA.

Title: When to do code reviews when doing continuous integration?

Body:
We are trying to switch to a continuous integration environment but are not sure when to do code reviews. From what I've read of continuous integration, we should be attempting to check in code as often as multiple times a day.  I assume, this even means for features that are not yet complete.

So the question is, when do we do the code reviews?

We can't do it before we check in the code, because that would slow down the process where we will not be able to do daily checkins, let alone multiple checkins per day.

Also, if the code we are checking in merely compiles but is not feature complete, doing a code review then is pointless, as most code reviews are best done as the feature is finalized.  Does this mean we should do code reviews when a feature is completed, but that unreviewed code will get into the repository?


问:
Unit testing - getting started
I am just getting started with unit testing but I am not sure if I really understand the point of it all. I read tutorials and books on it all, but I just have two quick questions:

I thought the purpose of unit testing is to test code we actually wrote. However, to me it seems that in order to just be able to run the test, we have to alter the original code, at which point we are not really testing the code we wrote but rather the code we wrote for testing.

Most of our codes rely on external sources. Upon refactoring our code however, even it would break the original code, our tests still would run just fine, since the external sources are just muck-ups inside our test cases. Doesn't it defeat the purpose of unit testing?

Sorry if I sound dumb here, but I thought someone could enlighten me a bit.

Thanks in advance.

答: Some clever guy said "If it's hard to test, is is probably bad code". Thats why it is not a bad thing to rewrite code, to be able to unittest it. Code with external dependencies is VERY HARD to test, it represents a risc to the code, and should be avoided whereever possible, and concentrated in integration specific areas of your code, fx. facade/gateway type classes. This will make a change in the external component much easier to cope with. </p>

OwnerDisplayName: higgenkreuz

Title: Unit testing - getting started


答:
Does this mean we should do code reviews when a feature is completed, but that unreviewed code will get into the repository?

Well above is the way I've seen it done in at least three projects that were intensively using continuous integration and per my recollection it worked like a charm. This practice is known as post-commit code reviews - search web for this term if you're interested in details.

On the other hand, the only case when I've been in project trying to "marry" pre-commit code reviews with CI turned out rather painful. Well when things went 100% smoothly, it was OK - but even infrequent interruptions (like when main and backup reviewers were both unavailable for say a few hours) made noticeable stress. I also noticed that team morale somewhat suffered - there were a bit too much conflicts.


问:
Are there any good Java/JVM libraries for my Expression Tree architecture?
My team and I are developing an enterprise-level application and I have devised an architecture for it that's best described as an "Expression Tree". The basic idea is that the leaf nodes of the tree are very simple expressions (perhaps simple values or strings). Nodes closer to the trunk will get more and more complex, taking the simpler nodes as their inputs and returning more complex results for their parents.

Looking at it the other way, the application performs some task, and for this it creates a root expression. The root expression divides its input into smaller units and creates child expressions, which when evaluated it can use to build it's own result. The subdividing process continues until the simplest leaf nodes.

There are two very important aspects of this architecture:

It must be possible to manipulate nodes of the tree after it is built. The nodes may be given new input values to work with and any change in result for that node needs to be propagated back up the tree to the root node.

The application must make best use of available processors and ultimately be scalable to other computers in a grid or in the cloud. Nodes in the tree will often be updating concurrently and notifying other interested nodes in the tree when they get a new value.

Unfortunately, I'm not at liberty to discuss my actual application, but to aid understanding a little bit, you might imagine a kind of spreadsheet application being implemented with a similar architecture, where changes to cells in the table are propagated all over the place to other cells that need the result. The spreadsheet could get so massive that applying multi-core multi-computer distributed system to solve it would be of benefit.

I've got my prototype "Expression Engine" working nicely on a single multi-core PC but I've started to run into a few concurrency issues (as expected because I haven't been taking too much care so far) so it's now time to start thinking about migrating the Engine to a more robust library, and that leads to a number of related questions:

Is there any precedent for my "Expression Tree" architecture that I could research?

What programming concepts should I consider. I realise this approach has many similarities to a functional programming style, and I'm already aware of the concepts of using futures and actors. Are there any others?

Are there any languages or libraries that I should study? This question is inspired by my accidental discovery of Scala and the Akka library (which has good support for Actors, Futures, Distributed workloads etc.) and I'm wondering if there is anything else I should be looking at as well?

答:
This sounds like a very good use-case for Clojure. Quick bullets:

Functional language (lazy, impure) - the dominant idiom for creating programs is by composing functions in a very similar manner to your expression trees.

Lisp - as a homoiconic languages it's perfect for code generation and DSLs

JVM language with very easy access to all Java libraries and tools

Amazing concurrency features - see this video

Interactive developemnt (ability to interact with running program via REPL, redefining objects on the fly etc).

Dynamically typed

Furthermore, you seem to be descibing a Dataflow Architecture. There has been quite a lot of study on such approaches and they are indeed well suited to many domains. If you wanted to implement a distributed dataflow architecture using such "Expression Trees" you might be able to build upon the following:

Clojure for defining the core expression tree language

Storm library for distributed processing

Incanter for statistics, data processing and visualisation


问:
Being stupid to get better productivity?
I've spent a lot of time reading different books about "good design", "design patterns", etc. I'm a big fan of the SOLID approach and every time I need to write a simple piece of code, I think about the future. So, if implementing a new feature or a bug fix requires just adding three lines of code like this:

if(xxx) {
    doSomething();
}
```

It doesn't mean I'll do it this way. If I feel like this piece of code is likely to become larger in the nearest future, I'll think of adding abstractions, moving this functionality somewhere else and so on. The goal I'm pursuing is keeping average complexity the same as it was before my changes.

I believe, that from the code standpoint, it's quite a good idea - my code is never long enough, and it's quite easy to understand the meanings for different entities, like classes, methods, and relations between classes and objects.

The problem is, it takes too much time, and I often feel like it would be better if I just implemented that feature "as is". It's just about "three lines of code" vs. "new interface + two classes to implement that interface".

From a product standpoint (when we're talking about the result), the things I do are quite senseless. I know that if we're going to work on the next version, having good code is really great. But on the other side, the time you've spent to make your code "good" may have been spent for implementing a couple of useful features.

I often feel very unsatisfied with my results - good code that only can do A is worse than bad code that can do A, B, C, and D.

Is this approach likely to result in a positive net gain for a software project, or is it a waste of time?

答:
"good code that only can do A is worse than bad code that can do A, B, C, and D."

This may make some sense in product development; But most of the IT professionals work in 'projects' rather than product developemnt.

In 'IT projects', if you program a good componenet, it will function smoothly for the life time of the project - which may not run longer than 5 or 10 years by then the business scenario might have beome obsolete and a new project/ERP product might have replaced it. During this 5/10 year life span, unless htere are defects in your code, no one will notice it's existance and merits of your best thoughts are gone unnoticed! (unless you are good in beting your own trumpet loud!)

Not many get an opportunity to program the 'Windows Ctl+Alt+Del' and those few get that chance may not realise the future-potential of their code!


问:
Next in Concurrency
For past year I have been working a lot on concurrency in Java and have build and worked on many concurrent packages. So in terms of development in the concurrent world, I am quite confident. Further I am very much interested to learn and understand more about concurrent programming.

But I am unable to answer myself what next? What extra should I learn or work on to inherit more skills related to Multi-core processing. If there is any nice book (read and enjoyed 'concurrency in practice' and 'concurrent programming in java') or resource's related to Multi-core processing so that I can go to the next level?

答:
I'd strongly suggest you go and take a look at Clojure

The approach to concurrency is very novel, and in my view a significant advance on what you see in Java and most other languages. Some key points:

Identity and state are separated - OOP complects object identity with it's current state in the form of mutable member variables. Clojure strictly separates identity (managed references) and state (immutable data structures) in a way that significant simplifies development of reliable concurrent programs.

Persistent immutable data structures - because everything is immutable, you can take a snapshot of data / state at any time and be assured that it won't get mutated underneath you. But better than that - they are persistent data structures that share data with previous versions. As a result, operations are much closer to O(1) rather than the O(n) you would pay for a copy-on-write strategy for immutable data.

Software transactional memory - rather than using locks, you just enclose code in a (dosync ...) block and they are automatically run as a transaction. No risk of deadlocks, and no need to develop complex locking strategies. This is a massive win, especially when combined with the immutable data structures above. Effectively, Clojure implements multi-version concurrency control in its STM.

Functional programming paradigm is used to make it much easier to write reliable concurrent code. Basically if you take an immutable data structure, run it through a pure function and output a different immutable data structure, then your code is guaranteed to be safe for concurrency.

I'd suggest watching this video as an introduction

Title: Next in Concurrency


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

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

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

答: Right to use his own methods and allowed to do new experiment rather then using same old methods and sticking to the old rules. and of-course Light instrumental Music


问:
Create my own database system
I need to learn how databases work in order to use them more efficiently, and my way of learning is by doing.

I want to create my own database system. I am not referring to creating a pseudo-database that would use query to parse files; this would simply be a filesystem interface with a query language. I am talking about the actual structure of a database engine. And since what I have in mind is neither relational nor document-oriented (it's "node-oriented", if that even exists), I would need any resource to be as abstract and high-level as possible.

So how would I go about creating that? What resources/tutorials/books can I read to understand?

The language does not matter in the slightest. Ideally, the code would be pseudo-code to illustrate the concept, not tied to a particular language, but anything would do. I was not able to find anything on the matter on google (since I am so illiterate on the subject, maybe I am just not entering the right search).

If such resources are not available, then I guess something about how to create a client would at least be a step in the right direction.

答:
You should just do it and stop thinking too much. Enjoying the learning process and enthousiasm are gifts.

Asking others if it's a good idea is certainly not a good strategy. If I had listened to all the frogs, I would still work at Ikea today pushing shopping cart from the parking to the depot.

You don't have to justify yourself like Ayende did in that interesting post. The question was:

However as a pragmatic developer, I am wondering what new this project is offering in a saturated market where you have quite mature alternatives like CouchDB, MongoDB, Tokyo, Redis, and many more ?
  Many of these products are also cross platform and run at C speed with a proven record, being used in very big web sites where their sharding capabilities and fault tolerance have been pushed far.

If you take your pleasure in the process, don't be worry about the objective, you already won.

Title: Create my own database system


答: MySQL has pluggable storage engine structure, it might be an idea to check out how engines are created to work for MySQL. </p>

Title: Create my own database system

Body:
I need to learn how databases work in order to use them more efficiently, and my way of learning is by doing.

I want to create my own database system. I am not referring to creating a pseudo-database that would use query to parse files; this would simply be a filesystem interface with a query language. I am talking about the actual structure of a database engine. And since what I have in mind is neither relational nor document-oriented (it's "node-oriented", if that even exists), I would need any resource to be as abstract and high-level as possible.

So how would I go about creating that? What resources/tutorials/books can I read to understand?

The language does not matter in the slightest. Ideally, the code would be pseudo-code to illustrate the concept, not tied to a particular language, but anything would do. I was not able to find anything on the matter on google (since I am so illiterate on the subject, maybe I am just not entering the right search).

If such resources are not available, then I guess something about how to create a client would at least be a step in the right direction.


问:
Building a complete program?
Reading books, watching videos, and reviewing tutorials is all very easy. Taking notes and actually learning the material may be slightly harder, but even then, anyone with a decent brain and a fair amount of interest, it's easy enough (not to mention, fun).

The thing is, it doesn't really prepare you to write a full program or website. Let's say you're those teens (only in highschool, no true (college level) computer science or programming courses, and no real world experience), and you come out with Groupon. Or even Mark Zuckerburg, sure he was a genius, and he was a very capable programmer... but how?

How do you recommend that people who are not necessarily new to programming, but new to programming real applications and real programmers go about developing it? What is the "development process" - especially for single programmers (or maybe 2-3 teens)?

Also, as far as web development goes, what is the process? Was something like Facebook or Groupon written with a framework (like CodeIgniter or Zend for PHP)? Or do they develop their own frameworks? I'm not asking how to come up with a great idea, but how to implement great ideas in an effective way? Does anyone have advice?

I've read a couple of books on both C and C++ (primarily the C Programming Language and the C++ Programming Language) and taken AP Computer Science (as well as read a few additional books on Java and OOP). I also have read a few tutorials on PHP (and CodeIgniter) and Python. But I'm still in highschool, and I'm technically not even old enough to work at an internship for a few more months.

答:
It's the same very common problem with (indie) game development : how to finish.

Other than making sure that you can do it, either because you have all the required knowledge or you are willing to learn - and you checked that other people did check that it wasn't impossible...

... the main thing that makes "finishing" possible is to set objectives.

Objectives are the target to reach, they must not describe how to get there, only what is the basic requirements/features you need to consider a first version of your app as "finished". Also, don't set objectives too far in time.

Write your objectives somewhere. Write it.

Once you've set objectives, you'll have to just find ways to reach it. That is the famous "path" that is more interesting that the arrival. Don't worry about reaching walls and discovering how wrong you'll be. Most of the time, if the subject is new, you'll get it wrong and you'll learn why and be able to get it right and have done one another setup to get closer to the objectives.

Even in game design, we know that you have to provide objectives to make sure the player knows, even in an abstract way, what he need to achieve, whatever the way he does.

Title: Building a complete program?


问:
Workflow of sharing code for small teams
Problem is, we have developed a small CMS, that is different per implementation (currently).

Of course development of this is never complete. Sometimes, we are working on more than one project that implements it (by copying-pasting the code files of the CMS to each project), and we add a new feature that we want to share on other projects as well (these can be small ones too, ie a custom ajax JSON controller - we use MVC)

What we want to do is quickly and uniformly share the code with all other projects, via a version control system (or something similar), and generally organize the workflow as we know this isn't a very good workflow that we have. What would you suggest?

Also, at the momment, the software we use is Visual Studio 2010, so we are strongly considering TFS, but even if we get it we still don't know the ideal workflow, or even if TFS supports what we want to do.

Edit: Also note, we have specific implementations that have modifications over the CMS base that we want to KEEP only in the project area. (ie: a specific feature that we DONT want to share with the base CMS code)

答:
First off, you should indeed use source control - this is less a means for sharing as much as a means to ensure that changes are recorded.

In regards to sharing of code - you need to identify the common parts of these applications, the things that do not change. Take these and create a project from them (or even a set of projects) - ideally things that are pure code and no markup. This can then produce a shared DLL to be used by all of your customized projects.

As for the markup - you could do something similar, but the UI tends to differ between projects, so I don't know how much use that will be.


答:
There is a difference between simply knowing how to program, and knowing how to structure a program (software architecture).

A simple book about a specific programming language will only teach you the tools you can use in order to go about setting up the architecture of a program.

There are also books which help you with software architecture. Topics you should look for are design patterns, software abstraction, software architecture/design, and many more ... (Head First Design Patterns was a real eye-opener for me.)

For a wider set of resources, this question might interest you.

Still the best way to learn how to properly structure an entire program is hands on experience doing so, being very open to suggestions and new techniques while doing so.

Title: Building a complete program?

Body:
Reading books, watching videos, and reviewing tutorials is all very easy. Taking notes and actually learning the material may be slightly harder, but even then, anyone with a decent brain and a fair amount of interest, it's easy enough (not to mention, fun).

The thing is, it doesn't really prepare you to write a full program or website. Let's say you're those teens (only in highschool, no true (college level) computer science or programming courses, and no real world experience), and you come out with Groupon. Or even Mark Zuckerburg, sure he was a genius, and he was a very capable programmer... but how?

How do you recommend that people who are not necessarily new to programming, but new to programming real applications and real programmers go about developing it? What is the "development process" - especially for single programmers (or maybe 2-3 teens)?

Also, as far as web development goes, what is the process? Was something like Facebook or Groupon written with a framework (like CodeIgniter or Zend for PHP)? Or do they develop their own frameworks? I'm not asking how to come up with a great idea, but how to implement great ideas in an effective way? Does anyone have advice?

I've read a couple of books on both C and C++ (primarily the C Programming Language and the C++ Programming Language) and taken AP Computer Science (as well as read a few additional books on Java and OOP). I also have read a few tutorials on PHP (and CodeIgniter) and Python. But I'm still in highschool, and I'm technically not even old enough to work at an internship for a few more months.