问:
Algorithm for determining grid based on variably sized "blocks"?
I'm trying to convert a set of "blocks" in to a grid-like layout. The blocks have a width of either 25%, 33%, 50%, 66%, or 75% of their container and each row of the grid should try to fit as many blocks as possible, up to a total width of 100%.

I've discovered that trying to do this while leaving no remaining blocks in the original set is very hard. Eventually, I think my solution will be to upgrade/downgrade various block sizes (based on their priority or something) so they all fit in to a row.

Either case, before I do that, I thought I'd check if someone has some code (or a paper) demonstrating a solution to this problem already? And bonus points if the solution incorporates varying block heights in to its calculations :)

答: This is an NP-complete problem- there are no known polynomial time algorithms in the general case. It is known as Bin Packing or Subset Sum.</p>


问:
Creating a shared library that might be used with desktop applications and web projects
I have been involved in a number of MVC.NET and c# desktop projects in our company over the last year or so while also managing to kept my nose poked into other projects (in a read-only learning capacity of course).

From this I've noticed that across the various projects and teams there is a-lot of functionality that has been well designed against good interfaces and abstractions.  Because we tend to like our own work at times, I noticed a couple of projects had the exact same class, method copied into it as it had obviously worked on one and so was easily moved to a new project (probably by the same developer who originally wrote it)

I mentioned this fact in one of our programmer meetings we have occasionally and suggested we pull some of this functionality into a core company library that we can build up over time and use across multiple projects.  Everyone agreed and I started looking into this possibility.

However, I've come across a stumbling block pretty early on.  Our team primarily focuses on MVC at the moment and we have projects mainly in 2.0 but are starting to branch to 3.0.  We also have a number of desktop applications that might benefit from some shared classes and basic helper methods.

Initially when creating this DLL I included some shared classes that could be used across any project type (Web, Client etc) but then I started looking at adding some shared modules that would be useful in our MVC applications only.  However this meant I had to include a reference to some Microsoft Web DLL's in order to leverage some of the classes I was creating (at this stage MVC 2.0).

Now my issue is that we have a shared DLL that has references to web specific libraries that could also possibly be used in a client application.  Not only that, our DLL referenced initially MVC 2.0 and we will eventually move onto MVC 3.0 for all projects.  But alot of the classes in this library I expect to still be relevant to MVC 3 etc

Our code within this DLL is separated into it's own namespaces such as:

CompanyDLL.Primitives

CompanyDLL.Web.Mvc

CompanyDLL.Helpers etc etc

So, my questions are:

Is it OK to do a shared library like this, or if we have web specific features in it should we create a separate web DLL only targeted at a specific framework or MVC version?

If it's OK, what kind of issues might we face when using the library that references MVC 2 in a MVC 3 project for example.  I would be thinking that we might run into some sort of compatibility issue, or even issues where the developers using the library doesn't realize they need MVC 2.0 libraries.  They might only want to use some of the generic classes etc

The concept seemed like a good idea at the time, but I'm starting to think maybe it's not really a practical solution.  But the number of times I've seen copied classes and methods across projects because they are proven tested code is a bit unnerving to be perfectly honest!

UPDATED:
Further to Bernards answer which I have taken on board and seems good advice.  However I want to create some shared classes that will probably be useful in both MVC 2 and MVC 3 projects.  However my shared assembly will have to reference one of the MVC frameworks in order for me to create my shared classes in the first place.

So further to expand on my Q2 above.

If I wanted a MVC 3 web solution would I have to have a shared CompanyDLL.Web.Mvc3 project that would then specifically be referencing MVC 3?  Would that mean copying over all the code from my CompanyDLL.Web.Mvc2 solution to this new Mvc3 shared project?

It seems I'm missing some fundamental designing skills in the creation of shared assemblies and building and referencing against different framework versions.  Or it might just be as simple as we suck it up and create a CompanyDLL.Web.Mvc2, CompanyDLL.Web.Mvc3, CompanyDLL.Web.Mvc4 etc etc libraries...

答:
Create separate shared libraries for your different platforms (desktop and web). Whatever both of these libraries will need should go in a separate shared library. Thus, you could split these libraries up as follows:

Company.Core: Used by all libraries. Contains generic code, helper classes, etc. that are not specific to any platform. References no other shared libraries.

Company.Core.Desktop: Used by desktop applications. References Company.Core library.

Company.Core.Web: Used by web applications. References Company.Core library.

This allows you to change the web technology being used without affecting the desktop technology being used. This also allows you to add more platforms in the future (e.g. Company.Core.Mobile).

Ensure these libraries are unit tested and never again copy code between projects.

ContentLicense: CC BY-SA 3.0


问:
What are some potential pitfalls to using URL rewriting with SSL?
Using URL rewriting for session management for plain HTTP communication is a recipe for disaster, however, does some of that risk go away if you're using SSL (https)?</p>

答:
Yes, SSL mitigates the threat of a man-in-the middle attack.

The only shortcoming is that, with a long-running session, a hacker could potentially capture the session id in a server log and use it for malicious purposes.


问:
Is it better to use a Database or a data structure for network stack?
I've built a multi threaded messaging application in C and I'm currently using a MySQL Memory table to save the session ID, but I'm not sure whether this was a good decision or not.

It works like this, the application sends a message and saves the source session ID in the MySQL table. When the application gets the success response it will remove the session's ID from the MySQL table, or if it received an error response then it will keep the ID to be retried later.

I've built it this way so that I don't need to care about building a data structure by myself, and the Database provides flexibility when it comes to querying it.

Do you think this is appropriate or do I need to use something else? Please note that the application is expecting to handle a large number of transactions/sec.

答:
I can share what we did to solve this problem.
We built a write-ahead-log, and used an in-memory black/red tree for lookup on a very large set of keys.

The benefits of doing this yourself are many... Encapsulation, less dependencies, performance, no network overhead, etc.


问:
RESTFul: state changing actions
I am planning to build a RESTfull API but there are some architectural questions that are creating some problems in my head. Adding backend business logic to clients is an option that I would like to avoid since updating multiple client platforms is hard to maintain in real time when business logic can rapidly change.

Lets say we have article as a resource ( api/article ), how should we implement actions like publish, unpublish, activate or deactivate and so on but to try to keep it as simple as possible?

1) Should we use api/article/{id}/{action} since a lot of backend logic can happen there like pushing to remote locations or change of multiple properties. Probably the hardest thing here is that we need to send all article data back to API for updating and multiuser work could not be implemented. For instance editor could send 5 seconds older data and overwrite fix that some other journalist just did 2 seconds ago and there is no way that I could explain to clients this since those publishing an article is really not in any way connected to updating the content.

2) Creating new resource can also be an option, api/article-{action}/id , but then returned resource would not be article-{action} but article which I am not sure if this is proper. Also in server side code article class is handling actuall work on both resource and I'm not sure if this goes against RESTfull thinking

Any suggestions are welcomed..

答:
REST is data oriented and as such resources work best as "things" not actions.  The implicit semantics of http methods; GET, PUT, DELETE, etc serve to reinforce the orientation.  POST of course, is the exception.

A resource can be a mixture of data ie. article content; and metadata ie. published, locked, revision.  There are many other possible ways to slice up the data, but you have to go through the what the data flow will look like first in order to determine the most optimal one (if there is one).  For example it may be that revisions should be their own resource under the article as TokenMacGuy suggests.

Regarding implementation I would probably do something like what TockenMacGuy suggests.  I would also add a metadata fields on article, not revision, like 'locked' and 'published'.

ContentLicense: CC BY-SA 4.0

Title: RESTFul: state changing actions


问:
Examples of continuous integration workflow using git
Can anyone provide a rough outline of their git workflow that complies with continuous integration.
E.g. How do you branch? Do you fast forward commits to the master branch?

I am primarily working with Rails as well as client and server side Javascript. If anyone can recommend a solid CI technology that's compatible with those, that'd be great. I've looked into Jenkins but would like to check out other good alternatives.

To put some context into this, I am planning on transitioning from working as a single developer into working as part of the team. I'd like to start standardizing my own personal workflow so that I can onboard new devs quickly.

答:
Work

Commit to your local repo

Push (to master repo)

CI detects new revision

CI checks out new revision

CI builds and tests new revision

CI updates Changelog (commit and push)

CI creates a version file and then tags master repo

CI packages build

CI pushes package to artifact repo (in our case a YUM repo)

rinse, repeat

We don't work of branches.  We always commit to trunk, but then again we also do ATDD to mitigate the common issues like instability.


问:
What is the difference between Static code analysis and code review?
I just wanted to know what the difference is between static code analysis and code review. How are each of these two done?  More specifically, what are the tools available today for code review/static analysis of PHP?  I would also like to know about good tools for code review for any language.</p>

答:
Code review is something people do, static analysis is something machines do. There are (sometimes good) static analysis tools. Code review is when a colleague/mentor/professor/friend goes over your code and gives you constructive criticism.

Static analysis is, on the other hand, an automated process in which a machine, informed by what it knows about the language it is analyzing (usually from the type system), analyzes a program and tries to pick out things that could be incorrect, inefficient, poor style, or otherwise suboptimal.

OwnerDisplayName: Xander

OwnerDisplayName: Rafe Kettler


答:
Code Review is when A senior or a dedicated authority checks your code, your way of coding, the standards followed in the code and specifically the logic level of the code

As far As static analysis is concerned, it is the analysis of computer software  that is performed without actually executing programs built from that software (analysis performed on executing programs is known as dynamic analysis)

The List of tools as per the technology is given in below link

List Of Tools for Static Analysis

Hence code review and static analysis are completely different terms.

Title: What is the difference between Static code analysis and code review?

Body: I just wanted to know what the difference is between static code analysis and code review. How are each of these two done?  More specifically, what are the tools available today for code review/static analysis of PHP?  I would also like to know about good tools for code review for any language.</p>

OwnerDisplayName: OM The Eternity


答:
static code analysis is performed by automated tool, code review is done with people before the code is committed.

Tools for code review:

1.beyond compare

2.the diff of version control software

These tools are always used to generate the difference between the old version and the new version.

OwnerDisplayName: upton


问:
Will javascript be in the HTML5 standard
I'm pretty new to the web development scene, and I just want to be absolutely clear on this because I've read a few conflicting statements.

I was under the impression that "html5" is a particular way of constructing xml to represent data for a webpage and "javascript" is a programming language that runs as client-side code in the browser. But left and right I see APIs for javascript (workers, geolocation, local storage, etc.) being referred to as an "html5 technology". Wikipedia says that html5 doesn't have a standard yet, so I can't look it up to see if it somehow mandates stuff about javascript.

So will APIs for javascript somehow be apart of the html5 standard? Or has it become a common bad practice to label javascript APIs "html5 technology"?

答: It's not a standard yet, but you can read the draft specification on the W3 web site. Javascript/Ecmascript is part of section 6.1.6: Events.</p>


答:
Static analysis is the process of analyzing a software without executing it. This is very good and recommended, but you have to keep in mind that

different static analysis tools have different understanding of the code they are studying, hence they can signal (or not signal) different issues. One tool can give a clean report, and the other may complain about a million things.

a dynamic tool (to name an example, think of valgrind) can find many other issues, at the price of a serious burden on the resource consumption (time, memory usage). This is so because you are usually running an instrumented version of the software. Notice that, by being instrumented in some way (replace your malloc with a debugging malloc) it is not exactly identical to your software (as you can see from the execution times)

Both of these approaches suffer from the lack of context: they don't know what the sw is supposed to achieve.

Code review is done by another coder, who supposedly knows it and can check

if the code is right

if the software is semantically correct.

It is much more expensive and it has a varying degree of repeatability but is a great help.

As always, there is not a single silver bullet which will fix all the bugs and avoid all the problems.
Applying - as much as possible given the place, the code, the time, the three forms of check (static, dynamic, more eyes (and brains) actually looking at the code) is recommended.

ps: I must note that it is usually much better to apply the tools from scratch. Converting a legacy system is a much less pleasurable experience, due to false positives. If you start from scratch and always aim at keeping the analysis tool clean, you will probably avoid a lot of problems.

pps: as for tools, it depends on the language. In the C and C++ world you can start by looking at Visual Studio itself, which contains a built-in static analysis tool. A relatively complete list can be found on Wikipedia.

ppps: Static analysis is more suited to static languages, like C or C++. For Python it can be really difficult to say if a name which refers to a list at a point will refer to a list for the rest of the program, due to its dynamic properties. This doesn't mean that nothing can be done, as a JIT effort like PyPy shows.


问:
Visually and audibly unambiguous subset of the Latin alphabet?
Imagine you give someone a card with the code "5SBDO0" on it.

In some fonts, the letter "S" is difficult to visually distinguish from the number five, (as with number zero and letter "O").

Reading the code out loud, it might be difficult to distinguish "B" from "D", necessitating saying "B as in boy," "D as in dog," or using a "phonetic alphabet" instead.

What's the biggest subset of letters and numbers that will, in most cases, both look unambiguous visually and sound unambiguous when read aloud?

Background:

We want to generate a short string that can encode as many values as possible while still being easy to communicate.

Imagine you have a 6-character string, "123456".  In base 10 this can encode 10^6 values.

In hex "1B23DF" you can encode 16^6 values in the same number of characters, but this can sound ambiguous when read aloud. ("B" vs. "D")

Likewise for any string of N characters, you get (size of alphabet)^N values.

The string is limited to a length of about six characters, due to wanting to fit easily within the capacity of human working memory capacity.

Thus to find the max number of values we can encode, we need to find that largest unambiguous set of letters/numbers.  There's no reason we can't consider the letters G-Z, and some common punctuation, but I don't want to have to go manually pairwise compare "does G sound like A?", "does G sound like B?", "does G sound like C" myself.  As we know this would be O(n^2) linguistic work to do =)...

答: You could use Mechanical Turk to have real people rate all 26^2 pairs of letters for aural and visual similarity. The advantage is that you could even get data for various native languages this way.</p>


问:
What is a microframework?
Why are some frameworks (e.g. Flask for Python, Sinatra for Ruby) called microframeworks?

What differentiates them from full-fledged frameworks, like Django or Rails?

答:
This link should provide you with all the info you need (in terms of Flask)...

Extract from the same link:

The main reason Flask is called a “microframework” is the idea to keep
  the core simple but extensible. There is no database abstraction
  layer, no form validation or anything else where different libraries
  already exist that can handle that.

I hope that makes it clear. :)

Title: What is a microframework?


答: It's a shorthand for "framework written by someone annoyed by established farmeworks' percieved excessive complexity, which is going to gradually accumulate a similar amount of complexity proportional to its growth in popularity as it's extended to handle more varied requirements."</p>

Title: What is a microframework?

Body:
Why are some frameworks (e.g. Flask for Python, Sinatra for Ruby) called microframeworks?

What differentiates them from full-fledged frameworks, like Django or Rails?


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答: "Real programmers don't see code, they see trees."</p>

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Which way is practical for improving your skills with pet project?
About your own project, in which way does it give you more improvement?

Read high quality code in the same domain, implement your own.

Write one project from scratch with your imagination.

My point is that it is not practical to write something like networking lib or graphic engine without knowing what other people did in the same domain.

答:
Let me list down my approach to learning something new. Theses are raw and generalized steps.

Read little about what you are going to learn. You may not understand everything but will definitely create lots of questions in your mind.

Get a some sample code (from multiple sources) read and understand it.

Hack the code, add your stuff, break it , debug and fix it.

Read again (what you have learned from step 1 ) try and implement whats in the book.

Start with a simple application of your own, keeping reference of what you have learned from the practice. In this step you should code, code and code.

Read more to get thorough with concept and usage.


问:
What arguments can I use to "sell" the BDD concept to a team reluctant to adopt it?
I am a bit of a vocal proponent of the Behaviour Driven Development methodology (aka BDD).  I've been applying BDD for a couple of years now, and have adopted StoryQ as my framework of choice when developing DotNet applications. Even though I have been unit testing for many years, and had previously shifted to a test-first approach, I've found that I get much more value out of using a BDD framework, because my tests capture the intent of the requirements in relatively clear English within my code, and because my tests can execute multiple assertions without ending the test halfway through - meaning I can see which specific assertions pass/fail at a glance without debugging to prove it.

This has really been the tip of the iceberg for me, as I've also noticed that I am able to debug both test and implementation code in a more targeted manner, with the result that my productivity has grown significantly, and that I can more easily determine where a failure occurs if a problem happens to make it all the way to the integration build due to the output that makes its way into the build logs. Further, the StoryQ api has a lovely fluent syntax that is easy to learn and which can be applied in an extraordinary number of ways, requiring no external dependencies in order to use it.

So with all of these benefits, you would think it an easy to introduce the concept to the rest of the team.  Unfortunately, the other team members are reluctant to even look at StoryQ to evaluate it properly (let alone entertain the idea of applying BDD), and have convinced each other to try and remove a number of StoryQ elements from our own core testing framework, even though they originally supported the use of StoryQ, and even though the code they wish to remove doesn't impact on any other part of our testing system. Doing so would end up increasing my workload significantly overall and really goes against the grain, as I am convinced through practical experience that it is a better way to work in a test-first manner in our particular working environment, and can only lead to greater improvements in the quality of our software, given I've found it easier to stick with test first using BDD. To further clarify, the majority of the unit tests we have tend to be quite brittle and difficult to maintain, a holdover from years of poorly applied testing where a reluctance to stick with a test-driven process has seen developers fall back on old habits and do all of their testing at the end of the project (these same people claim to be Agile!).

So the question really comes down to the following:

What arguments can I use to really drive the point home that it would be better for this team to use StoryQ, or at the very least to adopt the BDD methodology?

Can you point me to any anecdotal evidence that I can use to support my argument to adopt BDD as our standard method of choice?

What counter arguments can you think of that could suggest that my wish to encourage the team to adopt BDD might be in error?  Yes, I'm happy to be proven wrong provided the argument is a sound one.

NOTE: I am not advocating that we rewrite our tests in their entirety, but rather to simply start working in a different manner for all future testing work, and preferably in the manner in which we engage our customers.

And for those of you wishing to learn more about BDD, the following links may be useful:

http://dannorth.net/introducing-bdd/

http://en.wikipedia.org/wiki/Behaviour_driven_development

http://behaviour-driven.org/Introduction

For those interested in more details, we're a small team of 4 working on about 5 large projects. The "pilot trial" for BDD ran for about 2 months initially, with another approximately 4 month period following. Team accepted that I should continue to work this way and were to do their own trials. I've been BDD-ing for about 2 years now since the trial ended, while the others have become very good at ducking the issue. Rather than forcing a "confrontation" over the issue, I'm looking for ways to gently persuade the team to get off their collective behinds and make the time to do their bit.

答:
In a team reluctant to adopt BDD, there likely are no "arguments" that you can use to "convert" your colleagues into full-scale adoption.

I think the best you can do is to convince them to give it a try ("smoke test", "dry run", "pilot project") - especially if you make it perfectly clear that you'll drop the idea if testing results are negative.

Your approach for finding anecdotal evidence fits perfectly to the idea of convincing team to give it a try. For that, I'd simply search the web for something like "Behavior Driven Development success story" and pick what feels easier to use to me.

There are couple counter arguments I can think of that could suggest that your wish to convert the team efforts to BDD might be in error.

None of these are particularly constructive, especially from the point of view of a "change advocate" but unfortunately you'll likely have to deal with exactly this kind rhetoric (BTDTGTTS):

you can't guarantee that overall team productivity will improve

you can't guarantee that efforts invested into adopting BDD will give substantial ROI

team was doing sufficiently well without BDD, risk of changing current approach is not justified

Google (or Microsoft, or IBM - just fill in the name of whatever "respectable" software vendor) are going just fine without BDD, which "proves" that BDD is not necessary

non-BDD approaches weren't given a fair chance in comparative testing

BDD might be generally OK but for this and that module / project it is not applicable

Per my experience, least painful way to address counter arguments like listed above was by performing a limited controlled test run for a proposed change.

"Limited testing" status essentially invalidates three of four arguments above, except for one about "respectable vendor", which could be countered by providing anecdotal evidence of success story (anecdotal evidence won't probably work for a "big bang change" but for limited testing it is good enough).

If the change is indeed worthwhile and test run is arranged properly, you will notice a positive shift in team and management attitude, making transition to full-scale change smooth and painless.

Another benefit of limited test run is that it lets you clarify and adjust target process detail without causing too much trouble and with lower risk of "reputation damage" to the idea. Every time I participated in such test runs, I was pleasantly surprised to find out how smooth it was to switch to full-scale adoption having most important details set and clarified in test run.


答:
Having your own project gives you the drive to learn and keep at it when things get rough. In fact, it gives you as much or more drive to learn than taking a class because (by definition) the goal interests you.

This drive will push you to do all the things ManuPK put in his answer and you'll like it because it'll allow you to get closer to finishing your project.

Title: Which way is practical for improving your skills with pet project?

Body:
About your own project, in which way does it give you more improvement?

Read high quality code in the same domain, implement your own.

Write one project from scratch with your imagination.

My point is that it is not practical to write something like networking lib or graphic engine without knowing what other people did in the same domain.


问:
Secure Open Source?
I want to make a delicate application of mine (an antivirus actually) open source but I want to have a control on who really obtains the source or not. Preferably they should apply and I or administrators approve their applications. Is there any online platform for this?

The main reason for the control/security is to possibly prevent malware makers to easily discover how to bypass the stealth checking methods it utilizes for malware detection.

Edit: I am looking for advice - possibly to hear from someone who has done something similar.

Thanks!

答:
You can't really make sure the bad guys won't get to the source code once you release it to anybody.

The bad guys don't really need the source code. They are quite used to finding vulnerabilities by disassembling and experiments.

Many people trust open source (real one, where the source is free to download off the web somewhere) more, because that way they know that:

It does not rely on security by obscurity (with closed-source you never know).

If it's broken and the original author does not fix it, somebody else can step up to do it.

Title: Secure Open Source?


答:
Static analysis is when an artifact is analyzed without being executed. Although it can be applied to any artifact, it is often applied to source code or object code and refers to the use of specific tools to analyze and gain information about these work products. These tools produce reports that are interpreted by an engineer for use in determining the quality of the system under construction, and as a guide to planning development and maintenance. Wikipedia has a list of tools for static analysis, organized by language and with a brief description of their capabilities.

Reviews are a human evaluation of some work product, which could be code. Reviews can also be conducted on designs or other documents as well. The idea is that people familiar with the work product other than the developer are looking at it in order to find mistakes, ranging from security problems to violations of the coding standard.

Technically, a code review can be considered a form of static analysis, since the code is not actually executed during the review. However, in common terminology, "static analysis" typically refers to machine parsing of source or object files while "review" indicates that humans are the one doing the analysis.


答:
Code review is more qualitative assessment, static code analysis is more quantitative assessment.

Hey, boy, this method can be written better

vs, f.e

Decreased performance. It is inefficient to identify an empty string
  by using 'wcslen(str) > 0' construct. A more efficient way is to
  check: str[0] != '\0'.

Decreased performance. The expression of strlen(MyStr.c_str()) kind
  can be rewritten as MyStr.length()

Decreased performance. In case 'Order' is iterator it's more effective
  to use prefix form of increment. Replace iterator++ with ++iterator.

While real errors can (obviously) exist and be detected by SCA

Incorrect format. Consider checking the N actual argument of the 'Foo'
  function

The expression was enclosed by parentheses twice: ((expression)). One
  pair of parentheses is unnecessary or misprint is present

A call of the 'memset' function will lead to underflow of the buffer
  'dest.lfFaceName'


问:
Does SRP with ORM provoke SOA?
Sorry about the many abbreviations in the title... My observation is that applications built with an object-relational mapping like Hibernate tend to follow a service-oriented architecture instead of an object-oriented one.

Some people (e.g. here) say the Single Responsibility Principle suggests that dealing with reading/writing attributes of persisted objects as well as creating and finding these objects is enough responsibility for one class. Any business logic using such an object should go to separate classes. That leads us to a design with two separate types of classes: state-full but dumb record keeping ones, and logic bearing but state-less ones.

Here's why I don't like this kind of design:

(1) To me, this separation of data and code is not a goal of object-oriented but is the design of service-oriented architecture. OOD says that operations should go to the classes where the attributes it uses are defined at.

(2) Also, it's a bogus solution: whenever the structure of one of the state-full classes changes, I'll have to change all the service classes that use it, too. If I had the logic inside those classes, the change would stay in one class.

(3) I'm using an ORM framework which pretty much generates all the code necessary for accessing the persisted data for me into a class. If I wasn't adding the business logic to it, the class would stay rather "empty", i.e. it would contain the generated code only.

I know that many programmers follow the service-oriented design, especially when using frameworks that suggest this, like Spring. If I were using such a framework, I'd go with the separation of code and data, too.

I don't want to provoke a discussion whether SOA is good or not. I'm interested in the question whether it's good OOD (as per SRP) to separate business logic from classes representing entities.

答:
TL;DR:

There is no silver bullet™

Long version:

The background regarding SOA and ORMs seems relatively unnecessary, so I'll just focus on Is it good object-oriented design to separate business logic from classes representing entities?

I'll just try to reason about a architectural situation where I personally found it useful to have 'thin' entity classes.

Situation:

In a program I am currently, privately building I am designing an NHibernate modeler; you make a visual diagram with boxes and lines and stuff and in the end it is translated into some form of output recognizable by NHibernate.

Core system:

Model elements such as mapped values, has-many, has-one, many-to-many etc.

Output these into POCO classes, NHibernate xmlfiles and/or Fluent NHibernate mapping classes.

So, what should go into for example ManyToManyRelation (i.e symmetrical relationship with another entity)?

I think it is obviously not feasible to put both display logic, output logic for POCO, output logic for Fluent and output logic for XML in ManyToManyRelation.

Display data for an element (i.e render it on the screen at x,y etc) is orthogonal to the relational data. It must be persistent, but not in the same files as the relational data. This makes it natural for me to create some form of external 'attribute' classes which maps to the elements, that is persistable but entirely separate. So display data and logic does not go into entity classes.

We have three different output formats, at least. Since we are likely only interested in one type of output (XML vs Fluent) at one time, it makes a lot of sense to separate this out to separate 'service' classes with some form of common interface.

Furthermore, if we represent the model as some form of graph and consider ManyToManyRelation, we realize that it is symmetrical regarding the entity classes - it belongs just as much to Entity A as Entity B. One way to model this is that both Entity A and Entity B 'contains' the ManyToManyRelation. But then, which of them actually draws and outputs these 'shared-ownership' objects? By delegating out to a third 'service' class this becomes a non-issue. So output logic does not go in the entity classes

I realize much of these issues can be solved in other ways - that's not the focus of my reasoning. I think it is entirely reasonable to have thin 'data' classes and then build an application that acts on this data. It is also entirely reasonable to put at least some core logic in these classes. It all depends on the domain.

If you have read this far, congratulations, thank you and have a cookie :)

Title: Does SRP with ORM provoke SOA?


问:
What's the difference between computer science and programming?
I'm new at computer science and programming, and I was wondering, is there a difference between computer science and programming? and do you get to choose to study only one of them at the university, or both of them?</p>

答: A degree in computer science is a lot broader in scope and covers the theory behind computing. A degree in computer programming, on the other hand, is focused on developing the coding or programming skills of students by training them in different programming languages. If you’re confused, you can browse through the details of both these programs at California College San Diego. That may provide you some clarity regarding the scope of these degrees!</p>


答:
Is it a good design to have save and load methods on a data class? Yeah, I don't see why not. Is it a good design for the data object to know HOW to persist itself? No, I don't think so.

I always like Robert Martin's definition of the SRP:

There should never be more than one reason for a class to change.

This is much clearer than talking in terms of responsibility, which really doesn't mean anything in programming terms.

So, if we change the properties of a class, we should go to that class to change it. Thus there should be no other reasons to change that class. If we decide that XML files just aren't cutting it any more and we need to move to a database, we should go to another class. If we change the validation rules for an object, we should go to another class.

Does that mean we cannot have a save or validate method on a class, passing the request on to a repository or validator class? Not at all.

One of Martin Fowler's famous Bad Smells in Code (see Refactoring, 1999) is "Data Class". He suggests that, where there is an excess of getters and setters on a class, we should endeavour to move the methods that call these getters and setters into the class itself - the intent being to eventually remove access to the data and only allow operations on an object.

But that does not mean that Fowler believes the single-responsibility principle to be worthless. It just means that there are sensible lines to be drawn.

In the same way that we have said "There should never be more than one reason for a class to change," we should also avoid having a spaghetti of code where a single change requires changes to many, many classes.

In our earlier example of persistence, we could argue that when I add a property to the class, I also have to change the way it is persisted. In that case, many years of combined experience tells us that this is fair enough. It is basically two changes (how it is perceived by the application and how it is persisted) so changing two classes is about right.

But it's all pretty subjective. We have to consider every case on its own merits.

ORMs really have little to do with this, except that they do reduce the boilerplate code in between data and storage -- this should suggest to us that we were right to choose this as the line.

Title: Does SRP with ORM provoke SOA?

Body:
Sorry about the many abbreviations in the title... My observation is that applications built with an object-relational mapping like Hibernate tend to follow a service-oriented architecture instead of an object-oriented one.

Some people (e.g. here) say the Single Responsibility Principle suggests that dealing with reading/writing attributes of persisted objects as well as creating and finding these objects is enough responsibility for one class. Any business logic using such an object should go to separate classes. That leads us to a design with two separate types of classes: state-full but dumb record keeping ones, and logic bearing but state-less ones.

Here's why I don't like this kind of design:

(1) To me, this separation of data and code is not a goal of object-oriented but is the design of service-oriented architecture. OOD says that operations should go to the classes where the attributes it uses are defined at.

(2) Also, it's a bogus solution: whenever the structure of one of the state-full classes changes, I'll have to change all the service classes that use it, too. If I had the logic inside those classes, the change would stay in one class.

(3) I'm using an ORM framework which pretty much generates all the code necessary for accessing the persisted data for me into a class. If I wasn't adding the business logic to it, the class would stay rather "empty", i.e. it would contain the generated code only.

I know that many programmers follow the service-oriented design, especially when using frameworks that suggest this, like Spring. If I were using such a framework, I'd go with the separation of code and data, too.

I don't want to provoke a discussion whether SOA is good or not. I'm interested in the question whether it's good OOD (as per SRP) to separate business logic from classes representing entities.


问:
Resources for creating a turn-by-turn navigation system
I'm trying to create a kind of turn-by-turn satellite navigation system using the iOS SDK. I get the directions from the server and draw them on the map, then I keep getting location updates from the iPhone's GPS chip. Currently I start by finding the nearest turning point then, each time the user comes within a certain distance of the next turning point, a verbal cue is given and the turning point index is incremented. This is a delicate system and I'd like to make it more robust so I can tell when the user is going the wrong direction etc.

Basically I'm looking for some literature about turn-by-turn navigation, in terms of tracking the user's progress and whether they're going the right direction. I'd have thought there's a lot of research out there but I can't seem to find anything apart from simple tutorials on how to use a given SDK or directions API. Can anyone direct me to a good run-through of the various techniques used in software such as TomTom or Google Maps Navigation?

答:
I don't think there is any such thing. There is just handful of turn-by-turn navigations out there, so each team just found out on their own and didn't publish anything, because after all, it was commercial product, not a research. There is however at least one open-source turn-by-turn navigation, navit, so you can get some inspiration there.

Also don't think that it's easy. It's probably several man-months effort even if you know what you are doing. The thing is incredibly tricky, because the GPS signal you get has random error, which can easily be 50 meters on crappy phone GPS in bad conditions (the error usually does not vary much between successive positions, so you can rely actually trust direction a bit more than position, but only if moving fast).

So you need vector data for the segments around current position, guess which of them the user is actually most likely to be on and if it's not on the route, request new route from that segment. And when selecting the likely segment, you have to take into account whether it's on route and whether it's connected to the one he's been on before and be ready to ignore a few positions if they seem too wrong and do a LOT of testing to get various fudge factors just about right.

You also need to take into account things like loosing signal in a tunnel (should somehow continue to the end of it and than wait for reacquiring the signal) and under bridges (few completely bogus positions).

(I am working on navigation system, so while not working on that bit myself, I know roughly what's there).


问:
Is there any algorithm book that teaches like Head First series?
As a Java programmer I need to learn algorithms (for programming Challenges). I read some Head First Series (JAVA owned by me) and they are pretty brain friendly. So I was wondering is there any algorithm book that will be simple to understand and also goes to the crux of each algo.</p>

答: Personally I learned with Algorithm Design Manual by Steven S.Skiena, and currently use Algorithms In a Nutshell to as a quick reference for algorithms I don't implement to much. Algorithms In a Nutshell uses both Java, Ruby, C, and C++ for its code examples but being a Java coder you shouldn't have too much trouble reading the C/C++ code snippets. And even if you couldn't read them, they aren't essential for understanding the algorithm, a full description is available purely based on text and pictures.</p>


问:
How to work on my personal ideas during the weekend?
I'm working full time 5 days a week, mostly between 10 and 14 hours a day.
In the end of the day I'm very tired and just wanna take a shower, hang out and go to sleep.

I have a lot of ideas that I want to implement and someday sell maybe through an online software business.

I have my weekends free. However, when I get to the weekend I can't even imagine myself turn on the computer.

But I really want to make my ideas happen, and I can't leave my job right now to devote myself only to my ideas.

What do you say? Do you find some method helpful? Do you use some technique?

Thanks

答:
I think it comes down to "Just do it". Nike has it right. If you are passionate about those side projects you just dredge through it. I know I have a hard time as well. I'm in a similar situation as you. I have several side projects that I'd love to work on but after a week of programming it's tough.

What I do is reserve several hours on Sunday for the given project. I will dedicate myself to that for 2 weeks. If on the 3rd week I don't feel inspired I take it off. After that off week I'm back to my dedication of 2 consecutive Sundays.

It's hard to think about it in such a way but you have to almost consider it a job. You "HAVE" to do it or you will get fired...never complete it anyway...


答:
I would suggest the following from my own experience:

Read high quality code across all domains. It's the style and motivations behind the code design that is important.

Work on the project over a long period of time (like years). As your skill at coding improves, you will see the old problems in a new light. This makes your learning tangible. You remember how you used to think and notice how you think with your new information and your new understanding.

Rewrite the project from scratch every 6 months or year. It sounds like a lot of work but it is very fast and very rewarding because you can see how much progress you have made.

Get some great books and work through one every 3 months or so. My favorites are Clean Code and Pro C#. You can find awesome books by looking at Amazon reviews, Programmers SE or Stack Overflow.

Learning is a skill, and a critical one for programmers. Get good at it and find ways of learning that work for you.

For more practice (if you get bored of your project), got to Project Euler and solve problems.


答:
In my case I try to keep up with my ideas by having them in a server, that I try to update fairly regular.

In the past I used the wikipedia But I had the problem of how to trace back what I'm doing with the code, then after trying collabtive and some others I end up with redmine (so far so good, I can track the code and targets)

The only "problem" is that you may have to sacrifice your lunchtime/cofeetime/whatevernotcomputertime you have left to access to your own server and keep up with the latest ideas you had. Also have a computer close to you, and if no computer, then a blocknote.

Good luck, and don't burn out!

Title: How to work on my personal ideas during the weekend?

Body:
I'm working full time 5 days a week, mostly between 10 and 14 hours a day.
In the end of the day I'm very tired and just wanna take a shower, hang out and go to sleep.

I have a lot of ideas that I want to implement and someday sell maybe through an online software business.

I have my weekends free. However, when I get to the weekend I can't even imagine myself turn on the computer.

But I really want to make my ideas happen, and I can't leave my job right now to devote myself only to my ideas.

What do you say? Do you find some method helpful? Do you use some technique?

Thanks


问:
Why are statements in many programming languages terminated by semicolons?
Is there a reason that a semi-colon was chosen as a line terminator instead of a different symbol?

I want to know the history behind this decision, and hope the answers will lead to insights that may influence future decisions.

答:
Rather than trying to answer your headline question, I think it's better to focus on your implicit question:

I want to know the history behind this decision, and hope the answers will lead to insights that may influence future decisions in the design and implementation of programming languages.

If you want to learn about programming language design and implementation history, and gain more insight into the process, then the proceedings of the History of Programming Languages Conferences are a very good place to start. (I think you will need an ACM membership to be able to access the proceedings though.)

Why are statements in many programming languages terminated by semicolons?
  Is there a reason that a semi-colon was chosen as a line terminator instead of a different symbol?

Taking your headline question as an example question that you might want to try to answer by reading the HOPL proceedings, I'd like to offer the following point: people designing a new programming language usually do so because they consider the ones they know to be broken / deficient somehow. Their new language is, on one hand, designed to fix this deficiency. On the other hand, language designers will also copy design elements from other languages that they think are good, or they simply don't change those elements that they didn't experience a problem with.

Especially that last part is important: instead of trying to find out which programming language ever was the first one to use semicolons as terminators and why a lot of other programming languages copied that, you will probably learn more by looking at languages that did not copy it. For example, while Smalltalk took a lot of inspiration from Simula, it did not copy its syntax and in particular its use of semicolons as statement terminators. It changed terminators (separators really) to a full stop, and uses the semicolon for something else. Conversely, the first language that ever used a semicolon as a statement terminator may have had a reason to change this from what was used in languages that came before it. It's also possible that it was the first language to introduce the whole concept of a statement terminator (or did so independently of other languages) and that the semicolon was used for some reason that is now lost to time. (I suspect the latter is the case here, as none of the other answerers have been able to dig up a quote from the person who introduced the semicolon rather than offer retrofitted suppositions about why the semicolon was a good choice.) But to restate my point, I think you will learn more by looking at why language designers changed things rather than why they copied/kept them. When people change things they usually want or have to explain the change, while they don't do so when copying or keeping things the same because “why would we change it? that's just the way it's done!”


问:
if/else statements or exceptions
I don't know whether this question fits better on this site or on Stack Overflow, but because my question is connected rather to practices, that some specified problem.

So, consider an object that does something. And this something can (but should not!) can go wrong. So, this situation can be resolved in two ways:

first, with exceptions:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
try
{
     exampleObject.DoSomething();
}
catch (ThisCanGoWrongException ex)
{
     [...]
}
</code>```

And second, with if statement:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
if(!exampleObject.DoSomething())
{
     [...]
}
</code>```

Second case in more sophisticated way:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
ErrorHandler error = exampleObject.DoSomething();
if (error.HasError)
{
     if(error.ErrorType == ErrorType.DivideByPotato)
     {
         [...]
     }
}
</code>```

Which way is better? On one hand, I heard that exceptions should be used only for real unexpected situations, and if the programmer knows that something may happen, they should use if/else. On the other hand, Robert C. Martin in his book Clean Code wrote: "exceptions are far more object oriented, and more simple to keep clean."

答:
Typically, I tend to use exceptions for exceptional cases - the instance where nothing should go wrong, and if it does go wrong, that's a big problem. An example might be a missing configuration file that ships with the software or a missing hardware driver. If these things happen, that's a huge problem. I will perform checks on things like user input or optional instances where there's a good chance that I'll be given invalid information.

However, it should also be noted that some languages appear to favor exceptions. For example, I've noticed that the use of exceptions for even minor problems is much more common in Python. In the Python community, this is known as EAFP - "Easier to ask forgiveness than permission".

Title: if/else statements or exceptions


答:
If you NEED your job like most people do, then the only other option is working outside those hours.

First off, why is your job consistently making you work 10-14 hour days. That is not normal.

Fix that, either by limiting those hours, or finding a new job (not necessarily easy of course in the current economic climate) and you suddenly have whole lot of time to play with.


答:
If exampleObject.DoSomething(); SHOULD NEVER cause a problem, use exceptions.

If there are valid, expected business cases where exampleObject.DoSomething() will cause an error, use if/then/else and use comments to describe cases when this might cause a problem.

Example:

```<code>Thing thing = findThingInDatabase();

//if a thing was found in the database (we EXPECT thing to not be found sometimes, hence if stmt as opposed to exception)
if (thing != null){
    thing.doStuff();
}
</code>```

Title: if/else statements or exceptions

Body:
I don't know whether this question fits better on this site or on Stack Overflow, but because my question is connected rather to practices, that some specified problem.

So, consider an object that does something. And this something can (but should not!) can go wrong. So, this situation can be resolved in two ways:

first, with exceptions:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
try
{
     exampleObject.DoSomething();
}
catch (ThisCanGoWrongException ex)
{
     [...]
}
</code>```

And second, with if statement:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
if(!exampleObject.DoSomething())
{
     [...]
}
</code>```

Second case in more sophisticated way:

```<code>DoSomethingClass exampleObject = new DoSomethingClass();
ErrorHandler error = exampleObject.DoSomething();
if (error.HasError)
{
     if(error.ErrorType == ErrorType.DivideByPotato)
     {
         [...]
     }
}
</code>```

Which way is better? On one hand, I heard that exceptions should be used only for real unexpected situations, and if the programmer knows that something may happen, they should use if/else. On the other hand, Robert C. Martin in his book Clean Code wrote: "exceptions are far more object oriented, and more simple to keep clean."

Body:
If exampleObject.DoSomething(); SHOULD NEVER cause a problem, use exceptions.

If there are valid, expected business cases where exampleObject.DoSomething() will cause an error, use if/then/else and use comments to describe cases when this might cause a problem.

Example:

Thing thing = findThingInDatabase();

//if a thing was found in the database (we EXPECT thing to not be found sometimes, hence if stmt as opposed to exception)
if (thing != null){
    thing.doStuff();
}


答:
Run it like your project manager does.

Scope and define your project

Document your requirements

break it into workable chunks

Set goals for when you will complete each.

Work to meet your goals adjusting as necessary.


答:
Take in account that in case of if/else you're going to perform that check every time, regardless if execution was successful or not. Thus if error case is occurring rarely or practically never under normal circumstances, then exception handling is way more efficient, as on successful execution you're not evaluating any additional conditions.

Another advantage of exceptions over checking in case of multithreading or distributed systems is avoiding race conditions resulting from TOCTTOU (time of check to time of use) problem. You check condition first, then execute code assuming that condition holds. Without assuring atomicity with locks/mutex or so, at time of executing code condition might already been changed by another thread/process.

Title: if/else statements or exceptions


答:
The usual way of error handling is this:

If you can solve the problem locally, then use the if statement (or if the function throw an exception, handle that exception).

If you can not solve the problem locally, then throw an exception (or if the function throw an exception, let it propagate further), and handle it where you know what to do about it.

Title: if/else statements or exceptions


问:
Best process for product development and maintenance by a small team?
I'm going to be managing projects for a very small (2-5) senior developer team.  They develop a subscription based web application.  It has been in use for many years so at this point the work involves:

Developing new features and updates to existing features

Developing in-house tools and reports

Fixing bugs

Investigating customer service issues

Production releases are sometimes determined by customer obligations, sometimes by competitive advantage, but for the most part are not time-critical.  I'd like to have regular production releases to keep the product fresh -- once every 2 months or so.

Since the team is so small, the developers themselves will have to be involved in designing, testing, deployment, and maintenance.

Since we do not have a dedicated maintenance team I see the major challenge being development and planning disrupted by bug fixing and customer service issues.  They can distract us during new feature development and disrupt the release schedule.

My initial thought is to do the following:

Hire a junior programmer to buffer the senior developers from maintenance tasks.  In between maintenance tasks this person can assist the senior devs.

Adopt a scrum style approach where we have a series of sprints leading up to a production release.  This will allow us to keep the stakeholders in the loop and allow us to reflect and improve our process with each sprint.

Shortly following the release, which is when most bugs surface, the team can focus on design for the next release with the expectation that each one will likely get pulled into bug fixing.

I'd love to hear your thoughts and lessons learned.

答:
Scrum is the perfect choice here

Forget the point 1. Let your cross functionnal team self manage itself.

Do point 2, but implement everything in Scrum, not just what you think is useful. Also don't try alone, hire a certified Scrum Practionner or a Certified Scrum Coach.

Forget the point 3. Hire a tester and put it in your Scrum team. Also using Scrum properly, that will help to reduce bugs in production.


问:
User input and automated input separation
I have a MySQL database and an automation script which modifies the data inside once a day. And these columns may have changed by an user manually. What is the best approach to make the system only update the automated data, not the manually edited ones? I mean yes, flagging the cell which is manually edited is one way to do it, but I want to know if there's another way to accomplish this? Just curiosity.

BTW, the question is about cell values, not rows.

答: I would put two DateTime columns in those tables, one called lastUserEdit and the other one called lastAutomatedEdit.  That way, you always know whether the last edit on each row was done by a user or automatically by simply comparing these two dates.


答:
Try to change only one variable at a time (ie: A new framework, a new ORM, a new work methodology).

As such you are proficient in one programming language, do as you would normaly do, but add a new element to it, like a framework. Next time, use the same framework, but add an other variable (like an ORM) and keep repeating.

Make sure to choose project that are not too wide, but not too small to make sure you can cover most use cases of your new element.

Treat every project as if it's a "pilot", this way you won't stay in your comfort zone and you will keep learning an improving.


问:
Why to keep wrapping closure in each js-file if it can be added after concatenating?
At the moment every javasrcipt file in our project includes closure wrapper. Before deploying all files are concatenated and minimized.

And i'm asking myself, do we really need all that closures OR one closure added after concatenation will do the job.

I can see only one reason not to do that - the variable we are sharing between files will get in the global namespace. But there is no conflict so is don't see any problem.

The real question is what other cons may be?
Or more generally what approach is better - one closure or many?

答:
Yes, you need all the closures so the files are separate from each other.

If you concatenate more then one file inside the same function then they will share variables, just as if they had been global. The only advantage at this point would be insulating your code from external 3rd party Javascript.

In any case, I would say that the best thing you can probably do is use a Javascript modularization tool like RequireJS so you can stop worrying about concatenating and generating the files yourself.


答:
But there is no conflict so is don't see any problem

thats a horrible understatement, wrap every single file in a closure so that the you can "file local" variables inside that file.

The fact that wrapping it in a closure adds 15 bytes is the only disadvantage, if you care about those 15 bytes then your micro optimizing.

Title: Why to keep wrapping closure in each js-file if it can be added after concatenating?

Body:
At the moment every javasrcipt file in our project includes closure wrapper. Before deploying all files are concatenated and minimized.

And i'm asking myself, do we really need all that closures OR one closure added after concatenation will do the job.

I can see only one reason not to do that - the variable we are sharing between files will get in the global namespace. But there is no conflict so is don't see any problem.

The real question is what other cons may be?
Or more generally what approach is better - one closure or many?


答:
Most important requirement for learning is to have a concrete project to work on. One year back I was too confused about how to improve and try to code a great code in my first major project.

What I learned after researching a lot is code and just code with an aim in mind.

Another thing is try to follow coding conventions which exists in your choice of language. For example, in python world pep8 conventions are followed and I did the same. Don't ever think that let me code first and then I will worry about conventions. Conventions are there for your benefits, use them.

Learning to code is easy but learning to write proper and maintainable code is a must.

After some time (if you are in learning stage not on sharp deadlines) go back and read your old code again and there is lot of chance you will cringe at it or may want to improve it.

No code is perfect. Always try to refactor after writing a working code.

Always unit test your code because unit test brings out your mistakes very soon not when you have written so much code that it pains you to find out that small mistake.


答:
Flagging as you have mentioned is what I'd do.
Just by updating the value in an ENUM column ('0','1') to let you know who last updated the record.

Title: User input and automated input separation

Body:
I have a MySQL database and an automation script which modifies the data inside once a day. And these columns may have changed by an user manually. What is the best approach to make the system only update the automated data, not the manually edited ones? I mean yes, flagging the cell which is manually edited is one way to do it, but I want to know if there's another way to accomplish this? Just curiosity.

BTW, the question is about cell values, not rows.


问:
Optimal Database design regarding functionality of letting user share posts by other users
I want to implement functionality which let user share posts by other users similar to what Facebook and Google+ share button and twitter retweet.

There are 2 choices:

1) I create duplicate copy of the post and have a column which keeps track of the original post id and makes clear this is a shared post.

2) I have a separate table shared post where I save the post id which is a foreign key to post id in post table.

Talking in terms of programming basically I keep pointer to the original post in a separate table and when need to get post posted by user and also shared ones I do a left join on post and shared post table

```<code>    Post(post_id(PK), post_content, posted_by)

    SharedPost(post_id(FK to Post.post_id), sharing_user, sharedfrom(in case someone shares from non owners profile))
</code>```

I am in favour of second choice but wanted to know the advice of experts out there?

One thing more posts on my webapp will be more on the lines of facebook size not tweet size.

答:
Your intuition is correct, definitely use option 2.  There is no reason to duplicate the entire post in the database each time someone shares it.  Just have a separate SharedPosts table which simply maps userIDs to other users' posts, like you say.

EDIT

The above answer assumes that a post cannot be changed after the original user shared it.  If it can be changed by the OP, then the users who shared it may not wish to share the updated version, so you can:

delete all shares of a post if the original post gets updated, OR

store each shared post as duplicates of the original, like you mentioned in your option 1

Mike's answer does a great job of explaining the benefits of storing duplicates.


问:
Ruby Shoes for non-trivial apps
I've been taking a look at Ruby Shoes for GUI development with Ruby. So far, it's been a pretty good experience for making simple apps. However, I am quite worried about being able to write large scale applications with it. For example, how would I go about using MVP pattern with this framework?

For now, I have not been able to not make presentation concerns leak into the view because of the lack of some kind of "data binding". I have code that looks like this :

```<code>Shoes.app do
    @view = SampleView.new
    @presenter = SamplePresenter.new @view

    @label = para @view.sample_property

    button "Update sample_property" do
        @presenter.update_sample_property
    end
end
</code>```

Here, the call to @presenter.update_sample_property updates @view.sample_property but the label is not updated accordingly.

For this to work, I would have to make @presenter.update_sample_property to return a string, and then call @label.text = return_value, but I think that would violate the MVP principle of not having presentation logic in the view.

I'm used to work in .Net with the MVP pattern so I don't know if the pattern applies correctly to Shoes like I tried to do.

Are there any resources out there for making non-trivial apps with Shoes? Especially using the MVP pattern or something similar?

EDIT : I took a look at the shoebox to see what other people have achieved with the framework. Though I did not look through it extensively, at first sight it seems like they are all simple projects with no real purposes.

UPDATE : I've finally been able to come up with something that satisfies me. Oh, and by the way, I moved to green_shoes because it is all written in ruby and I can run it from the command line rather than from the Shoes application. Packaging is not an issue for me quite yet.

答:
From the first page in the Shoes manual:

Shoes is a tiny graphics toolkit. It's simple and straightforward. Shoes was born to be easy! Really, it was made for absolute beginners. There's really nothing to it.

From this statement I would say that Shoes was not really designed with large-scale apps in mind.

You may be able to implement an MVP or MVC pattern with help from the ruby observerable library.

Title: Ruby Shoes for non-trivial apps


问:
C is written in C, how is this possible?

Possible Duplicate:

  How could the first C++ compiler be written in C++?

I know my question goes to the underground galaxy cave where languages are born and involves some lambda math and light-years of google-studying. But what kind of knowledge is necessary to create a language?

答:
Look up "bootstrapping".

Basically you start with a very minimal process/set of functions that can be used to compile the code that defines a slightly more functional compiler. This creates your next compiler which then can then be used to build code that can do even more. You repeat this process until you have a full blown compiler that can compile all the language features.

The other alternative is to write the first version of the compiler in a different language and then write the next version in your target language.


问:
What is the simplest human readable configuration file format?
Current configuration file is as follows:

```<code>mainwindow.title = 'test'
mainwindow.position.x = 100
mainwindow.position.y = 200

mainwindow.button.label = 'apply'
mainwindow.button.size.x = 100
mainwindow.button.size.y = 30

logger.datarate = 100
logger.enable = True
logger.filename = './test.log'
</code>```

This is read with python to a nested dictionary:

```<code>{
  'mainwindow':{
    'button':{
      'label': {'value':'apply'},
       ...
  },
  'logger':{
     datarate: {'value': 100},
     enable: {'value': True},
     filename: {'value': './test.log'}
  },
  ...
}
</code>```

Is there a better way of doing this? The idea is to get XML type of behavior and avoid XML as long as possible. The end user is assumed almost totally computer illiterate and basically uses notepad and copy-paste. Thus the python standard "header + variables" type is considered too difficult.

The dummy user edits the config file, able programmers handle the dictionaries. Nested dictionary is chosen for easy splitting (logger does not need or even cannot have/edit mainwindow parameters).

答:
You could use something like YAML.  Here is a link to an example:

http://www.yaml.org/start.html

```<code>--- !clarkevans.com/^invoice
invoice: 34843
date   : 2001-01-23
bill-to: &id001
    given  : Chris
    family : Dumars
    address:
        lines: |
            458 Walkman Dr.
            Suite #292
        city    : Royal Oak
        state   : MI
        postal  : 48046
ship-to: *id001
product:
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
    - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.52
comments: >
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338.
</code>```

You can find Python bindings for it at PyYAML.  It's a little more user friendly than JSON (which is what your second example looks like).

OwnerDisplayName: Juha

Body:
You could use something like YAML.  Here is a link to an example:

http://www.yaml.org/start.html

--- !clarkevans.com/^invoice
invoice: 34843
date   : 2001-01-23
bill-to: &id001
    given  : Chris
    family : Dumars
    address:
        lines: |
            458 Walkman Dr.
            Suite #292
        city    : Royal Oak
        state   : MI
        postal  : 48046
ship-to: *id001
product:
    - sku         : BL394D
      quantity    : 4
      description : Basketball
      price       : 450.00
    - sku         : BL4438H
      quantity    : 1
      description : Super Hoop
      price       : 2392.00
tax  : 251.42
total: 4443.52
comments: >
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338.

You can find Python bindings for it at PyYAML.  It's a little more user friendly than JSON (which is what your second example looks like).


问:
In order traversal of M way Trees
If we have a 4 way tree such as the one shown below, and we do an in order traversal, what would the output of the in-order traversal be for an M-way tree?

In which order would the nodes be visited? When would the value in the node be processed (upon first visit or upon second visit)?

(As a concrete example, what would the step by step procedure for the in order traversal be for the example tree shown below?)

答:
I believe the in order traversal of m-way trees can be generalized. Lets take the example of the tree you have provided. Following are the steps for that :

Go to the left most node first and print its first element. Then check if there is any subtree between this element and the next element in that node. If it exists then apply the same approach on that sub-tree, else print element. Similarly move through all the elements in that node.
Since in your tree there is no sub-tree in your left most node so print all the elements. Thus the output of first step will be  : 2, 5, 6.

Then apply same algo in the parent node and move up towards your root node recursively.

Thus the output of the in-order traversal of your tree should be :

2,5,6, 7, 9,12,17, 20, 26,31,39, 45, 46,53,71

You can refer to this ppt for more info :
In order Traversal of M-Way Trees

Title: In order traversal of M way Trees


答: Bootstrapping is definitely the standard way to build a compiler today. But remember that you don't need a compiler or interpreter to write a program in a language. For instance, Christopher Strachey wrote a famous AI program that was able to play Checkers in CPL before there was a compiler for CPL. He had to translate the program to machine code "manually", which is tedious and error-prone, but not really difficult (that's why computers can do it so well).</p>

Title: C is written in C, how is this possible?

Body:
Possible Duplicate:

  How could the first C++ compiler be written in C++?

I know my question goes to the underground galaxy cave where languages are born and involves some lambda math and light-years of google-studying. But what kind of knowledge is necessary to create a language?


问:
What arguments can I use to "sell" the BDD concept to a team reluctant to adopt it?
I am a bit of a vocal proponent of the Behaviour Driven Development methodology (aka BDD).  I've been applying BDD for a couple of years now, and have adopted StoryQ as my framework of choice when developing DotNet applications. Even though I have been unit testing for many years, and had previously shifted to a test-first approach, I've found that I get much more value out of using a BDD framework, because my tests capture the intent of the requirements in relatively clear English within my code, and because my tests can execute multiple assertions without ending the test halfway through - meaning I can see which specific assertions pass/fail at a glance without debugging to prove it.

This has really been the tip of the iceberg for me, as I've also noticed that I am able to debug both test and implementation code in a more targeted manner, with the result that my productivity has grown significantly, and that I can more easily determine where a failure occurs if a problem happens to make it all the way to the integration build due to the output that makes its way into the build logs. Further, the StoryQ api has a lovely fluent syntax that is easy to learn and which can be applied in an extraordinary number of ways, requiring no external dependencies in order to use it.

So with all of these benefits, you would think it an easy to introduce the concept to the rest of the team.  Unfortunately, the other team members are reluctant to even look at StoryQ to evaluate it properly (let alone entertain the idea of applying BDD), and have convinced each other to try and remove a number of StoryQ elements from our own core testing framework, even though they originally supported the use of StoryQ, and even though the code they wish to remove doesn't impact on any other part of our testing system. Doing so would end up increasing my workload significantly overall and really goes against the grain, as I am convinced through practical experience that it is a better way to work in a test-first manner in our particular working environment, and can only lead to greater improvements in the quality of our software, given I've found it easier to stick with test first using BDD. To further clarify, the majority of the unit tests we have tend to be quite brittle and difficult to maintain, a holdover from years of poorly applied testing where a reluctance to stick with a test-driven process has seen developers fall back on old habits and do all of their testing at the end of the project (these same people claim to be Agile!).

So the question really comes down to the following:

What arguments can I use to really drive the point home that it would be better for this team to use StoryQ, or at the very least to adopt the BDD methodology?

Can you point me to any anecdotal evidence that I can use to support my argument to adopt BDD as our standard method of choice?

What counter arguments can you think of that could suggest that my wish to encourage the team to adopt BDD might be in error?  Yes, I'm happy to be proven wrong provided the argument is a sound one.

NOTE: I am not advocating that we rewrite our tests in their entirety, but rather to simply start working in a different manner for all future testing work, and preferably in the manner in which we engage our customers.

And for those of you wishing to learn more about BDD, the following links may be useful:

http://dannorth.net/introducing-bdd/

http://en.wikipedia.org/wiki/Behaviour_driven_development

http://behaviour-driven.org/Introduction

For those interested in more details, we're a small team of 4 working on about 5 large projects. The "pilot trial" for BDD ran for about 2 months initially, with another approximately 4 month period following. Team accepted that I should continue to work this way and were to do their own trials. I've been BDD-ing for about 2 years now since the trial ended, while the others have become very good at ducking the issue. Rather than forcing a "confrontation" over the issue, I'm looking for ways to gently persuade the team to get off their collective behinds and make the time to do their bit.

答:
What arguments can I use to really drive the point home that it would
  be better to use StoryQ, or at the very least apply the BDD
  methodology?

"The customer wants it."

IMO you want to sell BDD to your customers/domain experts at least as much as to the development team.

BDD is a collaborative outside-in process where multiple stakeholders are involved. Benefits of BDD are not just for developers to automatically infer their test code from acceptance tests, they also lie in the creative cooperation that takes place between technical and business people to produce valuable, well-defined specifications of the system's intended behavior.

Giving customers/business analysts access to an interface where they can run each executable specification, control their status and see the progression in their implementation is generally much appreciated as well.

There's a presentation by Dan North on how you can sell BDD to the business :
http://skillsmatter.com/podcast/java-jee/how-to-sell-bdd-to-the-business


问:
Should main method be only consists of object creations and method calls?
A friend of mine told me that, the best practice is class containing main method should be named Main and only contains main method. Also main method should only parse inputs, create other objects and call other methods. The Main class and main method shouldn't do anything else. Basically what he is saying that class containing main method should be like:

```<code>public class Main
{
    public static void main(String[] args)
    {
        //parse inputs
        //create other objects
        //call methods
    }
}
</code>```

Is it the best practice?

答:
In languages that support functions main is just a regular function and so there's nothing else you can do with it other than what you said. And then there are <s>idiotic</s> languages that ditch functions in favor of having everything be an object, which means every time you want a function you have to wrap it in an unnecessary class.

Well, enough rambling. The point I'm trying to make is that Main is not really a class, but a function and so you shouldn't have do anything but parse inputs, create other objects and call other methods because that's all a function can do.


答:
I hope this is not out of topic, but I wanted to point out that, once you have one C compiler for one platform X, bootstrapping for other platforms can be done by using cross-compilation:

You have a C compiler c1 for architecture X that runs on architecture X.

You write a C compiler c2 for architecture Y, written in C.

You compile the compiler c2 on X using c1 and obtain the binary for compiler c2 that runs on X.

You use the binary for c2 that runs on X to compile itself and obtain a binary of c2 that will run on Y.

In other words, when you have the first egg, it is easy to make more eggs.


问:
Better word for Optional Requirements?
What's a better word for an optional requirement in software engineering? The phrase is contradictory. I've used "Non-Core Requirements" in previous projects.</p>

答: If your requirements are prioritized, you might consider them to be low priority requirements.

Title: Better word for Optional Requirements?


答:
The point your friend is making is that an application should merely be bootstrapped by the main method, and nothing more. By having the main method in its own class, you are simply reinforcing that fact by keeping it independent of any application logic. The role of the main method would be to parse any inputs and to initialize the application with those, and possibly other, inputs.

```<code>public static void main(String[] args){
    new Foo().start(args[0]);
}
</code>```

The idea is that you don't need the main method in order to initialize Foo. This allows you to easily initialize and start Foo in another context, potentially with different semantics.

```<code>public Foo initSomewhereElse(String arg){
    Foo f = new Foo();
    f.start(arg);
    return f;
}
</code>```

Title: Should main method be only consists of object creations and method calls?

Body:
A friend of mine told me that, the best practice is class containing main method should be named Main and only contains main method. Also main method should only parse inputs, create other objects and call other methods. The Main class and main method shouldn't do anything else. Basically what he is saying that class containing main method should be like:

```<code>public class Main
{
    public static void main(String[] args)
    {
        //parse inputs
        //create other objects
        //call methods
    }
}
</code>```

Is it the best practice?

Body:
The point your friend is making is that an application should merely be bootstrapped by the main method, and nothing more. By having the main method in its own class, you are simply reinforcing that fact by keeping it independent of any application logic. The role of the main method would be to parse any inputs and to initialize the application with those, and possibly other, inputs.

public static void main(String[] args){
    new Foo().start(args[0]);
}

The idea is that you don't need the main method in order to initialize Foo. This allows you to easily initialize and start Foo in another context, potentially with different semantics.

public Foo initSomewhereElse(String arg){
    Foo f = new Foo();
    f.start(arg);
    return f;
}


答:
ChrisF's answer is excellent, but I wanted to add this example that always stuck by me after my computer science course on bootstrapping.

Suppose you have a basic C compiler that does not support escape codes for strings yet, and you wanted to add that. You could add a snippet of code similar to this:

```<code>if( str[i] == 0x5c ) {       // ASCII code for backslash
   switch( str[i+1] ) {
      case 'n': return 0x0a; // ASCII code for new line
      case 't': return 0x09; // ASCII code for tab
      // ...                 // more ASCII code for other escapes
      default: return str[i+1];
   }
}
</code>```

After you have added this to the compiler, and generated a new compiler binary, you could then rewrite this into:

```<code>if( str[i] == '\\' ) {
   switch( str[i+1] ) {
      case 'n': return '\n';
      case 't': return '\t';
      // ...
      default: return str[i+1];
   }
}
</code>```

That would remove any knowledge about ASCII codes from the compiler source code, but the compiler would still magically generate the correct codes.

Body:
ChrisF's answer is excellent, but I wanted to add this example that always stuck by me after my computer science course on bootstrapping.

Suppose you have a basic C compiler that does not support escape codes for strings yet, and you wanted to add that. You could add a snippet of code similar to this:

if( str[i] == 0x5c ) {       // ASCII code for backslash
   switch( str[i+1] ) {
      case 'n': return 0x0a; // ASCII code for new line
      case 't': return 0x09; // ASCII code for tab
      // ...                 // more ASCII code for other escapes
      default: return str[i+1];
   }
}

After you have added this to the compiler, and generated a new compiler binary, you could then rewrite this into:

if( str[i] == '\\' ) {
   switch( str[i+1] ) {
      case 'n': return '\n';
      case 't': return '\t';
      // ...
      default: return str[i+1];
   }
}

That would remove any knowledge about ASCII codes from the compiler source code, but the compiler would still magically generate the correct codes.


问:
Importing an existing project into Git

Background

During the course of developing our site (ASP.NET), we discovered that our existing source control (SourceGear Vault) wasn't working for us. So, we decided to migrate to Git. The translation has been less than smooth though.

Our site is broken up into three environments DEV, QA, and PROD. For tho most part, DEV and the source control repo have been in sync with each other. There is one branch in the repo, if a page was going to be moved up to QA then the file was moved manually, same thing with stuff that was ready for PROD. So, our current QA and PROD environments do not correspond to any particular commit in the master branch.

Clarification: The QA and PROD branches are not currently, nor have they ever been in source control.

The Question

How do I move QA and PROD into Git? Should I forget about the history we've maintained up to this point and start over with a new repo? I could start with everything on PROD, then make a branch and pull in everything from QA, and then make another branch off of that with DEV. That way not only will the branches reflect the differences in the environments, they'll be in the right order chronologically with the newest commits in the DEV branch.

What I've tried so far

I thought about creating a QA branch off of the current master and using robocopy to make the working folder look like the current QA environment. This doesn't work because the new commit from QA will remove new files from DEV and that will remove them when we merge up, I suspect there will be similar problems if I started QA at an earlier (though not exact) commit from DEV.

答: There is a project called Vault2Git(I have not tested this project myself) that can be used to convert your base repository into git. After the conversion is done if you need to spit them into diffrent repositories you can follow the guide here.</p>

Title: Importing an existing project into Git


问:
iOS build machine setup: problem with certificates
some background:

work with multiple team mates

each work on our own MBP

I'm setting a build machine that we can git push to in order to generate a build (aim to allow anyone to push to the build machine and then generate an archive, upload to testflight and send on its way)

problem:

getting my apple developer certificates on the build machine.

I installed Lion, XCode, etc and I signed into my developer account through Xcode organizer, provisioning profiles download,etc. but beside each one it says:

valid signing identity not found

I also download my certificate from the developer.apple.com page, imported it into keychain, etc but no luck.

Anyone else have a similar issue? Or maybe hints to fix?

Thanks

答:
I had to export private key as a p12 file. </p>

<p>This link http://forums.imore.com/ios-developer-forum/178890-developing-iphone-apps-multiple-machines-using-same-developer-certificate.html lead me to it. </p>

Body:
I had to export private key as a p12 file.

This link http://forums.imore.com/ios-developer-forum/178890-developing-iphone-apps-multiple-machines-using-same-developer-certificate.html lead me to it.


答:
I've used exceptions for their information carrying ability. In C++, a function return code is usually a single value. In contrast, you can throw exceptions of any class type containing any information that you want.

I used an exception to return the specific piece of a query that was not found. It seemed the lesser evil than to add a mostly unused pointer or reference to each function call in a 7-deep call stack.

Title: if/else statements or exceptions


问:
Is Ruby on Rails' Active Record an example of Aspect-Oriented Programming?
From Clean Code, about Cross-Cutting Concerns:

Note that concerns like persistence tend to cut across the natural object boundaries of a domain. You want to persist all your objects using generally the same strategy, for example, using a particular DBMS...

Is Active Record an example of aspect-oriented programming?

In AOP, modular constructs called aspects specify which points in the system should have their behavior modified in some consistent way to support a particular concern. This specification is done using a succinct declarative or programmatic mechanism.

If Active Record is an example of AOP, what is the "aspect"? Is it the class declaration that inherits from Active Record?

```<code>class Foo < ActiveRecord::Base
</code>```

答:
No, inheritance can't really handle cross cutting concerns - when they talk about cross cutting they basically mean multiple object hierarchies are the things being cross cut.

Aspect Oriented Programming mostly is used to talk about some sort of extension to a single inheritance language to handle cross cutting concerns.  It's a bit less useful to add AOP to a multiple inheritance language, because multiple inheritance can handle some of the problems AOP solves (though, depending on AOP implementation, it might allow things like adding implementation to code from a third party module).

Ruby doesn't have multiple inheritance, but it does have mixins, and that can also solve some of the problems AOP does.

However, AOP can still do some other things as well.  Think of logging as a cross cutting concern.  With AOP you can add logging to classes without touching the source of the original class.  This is done by the AOP implementation finding all the places in the code that match your criteria for where logging should occur, and patching in ("weaving") calls to do the logging.

This is also possible in Ruby without special AOP extensions, because it's so very dynamic.  You could modify a class (that previously had no notion of logging) at run time to call logging code at the time any of it's methods are run.  The code that you wrote to do this would be handling a cross-cutting concern.  The "aspect" would be logging.  In Ruby the classes you do this to need not even be classes you wrote.  So this is more than can be done via single or multiple inheritance or mixins (though, to be a bit pedantic, you can do aspect oriented things and propagate the code that implements it via inheritance or mixins, those are not language features sufficiently powerful in themselves to allow AOP).


答:
You Use Exceptions for Exceptional situations where if else block couldn't handle, like connecting to a database, if the database is not available, what will you do? would you connect to another database? or just abort the operation? and other situations like these are the ones where you should use exceptions.

But you should always keep in mind that don't over used Exceptions, like having an index Out of bounds index error, then you'll use exception for that.

Title: if/else statements or exceptions


问:
How would you know if you've written readable and easily maintainable code?
How would one know if the code one has created is easily readable, understandable, and maintainable? Of course from the author's point of view, the code is readable and maintainable, because the author wrote it and edited it, to begin with. However, there must be an objective and quantifiable standard by which our profession can measure code.

These goals are met when one may do the following with the code without the expert advice of the original author:

It is possible to read the code and understand at a basic level the flow of logic.

It is possible to understand at a deeper level what the code is doing to include inputs, outputs, and algorithms.

Other developers can make meaningful changes to the original code such as bug fixes or refactoring.

One can write new code such as a class or module that leverages the original code.

How do we quantify or measure code quality so that we know it readable, understandable, and maintainable?

答:
How would one know if the code he created is easily maintainable and
  readable?

You can spot easy to maintain and readable code by looking for these properties:

Objects, methods and/or functions always do one thing.

Methods and/or functions are concise (as in "brief but comprehensive").

Objects, methods and/or functions do essentially what you think they are supposed to do based on their names.

Code that is destined for re-use is actually re-usable.

Last but not least, if you can immediately unit-test the code, you have likely written single-responsibility, modular code at the very least.

How would we know if we've written pretty messy and unmaintanable
  code? Are there any constructs or guidelines to know if we developed
  messy software?

If you are reading through a method and it isn't apparent what the intent was, this is inelegant at best and likely unmaintainable at worst.

If it doesn't seem simple, it probably isn't simple and that is a sign of unmaintainable code or code that will soon become unmaintainable.

If there is a lack of symmetry (consistency) across the codebase, you are likely looking at unmaintainable code.