答:
You've extracted too much when your code itself is more clear than the method name.

Keep in mind, when not sure, almost any programmer I've seen has been building much larger and monolithic methods than optimal, rather than the other way around.

A method with just few lines of code is quite typical of well designed app/library.

Title: Should a method do one thing and be good at it?

Body:
"Extract Till You Drop" is someting I've read in Uncle Bob's blog, meaning that a method should do one thing alone be good at it.

What is that one thing? When should you stop extracting methods?

Let's say I have a login class with the following methods:

```<code> public string getAssistantsPassword()
 public string getAdministratorsPassword()
</code>```

These retrieve the respective accounts password in the database. Then:

```<code> public bool isLogInOk()
</code>```

The method compares the password that has been called or selected, and sees if the password the user provided is in the database.

Is this an example of "Extract Till You Drop"? When will you know when you are doing too much of extracting?


问:
how to find out if spelling mistakes in source code are a serious issue or not?
I find very troubling amount of spelling mistakes I see everyday in our codebase, from which I will reproduce a very short but representative example:

```<code>ArgumnetCount
Timeount
Gor message from queue
</code>```

Unfortunately this is in no way limited to one person. There is a lot of non-native English speakers in our team who contribute to that, however I can also pinpoint some of the worst spelling mistakes to our Software Architect who is American, born and raised.

These are also to be found even in emails, presentations, documents, whatever piece of written information we have in a software development company.

I'd like to know how to find out if it is a serious issue or not?

I've always met these spelling mistakes with concern, but my own, personal, official policy is that we are not paid to spell things right, we are paid to get things done, so inside the company I never really criticized anyone about it. But I have raised this issue with some of my close friends, and never settled it for good.

答:
Well, this is a many-sided cultural problem.

Speaking from a german perspective: we notice how our own language gets more and more influenced by english terms. This goes so far as national companies having english slogans or advertising. Some people, especially in management positions are meanwhile apparently unable to utter but one sentence in plain german. Their speech is full of buzz words and incomprehensible management slang. We say such persons are speaking "denglish".

Given this state of affairs and English being the "lingua franca" especially in software business, it is unavoidable that English itself is influenced by the vast number of non-native speakers. But for English native speakers this is still better than having to lern, say, Chinese in order to take part in the SW industry.

ContentLicense: CC BY-SA 3.0


问:
Are there reasons other than budget for hiring "entry-level" programmers?
Are there reasons other than budget for hiring "entry-level" programmers?</p>

答:
Budget should almost never be the reason why you should hire fresher.

The primary reason why you recruit freshers is when :

you need fresh energy and talent that makes organization more vibrant

You need to work in cutting edge or disruptive innovation where you don't want to hire people from old school of thought

You are yourself a young company wanting to explore the world and want to set it's own ideology and style.

ContentLicense: CC BY-SA 2.5


问:
Methodology for documenting existing code base
I work as part of a team on an existing application that has no inline documentation, nor does it have technical documentation.  As I've been working on various bug reports on the application, I've written a sort of breadcrumb trail for myself - bug numbers in various places so that the next developer can refer to that bug number to see what was going on.

My question is thus:

What is the most efficient method for documenting this code?  Should I document as I touch the area (the virus method, if you will), or should I document from each section on its own, and not follow paths that branch out into other areas of the application?  Should I insert inline comments where none previously existed (with the fear that I may end up incorrectly identifying what the code does)?

What method would you use to accurately and quickly document a rather large application that has no existing inline documentation, nor inline references to external documentation?

答:
Documenting legacy code-bases

I would highly recommend following the scout rule with legacy code-bases.

Trying to document a legacy project independently of working on it will just never happen. Even if you get in contractors to do it, as soon as they finish the project, that documentation will start falling behind all over again, because developers haven't got into the habit of updating it.

In-code documentation

The most important thing is to use the documentation facilities in your chosen development environment, so that means pydoc for python, javadoc in java or xml comments in C#. These make it easy to write the documentation at the same time as writing the code.

If you rely on coming back and documenting things later, you may not get around to it, but if you do it as you are writing the code, what needs to be documented will be fresh in your mind. C# even has the option to issue a compilation warning if the XML documentation is incomplete or inconsistent with the actual code.

Also, if reviewing documentation becomes part of your code review process, everyone can be encouraged to contribute, fostering a sense of ownership of the documentation as well as of the code.

Tests as documentation

Another important aspect is having good integration and unit tests.

Often documentation concentrates on what classes and methods do in isolation, skipping over how they are used together to solve your problem. Tests often put these into context by showing how they interact with each other.

Similarly, unit-tests often point out external dependencies explicitly through which things need to be Mocked out.

I also find that using Test-driven development I write software which is easier to use, because I'm using it right from the word go. With a good testing framework, making code easier to test and making it easy to use are often the same thing.

Higher level documentation

Finally there is what to do about system level and architectural documentation.

Many would advocate writing such documentation in a wiki or using Word or other word processor, but for me the best place for such documentation is also alongside the code, in a plain text format that is version control system friendly.

Just like with in-code documentation, if you store your higher level documentation in your code repository then you are more likely to keep it up to date. You also get the benefit that when you pull out version X.Y of the code, you also get version X.Y of the documentation. In addition, if you use a VCS friendly format, then it means that it is easy to branch, diff and merge, just like your code.

Not only that, but if you use something like readthedocs then you can publish version specific documentation for each software release.

I quite like rst, as it is easy to produce both html pages and pdf documents from it, and is much friendlier than LaTeX, yet can still include LaTeX math expressions when you need them.

OwnerDisplayName: George Stocker

ContentLicense: CC BY-SA 4.0


问:
Should a one person team use a process model?
I am about to start work on my biggest project yet (about 6 months full time work). For previous projects as they were only short I never intentionally used a model, I may have done but I didn't set out to do it.

So... Before I start this project would it be advised to try and use some model? And if it is then what do you think would be useful to a 1 person team?

答:
I would.

It does not need to be a heavy process, you can probably keep it quite light.

But it will allow you proper tracking through each stage of the lifecycle and provide proof of how you got to where you're going for management.

It will also be useful should someone else join your project mid-stream or for a phase 2, however unlikely you think this is just now.


答:
As a young guy fresh out of the college - i never used to use Source control.  However, now after having used to SCM, even if i do the project alone it makes life easier by using SVN. Imagine how easy it is to retrieve yesterdays' work if i mess up the code - and also take a look back of how things evolve. I don't have to keep all this in my mind.

This questions usually arrive because lot of times people think of Process they think of a lot of documentation, and whole bunch of formalities that looks like a waste of time. Yes, if you are alone, don't do anything which looks like a waste of time. (In fact in our company i leave people to question the proces and don't do it if it is a waste of time; but that is probably too much of stretch).

The point is: in a true sense a process is a tool, a mechanism that will ensure that simple mistakes (rather goof-ups) don't happen and don't create disasters-

A seasoned carpenter will always measure and remeasure the wood before putting a cut,

A good driver will always put the seat belt on while driving,

A good chef of a restaurent will have a simple way to test food

-- the sameway a good programmer will check-in the code before he goes back to sleep.

The complexity of the tool varies, but it is always important that practices are used in the way that helps you and it is really nothing about being alone or in the team.

Title: Should a one person team use a process model?

Body:
I am about to start work on my biggest project yet (about 6 months full time work). For previous projects as they were only short I never intentionally used a model, I may have done but I didn't set out to do it.

So... Before I start this project would it be advised to try and use some model? And if it is then what do you think would be useful to a 1 person team?


问:
Should a method do one thing and be good at it?
"Extract Till You Drop" is someting I've read in Uncle Bob's blog, meaning that a method should do one thing alone be good at it.

What is that one thing? When should you stop extracting methods?

Let's say I have a login class with the following methods:

```<code> public string getAssistantsPassword()
 public string getAdministratorsPassword()
</code>```

These retrieve the respective accounts password in the database. Then:

```<code> public bool isLogInOk()
</code>```

The method compares the password that has been called or selected, and sees if the password the user provided is in the database.

Is this an example of "Extract Till You Drop"? When will you know when you are doing too much of extracting?

答:
To quote Clean Code, on the page 36, it says:

So, another way to know that a function is doing more than "one thing" is if you can extract another function from it with a name that is not merely a restatement of its implementation.


问:
Is big-O really that relevant when working in industry?
In every interview I have been in, I have been quizzed on mathematical analysis of complexity, including big-O notation.

How relevant is big-O analysis to development in industry? How often do you really use it, and how necessary is it to have a honed mindset for the problem?

答:
Yes, complexity matters in the industry. If you end up designing something where a critical pathway scales as N-squared (doubling the number of something makes the system four times as loaded), you will hit your scaling bottleneck much faster than if you have something that scales at N.

However, it's usually not done as a proper, formal, proof that something is at a given complexity, so having a good intuition for what complexity a pattern of operations have is a good start.


问:
Documentation with images - what is the most git-friendly approach?
When documenting software I traditionally write a plain text file (like a README.txt) which works well, but unfortunately cannot contain images like HTML can.  Unfortunately images must be stored as separate files with a normal HTML document (using href=".../foo.png">) which give unnecessary clutter.

The "Save a single web-page" in Internet Explorer use MIME HTML (MHTML) to save all resources within a single file.  The requirement of having to use a browser to read it, is not a impediment these days.  Apparently Opera and Word support editing these documents directly.

We use git for our source code, hence the differences as seen by git between two edits of the same documents should not be large to avoid unnecessary disk usage and unusable diff's when looking at the document outside the MTHML editor.

What is the best mainstream HTML editor for producing git-friendly MHTML files?

答: Use RTF format. Unlike DOC/DOCX it's neither binary nor compressed, so it DIFFS quite nicely. Inserting images puts them at the end of the file and reference inside, so it's as source control friendly as possible.</p>


问:
Exporting huge data into XLS in a web application
I am developing a web application in Java/J2EE, in which I have export functionality.
I have used Jasper for the same. The issue is when trying to export a huge set of data it is consuming a lot of time.

Is there any design approach for export functionality so that I can improve the performance?

I had tried JExcel API earlier and then moved to DynamicJasper API.

答:
They way I've approached a similar issue was by creating a separate service.

Requests for excel data are placed in a queue.

The service then processes the requests and returns the excel as an email attachment, the return emails are specified as part of the initial request.

This has worked flawlessly for us, and when things crashes (I've only every had two instances), the requests are not lost, they simply queue up.


答:
The questions that are asked in interviews are there to find out if you can explain things and think in a logical way.  The interviewer is also trying to find out if you can employ what you know to solve a related problem.

Everyone that has done any worthwhile studying of software engineering will have come across “Big O”, also to answer a good question about “Big O” you must also have some understand of standard data structures and algorithms.

When interviewing for a member of staff you are looking for someone that can learn the job quickly not someone that already knows a given set of detailed skills, so it can be very hard to choose questions that both the interviewer and the interviewee have a common understanding of.

So questions about “big O” can be very relevant to the interviewing process.

At least every year over my long time as a computer programmer I have had to fix code that was slow due to someone not understanding the correct data structures and algorithms to use, but you can solve these problems without having a detailed understanding of Big O.   However people that do understand Big O tent not avoid these problems in the first place.

Title: Is big-O really that relevant when working in industry?

Body:
In every interview I have been in, I have been quizzed on mathematical analysis of complexity, including big-O notation.

How relevant is big-O analysis to development in industry? How often do you really use it, and how necessary is it to have a honed mindset for the problem?


答:
We do that using Apache POI, but since Jasper probably uses that too, I don't think you will get much faster results by directly using POI.

Large exports (like 50000 rows x 15 columns) require a lot of memory, so increasing the heap space is a must, but you have probably already figured that out.

You might want to give JExcelAPI a try. I have no experience with it, though.

Title: Exporting huge data into XLS in a web application

Body:
I am developing a web application in Java/J2EE, in which I have export functionality.
I have used Jasper for the same. The issue is when trying to export a huge set of data it is consuming a lot of time.

Is there any design approach for export functionality so that I can improve the performance?

I had tried JExcel API earlier and then moved to DynamicJasper API.


答:
All these answers with great and noble reasons for hiring entry level people are nice and all.

The real answer is: a company gets the best resource it can get for the amount of money it's willing to spend. That's business. If it's not willing to spend much, it advertises for someone who won't cost much. "Entry level" is a job posting signal phrase intended to result in that outcome. HR won't waste time interviewing rock god developers who they can't afford.

If they're lucky, they find someone underselling their value, underpricing themselves as "entry level" when in fact they're more senior than that. Can you imagine a company not snapping up such a tempting offer? Of course not. All the "we can develop them in our image" "fresh energy makes us more vibrant" stuff goes out the window at that moment.

So. Browse most of these answers to see the nice, happy-world justifications for it. The real answer is: yes, that decision is almost always budgetary.

Body: Are there reasons other than budget for hiring "entry-level" programmers?</p>


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

Programming

char = "tchar" not care?

! = bang not exclamation?

# = pound not hash? Exception #! = shebang

* = splat not star?

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

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

Unixen

| = pipe not vertical bar?

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

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

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

Annoyance

/ = slash not backslash

LaTeX = "laytek" not "lay teks"

答:
I don't deal with all these all the time but...

Programming

char = "tchar" not care?

hard c like car (because it comes from "character")

! = bang not exclamation?

I'm just used to calling this exclamation - where did "bang" come from?  Must be an Americanism.

# = pound not hash? Exception #! = shebang

hash - again, pound is an Americanism

* = splat not star?

star, or asterisk

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

rejex - hard g here just sounds weird

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

Both depending on what mood I'm in.  Normally, I say "Sequel Server", "My Sequel", but "S Q L" when on its own

Unixen

| = pipe not vertical bar?

pipe, though I used to call it vertical bar.

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

bin as in that's where all my junk goes :)

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

lib as in liberate because saying "libe" just sounds wrong.  Sounds like I'm trying to say "lube" in an Australian accent

etc = "ett see" , not "e t c"

et cetera, but I'm not a unix guy mainly so I could be wrong with that

Annoyance

/ = slash not backslash

slash or forward slash.

LaTeX = "laytek" not "lay teks"

as in latex since that's how it's spelt - maybe you can use it with your lib from above.

Title: Pronunciation in programming?


问:
How to approach functional tests in segregated systems
I'm implementing some automatic functional tests in an environenment that has about 20 applications talking to eachother using queues and/or restful interfaces.

The problem I'm facing is that I added some test to one of the application, lets call it Payments, and they all looked very nice and green. One of the changes on the Payments application added an extra field in a messages that is send to another application, lets
call it CRM, and the CRM discarded the message, which meant that the applications started to become out of sync. The Payments application (as most other applications) send messages in a fire-and-forget way, which means that the producer never knows if a message is processed or discarded.

I'm wondering is how to test these dependencies between systems. One option (that I dislike from my gut, but no idea why) is to connect to the other system and verify that the record was updated. Most applications have a restful interface and also provide clients, so is not a lot of work. But I have the strong feeling that doing this will
make the test more brittle. One of the reasons why I don't like this, is that most of the applications talk to another 4-10 other applications, so it's not just checking another app... and since lots of things are asyncronous, it adds even more uncertainity to the test.

So, how do you create functional tests for this type of environment?

答:
It may be a good idea to add some logging capabilities (or a logging service) to your message passing system. When logging is enabled, each application/service sending a message should log this. Also incoming messages should be logged, and it should be logged when a message was successfully processed, or when it was discarded. Your testing framework should have easy access to all logs, and the logging service should be designed to be queried by tests programmatically.

Then, when you create a test of your Payment application, you don't have to connect to your CRM service (and the 4-10 other applications) to verify if the message send by Payment was received. You will only have to connect to your logging service and check the log.


问:
Making sure database connection information is secured
This is the first time that I am working on a web application. I was going through the question What technical details should a programmer of a web application consider before making the site public? and noticed one thing that I knew nothing of:

Make sure your database connection information is secured.

I am confused about it because as per my knowledge the database info, password, etc will be on my server used in my coding to connect to the db. Then what does this line specifically mean?

答:
Basically, you need to ensure that your configuration files which contain that connection information are not in a place where they could be read by anything other than the code.

For example, often people will put such files under the webroot, where it is potentially possible that the webserver will serve them as plain text, so that users can read them. Clearly, that's bad. So put them somewhere outside of the webroot, accessible only to the code that's doing the connecting.


答:
Basically, it means that you must store the username and password to the database in a directory that the web server cannot access directly. For example, if you use PHP, and your Apache configuration points to /project-root/www, you could store the login information in /project-root/config/db.php; if you store it in, say, /project-root/www/config/db.php. Assuming that your server configuration isn't broken, this means that db.php cannot be accessed over the internet.

You also need to get the permissions for the config file right. The account the web server runs under (ideally a dedicated account for your application) should be the only one with any kind of access to the config file. In a UNIX environment, assuming Apache is configured to run your application's virtual host under your own account, 600 or even 400 is a suitable permission set. This ensures that other users with access to the same machine (except root) cannot read your configuration file.

Additionally, you'll want to take a few more security measures:

Create a database user specially for the application, and give it just enough permissions to do its job (SELECT, UPDATE, INSERT and DELETE on the tables it needs is usually enough). Do not give the user any permissions on any other databases: if your application is compromised, you can at least mitigate the risk for other databases. If the user also has permissions on system databases, a successful attacker can possibly elevate permissions by creating new users through the system tabls and granting them more permissions. Specifically, never ever use administrative database accounts for production websites.

Use a strong password. Since you won't have to manually type the password a lot, a sequence of, say, 32 random bytes, converted to base64, should make for a good enough password.

If the database runs on the same machine as the web server, configure it to refuse connections from anything but localhost. If it runs on a dedicated server, use a whitelist of allowed hosts, and put the whole thing behind a properly configured firewall.

If you use a quasi-interpreted language such as PHP (where the source code sits on the web server), it is a good idea to write your configuration as source code too, and use an appropriate filename extension. This way, if someone manages to request the configuration file over the internet, it will be executed, and produce a blank page, still hiding the database credentials from the attacker (this is a last straw though; you should never rely on this alone).

And of course, you need to check your application for general security flaws, especially SQL injection and path traversal: these are the most common ways of getting at your database.

If the application is really sensitive, you need to take more precautions, such as encrypting configuration files, but for your average low-profile website, this should do the trick.

Title: Making sure database connection information is secured

Body:
This is the first time that I am working on a web application. I was going through the question What technical details should a programmer of a web application consider before making the site public? and noticed one thing that I knew nothing of:

Make sure your database connection information is secured.

I am confused about it because as per my knowledge the database info, password, etc will be on my server used in my coding to connect to the db. Then what does this line specifically mean?


问:
How can I move a team from C# ASP.NET development to PHP development using Drupal?
I have a team of skilled C# developers with vast experience in creating ASP.NET MVC applications. We will soon be starting a new big web site project based on the Drupal platform. My developers do not have any experience in Drupal or PHP and I want to make the transition as quickly and effective as possible.

We decided to make this decision based on two factors:

In my organization there are a couple of teams competing on doing this project. None of the other teams has experience in PHP or Drupal, and I truly believe that my team would do it the best, whether it's ASP.NET or Drupal.

One of the requirements from higher management was that we won't build something from scratch, but use an existing foundation. Many of the requirements are available in plugins/modules for the various CMS.

I know this is not an ideal environment, but it's a given state and I have to make the best out of it. None of the .NET Framework based CMS supported all of our requirements. Since my team is dynamic in nature, I believe it can adapt to working with Drupal.

Hiring other people is not an option, and sending them to a course will take too much time.
I thought about dedicating a week in which each developer will study a specific subject and then will pass it on to the team.

Any suggestions on how you would do it?

答:
Do you think your team is able to perform a professional php project without any php knowledges? For sure PHP is easy going, it hasnt got the "restrictions" like asp.net or j2ee... (for sure the restrictions are the savety of this languas).

As you should know, PHP has many special facts which are not existing in C# or J2EE. It is easy to learn, but as a professional developer you have to know alot about how you can develop secure applications.

For sure if you just have an Drupal project with only design customization and no widgets, no plugins etc. pp. it could work, maybe. But thats a high risk.

I would prefer to give your team the chance to learn PHP for more than one week. Get as much a literatur as possible and teach and train your team as fast as you can. But having a project in a development language no one knows in such a short time is often called "suicide".

Good literature for your problem could be Development for Drupal and Professional PHP Development or a book about pattern for php. There are lot of good books available. Look into the development guide for drupal. So you have alot to learn :-)

Best wishes.


问:
What is the relationship between the business logic layer and the data access layer?
I'm working on an MVC-ish app (I'm not very experienced with MVC, hence the "-ish").

My model and data access layer are hard to test because they're very tightly coupled, so I'm trying to uncouple them.

What is the nature of the relationship between them?  Should just the model know about the DAL?  Should just the DAL know about the model?  Or should both the model and the DAL be listeners of the other?

In my specific case, it's:

a web application

the model is client-side (javascript)

the data is accessed from the back-end using Ajax

persistence/back-end is currently PHP/MySQL, but may have to switch to Python/GoogleDataStore on the GAE

答: Use an object-relational mapper, then the model in your business logic layer does not need a separate DAL. Any modern ORM takes metadata from your model classes and does the data access in a generic way, without any need for you to code an own data access layer.</p>


问:
Non-OOP Design Patterns?
I have only heard the term "design pattern" being used for object oriented code, and the GoF patterns include only OOP design patterns, but design patterns are elegant solutions for commonly occuring programming problems, right? There is nothing in there saying that they must be limited to OOP, is there?

I would like to see some examples of design patterns outside the realm of object oriented programming. Do you have any? Do such even exist (no book, like the GoF book, must necessarily have been written, they should just be used; that is enough)?

They can be specific to some programming language(s), but general (paradigm-level) patterns are preferred, of other paradigms than the object oriented one.

答: A good example of non-OOP patterns is my absolute favourite pattern catalog: Organizational Patterns of Agile Software Development, by James O. Coplien. This book isn´t about software patterns, is about people, a catalog for creating successful teams. Every manager should read this book!

Title: Non-OOP Design Patterns?


问:
if it's been designed correctly is AOP useful?

Possible Duplicate:

  Are certain problems solved more elegantly with AOP?

I don't know much about aspect oriented programming (AOP) but I looked at a few examples and it seems to me more of a debugging tool or patching things. I looked over the examples and I can't think of anywhere I'd use them in -my- code.

Assuming the code has been design right and the language supports it (such as AspectJ) what are real world uses where using AOP is good design and can't be done as easily with traditional well designed classes/code/software?

答:
AOP solves some problems, but is not useful in all cases.

Typically, AOP provides tools to manage separation of concerns. In many projects, you'll find yourself writing the same code repeatedly. A typical example is checking access:

```<code>if(!user.hasAccess(functionality)) throw new SecurityException();
// Functionality implementation.
</code>```

This is not clean code, because the problem of checking access is spread across the whole code base. It is error prone, which is not what you want in general, but even worse here, because an error is a security flaw.

AOP is definitively useful here, because it will allow you to define security at one place and functionality at another.

You'll find other patterns, like connecting to a database, doing some operation, and disconnecting. You'll have to handle all special cases (SQL error, network error, etc . . .) and be sure you rollback cleanly if something happens and disconnect properly. AOP could also help you here, avoiding the need to have all the error handling boilerplate spread over multiple functionalities.

Another problem is synchronization. As the system gets more and more distributed (multicore, network, cloud, GPGPU, etc . . .) it is of increasing importance.

Definitively, AOP is useful in some cases.

Body:
AOP solves some problems, but is not useful in all cases.

Typically, AOP provides tools to manage separation of concerns. In many projects, you'll find yourself writing the same code repeatedly. A typical example is checking access:

if(!user.hasAccess(functionality)) throw new SecurityException();
// Functionality implementation.

This is not clean code, because the problem of checking access is spread across the whole code base. It is error prone, which is not what you want in general, but even worse here, because an error is a security flaw.

AOP is definitively useful here, because it will allow you to define security at one place and functionality at another.

You'll find other patterns, like connecting to a database, doing some operation, and disconnecting. You'll have to handle all special cases (SQL error, network error, etc . . .) and be sure you rollback cleanly if something happens and disconnect properly. AOP could also help you here, avoiding the need to have all the error handling boilerplate spread over multiple functionalities.

Another problem is synchronization. As the system gets more and more distributed (multicore, network, cloud, GPGPU, etc . . .) it is of increasing importance.

Definitively, AOP is useful in some cases.


问:
Should I use Legitimate Email spoofing?
Recently I receive a request: users' emails are stored in the database, and as request of a user, the system will send an email on their behalves.

To add more context, it's like sending an email from the vendor, to their customers' email addresses. But it's not a fixed email (it depends on which vendor ask the system).

Using JavaMail, I can simply set the from field. But something doesn't seem right. When searching for this kind of work, I come across "Email spoofing" - which looks like what I'm going to do. There are some drawbacks for this approach, such as it may make the emails attractive to the spam filters, and so on...

Ofcourse I can just do as the client want, but I just wonder, is there any better alternative?

答:
And here is something that may come in help:

```<code>From: "YOUR CLIENTS NAME" <clients@email.com>
Sender: yourcompany@yourcomapny.com
To: destination.com
Date: 13 Jul 2009 15:39:42 -0400
Subject: Whatever subject you need
Return-Path: yourcompany@yourcomapny.com
</code>```

These fields are valid and will allow the receiving server to identify you as the server. On top of that bounnced-emails will go back to you.

Title: Should I use Legitimate Email spoofing?

Body:
And here is something that may come in help:

From: "YOUR CLIENTS NAME" <clients@email.com>
Sender: yourcompany@yourcomapny.com
To: destination.com
Date: 13 Jul 2009 15:39:42 -0400
Subject: Whatever subject you need
Return-Path: yourcompany@yourcomapny.com

These fields are valid and will allow the receiving server to identify you as the server. On top of that bounnced-emails will go back to you.


答:
I try to test as close to the fragility as possible.  If the CRM is the component that isn't doing its job, that's where there is a hole in testing.  It's the component that responded poorly to change.  It's the piece that dropped the message without raising an alarm.

I feel like people turn to big integration testing when a way to test a single system is non-obvious.  If you find that non-obvious simpler testing problem, you'll often discover a better way to design what you're doing.

Title: How to approach functional tests in segregated systems

Body:
I'm implementing some automatic functional tests in an environenment that has about 20 applications talking to eachother using queues and/or restful interfaces.

The problem I'm facing is that I added some test to one of the application, lets call it Payments, and they all looked very nice and green. One of the changes on the Payments application added an extra field in a messages that is send to another application, lets
call it CRM, and the CRM discarded the message, which meant that the applications started to become out of sync. The Payments application (as most other applications) send messages in a fire-and-forget way, which means that the producer never knows if a message is processed or discarded.

I'm wondering is how to test these dependencies between systems. One option (that I dislike from my gut, but no idea why) is to connect to the other system and verify that the record was updated. Most applications have a restful interface and also provide clients, so is not a lot of work. But I have the strong feeling that doing this will
make the test more brittle. One of the reasons why I don't like this, is that most of the applications talk to another 4-10 other applications, so it's not just checking another app... and since lots of things are asyncronous, it adds even more uncertainity to the test.

So, how do you create functional tests for this type of environment?


问:
Does Object Oriented Programming Really Model The Real World?
I've seen it commonly repeated the object-oriented programming is based on modeling the real world but is it?

It seems to me that is not true of anything outside of the business layer. My GUI classes/data access classes aren't modeling anything in the real world. Even in my business layer, I've got classes like observers, managers, factories, etc. which aren't real world objects. I try to design my classes to take advantage of things like encapsulation but is the real world encapsulated?

While some objects I create are modeling real-world objects, would not pre-OOP code do the same? I doubt that OO was the first people to include concepts like Customer in their code bases. But OO is really about how to model things, and that method of modeling doesn't seem inspired by the real world to me.

So: does object-oriented programming really model the real world?

答:
No, not at all.

However it's a methodology that does allow to create a nice abstraction to hold complex data structures along with some methods that act on the data structures.


答:
Models, of any kind, do not model the real world, not entirely.

They model selected portions, those that are relevant to the application at hand.

What you are talking about (observers, managers, factories etc...) is infrastructure that is there to help you with getting the abstraction right and support required functions such as persistence.

Title: Does Object Oriented Programming Really Model The Real World?

Body:
I've seen it commonly repeated the object-oriented programming is based on modeling the real world but is it?

It seems to me that is not true of anything outside of the business layer. My GUI classes/data access classes aren't modeling anything in the real world. Even in my business layer, I've got classes like observers, managers, factories, etc. which aren't real world objects. I try to design my classes to take advantage of things like encapsulation but is the real world encapsulated?

While some objects I create are modeling real-world objects, would not pre-OOP code do the same? I doubt that OO was the first people to include concepts like Customer in their code bases. But OO is really about how to model things, and that method of modeling doesn't seem inspired by the real world to me.

So: does object-oriented programming really model the real world?


问:
What is the name for the idiom using method chaining to build an object?
I frequently use a pattern where I using method chaining to setup an object, similar to a Builder or Prototype pattern, but not creating new objects with each method call, instead modifying the original object.

Example:

```<code>new Menu().withItem("Eggs").withItem("Hash Browns").withStyle("Diner");
</code>```

Just wondering if there is a name for this pattern and whether it is considered an anti-pattern, because although it can read more fluently, it can lead to long method chains.

答:
Fluent Interface

I've always heard of this method being called a 'fluent interface', as coined by Eric Evans (of Domain Driven Design fame) and Martin Fowler (of Agile Manifesto fame).

The main drawbacks are the readability (which some folks love and some hate), and the fact that it can be harder to debug in some cases because the entire chain of actions may be considered a single statement when stepping through it.

I certainly don't consider it an anti-pattern, although I've only used the technique a few times myself.


答:
I think teaching that there is a relationship between nouns and classes causes annoying bad habits to develop that have to be crushed later by an impatient architect or senior engineer.

What should be taught is that the classes model abstract objects, just like your brain does.  You have an abstract concept of "car" in your head that doesn't map to any particular physical car, it's reusable, specific implementations of car can inherit from it. Your brain even meta-models concepts for you.  You have a mental model of what thought is, what a concept is.

If we taught people to identify the models they're already generating in your head, they'd be a lot better prepared to build real software.


答:
The data access layer needs to be aware of the data, which is why it depends on the models. To improve maintainability, the Data-Access-Object (DAO) should solely take care of (de-)serialization. This way you can exchange the way you store data.

For instance, when your application makes use of a component which acts as a data access layer, the component's implementation can be changed to make use of different database types or providers.

How DAOs are implemented strongly depends on your approach to object relational mapping (ORM - assuming you are using an OO programming language). Martin Fowler describes a few common approaches to ORM in his book Patterns of Enterprise Application Architecture. Commonly, you will find some implementation of

Active Record

Data Mapper

Regarding the model, it shouldn't depend on the data access layer (although you will see that models are often littered with metadata for data storage).

Or should both the model and the DAL be listeners of the other?

Depending on your use case, it might be a good idea for your ORM to subscribe to model changes and synchronizes them with the database. Java Persistence 2.0 describes a similar pattern for data synchronization for attached entities (where attached means something like: synchronize the object's state with the database for the duration of the transaction).

In my specific case, it's an Ajax application. Currently I'm using PHP/MySQL for the backend but may have to switch to Python/GoogleDataStore on the GAE.

Various libraries are available for ORM for either technologies. You can check out the Wikipedia ORM comparison page to get a small overview. For GAE, there is Google's documentation.

Title: What is the relationship between the business logic layer and the data access layer?

Body:
I'm working on an MVC-ish app (I'm not very experienced with MVC, hence the "-ish").

My model and data access layer are hard to test because they're very tightly coupled, so I'm trying to uncouple them.

What is the nature of the relationship between them?  Should just the model know about the DAL?  Should just the DAL know about the model?  Or should both the model and the DAL be listeners of the other?

In my specific case, it's:

a web application

the model is client-side (javascript)

the data is accessed from the back-end using Ajax

persistence/back-end is currently PHP/MySQL, but may have to switch to Python/GoogleDataStore on the GAE


答:
To familiarize in a particular language to code efficiently takes a lot of time and effort. Without proper guidance during transition, an application would be a maintenance nightmare and might not work to your advantage on the long run.

That said, I suggest you have an experienced PHP developer and then work with your team to be guided by the experienced developer on the best practices in PHP and make a wise and gradual shift.

On a personal note, I am working as a C# developer for nearly 4 years now and I probably would be thinking a 100 times before I make the shift.

Good luck!

Title: How can I move a team from C# ASP.NET development to PHP development using Drupal?

Body:
I have a team of skilled C# developers with vast experience in creating ASP.NET MVC applications. We will soon be starting a new big web site project based on the Drupal platform. My developers do not have any experience in Drupal or PHP and I want to make the transition as quickly and effective as possible.

We decided to make this decision based on two factors:

In my organization there are a couple of teams competing on doing this project. None of the other teams has experience in PHP or Drupal, and I truly believe that my team would do it the best, whether it's ASP.NET or Drupal.

One of the requirements from higher management was that we won't build something from scratch, but use an existing foundation. Many of the requirements are available in plugins/modules for the various CMS.

I know this is not an ideal environment, but it's a given state and I have to make the best out of it. None of the .NET Framework based CMS supported all of our requirements. Since my team is dynamic in nature, I believe it can adapt to working with Drupal.

Hiring other people is not an option, and sending them to a course will take too much time.
I thought about dedicating a week in which each developer will study a specific subject and then will pass it on to the team.

Any suggestions on how you would do it?


答:
OOP may not be a perfect model of the real world and the objects contained there in, but it is a methodology that helps deal with the increasing complexity of real life software. It also helps write code better, by breaking it down in to logically related chunks.

While older procedure oriented methods will certainly deliver results too, OOP helps you get there faster and with relative ease, even when dealing with large & complex projects.

Abstraction and Encapsulation help concentrate on the core of the problem while hiding all of the plumbing that actually makes stuff happen. Inheritance and lets you establish a meaningful and logical relationship between various aspects of your code. Polymorphism promotes code reuse and lets you easily handle variations (those "almost same behaviour as an existing object" category of problems that happens so frequently) and extend code by extending the semantics associated with an object.

I feel OOP is more like a proven aid that lets you deal with all of the complexities of a real life system in an effective manner. So, while it may not be a very thorough model of the real world, it is close enough and helps you get stuff done, which IMHO is all that matters in the end.


问:
Throwing an Exception if a Query Doesn't Use an Index
I'm working on a largish webapp that was developed by several other programmers and I keep running into performance issues caused by poorly written SQL queries and queries that don't use an index.  I'm working on fixing the problems by logging how long each query takes to complete and if it's using an index.

I was wondering if other people have had this problem before and what they've done to keep it from happening again.  My initial idea is to throw an exception if any query doesn't use an index so it has to be taken care of in devel but to continue to log the large/slow queries so we can see long term where the slowness is.

Update 2012-03-05 11:56 EDT

We're using MySQL and my plan WAS to run explain on each query after it's run to check for indexs.

答:
Do you in every single case want to make sure an index is being used? Sure, most of the time you should be using an index. But sometimes its not worth the cost. So throwing an exception might be problematic in those cases.

Sometimes you'll want to just put a query in there to get the right results before making sure its properly optimized and using an index. Throwing an exception forces the optimization before you've tested for correctness.

How about making long running queries more annoying in the development environment? Popup a message saying, "long running query." The app won't die, and you can test your feature, but you'll notice that it needs some work.


答: I never think of big O in a mathematical perspective, I never think about big O at all, unless asked. I just see an algorithm in my head, and I can tell if it's bad because it does multiple loops through memory for each N, or if it does divide and conquer or something like that. If needed, I can translate that to big O notation in few seconds, but it's easier for me to just know how the algorithm/container works with memory, than to think about mathematical perspective.</p>


答: A lot of frameworks and products use AOP "under the hood". For instance, it's heavily used in Spring for things like transaction handling and method caching. Hibernate leverages AOP-style dynamic proxying to enable persistent collections.</p>

Title: if it's been designed correctly is AOP useful?

Body:
Possible Duplicate:

  Are certain problems solved more elegantly with AOP?

I don't know much about aspect oriented programming (AOP) but I looked at a few examples and it seems to me more of a debugging tool or patching things. I looked over the examples and I can't think of anywhere I'd use them in -my- code.

Assuming the code has been design right and the language supports it (such as AspectJ) what are real world uses where using AOP is good design and can't be done as easily with traditional well designed classes/code/software?


答:
Does Object Oriented Programming Really Model The Real World?

Not completely.

Well in the real world, we face real problems. We wish to solve this problem using a paradigm which replicates the system we wish to build which becomes the model.

For example, if a Shopping Cart application was the problem on hand, we have different entities like

Product which is an abstract term which can have multiple members like Books, Gadgets, Cars which can again be sub divided.

Tax Criteria like ( Sales Tax ) would depend on which location the software is implemented as it is subjected to change based on government policies.

Tax is considered based on whether the product was imported along with tax criteria.

User could have a shopping cart which has a list of products etc.

So as you can see, there are real problems that we are trying to solve but modularized to the OOP paradigm to make it as close to the real system as possible.


问:
Why should I choose Java, Flash, or HTML5 for an online game with server communication
I'm starting to design a game that is going to have the following characteristics, and I'm trying to decide how I should program it. I'll also give a bit of my experience after, to help make the decision a bit better.

The game should be able to support both Facebook integration, and a stand alone version.

I don't want to do it right away, but I am thinking it would be a good idea to port this to Android/ iPhone at some point in time.

The game will involve communication with a server. The method of communication is still opened, but I imagine most of it will be over HTTPS. I'm suspecting most of the work is going to be done on the server at this point in time, and that the client is mainly going to show the results of the previous frame, and select what to do for the next frame.

I suspect that at some point in time, I'm going to want to put in animations and the like, but this is not critical for the beginning of the game.

The game is essentially an online board game, complete with cards, a board, etc.

I'm currently looking at Flash, HTML 5, and a Java applet. Some random pieces of information.

I have access to Adobe Flash, actually the whole Design Premium, CS5.

I have some experience with programming Android apps.

I have done work with HTML, but it has been quite a while. I've only done a little bit of Javascript, but I don't recall it being particularly hard.

I routinely program in C, C++, Matlab, and Android (Java). I fairly often program in Python, Perl, Shell, and I have programmed before in Basic, HTML, Javascript.

答:
HTML5 is supported across the platforms you describe. Not having to code a native app for iphone and android will save you a lot of time.

Also, Flash for Phones has been officially dropped by Adobe (as in, they will not develop it further).


答: I tend to incorporate instrumentation of some form in all apps I build. JavaMelody is pretty nice and non-intrusive and it provides good JDBC-level instrumentation. If you are using Oracle, it even shows you execution plans for all queries.</p>

Title: Throwing an Exception if a Query Doesn't Use an Index

Body:
I'm working on a largish webapp that was developed by several other programmers and I keep running into performance issues caused by poorly written SQL queries and queries that don't use an index.  I'm working on fixing the problems by logging how long each query takes to complete and if it's using an index.

I was wondering if other people have had this problem before and what they've done to keep it from happening again.  My initial idea is to throw an exception if any query doesn't use an index so it has to be taken care of in devel but to continue to log the large/slow queries so we can see long term where the slowness is.

Update 2012-03-05 11:56 EDT

We're using MySQL and my plan WAS to run explain on each query after it's run to check for indexs.


答:
...The world is richer than what can be expressed with object-oriented syntax.

Consider a few common concepts that people universally use to understand and describe all systems – concepts that do not fit the object mold. The 'before/after' paradigm, as well that of 'cause/effect', and the notion of the 'state of the system' are amongst the most vivid examples. Indeed, the process of 'brewing coffee', or 'assembling a vehicle', or 'landing a rover on Mars' cannot be decomposed into simple objects. Yes, they are being treated that way in OO languages, but that's contrived and counter-intuitive. The sequence of the routine itself – what comes before what under what conditions based on what causality – simply has no meaningful representation in OO, because OO has no concept of sequencing, or state, or cause.

Processes are extremely common in the real world and in programming. Elaborate mechanisms have been devised over the years to handle transactions, workflow, orchestration, threads, protocols, and other inherently 'procedural' concepts. Those mechanisms breed complexity as they try to compensate for the inherent time-invariant deficiency in OO programming. Instead, the problem should be addressed at the root by allowing process-specific constructs, such as 'before/after', 'cause/effect', and, perhaps, 'system state' to be a core part of the language...

quote source: Victoria Livschitz, The Next Move in Programming


问:
Geo IP data on stackoverflow API?
Have just looked at stackgeography and at soapi.
I cannot see where the geo data comes from as it's not on the soapi.
Can anybody shed some light on that?
More info on the stackgeography</p>

答:
The Stack Exchange Data Explorer does give you access to user location data. It is open source, and Data dumps of this data are releases to the public.

No one knows how this code works behind the screen but the author. If I had to guess

I would say he using the soapi to get the real time events and marrying that up to user location data from the data dump. If an event occurs for a user that is not in his dump he just ignores it.

Title: Geo IP data on stackoverflow API?


答: I would say that you just need to increase the logging severity of such issues. I dont think you should throw an exception in such a case unless you can configure your project to only do so in the development environments.</p>


问:
What are the advantages of using bitwise operations?
Following reading the latest CodeProject newsletter, I came across this article on bitwise operations.  It makes for interesting reading, and I can certainly see the benefit of checking if an integer is even or odd, but testing if the n-th bit is set?  What can possibly be the advantages of this?</p>

答:
These kind of operations are often used when writing for embedded systems where memory or CPU power is restricted.

For example, to save space you may store multiple variables in a single 8-bit int variable by using each bit to represent a boolean. Then you need a fast way to set a specific bit or retrieve the bit value.

Generally when programming in higher level languages like C# on a desktop PC with Gigabytes of memory, you don't really care that each bool takes up a whole byte. But if you're programming a microcontroller in C with 2kb of memory, every single bit counts, so the ability to pack 8 bools into a single byte may be critical.


答:
My initial idea is to throw an exception if any query doesn't use an index so it has to be taken care of in devel but to continue to log the large/slow queries so we can see long term where the slowness is.

I think you should not do this, because:

Your application can never know if a query used an index or not

Exceptions are for real errors not for performance checks

Poor performance of queries can be attributed to indexes but not to indexes alone. It could be because the amount of data returned is so large, or the database is badly designed for the purpose required, or too many columns are read that are not needed, etc. Also, re-writing the query may make it use an index (indexable and non-indexable queries)

Adding indexes sometimes slows performance of inserts and updates, so be careful

To solve this problem, you need to:

Identify poor performing queries

Ensure that the problem is in SQL

Ensure that only needed rows and columns are retrieved

Profile the queries using a profiling tool and take the necessary action based on the results.

Also check with DBAs Forum


答:
Yes, OO can often be used to model real world entities.

Even in my business layer I've got classes like observers, managers, factories, etc. which aren't real world objects.

Do not confuse object oriented development with design patterns.  OO analysis and design is a means to approach programming maintainable code.  Coupled with an OO language, programmers are given the power to create re-usable code through the pillars of OO:  encapsulation, polymorphism, and inheritance.

To encapsulate an entity we can model that entity after its real world counterpart.  For example, if we have a guitar then a guitar class encapsulates the behaviors and properties of a real world guitar.  We can further abstract the guitar as, say, an IInventoryItem to take advantage of the potential for code re-use through polymorphism and inheritance.

On the other hand, we may find that a factory of guitars could assist us in maintening a set of different types of guitars.  This isn't because of OO.  Rather, a factory is a design pattern that has stood the test of time as a proven means of successfully creating maintenanble code for such a purpose.  In other words, we programmers are often solving similar problems.  So we came up with a common solution for solving them (don't reinvent the wheel).

That does not mean OO has to model the real world, nor that it is always the most optimal solution to do so.  Simply, that as a rule of thumb “OO modeling the real world” makes perfect sense.


答:
You have a way to catch the culprits, but causing an error is a bad idea. It's also a false sense of security. A query design may not change at all, but the data can change and affect performance. Depending on the RDBMS lack of statistics can cause performance problems. You're going to keep monitoring them anyway. Just because a query uses at least one index doesn't mean it shouldn't utilize others.

This is another way to create bad blood with your programmers and users. Who is really getting punished here?


答:
Method chaining like that is usually called a Fluent Interface when there is some kind of flow or discoverability in the chain. Alternatively, you can think of an api like jQuery that relies heavily on method chaining as not 'fluent' because there's not the same emphasis on discoverability -- it's more for convenience.

For your example (using withx, withy) you can consider this a variant of the Builder pattern because you've got a specialized class that, given some state (method calls) knows how to return a properly configured object.

This isn't an anti-pattern if used appropriately.

Title: What is the name for the idiom using method chaining to build an object?

Body:
I frequently use a pattern where I using method chaining to setup an object, similar to a Builder or Prototype pattern, but not creating new objects with each method call, instead modifying the original object.

Example:

```<code>new Menu().withItem("Eggs").withItem("Hash Browns").withStyle("Diner");
</code>```

Just wondering if there is a name for this pattern and whether it is considered an anti-pattern, because although it can read more fluently, it can lead to long method chains.


答:
I Understand your frustration. But penalizing the user with exceptions may not be a good idea in this case.

What you can do is :

Whenever you come across this problem in the code you can call a special logger say PerformanceIssueLogger.log which will log these issues in a different log with the specific query which you can scan it later and fix the issues.

Better yet, You can encapsulate the logic that PerformanceIssueLogger.log , which can throw an exception in addition to logging in the file if the environment != prod.


答:
Such a priori rules don't make much make sense. In a first step, just log what queries take how much time and how often they are called.

Then you can really see, which queries are an effective problem and work to fix it. Performance optimization is only possible after determining bottlenecks through proper profiling. Once a bottleneck is discovered, you must first understand it and then evaluate the different options. When it comes to SQL, slapping indices on the involved tables is one option. Denormalization, sharding or caching (through memcache or redis) are others. Much like there's no simple rule that will tell you how much resources a given query will eat up (because this depends on things that you can either speculate about or simply measure), there's no simple rule to how you can reduce the resource consumption.


答:
What is a model, anyway:

A model is a simplified representation used to explain the workings of a real world system or event

Does object oriented programming allow you to model the real world?

Definitely YES

It is almost impossible to model the system to exactly match the real world.

Do I always have to model the software exactly after the real world?

NO

Having said that you can model everything doesn't mean you have to model everything. In fact, the essence of useful modeling is to present a simplified representation. How much simplification is sufficient to express the current business need, and what needs to be omitted, is a fine balance between using the technique successfully vs. getting lost with it or not using it at all.

There are of course entities that doesn't exists really, but only through the modeling we can actually conceptualize well.


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

答:
Drupal, specifically Drupal 7, is probably one of the most high-profile and most comprehensively unit-tested public PHP projects, with built-in unit testing support, over 24,000 tests, and a requirement that all core contributions have tests.

Its unit testing support is based on SimpleTest, and has been in active use for a couple of years now. One of the neat things that Drupal does is test all patches that are attched to issue queues, giving feedback to contributors discussing a particular issue without having to manually apply patches themselves (example).


答:
I've seen it commonly repeated the object oriented programming is based on modelling the real world, but is it?

It seems to me that is not true of anything outside of the business layer.

No. As you point out, many of the things "modeled" in an OOP language are abstract concepts like message queues and controllers and stacks.

Even in your business layer, you're still not modeling "the real world". Assume you have an employee class. Employees are also People, who are also Mammals, who are also Animals, who are also… (yawn) Employees have favorite colors, and they wear certain clothes and believe certain things. In short, there's a huge range of complexity in the real world that we don't even attempt to capture in most programs.

In modeling, we only focus on the aspects of the model that are meaningful to the task at hand. If we're designing a time entry system, then we probably want some sort of Employee class, but that class doesn't need a property to express the employee's favorite color.

Therefore, models shouldn't attempt (or pretend) to completely represent the "Real World".

While some objects I create are modelling real world objects, would not pre-OOP code do the same? I doubt that OO was the first people to include concepts like Customer in their code bases.

You are correct. If you look at large programs that are not OOP, they are often still organized around data structures. A data structure and all of the functions that manipulate are defined near each other, for clarity reasons. (The subversion project is a good example of this. Data structures and functions are prefixed with module names so that it's clear which structures and functions are intended for use with each other.)

I'm no expert on the history of programming languages, but I imagine that OOP grew out of the casual observation that code was clearer and easier to understand when it was organized this way, so language designers started designing languages where that type of organization was more strictly enforced.

The biggest difference between OOP and non-OOP is that OOP binds code to data. So rather than calling code like this:

```<code>verb(noun);
</code>```

we do this instead:

```<code>noun->verb();
</code>```

Although this may seem like a grammatical difference, the difference is actually in mindset. We tell objects what to do, and typically don't care what the internal state or workings of the object are. When describing an object, we only need to describe it's public interface in order to work with it.

Body:
I've seen it commonly repeated the object oriented programming is based on modelling the real world, but is it?

It seems to me that is not true of anything outside of the business layer.

No. As you point out, many of the things "modeled" in an OOP language are abstract concepts like message queues and controllers and stacks.

Even in your business layer, you're still not modeling "the real world". Assume you have an employee class. Employees are also People, who are also Mammals, who are also Animals, who are also… (yawn) Employees have favorite colors, and they wear certain clothes and believe certain things. In short, there's a huge range of complexity in the real world that we don't even attempt to capture in most programs.

In modeling, we only focus on the aspects of the model that are meaningful to the task at hand. If we're designing a time entry system, then we probably want some sort of Employee class, but that class doesn't need a property to express the employee's favorite color.

Therefore, models shouldn't attempt (or pretend) to completely represent the "Real World".

While some objects I create are modelling real world objects, would not pre-OOP code do the same? I doubt that OO was the first people to include concepts like Customer in their code bases.

You are correct. If you look at large programs that are not OOP, they are often still organized around data structures. A data structure and all of the functions that manipulate are defined near each other, for clarity reasons. (The subversion project is a good example of this. Data structures and functions are prefixed with module names so that it's clear which structures and functions are intended for use with each other.)

I'm no expert on the history of programming languages, but I imagine that OOP grew out of the casual observation that code was clearer and easier to understand when it was organized this way, so language designers started designing languages where that type of organization was more strictly enforced.

The biggest difference between OOP and non-OOP is that OOP binds code to data. So rather than calling code like this:

verb(noun);

we do this instead:

noun->verb();

Although this may seem like a grammatical difference, the difference is actually in mindset. We tell objects what to do, and typically don't care what the internal state or workings of the object are. When describing an object, we only need to describe it's public interface in order to work with it.


问:
IF ELSE shorthand. Does it hurt readability

Possible Duplicate:

  Is the ternary operator evil?

Does using shorthand if else statments hurt readability?

Compare:

```<code>string name = street != null ? street.Owner : "Not known";
</code>```

With:

```<code>string name;

if(street != null)
{
    name =  street.Owner;
}
else
{
    name = "Not known";
}
</code>```

I have become familiar enough with the shorthand that its just as readable for short statements as the long version. Is that true for most developers or should I favor the more verbose version

答:
What you are referring to is a ternary operator. In my opinion it can increase readability for simplistic conditional checks like the one in your question. It's short and provides a clear and obvious pair of return values. Nesting them hurts readability. While not quite a duplicate question the "hurts" is clearly demonstrated in THIS question.

Code from that question:

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

Body:
What you are referring to is a ternary operator. In my opinion it can increase readability for simplistic conditional checks like the one in your question. It's short and provides a clear and obvious pair of return values. Nesting them hurts readability. While not quite a duplicate question the "hurts" is clearly demonstrated in THIS question.

Code from that question:

int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}


问:
Minimal linux distro for compiling arm binaries
I have this setup:
A windows/x86 development box and a PandaBoard ES for testing with a linux on it.
I would like to ask you for recommending a linux distribution that I would run in Hyper-V on my devbox that would be used only for compiling arm/linux binaries. After compiling these binaries I will copy them to an SD Memory Card and test them on PandaBoard.

Thanks!

答:
I use Zenwalk for whenever I need a real linux box (2.6 kernel + XFCE 4.8). It's not really a minimal distro (in the sense that DSL and Puppy are), but it feels fast and snappy in VirtualBox 4.1 with 1GB RAM allocated to it . The machine runs on a Windows 7 x64 host with a total of 4GB of RAM with hardware virtualization support and nested paging.

If you're going to use Linux frequently and/or for extended periods of time, why not consider dual booting with Windows rather than running it inside a VM?

Also, have you considered Cygwin? It provides quite a few linux tools on a Windows machine.


答:
I often hear form programmers coming from other languages than it hurts readability. But once they got used to it, it becomes natural. For programmers of other languages (e.g. Delphi) it may not translate to anything they already know, so they think it's difficult.

When you know the language, I think it actually improves readability (unless you chain this shorthand multiple times or use really complex conditions).

Title: IF ELSE shorthand. Does it hurt readability

Body:
Possible Duplicate:

  Is the ternary operator evil?

Does using shorthand if else statments hurt readability?

Compare:

```<code>string name = street != null ? street.Owner : "Not known";
</code>```

With:

```<code>string name;

if(street != null)
{
    name =  street.Owner;
}
else
{
    name = "Not known";
}
</code>```

I have become familiar enough with the shorthand that its just as readable for short statements as the long version. Is that true for most developers or should I favor the more verbose version


答:
It's readable as long as you don't abuse it by using complicated boolean logic or using too much logic.

Example:

```<code>string name = street != null & street.Length > 0 ? GetNumber(street) + " " + street + " " + GetOwner(street) : Properties.Resources.UnknownStreet;
</code>```

Body:
It's readable as long as you don't abuse it by using complicated boolean logic or using too much logic.

Example:

string name = street != null & street.Length > 0 ? GetNumber(street) + " " + street + " " + GetOwner(street) : Properties.Resources.UnknownStreet;


答:
It took me about five minutes to get used to the short form (a "ternary operator").

The ternary operator is much better for this particular example, because it's  just a validation transformation, if you will.  As part of a validation process, there can be many of these, and using ordinary if/thens can quickly become unwieldy.


答:
Like most of the shorthand, it can be good for readability if use correctly.

If you start to merge long condition with other  ternary operator, you will start having trouble.

If you hesitate, I suggest to do a code review about it. If everyone in your team prefer the shorthand version, go with it.

Readability is subjective


答:
```<code>string name = street != null ? street.Owner : "Not known";
</code>```

This one was horrible to read at the first sight! I was busy figuring out name = street but realized later that your syntax was actually perfect.

```<code>string name;

if(street != null)
{
name =  street.Owner;
}
else
{
name = "Not known";
}
</code>```

This one i didn't too effort to understand at all (partly because the first one fixed my brain already). However, i agree that this is too inefficient.

However, keeping brevity while the readability both, i would have done this way,

```<code>string name = (street != null) ? (street.Owner) : "Not known";
</code>```

This is fine, but i won't use ternary operator ? in lieu of if ever, in case either of the clauses are more than a single variable. or any complex expression with more than 2 parenthesis or 2 lines.

Body:
string name = street != null ? street.Owner : "Not known";

This one was horrible to read at the first sight! I was busy figuring out name = street but realized later that your syntax was actually perfect.

string name;

if(street != null)
{
name =  street.Owner;
}
else
{
name = "Not known";
}

This one i didn't too effort to understand at all (partly because the first one fixed my brain already). However, i agree that this is too inefficient.

However, keeping brevity while the readability both, i would have done this way,

string name = (street != null) ? (street.Owner) : "Not known";

This is fine, but i won't use ternary operator ? in lieu of if ever, in case either of the clauses are more than a single variable. or any complex expression with more than 2 parenthesis or 2 lines.


问:
Flexible development environments for creating a common code base targeting tablets (iPad/Android) and x86 PCs
Hopefully this won't be flagged for being too vague, but I'm really looking for suggestions from anyone with experience in this sort of situation.

I work for a group that develops very specialized engineering calculations for Intel x86 platforms.

We do not intend to continue using this existing x86 code. Instead, we would like to start a new code base capable of targeting both x86 PCs and iPad and/or Android tablets. Clearly the UI code will have to be maintained independently. But I suspect the backend engineering code, which we want to keep common, is possible to be shared among all platforms.

I would like to know if there are any development environments or techniques for simplifying this multiple-platform development with a common backend code base, or will it be necessary to develop this backend code for each platform independently as well.

Please let me know if you need any clarification!

Thanks

EDIT

For example, we would need to write a large amount of code in C. Is it true both the iOS SDK's objective-C compiler can build native iOS code using the (relatively) same C code we would use to build native windows code using MSVC? Mind you, the code would not need to rely on specialized OS-dependent facilities.

Are there any tools for assisting in this sort of cross-platform development that may require multiple compilers? or perhaps any individual compilers that can target both platforms?

答:
I would suggest you want to look at the Mono project which will lead you to C# that can run on Windows, Linux, iOS and Android. Actually on Apple too via Silverlight (for now at least). And in back of websites via ASP.NET... Oh and on the shiny new Win8 tablets when they arrive.

Specifically you want to visit http://xamarin.com - the tools you need are commercial, but you should win in productivity terms (given that you'll get help with the front end code too).


答:
Bitwise operations are absolutely essential when programming hardware registers in embedded systems.  For example every processor that I have ever used has one or more registers (usually a specific memory address) that control whether an interrupt is enabled or disabled.  To allow an interrupt to fire the usual process is to set the enable bit for that one interrupt type while, most importantly, not modifying any of the other bits in the register.

When an interrupt fires it typically sets a bit in a status register so that a single service routine can determine the precise reason for the interrupt.  Testing the individual bits allows for a fast decode of the interrupt source.

In many embedded systems the total RAM available may be 64, 128 or 256 BYTES (that is Bytes not kilobytes or megabytes)  In this environment it is common to use one byte to store multiple data items, boolean flags etc. and then use bit operations to set and read these.

I have, for a number of years been working with a satellite communications system where the message payload is 10.5 bytes.  To make the best use of this data packet the information must be packed into the data block without leaving any unused bits between the fields.  This means making extensive use of bitwise and shift operators to take the information values and pack them into the payload being transmitted.

Title: What are the advantages of using bitwise operations?

Body: Following reading the latest CodeProject newsletter, I came across this article on bitwise operations.  It makes for interesting reading, and I can certainly see the benefit of checking if an integer is even or odd, but testing if the n-th bit is set?  What can possibly be the advantages of this?</p>


答:
While some objects I create are modelling real world objects, would
  not pre-OOP code do the same?

I would say not. OOP ties down the relationship between things (properties/objects) and what they can do/can be done to them (methods), whereas procedural programming doesn't do this (aside from, to a small degree, when using strict typing). A model isn't just about defining discrete parts and processes, it's also about defining how they fit together, and OOP is particularly good at this.


答:
I've seen it commonly repeated the object oriented programming is
  based on modelling the real world, but is it?

Yes. The emphasis here is based on. OOP doesn't model the real world (if it does, then incidentally) and it is not supposed to. What OOP does is to allow us model programming problems the way we model the real world: as a system of entities that are defined through our abstraction of their behavior.


答: It's up to you, finally. But OOP is a precise way doing so than other methodologies like Structured or Procedure-oriented programming. Procedureal tact could possibly solve your problems but by following OOP can make you life more easier.</p>


答: I think you are reading too much into what is intended to be a very prosaic, historical, statement. Many of the ideas of OO programming, classes, polymorpism, virtual functions, etc. were introduced in the language Simula, back in the 1960s (http://en.wikipedia.org/wiki/Simula). As the name suggests, Simula was designed to be a language for writing simulations. So historically, yes, OO ideas were introduced in an effort to model the "real world". Whether they succeed more than other styles is a matter of debate.</p>


问:
Is Visual Source Safe (The latest Version) really that bad? Why? What's the Best Alternative? Why?
Over the years I've constantly heard horror stories, had people say "Real Programmers Dont Use VSS", and so on. BUT, then in the workplace I've worked at two companies, one, a very well known public facing high traffic website, and another high end Financial Services "Web-Based" hosted solution catering to some very large, very well known companies, which is where I currently Reside and everything's working just fine (KNOCK KNOCK!!).

I'm constantly interfacing with EXTREMELY Old technology with some of these financial institutions.. OLD LIKE YOU WOULDN'T BELIEVE.. which leads me to the conclusion that if it works "LEAVE IT", and that maybe there's some value in old technology? at least enough value to overrule a rewrite!? right??

Is there something fundamentally flawed with the underlying technology that VSS uses? I have a feeling that if i said "someone said VSS Sucks" they would beg to differ, most likely give me this look like i dont know -ish, and I'd never gain back their respect and my credibility (well, that'll be hard to blow.. lol), BUT, give me an argument that I can take to someone whose been coding for 30 years, that builds Platforms that leverage current technology (.NET 3.5 / SQL 2008 R2 ), write's their own ORM with scaffolding and is able to provide a quality platform that supports thousands of concurrent users on a multi-tenant hosted solution, and does not agree with any benefits from having Source Control Integrated, and yet uses the Infamous Visual Source Safe.

I have extensive experience with TFS up to 2010, and honestly I think it's great when a team (beyond developers) can embrace it. I've worked side by side with someone whose a die hard SVN'r and from a purist standpoint, I see the beauty in it (I need a bit more, out of my SS, but it surely suffices). So, why are such smarties not running away from Visual Source Safe? surely if it was so bad, it would've have been realized by now, and I would not be sitting here with this simple old, Check In, Check Out, Version Resistant, Label Intensive system. But here I am...

I would love to drop an argument that would be the end all argument, but if it's a matter of opinion and personal experience, there seems to be too much leeway for keeping VSS.

UPDATE: I guess the best case is to have the VSS supporters check other people's experiences and draw from that until we (please no) experience the breaking factor ourselves. Until then, i wont be engaging in a discussion to migrate off of VSS..

UPDATE 11-2012: So i was able to convince everyone at my work place that since MS is sun downing Visual Source Safe it might be time to migrate over to TFS. I was able to convince them and have recently upgraded our team to Visual Studio 2012 and TFS 2012. The migration was fairly painless, had to run analyze.exe which found a bunch of errors (not sure they'll ever affect the project) and then manually run the VSSConverter.exe. Again, painless, except it took 16 hours to migrate 5 years worth of everything.. and now we're on TFS.. much more integrated.. much more cooler.. so all in all, VSS served it's purpose for years without hick-up. There were no horror stories and Visual Source Save as source control worked just fine. so to all the nay sayers (me included). there's nothing wrong with using VSS. i wouldnt start a new project with it, and i would definitely consider migrating to TFS. (it's really not super difficult and a new "wizard" type converter is due out any day now so migrating should be painless). But from my experience, it worked just fine and got the job done.

答:
The fundamental problem with technologies like Access and SourceSafe is that they are shared-file solutions.  This makes them vulnerable to catastrophic crashes (yes, it's happened to me before).

That said, if you're working in a very small developer environment, SourceSafe works perfectly fine.  Checkouts are exclusive by default (unless you enable "multiple checkout" mode, which I've never used), which means only one person can work on a file at any given moment, but if you're all in one room, that's not an issue.

Everyone should be required to check in when they leave for the day.  The person who doesn't check in and then takes a day off gets to buy everyone donuts when he gets back.


答:
The problem isn't how "old" it is.  VSS suffered from the same problem a lot of Microsoft technologies had:  something originally designed for a single user had some design decisions that caused problems with multiple users, like the lack of atomic commits and dependence on shared file access.

It looks like Microsoft fixed a lot of those issues in 2005, but it's sort of the case of "too little too late."  By that time most people had moved onto other systems that had other modern features they liked and none of the problems.

Title: Is Visual Source Safe (The latest Version) really that bad? Why? What's the Best Alternative? Why?

Body:
Over the years I've constantly heard horror stories, had people say "Real Programmers Dont Use VSS", and so on. BUT, then in the workplace I've worked at two companies, one, a very well known public facing high traffic website, and another high end Financial Services "Web-Based" hosted solution catering to some very large, very well known companies, which is where I currently Reside and everything's working just fine (KNOCK KNOCK!!).

I'm constantly interfacing with EXTREMELY Old technology with some of these financial institutions.. OLD LIKE YOU WOULDN'T BELIEVE.. which leads me to the conclusion that if it works "LEAVE IT", and that maybe there's some value in old technology? at least enough value to overrule a rewrite!? right??

Is there something fundamentally flawed with the underlying technology that VSS uses? I have a feeling that if i said "someone said VSS Sucks" they would beg to differ, most likely give me this look like i dont know -ish, and I'd never gain back their respect and my credibility (well, that'll be hard to blow.. lol), BUT, give me an argument that I can take to someone whose been coding for 30 years, that builds Platforms that leverage current technology (.NET 3.5 / SQL 2008 R2 ), write's their own ORM with scaffolding and is able to provide a quality platform that supports thousands of concurrent users on a multi-tenant hosted solution, and does not agree with any benefits from having Source Control Integrated, and yet uses the Infamous Visual Source Safe.

I have extensive experience with TFS up to 2010, and honestly I think it's great when a team (beyond developers) can embrace it. I've worked side by side with someone whose a die hard SVN'r and from a purist standpoint, I see the beauty in it (I need a bit more, out of my SS, but it surely suffices). So, why are such smarties not running away from Visual Source Safe? surely if it was so bad, it would've have been realized by now, and I would not be sitting here with this simple old, Check In, Check Out, Version Resistant, Label Intensive system. But here I am...

I would love to drop an argument that would be the end all argument, but if it's a matter of opinion and personal experience, there seems to be too much leeway for keeping VSS.

UPDATE: I guess the best case is to have the VSS supporters check other people's experiences and draw from that until we (please no) experience the breaking factor ourselves. Until then, i wont be engaging in a discussion to migrate off of VSS..

UPDATE 11-2012: So i was able to convince everyone at my work place that since MS is sun downing Visual Source Safe it might be time to migrate over to TFS. I was able to convince them and have recently upgraded our team to Visual Studio 2012 and TFS 2012. The migration was fairly painless, had to run analyze.exe which found a bunch of errors (not sure they'll ever affect the project) and then manually run the VSSConverter.exe. Again, painless, except it took 16 hours to migrate 5 years worth of everything.. and now we're on TFS.. much more integrated.. much more cooler.. so all in all, VSS served it's purpose for years without hick-up. There were no horror stories and Visual Source Save as source control worked just fine. so to all the nay sayers (me included). there's nothing wrong with using VSS. i wouldnt start a new project with it, and i would definitely consider migrating to TFS. (it's really not super difficult and a new "wizard" type converter is due out any day now so migrating should be painless). But from my experience, it worked just fine and got the job done.


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

This question has two parts...

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

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

Update:

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

- specific server side programming optimizations

- test labs

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

答:
If I was given a slow machine I'd spend my day optimising the development process and not optimising my delivered code.
So: NO!</p>


问:
How can I feel more confident about my programming skills?
Programming isn't alien to me. I first starting doing markup (HTML, now please don't laugh at me) when I was 12 and a little bit of BASIC when I was 13 (I knew much about Flowcharts, Pseudocodes at this point), but then I was admonished into Biology in high school and hence missed out on "real" programming knowledge of languages such as C, Java, etcetera. I took up CS for my UG B.E. (similar to BS, but way more theoretical). I learnt C & C++ (to a lesser extent) on my own (my prof was a total pain and the class was filled with code-jocks (who had already learnt it in school, and hence paid no attention to class and didn't let lesser mortals like me to pay any attention to class either)) and could whip up an awesome addition or multiplication program (ones which now even kinder-gardeners' whip up with way more finesse) and a piss-poor knowledge of Java (which has even grown rusty in recent times).

My main problem is that I've always felt inadequate and strangled by my limited programming skills and belittled by the code-jocks (believe me, I've come across this site ages ago, but could just now build up the courage to actually post a question) and have been at times even depressed over said inability. Most people say that Programming isn't necessarily about the language but the state of mind that the person has and the techniques they employ to solve problems/issues. I agree with such sentiments, but can I ever acquire such a "state of mind", and if such how should I approach "Programming/Coding", and if there are any set ways and steps one most go through to attain the "Zen of Coding". How do I do so? Also, it wouldn't hurt if some Saint wanted to mentor this downtrodden piece of $#!^.

P.S. I would forever be grateful to any person who considers me worth their time, and as a bonus would name my first piece of Software I ship after them. (If I ever get to ship one, i.e.,)

TL;DR: Never really learnt "Programming/Coding", can't solve problems even if I try to. Help me!

答:
There are a lot of good comments about practice on here, it really does make all the difference.

You should worry less about "code jocks" and take their advice or comments for what they are.  If they're hard to deal with in a thread, they're probably hard to deal with in real life also ; and really, who has time to worry about their social ineptitude?

The end result is, there are thousands of ways to approach programming tasks.  A lot of things boil down to personal preferences.  I for instance, hate reading code with tenary operators.  Others, love them.  Do I think they're right or wrong?.. actually, neither.  It's personal preference though a lot of heated debates will be had on the topic.

If someone berates your code because you took 25 lines instead of 20 I would tend to just ignore them unless they have found an actual flaw in logic.  Sometimes in the real world, we have to just get things done (and who really wants to listen to someone chest puffing about how complicated... err, elegant they managed to make a piece of code that should have been done in 10 minutes).  Can you learn something from endless philosophical debates on how far to abstract things?  Sure... but there is dimishing returns in getting sucked into constant 100% elegance.  It's not realistic all the time as much as we'd like to pretend that it is.  Some of my least elegant code that I'd be embarrased to share with anyone (that I wrote in the beginning of my career) has saved people weeks upon weeks worth of time, been used since its inception over a decade ago and would have to be pried from the users' cold dead fingers (and also works, has never broken thus has never been given time to go back and "clean up" which is always the story).

There's a great blog post by Joel Spolsky called the Duct Tape Programmer.  It's a great read and IMO puts some of your fears into perspective.

http://www.joelonsoftware.com/items/2009/09/23.html

I'm not saying write crap code and ignore best practices, but take ranty programmers with a grain of salt.

OwnerDisplayName: Ameen


答:
The SVN Book points out one very critical thing that i didn't quite realized the value of it but now i deeply endorse it. I don't have exact excrept but here is the jist:

VSS philosophy is that conflict is bad. So avoiding conflicts (by way of exclusion) might looks like a solution but that is really not good.

In case of SVN (and also true for others) - first off, there can be mechanism to merge things without conflicts - but even if conflicts do happen, it is a good thing! Conflicts implies that two developer were attempting to do something similar simultaneously and conflict thrown by SCM, actually forces them to talk.

Conflicts motivates communication where as exclusivity locks you out