问:
Generic file parser design in Java using the Strategy pattern
I am working on a product in which the responsibility of one of the modules is to parse XML files and dump the required content in a database. Even though the present requirement is only to parse XML files, I want to design my parsing module in a fashion that I can support any kind of files in the future. The reason for this approach is that we are building this product for a specific client but plan to sell it to other clients in the near future. All the systems in the ecosystem for the current client produce and consume XML files but this may not be the case for other clients.

What have I tried so far? (The Present)
I have the following design in mind which is based on the Strategy pattern. I have quickly written down the code in eclipse to convey my design so it would be great if other aspects such as proper way of handling exceptions are ignored for now.

Parser : The strategy interface that exposes a parse method.

```<code> public interface Parser<T> {
        public T parse(String inputFile);
    }
</code>```

*The reason for using a generic parameter is to allow any return type as well as ensure type safety at compile time.

ProductDataXmlParser A concrete class for parsing a product.xml file that contains product related information. (using XMLBeans)

```<code>public class ProductDataXmlParser implements Parser<ProductDataTYPE> {

    public ProductDataTYPE parse(String inputFile) {
        ProductDataTYPE productDataDoc = null;
            File inputXMLFile = new File(inputFile);

        try {
            productDataDoc = ProductDataDocument.Factory.parse(inputXMLFile);
        } catch(XmlException e) {
            System.out.println("XmlException while parsing file : "+inputXMLFile);
        } catch(IOException e) {
                 System.out.println("IOException while parsing file : "+inputXMLFile);
        }
        return productDataDoc.getProductData();
    }
}
</code>```

where : ProductDataTYPE and ProductDataDocument are XMlBean POJO classes generated using an xsd and the scomp command.

The future

If I have a product.txt file to be parsed in the future, I can define my own POJO called ProductData that will hold the required contents of the file. I can then create a concrete class called ProductDataFlatFileParser that implements the Parser interface and have the parse method populate the ProductData POJO for me after parsing the file.

Does this design make sense? Are there any obvious flaws in this design? As the design stands, I am allowing the concrete classes to define the algorithm to parse a file and letting the concrete class decide where to populate the data. The design seems to be more dependent on the domain objects rather than the file formats. Is this a bad thing? Any inputs on how I can improve my design will be highly appreciated.

答:
I have a couple of concerns:

I would make sure you actually need a generic design before implementing one.  Are you sure you're going to need file types other than XML?  If not, why code for them?  If you eventually need it, you can retrofit your code at that point.  It won't take much longer, you will probably have other requirements that will make the code look different than what you're currently proposing, and you will probably never need to write it anyway.  As they say, YAGNI (You Ain't Gonna Need It).

If you do actually need a generic design, and you're quite sure of this, then I'd say that Parser<T> is basically sound.  I do see two potential problems: (1) it assumes file input -- what if you're trying to parse a JSON stream that you retrieved from an HTTP response, for example? and (2) it doesn't necessarily provide much value except as part of some larger generic framework where you have lots of different types of parsers for lots of different types of data.  But I'm not convinced you need any such large generic framework.  You just have a very simple, concrete use case right now, as far as I can tell: parse an XML file into a list of ProductDatas.

It's almost never a good idea to swallow exceptions as you are doing in ProductDataXmlParser.  I would convert it to some sort of RuntimeException instead.

OwnerDisplayName: bot

OwnerDisplayName: Eric Galluzzo


答:
Just in case you'll prefer to use something already available, I've made a java library called JRecordBind that's based on XMLSchema (backed by JAXB).

It was born to consume/produce fixed length files, and, since XMLSchema defines their structure, you can use it with plain JAXB to marshall/unmarshall XML files

ContentLicense: CC BY-SA 3.0

Title: Generic file parser design in Java using the Strategy pattern

Body:
I am working on a product in which the responsibility of one of the modules is to parse XML files and dump the required content in a database. Even though the present requirement is only to parse XML files, I want to design my parsing module in a fashion that I can support any kind of files in the future. The reason for this approach is that we are building this product for a specific client but plan to sell it to other clients in the near future. All the systems in the ecosystem for the current client produce and consume XML files but this may not be the case for other clients.

What have I tried so far? (The Present)
I have the following design in mind which is based on the Strategy pattern. I have quickly written down the code in eclipse to convey my design so it would be great if other aspects such as proper way of handling exceptions are ignored for now.

Parser : The strategy interface that exposes a parse method.

```<code> public interface Parser<T> {
        public T parse(String inputFile);
    }
</code>```

*The reason for using a generic parameter is to allow any return type as well as ensure type safety at compile time.

ProductDataXmlParser A concrete class for parsing a product.xml file that contains product related information. (using XMLBeans)

```<code>public class ProductDataXmlParser implements Parser<ProductDataTYPE> {

    public ProductDataTYPE parse(String inputFile) {
        ProductDataTYPE productDataDoc = null;
            File inputXMLFile = new File(inputFile);

        try {
            productDataDoc = ProductDataDocument.Factory.parse(inputXMLFile);
        } catch(XmlException e) {
            System.out.println("XmlException while parsing file : "+inputXMLFile);
        } catch(IOException e) {
                 System.out.println("IOException while parsing file : "+inputXMLFile);
        }
        return productDataDoc.getProductData();
    }
}
</code>```

where : ProductDataTYPE and ProductDataDocument are XMlBean POJO classes generated using an xsd and the scomp command.

The future

If I have a product.txt file to be parsed in the future, I can define my own POJO called ProductData that will hold the required contents of the file. I can then create a concrete class called ProductDataFlatFileParser that implements the Parser interface and have the parse method populate the ProductData POJO for me after parsing the file.

Does this design make sense? Are there any obvious flaws in this design? As the design stands, I am allowing the concrete classes to define the algorithm to parse a file and letting the concrete class decide where to populate the data. The design seems to be more dependent on the domain objects rather than the file formats. Is this a bad thing? Any inputs on how I can improve my design will be highly appreciated.

OwnerDisplayName: Federico Fissore


问:
Why are HDL IDEs so user-unfriendly when compared to generic-purpose language (like Java/C) IDEs?
I've been programming for a while now, and I've covered a lot of languages. And this trend that I noticed is that all HDL languages have so painful IDEs!

In general, any development environment having some Hardware related development has very crappy UI.

I'm talking about uVision, ModelSim, VHDL Simili, Xilinx etc, compared with Netbeans, Eclipse, Visual Studio etc.

Why do hardware-guys hate their developers?

NOTE: There are exceptions (LABView is awsome!). Can you think of any more?

答: Because they don't sell products.  Features in the chips and features in the software sell chips.  Ease of use is better in Altera than Xilinx, however.  And ModelSim sells for its good simulator, not for the GUI.</p>

ContentLicense: CC BY-SA 2.5


问:
How would you architect an application which is largely a collection of flowcharts?
I am working with a history teacher on a history app. He has like 200 flowcharts that he wants to put into the app (among other things). The two likeliest-looking ways to do it:

HTML/CSS. The big minus here is that neither one of us is a big HTML/CSS person. Though I do know a bit about them.

Adobe Illustrator. The interface makes it easy to draw stuff, and we can make vector graphics files and work from those. The drawback is that the text of a box, the graphical box, and the corresponding hyperlink would be different entities, where as if the HTML/CSS is done right, they might all be a single thing.

There are some flowchart-drawing websites out there. But the ones I have looked at have some problems:

In the ones I have looked at, the HTML is big and messy. We need ours to be short and simple.

Often a large amount of JavaScript is involved. We could do that, but it adds to the complexity of our mobile app, as well as the risk of failures.

We are starting on iOS but may add other platforms later.

答:
If the flowcharts are intended to be dynamic on the server then I would do the following:

Collect the data as json via ajax calls

Pass the json data into javascript methods, named and organised by you in an mvc like structure which then pass the data to a plugin which draws the chart: svg, jgraph, ext-js sencha, canvas or alternative (something which has plenty of documentation, so you don't have to re-invent the wheel)

I would not do flow charts in html and css because then you have to consider browser and platform variations and you will have to make amendments multiplied by 5 for each browser edgecase. Atleast, with the plugins you can avoid most of this. I also wouldn't support legacy browsers like IE6, IE7 etc. The amount of time and cost massive corporations lose on developing for these, and messing up clean code adds to unscalable poor code, increasing maintenance.


问:
How to handle committed and merged code that has no tests?
When developing an application in a team not everyone on this team will be equally good developers. Some will be skilled in some things and some in others and some not at all.

As a team working in an agile process you usually have a definition of 'done' to follow. In our DoD it says never to merge code that is not documented and have proper tests. Sometimes though, a feature is so critical to some team member so the code has to be merged without tests. Sometimes a lazy developer might merge and call it a weekend.

A merge like this means that when other team members pull the code, they will receive code that may or may not function properly and since there are no tests it is hard to verify. It can be very cumbersome to walk through that code to make sure it works before the team member can work on their task.

It has happened on several occasions that the code that was committed without tests has been broken by other team members without them noticing.

So my question becomes:

How would you handle issues like this?

Does it point to bad planning rather then bad behaviour?

Who is to "blame" if code that lacks tests is broken?

答:
How would you handle issues like this?

Work on training the less good developers to be better.

Work on educating management about the wasted time/money caused by bad commits and poor quality.

Work on pushing technical solutions like gated check-ins or "only team leads can commit"

Does it point to bad planning rather then bad behaviour?

Sometimes. If a feature is so important due to time pressure or dependencies, that's a planning issue. If the developer is lazy, or estimated it to take a week (with tests) and then cut the tests to meet the goal that's not a planning (PM) issue really.

Who is to "blame" if code that lacks tests is broken?

Everyone. Even if one person pushed you too hard, you could still take the time to write the tests or push back on the schedule. Even if one person just was lazy, the culture/boss/peers let that happen and/or didn't mitigate against natural human laziness.

Mistakes will be made, but complacency is what will really destroy your department. Acceptance of this issue and pushing the blame to others will not improve it.


问:
Setting up a simple Ruby\Rails environment
I am coming from a .NET background and beginning my journey into the Mac OSX\Ruby\Rails environment.

A lot of the resources I have found such as this one have between 5-10 steps for setting up a Ruby\Rails environment.

My question is, what are the bare minimum requirements for setting up a working Ruby\Rails environment?

Can I use RailsInstaller and be done?
Should I install all of the tools that the above link suggests (XQuartz, Homebrew, RVM, etc) even though I don't really know what they do?

Right now I am not being paid to do this, but am also curious what professional Rails developers do when setting up an environment.

I am also more concerned about the why as in why I shouldn't use RailsInstaller or why I should install RVM.

答: One advantage of using the railsinstaller would be that you can get started with Ruby on Rails programming right away.  There can be some headache with getting the typical Ruby on Rails tool set installed which the railsinstaller takes care of for you.  After that I would follow James Adam advice from another answer and do the Ruby on Rails tutorial.  Has to why you want to use RVM, that allows you to use multiple versions of Rubies/Gemsets such has JRuby(which is a ruby that runs on that JVM).</p>


问:
Is it possible to get dynamically generated html in asp.net tags using HTTP Modules?
I want to know if it is possible to write to a log/text file dynamically generated HTML in asp.net tags in an .aspx page using HTTP modules.

By dynamically generated HTML, I mean the html content that asp.net generates in response to statements between the tags <% %> or <%# %> or <%$ %>.

So when asp.net renders a page, it essentially converts everything into HTML. There is some static html written in the asp.net page, rest is what i call dynamically genrated HTML. My goal is to dump somewhere all the dynamically generated HTML content.
Can it be done using HTTP Modules or any other mechanism ?

Example:

If the .aspx page is like this

...

        Total Credit Line

            <%=creditLimit.ToString("C")%>

...

I want the HTTP Module to write in a log file, the HTML rendered by the <%=creditLimit.ToString("C")%> asp tag and all other asp tags on the page. The HTTP Module would be generic and can be added to any IIS website.
Note that there would be no difference in the output that is seen by a browser.

答: You can dump any valid html or text output you want into a LiteralControl, and it will be passed directly into the output page without being processed on the ASP.NET server.</p>


问:
How do SaaS companies provide data liberation services?

Overview

I considered posting this to DBA but I think the question goes beyond the database. Of all the software-related Stack Exchange sites, the Programmers FAQ seemed most in tune with what I'm asking here.

My company provides a SaaS offering. Our customers collect a lot of data using our service, and we wish to make that data more easily available to our users than our web application currently provides. Our largest customer databases can run into the tens of GB including indexes. Stripping away indexes, a single database can still be several GB and will grow with each additional year of service.

The primary use cases our prospects and customers cite are:

As a prospect/customer, I want guaranteed access to my data in the event your company should fail.

As a prospect/customer, I want access to query my data so that I can build my own reports, dashboards, applications using that data.

I like the phrase "data liberation" to classify these kinds of use cases. Google seems to be at the vanguard of the data liberation movement. They've done admirable work to enable their customers to get access to their data and to raise awareness of the state of SaaS data accessibility. As a SaaS provider, I'd like to give our customers better access to their data.

The Evolution

In the past, we developed many custom report-like web pages to give customers a degree of access. This led to a lot of complex, custom pages that we must maintain.

We later added a separate reporting solution and began charging for custom reports. Although this gives us more flexibility and we can deliver faster, this is also costly to maintain and not scalable. Customers also don't like being charged for every custom report, as they see it as us charging them for access to data they own.

While we are meeting the needs of some customers, others want more. Some want to combine their SaaS data with in-house data, and they can't do that without the ability to query their SaaS data.

There are many approaches to solving these problems. I'll talk about the two use cases and approaches I've considered, then ask for your input.

I'm going to willfully avoid the question, "How useful is the data without the application?"

Side Note: Our database is Microsoft SQL Server, but that's largely irrelevant.

Use Case 1

As a prospect/customer, I want guaranteed access to my data in the event your company should fail.

Host Our Own Download Service

A relatively easy solution would be to set up our own download service on a separate server hosted in the same data center. We'd put nightly database backups here for every customer to download at their leisure.

Pros:

We use free internal bandwidth to move files around.

Customer only incurs bandwidth costs when they want to download.

Cons:

Some customers may download nightly "just because we can".

Provisions must be made to keep the download service operational in the event the company fails, otherwise we've solved nothing. The customer still has to trust us to keep this service running, which is the core issue in the first place.

An extreme variation of this model is to create a separate company to own the download service and pre-fund the hosting for a period of time sufficient to allow customers to download their last backup.

Push Database Backups to the Customer

Here we copy full nightly backups to a storage account or service (FTP over SSL, SFTP/SSH, Dropbox, Box.net, SkyDrive, Amazon S3/Glacier, etc.) of the customers' choosing.

Pros:

Customer always has access to their data.

Cons:

This method is bandwidth intensive and wasteful. We're pushing mostly the same data, night after night. The customer only needs the data in the event of a catastrophe.

This method runs the risk of losing up to 24 hours of the customers' data if we only copy nightly backups. Copying periodic diff backups would help to reduce the recovery point objective at the expense of more bandwidth.

Managing all the possible destination types, auth credentials and integrating new targets is complex.

A less complex variation is to require our customers to provide credentials to a storage service of a single type, like Amazon Glacier. Everyone uses Glacier, or you don't benefit from the service.

Third-Party Backup Tie-In

There are services out there like Backupify that hook into Google Apps and back up data on a regular basis. I'm seeking out more services like this which could provide an independent, turn-key solution that our customers could sign up and pay for, and which we could fully automate.

Unless the third party service ties into SQL Server in an intelligent way to only pull data differences from night to night, this is still going to be bandwidth intensive.

Native Database Replication

There are several built-in SQL Server features of interest, such as log shipping, mirroring, replication and "always-on availability groups". These all require a SQL Server on the remote side, as well as requiring the remote server be joined to a single domain and/or be part of a Windows Server Failover Cluster controlled by us. These methods therefore don't seem viable for this use case.

Use Case 2

As a prospect/customer, I want access to download and/or query my data so that I can build my own reports, dashboards, applications using that data.

Web API

Providing a comprehensive REST or SOAP/XML (or both) API would help some, but not most of our customers. Many customers really want some kind of SQL access, through ODBC/JDBC/ADO.NET or the like.

Open Data Protocol (OData)

We could expose denormalized data sets and present them using OData (see also SO questions on OData). However, being newish (1) I'm not sure OData will become mainstream enough to warrant a long-term investment and (2) it may be challenging for our customers to both understand and access. I'm not married to this opinion. I do know that the PowerPivot plugin for Excel 2010 can connect to OData sources, and Tableau (a tool at least one customer users) can as well. That's promising.

Data Replication

We've experimented with using Microsoft SQL Server transactional (pub/sub) replication of de-normalized subsets of data with a couple of customers. This requires VPNs and DBAs, making it complicated to set up and maintain. The dependence on SQL Server isn't ideal.

Third Party Connectors

I've researched and found a couple of companies who provide offerings around opening SaaS data to end customers.

Connection Cloud

Progress DataDirect

Both companies have products that would seem to enable exactly what I'm looking to do. These are the only two providers I've found so far. I'm talking to representatives from both companies to evaluate their offerings.

The Question

How have you solved your own customers' "data liberation" problems?

答:
We do this process with data from/for school districts.  Our approach includes:

focus on excel and csv for both import and export of data as this is what most non-technical customers are familiar with.  csv is extremely 'universal' as a data transport format.

Not doing database backups for customers.  The db is not much use without the app that currently access it.

To be honest though, I've worked for half a dozen companies that provide saas in one way or another and this has never been a hot topic for any of them.  The main focus is the apps that currently accompany the data and the value they provide and that's about where it stops.

This doesn't address some of your questions but I hope it helps.  It's also not a good idea to ask a ton of minor questions within a big one.  Just like software, it's best to take one small question at a time, even when tackling a big problem.


答:
We've performed some of this with our application.

The best approach is a simple one.  Namely,

Provide a simple web api with basic querying capability;

Provide a simple report generator / downloads into csv; and,

Provide a way to schedule auto exports of data.

Those can work hand in hand.  You don't want to build anything overly complicated as few would bother trying to use it.  However, if you can allow your customer to effectively do a "select * from ..." call then you are good.

Of course some of them want direct SQL access.  This is almost universally a bad idea depending upon your data structures.  Never mind that you most likely have a level of business logic embedded in the application itself that would be difficult to teach others about.

It's far better to give them a simple api with a few parameters allowing them to pull some json data or a csv/excel export; with CSV being preferred.

Most devs can work with csv.  Amazingly few can work with json / xml; this actually boggles my mind.

Don't give them backups.  Those have limited usability that is usually heavily dependent upon the business logic in the application to work well.

Title: How do SaaS companies provide data liberation services?

Body:
Overview

I considered posting this to DBA but I think the question goes beyond the database. Of all the software-related Stack Exchange sites, the Programmers FAQ seemed most in tune with what I'm asking here.

My company provides a SaaS offering. Our customers collect a lot of data using our service, and we wish to make that data more easily available to our users than our web application currently provides. Our largest customer databases can run into the tens of GB including indexes. Stripping away indexes, a single database can still be several GB and will grow with each additional year of service.

The primary use cases our prospects and customers cite are:

As a prospect/customer, I want guaranteed access to my data in the event your company should fail.

As a prospect/customer, I want access to query my data so that I can build my own reports, dashboards, applications using that data.

I like the phrase "data liberation" to classify these kinds of use cases. Google seems to be at the vanguard of the data liberation movement. They've done admirable work to enable their customers to get access to their data and to raise awareness of the state of SaaS data accessibility. As a SaaS provider, I'd like to give our customers better access to their data.

The Evolution

In the past, we developed many custom report-like web pages to give customers a degree of access. This led to a lot of complex, custom pages that we must maintain.

We later added a separate reporting solution and began charging for custom reports. Although this gives us more flexibility and we can deliver faster, this is also costly to maintain and not scalable. Customers also don't like being charged for every custom report, as they see it as us charging them for access to data they own.

While we are meeting the needs of some customers, others want more. Some want to combine their SaaS data with in-house data, and they can't do that without the ability to query their SaaS data.

There are many approaches to solving these problems. I'll talk about the two use cases and approaches I've considered, then ask for your input.

I'm going to willfully avoid the question, "How useful is the data without the application?"

Side Note: Our database is Microsoft SQL Server, but that's largely irrelevant.

Use Case 1

As a prospect/customer, I want guaranteed access to my data in the event your company should fail.

Host Our Own Download Service

A relatively easy solution would be to set up our own download service on a separate server hosted in the same data center. We'd put nightly database backups here for every customer to download at their leisure.

Pros:

We use free internal bandwidth to move files around.

Customer only incurs bandwidth costs when they want to download.

Cons:

Some customers may download nightly "just because we can".

Provisions must be made to keep the download service operational in the event the company fails, otherwise we've solved nothing. The customer still has to trust us to keep this service running, which is the core issue in the first place.

An extreme variation of this model is to create a separate company to own the download service and pre-fund the hosting for a period of time sufficient to allow customers to download their last backup.

Push Database Backups to the Customer

Here we copy full nightly backups to a storage account or service (FTP over SSL, SFTP/SSH, Dropbox, Box.net, SkyDrive, Amazon S3/Glacier, etc.) of the customers' choosing.

Pros:

Customer always has access to their data.

Cons:

This method is bandwidth intensive and wasteful. We're pushing mostly the same data, night after night. The customer only needs the data in the event of a catastrophe.

This method runs the risk of losing up to 24 hours of the customers' data if we only copy nightly backups. Copying periodic diff backups would help to reduce the recovery point objective at the expense of more bandwidth.

Managing all the possible destination types, auth credentials and integrating new targets is complex.

A less complex variation is to require our customers to provide credentials to a storage service of a single type, like Amazon Glacier. Everyone uses Glacier, or you don't benefit from the service.

Third-Party Backup Tie-In

There are services out there like Backupify that hook into Google Apps and back up data on a regular basis. I'm seeking out more services like this which could provide an independent, turn-key solution that our customers could sign up and pay for, and which we could fully automate.

Unless the third party service ties into SQL Server in an intelligent way to only pull data differences from night to night, this is still going to be bandwidth intensive.

Native Database Replication

There are several built-in SQL Server features of interest, such as log shipping, mirroring, replication and "always-on availability groups". These all require a SQL Server on the remote side, as well as requiring the remote server be joined to a single domain and/or be part of a Windows Server Failover Cluster controlled by us. These methods therefore don't seem viable for this use case.

Use Case 2

As a prospect/customer, I want access to download and/or query my data so that I can build my own reports, dashboards, applications using that data.

Web API

Providing a comprehensive REST or SOAP/XML (or both) API would help some, but not most of our customers. Many customers really want some kind of SQL access, through ODBC/JDBC/ADO.NET or the like.

Open Data Protocol (OData)

We could expose denormalized data sets and present them using OData (see also SO questions on OData). However, being newish (1) I'm not sure OData will become mainstream enough to warrant a long-term investment and (2) it may be challenging for our customers to both understand and access. I'm not married to this opinion. I do know that the PowerPivot plugin for Excel 2010 can connect to OData sources, and Tableau (a tool at least one customer users) can as well. That's promising.

Data Replication

We've experimented with using Microsoft SQL Server transactional (pub/sub) replication of de-normalized subsets of data with a couple of customers. This requires VPNs and DBAs, making it complicated to set up and maintain. The dependence on SQL Server isn't ideal.

Third Party Connectors

I've researched and found a couple of companies who provide offerings around opening SaaS data to end customers.

Connection Cloud

Progress DataDirect

Both companies have products that would seem to enable exactly what I'm looking to do. These are the only two providers I've found so far. I'm talking to representatives from both companies to evaluate their offerings.

The Question

How have you solved your own customers' "data liberation" problems?


问:
What the white box testers create test cases against?
I'm wondering, what are the white box testers using to create test cases? The actual code? Some kind of diagrams?

I mean, if I am given a task to create test cases for complete branch coverage, is it possible they give me a code?

Because I saw something like that:

```<code>Reader r=null;
if(condition)
{
  r=new Reader();
}
r.toString();
</code>```

There is an obvious bug as the last statement should be in the body of the If statement. It will be easily exposed by false-decision test case of the condition.

But is it not more like unit tests? What is then the white box testers goal of testing?

Wikipedia article on white-box testing states:

The tester chooses inputs to exercise paths through the code and determine the appropriate outputs.

I understand this as you choose inputs to reach the coverage and reveal possible bugs. But isn't it simple unit testing done by developers?

答:
Yes, white box testing is akin to unit tests created by developers.

However, see the following for a discussion:
https://stackoverflow.com/questions/9892963/does-unit-testing-falls-under-white-box-or-black-box-testing

If they are asking you to white-box test something then you will need to read the code to come up with the tests.


问:
Is tracking Android OS.Buid/Manufacturer info a privacy issue?
On the Android operating system details about the phone are available via the Android.OS.Build class. These details include things such as the phone manufacturer, model, version, etc. The customer may want us to collect this data and save it to our database for analytics and tracking. I think this raises some privacy concerns for the end user.

Are we obligated to inform the user that we are collecting this information (similar to how the use of the device's capabilities, such as camera or microphone, are presented in the Play Store) and what we intend to use it for? If we are not required to do so, is this something that we should, from an ethical perspective, inform the user that we are doing?

答:
The available hardware/os specifications given to an application running on a device are no more secret than the user agent of a web browser hitting a given web page.  I assume that every web site out there is collecting information about that I am browsing with a linux firefox application.

Some of this information is widely reported (Google has such information on the android dashboard). Gathering and reporting the information back would be invaluable use for marketing.

The question of if this is privacy is "are you reporting back information that can be uniquely identifiable to an individual?"  If not, there is likely no privacy issue nor any ethical issue.

Realize that many people are quite savvy and analyze the data going back.  If you do not disclose that you are reporting such, people might be frustrated or alarmist.  But this is a question for do you want to do that, the risks, benefits, and how you want to respond.

One approach could be "on startup, put the information that you are reporting back in an alert and ask if they want to send the information back."  This gives the user a way to say "no", and yet still collect the data (you only need to do this once).  For additional user happiness, allow different fields to be reported (yes, I'm willing to report back the hardware and the os, but not the carrier).


答:
If I understand you correctly than Yes

At a fundamental level a webpage no different than a Webservice. They both go over HTTP and return a Header with some data in the Body.

You just need to access your .net page as would any Http client, that would return the rendered HTML just like a web service returns HTML.

See: How to Request Data Using the WebRequest Class

Title: Is it possible to get dynamically generated html in asp.net tags using HTTP Modules?

Body:
I want to know if it is possible to write to a log/text file dynamically generated HTML in asp.net tags in an .aspx page using HTTP modules.

By dynamically generated HTML, I mean the html content that asp.net generates in response to statements between the tags <% %> or <%# %> or <%$ %>.

So when asp.net renders a page, it essentially converts everything into HTML. There is some static html written in the asp.net page, rest is what i call dynamically genrated HTML. My goal is to dump somewhere all the dynamically generated HTML content.
Can it be done using HTTP Modules or any other mechanism ?

Example:

If the .aspx page is like this

...

        Total Credit Line

            <%=creditLimit.ToString("C")%>

...

I want the HTTP Module to write in a log file, the HTML rendered by the <%=creditLimit.ToString("C")%> asp tag and all other asp tags on the page. The HTTP Module would be generic and can be added to any IIS website.
Note that there would be no difference in the output that is seen by a browser.


答:
If you are collecting personally identifiable information (PII) then you should tell them quite loudly what you are doing.  Beyond that it's pretty much a given that most applications report non-PII usage info back to their home base.

However, in the real world, you should tell them if you are collecting anything at all regardless of if its PII.  You should explicitly spell out what it is you are collecting and give them the option to opt out.

Most vendors (Apple, MS, etc) have these types of usage / auto bug reporting features.  And those vendors let you know exactly what it is they are collecting and why.  They also give you the option to opt out of sending it.

This is expected behavior in today's world regardless of any laws requiring you, as a developer, to do anything.

The reality is that even if you think it's not PII, it can usually be linked to information that is.  In most cases, this is OK.  However, some people are uber paranoid (in many cases for good reason) and don't wish our devices to tell anyone anything.

Title: Is tracking Android OS.Buid/Manufacturer info a privacy issue?

Body:
On the Android operating system details about the phone are available via the Android.OS.Build class. These details include things such as the phone manufacturer, model, version, etc. The customer may want us to collect this data and save it to our database for analytics and tracking. I think this raises some privacy concerns for the end user.

Are we obligated to inform the user that we are collecting this information (similar to how the use of the device's capabilities, such as camera or microphone, are presented in the Play Store) and what we intend to use it for? If we are not required to do so, is this something that we should, from an ethical perspective, inform the user that we are doing?


问:
code review with git-flow and github
With regular git and github I can do a code review by simply creating a pull request of the feature branch I'm working on to the master branch. How would I do code reviews with git-flow? With workflow like "git flow feature finish` I'm confused as to where the code review actually happens and how git-flow or git can facilitate that review.</p>

答:
If you're doing code reviews, then I will assume that you have a central repository that contains the "official" code. Developers pull from and push to this central repository.

When you use Gerrit, Gerrit itself becomes the central repository (it has built-in SSH and HTTP servers that let users interact with it in basically the same way they already are). When using Gerrit, the workflow becomes:

Developer makes changes on whatever branch, commits locally.

Developer pushes those changes to Gerrit.

Gerrit creates review items for others to review.

Peers review the code, making comments and accepting or rejecting the commit.

When the commit is accepted, then Gerrit makes those changes available for others to pull from the branch.

When using a central repository, other developers can see the submitted changes after step 2. Gerrit introduces the code review workflow, and so other developers only see the submitted changes after step 5.

This works well with git-flow (or any other branching scheme) because Gerrit supports reviewing changes made on any branch.

Title: code review with git-flow and github


问:
Peer programming and experience sharing
There was a mention in the Java Posse Podcast about how teams should be divided up into pairs. However, there was a mention from the lady on the podcast that: "Pairs should be mixed up [sic]" (an encouragement for diversity)

I understand the benefits of pair programming, but what benefit is there to intentionally mix people up. To me it would seem that it would be better to take a genetic algorithm like approach to find optimal groups to generate pairs.

An example: Let's say you have a tax developer and a front end developer how would either of these guys benefit from the intentional mixing of peer groups? Why did her assertion go unchallenged? (I got the sense that she was advising that it should go cross groups and development tiers)

答:
This seems to be similar to Joel Spolsky's concept of diversity. You mix up types of programmers explicitly to get exposed to how other people think and do things.

"Ideal" pairings, I don't think, truly exist in the long-term: if you're not constantly growing etc, you're stagnating. Would you rather be paired and stagnate because you both work the same way, or paired and grow because you think differently because of different foci and backgrounds?

Title: Peer programming and experience sharing


问:
Effective Java for experienced Java programmers?
I own and read 'Java Puzzlers', 'Clean Code' and GOF's 'Design Patterns' and more specific technology books however I have not yet read 'Effective Java'. Whenever I  see a list of must read books I always see a copy a 'Effective Java' but I have put off buying it seeing as a learn to write Java book rather than a  write better Java book. Is it still worth a read or even a purchase. What is special about this book that I am missing out on by not reading this.

I know my design patterns and practice TDD and attempt to write clean code :), what will I gain from this book?

答: It's definitely not a "learn to write Java" book - it's quite useful even for experienced programmers. The level is similar to 'Java Puzzlers', but instead of showing off weird details for their own sake, it teaches stuff that matters for everyday programming - gotchas and best practices (and most importantly why they are best practices). You probably already know a lot of it, but I can almost guarantee that you'll still learn some valuable and new things.


问:
Is there a viable alternative to the agile development methodology?
The two predominant software-development methodologies are waterfall and agile.  When discussing these two, there is often much focus on the particular practices that distinguish them (pair programming, TDD, etc. vs. functional spec, big up-front design, etc.)

But the real differences are far deeper, in that these practices come from a philosophy.

Waterfall says:  Change is costly, so it should be minimized.

Agile says:  Change is inevitable, so make change cheap.

My question is, regardless of what you think of TDD or functional specs, is the waterfall development methodology really viable?

Does anyone really think that minimizing change in software is a viable option for those that desire to deliver valuable software?  Or is the question really about what sort of practices work best in our situations to manage the inevitable change?

答:
First, I'm going to disagree with your statements:

Waterfall says: Change is costly, so it should be minimized.

  Agile says: Change is inevitable, so make change cheap.

My interpretation is:

Waterfall says: The customer knows what they want.

Agile says: The customer doesn't know what they want so we're going to have to make a few different versions.

The best implementation of "waterfall" that I've ever seen was a huge integration project with a very large financial customer and there were about 40+ sub-projects involved. The desktop and website package we supplied was just 1 of those 40+ sub-projects. While I thought they blew through other people's money rather excessively, they had their stuff together and kept 40+ different ships all moving together in formation. The project went live on the target date (the target moved once during the project) and while I thought they could have done it more frugally and agily, it got done on time and on spec. The go-live night's schedule was about 100 pages long and about 40 of those pages were emergency panic contact details of all sorts of people involved. I was very impressed by this client.

Or, you could do what we do, which is run around and do what the most recent complaint/bug report is, and call that agile.


问:
Simple real-world PHP OOP example?
I'm trying to learn PHP OOP, but when I've followed tutorials, all the examples seem to involve things like:

```<code>class Human {
    $_sex;

    public function setSex($sex) {
        $this->_sex = $sex;
    }

    public function getSex() {
        return $this->sex;
    }
}
</code>```

(Pointless example, but hopefully you get what I mean -- An object has properties that are stored in the object.)

I've never come across a web application where I've needed to create objects about humans, dogs, cars, or any of the other weird examples you find when reading tutorials about OOP...

So I'm trying to find a similarly simple, but more realistic, project with which to learn OOP. I've chosen a website for an internet comic (e.g. XKCD.com). (This would allow people to view the comic, but also the author to edit and update it.)

So how would this translate to real-world PHP OOP?

My initial instinct would be to break the objects down thusly:

Catalogue

Episode

Where the Catalogue class would contain methods pertaining to all the episodes of the comic, e.g. getMostRecentEpisodeID(), deleteEpisode($episodeID), addNewEpisode($newEpisode), etc. etc.

And Episode would contain methods pertaining to the individual episode, e.g. getEpisodeComments($episodeID) (if the website allowed people to leave comments on individual episodes), editEpisode($episodeID), getEpisode($episodeID), etc.

Is this right, or have I made an absolute hash of what OOP is for?

Edit: Rather than just giving me a list of examples, it would really be helpful if your answer made specific reference to the problem I'm trying to solve.

Thanks.

答:
Is this right, or have I made an absolute hash of what OOP is for?

It's not right, but also not completely wrong.

The main point of OOP is that classes aren't just collections of methods, but also contain the data those methods operate on - you wouldn't call editEpisode($episodeID), but instead $episode->edit(). This has two advantages:

Less passing around of data, which leads to less cluttered function signatures and less potential for errors.

By making the data (fields) private, it's possible to control access to it and allow only those operations on it that make sense.

For a real-world useful example, look at mysqli and compare its procedural and its OOP API. The procedural one requires you to pass a link, statement or result handle to almost every method, while the OOP API doesn't need that because you call the methods on an object. Additionally, the OOP method names don't need the mysqli prefix.

It's not a big difference, but still leads to nicer code, and of course that's just the beginning.

Title: Simple real-world PHP OOP example?


答:
Assuming you have knowledge of coding, instead of building them in pure HTML, PDF or drawing similar environment, I would recommend the store flowchart data in XML files and render them with a javascript based engine. You may also generate different outputs (mobile, pdf etc) later if needed.

You can find some force directed tree layout engines in javascript, with weight changes on engine I think you can get the result that you want.

Some js engines;

https://stackoverflow.com/questions/7034/graph-visualization-code-in-javascript

http://jgraph.github.com/mxgraph/javascript/examples/swimlanes.html

http://philogb.github.com/jit/demos.html

Title: How would you architect an application which is largely a collection of flowcharts?

Body:
I am working with a history teacher on a history app. He has like 200 flowcharts that he wants to put into the app (among other things). The two likeliest-looking ways to do it:

HTML/CSS. The big minus here is that neither one of us is a big HTML/CSS person. Though I do know a bit about them.

Adobe Illustrator. The interface makes it easy to draw stuff, and we can make vector graphics files and work from those. The drawback is that the text of a box, the graphical box, and the corresponding hyperlink would be different entities, where as if the HTML/CSS is done right, they might all be a single thing.

There are some flowchart-drawing websites out there. But the ones I have looked at have some problems:

In the ones I have looked at, the HTML is big and messy. We need ours to be short and simple.

Often a large amount of JavaScript is involved. We could do that, but it adds to the complexity of our mobile app, as well as the risk of failures.

We are starting on iOS but may add other platforms later.


答:
I would do this:

Quickly get images (any web friendly format) onto 200 or so pages

Start using a package such as ABC flowcharter

One by One convert each image into real objects with real attributes and references within the flowcharting application

Export each flowchart in a data format that is usable by others applications.

Import the result into other apps.


答:
Installing various bits and pieces and different tools and getting them working together actually turns out to be fairly constant in the Ruby on Rails world.

This was a change for me as the previous frameworks I'd used changed much slower and had far less choice (and changing) of which tools to use.

Rails installer is great and I would use it.

Xcode is pretty essential on a mac for installing stuff, make sure to avoid the older Macports.

Homebrew is also a really good idea - it will help you install stuff and diagnose any issues.  It's really more of a help than a hindrence.  Plus is easy to install.

RVM will help you with your Ruby install and version changes.  Both Ruby and Rails both have versions changes every few weeks, not every few months/years as was common with older languages and frameworks.

Part of the trick of being a full-stack rails developer is being comfortable with exactly this kinda stuff.  Rails gives you a ton of benefits by using convention over configuration and DRY principles, so you write less code.  The 'cost' you pay is needing to be good at the infrastructure stuff to install components (such as gems) and systems and not be re-inventing the wheel by writing them yourself.

Title: Setting up a simple Ruby\Rails environment

Body:
I am coming from a .NET background and beginning my journey into the Mac OSX\Ruby\Rails environment.

A lot of the resources I have found such as this one have between 5-10 steps for setting up a Ruby\Rails environment.

My question is, what are the bare minimum requirements for setting up a working Ruby\Rails environment?

Can I use RailsInstaller and be done?
Should I install all of the tools that the above link suggests (XQuartz, Homebrew, RVM, etc) even though I don't really know what they do?

Right now I am not being paid to do this, but am also curious what professional Rails developers do when setting up an environment.

I am also more concerned about the why as in why I shouldn't use RailsInstaller or why I should install RVM.


答:
As I see it one of the major advantages to pair programming is that different people come at a problem from different points of view, due to their previous experiences.  These different points of view can lead to a more creative and better thought out solution.  If the same pair always work together I see that their experiences, at least at work, will be similar and so not "mixing up" the pairs would lead to less diverse points of view and less creative solutions.

Pairing also allows for shared experience and training.  In your example the two developers might leave with more of an understanding of the field of the other. If nothing else they would be exposed to how each other thought.

Your example is not as over the top as you might think. I had a friend with a zoology degree who was hired out of Uni as a developer for IBM.  They saw that the different point of view that he brought to development was worth the over head of spending time improving his development skills.

Title: Peer programming and experience sharing

Body:
There was a mention in the Java Posse Podcast about how teams should be divided up into pairs. However, there was a mention from the lady on the podcast that: "Pairs should be mixed up [sic]" (an encouragement for diversity)

I understand the benefits of pair programming, but what benefit is there to intentionally mix people up. To me it would seem that it would be better to take a genetic algorithm like approach to find optimal groups to generate pairs.

An example: Let's say you have a tax developer and a front end developer how would either of these guys benefit from the intentional mixing of peer groups? Why did her assertion go unchallenged? (I got the sense that she was advising that it should go cross groups and development tiers)


问:
Alternative to "Passing/Broken build" indicator?
When having a continuous integration executing the tests at each commit, a common best practice is to have all the tests passing at all times (aka "do not break the build").

I find some problems with that:

For example one cannot help an open source project by creating tests corresponding to tickets. I know if I propose a Pull Request to an open source project containing failing test, the build will be marked as failed and the project will not want that merged into its repository because it would "break the build".

And I don't believe it is a bad thing to have failing tests in your repo, it's like having open issues in your tracker. These are just things waiting to be fixed.

The same goes in a company. If you work with TDD, you can't write tests, commit and then write the logic code that fulfills the test. That means if I have written 4-5 tests on my laptop, I can't commit them before going on holidays. Nobody can take back my work. I can't even "share" them with a colleague except by sending them by email for example. It also prevents working with one person writing the tests, the other one writing the model.

All that to say, am I misusing/misunderstanding the build process/continuous integration? It seems to me that "passing"/"not passing" is a too narrow indicator.

Is there a way to make continuous integration and TDD compatible?

Maybe there is a standard solution/practice to distinguish "new tests" (that can fail) and "regression tests" (that should not fail because they used to work)?

答:
I use skipped tests.

In the particular unit testing framework I use, I can raise a SkipTest exception. The test isn't actually run, and its failure won't break the build. However, I can see the number of skipped tests and see if there is work to be done in that area.


问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答:
I'm using the ACM Library to help intro students do simple graphics and games. We've been able to do basic, two-player click-based games with nothing more than the skills you outlined. This week they are doing the Fox and Hounds game.

I've been trying to stay away from console I/O as long as possible. It's a foreign concept to many students these days, as they've all grown up with GUIs. So I focus on MVC, getting the model correct, and adding the GUI only after they've tested their model. Testing is done via automated unit testing and the Code Pad in BlueJ. No public static void main() is necessary, ever.


问:
Functional testing and Acceptance testing leading to redundant code
What I know is:

A Functional test aims to test a single component (like a WebApp's Controller) from the point of view of the developer. => Did I achieve all the requirements to make it work well?

An Acceptance test aims to to test a group of components together and is focused on the Business point of view. => Does my program fulfill requirements provided by the Client/Business/Customer?

Today, I work on a personal project and I started following BDD/testing methods and thus created Acceptance tests and Functional tests.

I notice that a lot of requirement for functional tests are exactly the same that Acceptance tests need.

Suppose a webapp controller aiming to add a product to my e-commerce's basket.

One of concerned functional tests would be:

When I go to productList.html page and I call the addProductToBasket action, I expect my controller to retrieve the right quantity and the right product
  name, and expect my view to display it.  (very generic)

Surely, Business would expect application to behave the same way a developer had written in some of its functional test, so in this case, an acceptance test would be:

Given Bob enters in the product list page, when he clicks on the
  button "addToBasket" near to the "Nike basket n°2" product, basket
  should display quantity '1' and "Nike basket n°2". (specification by example)

Both tests are very similar, aren't they?

So my question is: Do we risk to create a lot of duplication code and redundant tests while creating functional and acceptance tests in parallel?

What is a good practice? Making functional test carry about some pure technical things only, like exceptional/buggy behaviours, inconsistent variables scenarios etc... and let acceptance tests deal with the whole business scenarios side?

I would even say: Is functional testing really needed when we attach a huge importance to acceptance test?

答:
yes, there can be duplication.   Often with line of business type websites, you find the acceptance tests can actually substitute for developer oriented tests, because the depth of code needed to implement features is not too great.  As a comparison, image recognition software may have huge depth, but at an acceptance level it might be simple as needs to recognize this as a circle, and this as a square.  Developer wise, you need to test your image capture, light correction, object detection, object recognition, blah blah....

So if you have a shallow amount of code between acceptance and implementation, it quite often does feel redundant.

However, there are a few other differences in terms of process.  You can have a suite of acceptance tests build up, and they don't all have to pass all the time,  they can act as targets, so you go from 5% passed, to 10% to 50% etc, until you knock all the tests off. In some cases, ideally these tests can be put together semi independently of the developer. Developer oriented tests, the intention there is to have them passing all the time.


答:
Yes, Tests should exist at multiple levels, in multiple forms and yes, you will see a lot of redundancy.

For example in a MVC you may have test in all three places that are checking on the value of an attribute.  This can be seen as as a positive thing because then you can change any piece and know the effect of the change.

So yes, as you mention the different tests should test different things.  Database tests can exercise CRUD operations and check the results, middleware can be tested similarly and can be used to actually drive the development (TDD).

Front-end tests can make sure that the user actually ends up seeing the intended results, regardless of the vagaries of output devices and versions.

Title: Functional testing and Acceptance testing leading to redundant code

Body:
What I know is:

A Functional test aims to test a single component (like a WebApp's Controller) from the point of view of the developer. => Did I achieve all the requirements to make it work well?

An Acceptance test aims to to test a group of components together and is focused on the Business point of view. => Does my program fulfill requirements provided by the Client/Business/Customer?

Today, I work on a personal project and I started following BDD/testing methods and thus created Acceptance tests and Functional tests.

I notice that a lot of requirement for functional tests are exactly the same that Acceptance tests need.

Suppose a webapp controller aiming to add a product to my e-commerce's basket.

One of concerned functional tests would be:

When I go to productList.html page and I call the addProductToBasket action, I expect my controller to retrieve the right quantity and the right product
  name, and expect my view to display it.  (very generic)

Surely, Business would expect application to behave the same way a developer had written in some of its functional test, so in this case, an acceptance test would be:

Given Bob enters in the product list page, when he clicks on the
  button "addToBasket" near to the "Nike basket n°2" product, basket
  should display quantity '1' and "Nike basket n°2". (specification by example)

Both tests are very similar, aren't they?

So my question is: Do we risk to create a lot of duplication code and redundant tests while creating functional and acceptance tests in parallel?

What is a good practice? Making functional test carry about some pure technical things only, like exceptional/buggy behaviours, inconsistent variables scenarios etc... and let acceptance tests deal with the whole business scenarios side?

I would even say: Is functional testing really needed when we attach a huge importance to acceptance test?


问:
What's the most effective way to perform code reviews?
I've never found the ideal way to perform code reviews and yet often my customers require them. Each customer seems to do them in a different way and I've never felt satisfied in any of them.

What has been the most effective way for you to perform code reviews?

For example:

Is one person regarded as the gatekeeper for quality and reviews the code, or do the team own the standard?

Do you do review code as a team exercise using a projector?

Is it done in person, via email or using a tool?

Do you eschew reviews and use things like pair programming and collective code ownership to ensure code quality?

答:
We find the most effective way to do do code reviews is 1-on-1 using github to show the differences in the branch.

Is one person regarded as the gatekeeper for quality and reviews the code, or do the team own the standard?

Depends on the size of the team - team of 3 will have 1 senior who has the best knowledge of good practices, whereas a team of 12 may have 3 or 4 people who will fulfill that role.

Do you do review code as a team exercise using a projector?

In person. 1 on 1 to be less threatening.  Sometimes done in the communal area though for knowledge spread. Depends on the exact situation, people, timetable, etc.

Is it done in person, via email or using a tool?

In person.  We use git and github and it has great code review and diff comparison tools to make code review easier.

Do you eschew reviews and use things like pair programming and collective code ownership to ensure code quality?

We try to do both as appropriate.  That means that when stuck on a particularly thorny problem, or when working on core infrastructure or when preparing for vacation or leaving the company, pairing may be done to share and transfer knowledge.  Most code or code that has anything more than cosmetic changes should be reviewed at the end as well.

As with all coding items, the right answer should take into account:

Type of company (e.g. startup vs. large corporation)

Company Size

Number of developers

Budget

Timeframe

Workload

Complexity of code

Ability of reviewer(s)

Availability of reviewer(s)


问:
Why Android created emulator rather simulator?
From https://stackoverflow.com/questions/4544588/difference-between-iphone-simulator-and-android-emulator

The difference between emulators and simulators is that emulators mimic the software and hardware environments found on actual devices. Simulators, on the other hand, only mimic the software environment; they otherwise have access to all of the host system's hardware resources such as disk space, memory and processor speed.

Apple always harps on the importance of device testing because iPhone Simulator does not emulate an iPhone processor, disk drive, memory constraints and whatnot. You hardly ever get memory warnings unless your Mac is struggling to manage resources itself, unless you simulate (again) memory warnings from the Simulator's menu item.

Though android emulator emulates the ARM processors and certain hardware, it still doesn't do a good job of matching the CPU performance.

Being an emulator it can match Memory consumption well, it can emulate certain simple devices well but fails when the devices gets complicated for example mobile GPU and HW media decoders. And as the emulation logic works on translating each ARM instruction to X86 instruction and executing its a performance hog and by design not cycle accurate.

My Question: Why Android created emulator rather simulator?

答:
My guess is that even if Android apps have to be written in Java, they're allowed to include extra code written in any language and compiled to machine language with any compiler you wish.  To run those, you have to emulate a phone CPU.

(Yes, now there is Android for x86, but it's somewhat of a fringe platform.)

iOS, on the other hand, allows only Objective C, and compiled only with XCode.  it doesn't sound so hard to include two compilation targets in the SDK: one for devices and one for the simulator.


问:
Which approach to follow for developing applications targeting multiple platforms?
For applications targeting multiple platforms, I see mainly two development approaches-

Go for some JAVA-like development platform. Have one code solution and let the intermediate runtime handle different platforms. If something goes wrong in any platform, tweak the code a bit. But keep it same for all.

Make modular code separating core logic and UI. Develop separate UIs for respective platforms which will be calling same core libraries. Build the application separately for each of the target platforms.

So, which one to follow? I know, the answer will start with "It depends". But I want to hear your opinions on these approaches and the factors to be considered to choose any of them.

答:
Current Oracle/Apache/Google squabbles aside, it's still hard to beat the JVM for this purpose. It's really very high quality on most platforms, universal, and you have a good number of languages to choose from (Java, Clojure, Scala etc.). It lets you target a single machine architecture (the VM), and not worry too much about the specific end-user hardware.

That said, there are certain application types it may not be as suitable for: low-level networking comes to mind, as does heavy graphics/video processing.


问:
Is Rebol a functional programming language?
I ran into Rebol and I was wondering about it.

I ran into the following script from here:

```<code> use [feed questions answers][
    feed: load-xml/dom http://stackoverflow.com/feeds/tag/rebol
    questions: map-each entry feed/get-by-tag <entry> [
        find/match entry/get <id> "http://stackoverflow.com/q/"
    ]

    answers: make block! length? questions

    foreach question questions [
        question: load-xml/dom join http://stackoverflow.com/feeds/question/ question
        foreach entry next question/get-by-tag <entry> [append answers entry/tree]
    ]

    insert clear feed/find-element <entry> answers
    feed/flatten
 ]
</code>```

All the collection manipulation operations like map-each remind me of JavaScript and C# both of which have functional abilities.

Is Rebol a functional language? Does it support functional programming? Would it classify as a pure functional language (PFL)?

答:
"Pure Functional Programming" in its formal definition is about the idea of designing computational machines whose output is purely "a function of the input to the machine".  If you feed the same input into the machine, it will produce the same output.  Each input is named explicitly so you know precisely what the dependencies are.  A pure functional programming language enforces this rigorously.

Yet... in baseline "Rebol" you can write things like:

```<code>foo: function [value [integer!]] [
    either now/date = 20-Feb-2013 [
        value + 1
    ] [
        value
    ]
]
</code>```

Here we see a function that returns its integer input on every day but today, where you get the value plus one.  It includes an invisible dependency on the date which is not formally specified as an argument to the function.  It's the sort of thing that makes Haskell people and software formalists like myself scream bloody murder.

Hence Rebol is not pure functional out of the box.  (...but read on...)

The less strict definition of functional programming is when functions can act as values in the language.  So you can assign a function to a variable, and use it later.  In that sense, you can go read the likes of is javascript a functional language and see that the dicey definition would lead some people to say Javascript is a functional language.  If you're going to be that loose with the definition then this would be "functional":

```<code>>> foo: does [a + 10]

>> a: 20

>> print foo
== 30
</code>```

(Note: DOES is a convenience for defining a function with no arguments, that has only a body.)

I don't know that I'd consider that (or JavaScript) to fit what people I talk to would call functional programming.  YMMV.

If you spend any time in computer science you learn about things like Turing Tarpits and computability and these sort of principles of equivalences where "if you can connect X to Y then Z will be true".  And just as you can write a Haskell implementation in C, and then restrict yourself to only using C calls mapped into the Haskell library, you might claim you're doing "functional programming" and be technically correct.

So if you wanted to say Rebol can be bent to functional programming styles, you might be a pessimist and say "well it's no better than pretending you're doing C when you're actually using such a confined subset of the language that you're using Haskell by proxy".  The trick up Rebol's sleeve is how easily you slip from one "dialecting" paradigm to another.  Writing a little domain-specific-language that happens to be functional is so easy and natural that it doesn't feel like you're twisting your language out of joint to do it.  The ability to make domain specific languages that have functional character leads to the labeling of Rebol as "paradigm neutral".

Many people mix up Rebol with its most common dialect (the DO dialect) and think "that's what Rebol is".  But Rebol's "essence" is more like XML, it's a data exchange format that coincidentally (okay, not coincidentally) has hyper-optimized code focusing on processing it in some certain ways out of the box.  For a good background reading on how it beats the pants off XML, see Was XML flawed from the Start by Carl Sassenrath of AmigaOS (and now Rebol) fame.

Body:
"Pure Functional Programming" in its formal definition is about the idea of designing computational machines whose output is purely "a function of the input to the machine".  If you feed the same input into the machine, it will produce the same output.  Each input is named explicitly so you know precisely what the dependencies are.  A pure functional programming language enforces this rigorously.

Yet... in baseline "Rebol" you can write things like:

foo: function [value [integer!]] [
    either now/date = 20-Feb-2013 [
        value + 1
    ] [
        value
    ]
]

Here we see a function that returns its integer input on every day but today, where you get the value plus one.  It includes an invisible dependency on the date which is not formally specified as an argument to the function.  It's the sort of thing that makes Haskell people and software formalists like myself scream bloody murder.

Hence Rebol is not pure functional out of the box.  (...but read on...)

The less strict definition of functional programming is when functions can act as values in the language.  So you can assign a function to a variable, and use it later.  In that sense, you can go read the likes of is javascript a functional language and see that the dicey definition would lead some people to say Javascript is a functional language.  If you're going to be that loose with the definition then this would be "functional":

>> foo: does [a + 10]

>> a: 20

>> print foo
== 30

(Note: DOES is a convenience for defining a function with no arguments, that has only a body.)

I don't know that I'd consider that (or JavaScript) to fit what people I talk to would call functional programming.  YMMV.

If you spend any time in computer science you learn about things like Turing Tarpits and computability and these sort of principles of equivalences where "if you can connect X to Y then Z will be true".  And just as you can write a Haskell implementation in C, and then restrict yourself to only using C calls mapped into the Haskell library, you might claim you're doing "functional programming" and be technically correct.

So if you wanted to say Rebol can be bent to functional programming styles, you might be a pessimist and say "well it's no better than pretending you're doing C when you're actually using such a confined subset of the language that you're using Haskell by proxy".  The trick up Rebol's sleeve is how easily you slip from one "dialecting" paradigm to another.  Writing a little domain-specific-language that happens to be functional is so easy and natural that it doesn't feel like you're twisting your language out of joint to do it.  The ability to make domain specific languages that have functional character leads to the labeling of Rebol as "paradigm neutral".

Many people mix up Rebol with its most common dialect (the DO dialect) and think "that's what Rebol is".  But Rebol's "essence" is more like XML, it's a data exchange format that coincidentally (okay, not coincidentally) has hyper-optimized code focusing on processing it in some certain ways out of the box.  For a good background reading on how it beats the pants off XML, see Was XML flawed from the Start by Carl Sassenrath of AmigaOS (and now Rebol) fame.


答:
I have worked at many companies and seen many processes.  My current team handles this the best I have seen so far.

We use an agile development process and as part of that we have gates that each story has to go through.  One of those gates is the code review.  The story doesn't move to test until the code review is done.

Additionally we store our code at github.com.  So after a developer finishes their change, they post the link to the commit(s) on the story.

Then we tag a fellow developer to review.  Github has a comments system that allows for someone to comment right on the line of code in question.  Github then sends an email to the distro, so sometimes we actually get extra eyes from some of our other teams.

This process has worked very well for us.  We do use an agile process tool that makes posting the commits easy as well as facilitating communication.

If an issue is particularly sticky we will sit down and discuss it.  This works because it is integral to our process and everyone has buy in on how the process works.  We can move tickets back to in progress if the code review results in needed rework and then it can be reviewed again after changes are made, or the reviewer may note on the story that fixing the items is sufficient and doesn't need reviewed again.

If testing kicks something back it goes all the way back to in progress and any further changes are also reviewed.

Title: What's the most effective way to perform code reviews?

Body:
I've never found the ideal way to perform code reviews and yet often my customers require them. Each customer seems to do them in a different way and I've never felt satisfied in any of them.

What has been the most effective way for you to perform code reviews?

For example:

Is one person regarded as the gatekeeper for quality and reviews the code, or do the team own the standard?

Do you do review code as a team exercise using a projector?

Is it done in person, via email or using a tool?

Do you eschew reviews and use things like pair programming and collective code ownership to ensure code quality?


问:
Should I write a test to prove that deleting code fixes a bug?
Occasionally I'll run into the situation where fixing a bug requires that I delete a section of code. The TDD purist would (I assume) advocate writing a failing test, deleting the code, then watching the test pass.

Now, it seems really strange to have a test asserting that some code was removed. Sure, I suppose it would ensure no one dug into source control and put that code back in, but is it worth it? If it is worth it, it certainly seems less valuable than writing a test for code that has been added, right?

答:
You're looking at it the wrong way. The test does not assert that code was removed. The test does assert a certain functionality.

The test does not care about the amount of code required to make it pass, nor does it realize that you have removed some code. The value of having such a test is the very same as any other test that you create due to a bug: you have confidence in the absence of the bug when the test passes and the test's integration into the build process ensures you that the bug will most likely not be reintroduced.

Yet another way to look at it from a TDD perspective is the following: When you know that deleting the code fixes the bug and you then wonder whether to write a test, you already did TDD wrong. Once you start working on the bug you should first write the test that ensures the bug's presence by failing. Only afterwards do you fix the actual bug - which may require removing code or not - and make the test pass. The question you are asking does not even arise in that way.


问:
Calculating local results from global values using SQL and PHP
I have an interesting problem for you all. I have a partial solution but I feel you guys can come up with an efficient solution.

What I have a SQL table with following structure:

StockId <- a unique ID for the share

StockHolderId <- a unique ID for the share holder

StockPrice <- The price of the stock - if this is a request to purchase this is kept -1

BuyingorSelling <- value of 1 means the holder wants to buy, value 2 means he is selling

StockQuality <- a special record that stores a value calculated based on some complex
computation. The values are 1, 2, or 3 based on let us say bad, neutral, good.

What I want to do is to find out who all can give me the stock I want to buy and who can purchase the ones I got. I want the person who gives a good quality stock (local value) at cheapest price (global value) to be my best selling match and the person who can buy most (semi global) of my stocks to be my best buying match.

The formula to rank the seller is  0.5 * price + 0.3 * availability + 0.2 * quality.

How would you go about it? Any ideas? I have created a table that joins with itself to get info of every match and then grouping but how can I acquire the price value to be cheapest?

答: Without seeing the query I can't be too helpful, but on the surface level it sounds like a simple ORDER BY clause and a LIMIT.</p>


问:
Zend Framework View Helper Composition
So I'm reviewing a piece of code that is a perfect candidate to be abstracted away into a view helper. However at the moment, the piece of code uses two other view helpers to get the final display.

Now my question is, if a new view helper is created, is it recommended to inject the two helpers being used already, into the one created to get the final result needed?

I've not seen anything for or against, my initial feelings were that the code probably needs refactoring, but I don't think the dev will be willing to, so what I have outlined seemed like a nice middle ground.

答: I don't particularly like the ideas of a) duplicating code, b) having a view helper that has a coupling dependency to two other view helpers. Either write code to handle the needs in the singular view helper, or refactor and extend an abstract view helper in each implementation so all three classes can access the same functions in their appropriate scopes and the next developer can follow the code without a non-best practices hacked up solution.</p>

Title: Zend Framework View Helper Composition


问:
Is it a basic principle, or highly desirable, to have class methods that return "$this" rather than a value?
I've really just begun to learn OOP. I started about a year ago and have written probably 15,000 lines of it. But I wrote it all with hardly any experience looking at other people's OOP.

Most of my class functions return a value or make a change to the class properties and return true/false. Some of the ones that return a value also save that value into a class property (after first checking if the class property is already set, which can avoid a database call).

Now I'm doing a lot of digging in Magento/Zend and I notice a lot of their class methods return "$this". As I understand it, unlike in regular functions, class methods that return $this act by reference not by value, so that you get back the same object you started with rather than a copy.

Is returning $this something that I should be doing much more of? Does it make the code easier to maintain and use? Is returning $this necessary in order to chain class methods?

答:
"A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object."

The real advantage to returning $this is in object composition design patterns, especially in Magento. Take for example the Mage_Core_Sales_Order_Invoice->capture() which returns $this. This method looks like:

```<code>  public function capture()
    {
        $this->getOrder()->getPayment()->capture($this);
        if ($this->getIsPaid()) {
            $this->pay();
        }
        return $this;
    }
</code>```

the line:

```<code>$this->getOrder()->getPayment()->capture($this);
</code>```

Passes the invoice model as a reference, very useful in object composition patterns. The return of $this is also a reference. So the method calling ->capture() on an invoice model can continue working with a chained object call next for contextual code readability.

Body:
"A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object."

The real advantage to returning $this is in object composition design patterns, especially in Magento. Take for example the Mage_Core_Sales_Order_Invoice->capture() which returns $this. This method looks like:

  public function capture()
    {
        $this->getOrder()->getPayment()->capture($this);
        if ($this->getIsPaid()) {
            $this->pay();
        }
        return $this;
    }

the line:

$this->getOrder()->getPayment()->capture($this);

Passes the invoice model as a reference, very useful in object composition patterns. The return of $this is also a reference. So the method calling ->capture() on an invoice model can continue working with a chained object call next for contextual code readability.


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
Sheer waste. An IT spend that had to be cut by many millions. So the way to do this was to fly the IT people in from all over the world. Put them up in a flash hotel for a week. Then in the building where the meetings were held, lay a new floor. Marble of course. And overnight, between the meetings each day, the building was redecorated. Thats every evening for a week.

Err... priorities anybody?

Fantasyland.


问:
OOP question for product catalog
I have a question bugging me for some days. I made a webshop for a good friend of me. The problem is I have an OOP class question.

People can buy some clothing in the shop. The problem arise how to show different information for different products?

What I have now is the following:

abstract Product class

Cloth extends Product

Trousers extends Product

Problem is that trousers can contain extra information like:

fiber type

structure

How can I show those information in the shop? I query for all products and receive the Product class with only the selling price and name? What is the correct way to figure out it is a trouser to show those information like fiber structure on the detail page?

答:
If you're using jsp or jsf technologies, you don't need to know beforehand what getters and setters a object has before you access it as a bean.  However, understandably, you may want to offer alternative views for these items.

So generally speaking, my approach would be to establish an enumerator type which all Product classes must return in an abstract method.  The method would be derived from all its children and give you an indicator of what type you're dealing with and you can manage it accordingly.  In otherwords, if your current object has type "Trousers", then you include a view for that object called views/Trousers.xhtml.  Alternatively, rather than return an enumerator, you could return the actual view for that object (be careful since two product types may share the same view i.e. Jeans + Trousers, so don't use that as an indicator of type).

In the view, you know the object has already met a precondition that it is of a certain type or has explicitly indicated that particular view.  At that point, you can safely call upon the properties of that object that you know it'll have.

I hope that answers your question.

Edit:

That may not scale well depending on the number of products and how often you have to change these products.  In that case, I recommend you return a string indicator instead.  With that string, you can establish some patterns such as using a view with the same string indicator, etc.  You could conceivably use the class name as an indicator of type, if otherwise not overridden in your derived classes.

Title: OOP question for product catalog


问:
Is LISP still useful in today's world? Which version is most used?
I try to teach myself a new programming language in regular intervals of time. Recently, I've read how Lisp and its dialects are at the complete opposite end of the spectrum from languages like C/C++, which made me curious enough to know more about it. However, two things are unclear to me, and I'm looking for guidance on them :

Is LISP still practiced/used in todays world, or is it a legacy language like FORTRAN/COBOL ? I mean, apart from maintaining existing code, is it used on new projects at all ?

What is the most widely used dialect ? I came across Scheme and Common Lisp as the 2 most prevalent dialects, and wanted your opinion as to which is the most favored/useful one to learn - and would be immensely gratified if you can suggest any resources for a rank beginner to start from.

While eager to learn a language which is fundamentally different from the procedural languages I'm used to, I don't want to invest undue effort in something if its totally obsolete - I'd still learn it if it was professionally "dead", but only with an academic perspective...

答:
If you want to learn Lisp today, I'd have a look at either racket, which is a fast scheme implementation (well, it actually departed a little from scheme, so it is its own dialect now) or clojure, which benefits from the JVM it runs on (so gazillions of libraries are available, plus you can make it interact with your own Java code).

Even if you don't learn it to actually use it, learning it is always beneficial : you learn new ways to think and deal with problems, even in other languages, once you've wrapped your mind around Lisp for a while.


问:
How to document events?
Code documentation is usually related to a piece of code, be it small (method-level) or larger (class- or namespace-level). However, it is always about the inputs and the outputs of that piece of code, possibly describing its behavior and caveats.

It doesn't make much sense to document events fired by a class in the methods that may fire them: they may be duplicated and, by the definition of events, the listener is not expected to care about what triggers them, only handling them.

Documenting all events at the top of a class seems quite heavy, as someone willing to get an overview of the class behavior might not be so interested at deep diving at this “secondary interface”.

This problem is mitigated in strongly-typed languages such as Java (yes, unless you use anonymous classes, but it doesn't seem so common), as the events will be defined in their own classes, which can then be documented.

But, in languages with looser types, where an event is simply a String identifier and a series of parameters, it is much more difficult to find the proper place for documenting these id/params combinations.

So: where should fired events be documented in languages that don't model them explicitly?

答:
First, events are not secondary interface. They fully belong to the interface.

I document them in three parts:

at the sender's side: list of events that can be raised.

at the receiver's side: list of events that can trigger an action.

at a specific module where all events are declared: full description of each event.

Title: How to document events?


答:
It belongs in side documentation, which is usually called a reference. Such documentation, as you outlined it, doesn't belong to the class/method documentation, so the best place is to have dedicated documentation for them.

For exemple, take a look at how Symfony2 documents its exposed internal events: http://symfony.com/doc/current/reference/events.html

Don't be too quick to dismiss events as "secondary interface". They usually are quite the opposite, as they are the main way to extend functionnality in a really loosely coupled way.

Title: How to document events?

Body:
Code documentation is usually related to a piece of code, be it small (method-level) or larger (class- or namespace-level). However, it is always about the inputs and the outputs of that piece of code, possibly describing its behavior and caveats.

It doesn't make much sense to document events fired by a class in the methods that may fire them: they may be duplicated and, by the definition of events, the listener is not expected to care about what triggers them, only handling them.

Documenting all events at the top of a class seems quite heavy, as someone willing to get an overview of the class behavior might not be so interested at deep diving at this “secondary interface”.

This problem is mitigated in strongly-typed languages such as Java (yes, unless you use anonymous classes, but it doesn't seem so common), as the events will be defined in their own classes, which can then be documented.

But, in languages with looser types, where an event is simply a String identifier and a series of parameters, it is much more difficult to find the proper place for documenting these id/params combinations.

So: where should fired events be documented in languages that don't model them explicitly?