答:
About 2~3 hours into the project.

Just joking. There is not one good answer that will fit all situations. First of all, if you have a distributed version control system (like git or Mercurial) then commiting to your local repo is not going to preserve your data in the case of catastrophic failure. But a private remote repo may cost you money, e.g. on github. You will preserve the commit history, but in my experience you are not going to need that until your project is a bit advanced.

Also you don't probably want too much churn at the beginning, especially if you are moving files around. Committing changes will be a burden if only a small one. You may even decide to throw the thing away. But if you lose changes which are not trivial to replicate then you will miss having made a backup copy, and version control systems make for extremely valuable backup systems.

Some people nowadays use DropBox or similar to store their code. It may be a good compromise at the beginning of a project since it takes zero effort to set up. It is however a barbaric habit in serious software development, especially if several people are touching the code at the same time.

So, I tend to set up version control whenever I have something that is valuable, i.e. not trivial to replicate. Value is subjective (and depends on one's capacities) so you will have to make your own judgment. At that point I store a second repo on an external disk, or on github if it is a public project or my paying account will hold it.


问:
When should I make the first commit to source control?
I'm never sure when a project is far enough along to first commit to source control. I tend to put off committing until the project is 'framework-complete,' and I primarily commit features from then on. (I haven't done any personal projects large enough to have a core framework too big for this.) I have a feeling this isn't best practice, though I'm not sure what could go wrong.

Let's say, for example, I have a project which consists of a single code file. It will take about 10 lines of boilerplate code, and 100 lines to get the project working with extremely basic functionality (1 or 2 features). Should I first check in:

The empty file?

The boilerplate code?

The first features?

At some other point?

Also, what are the reasons to check in at a specific point?

答: Other point of view more related to software testing (TDD approach) would be committing as soon as you have new tests cases in green. This would mean you have a new "unit" of code completed.</p>

ContentLicense: CC BY-SA 3.0


问:
How to organize my site's file system properly?
Doing some reading on Stack Overflow, I've found a lot of information suggesting that proper organization of a file system is crucial to a well-written web app.  One of the key pieces of evidence is high-frequency references to "separation of concerns" in questions related to keeping programs organized.

Now, I've found some information on organizing file systems (Filesystem Hierarchy Standard) from 2004.  It raises only two concerns: first, the standard's a bit dated, so I believe it may be possible to do better given the changes in technology over the past 8 years; second, and most important, my application is very small compared to an entire Linux distro.  I think that the file system should be organized very differently because of that.

Here's what I'm looking at, currently:

```<code>/backup
/databases
/scripts
/www
  /www/dev
    /www/dev/login.php
    /www/dev/router.php
    /www/dev/admin pages (php files)
    /www/dev/sites
      /www/dev/sites/content types (php/html files)
      /www/dev/sites/static pages (php/html files)
      /www/dev/sites/modules
        /www/dev/sites/modules/module-specific-media
      /www/dev/sites/includes
      /www/dev/sites/css
      /www/dev/sites/media
  /www/production
    /www/production/login.php
    /www/production/router.php
    /www/production/admin pages (php files)
    /www/production/sites
      /www/production/sites/content types (php/html files; not a directory)
      /www/production/sites/static pages (php/html files; not a directory)
      /www/production/sites/modules
        /www/production/sites/modules/module-specific-media
      /www/production/sites/includes
      /www/production/sites/css
      /www/production/sites/media
</code>```

答:
There is no single structure which can fit all the cases. For example, if I compare the tree you quoted in your question with a web application I'm currently working on, it doesn't fit. For example, they separate static pages, while the separation between static and dynamic pages makes no sense in my context of my current app. They create a separate directory for CSS, while I have a single stylesheet which I put at the root and am happy to find it there. I don't have includes, but helpers and something comparable to partial views, etc.

If you create an application which stores and displays events, the logical structure would be by year, then by month, and finally by day.

If you create an application which has three logical parts in it, it should be reflected in the tree.

Also remember that actual file tree is only a tiny part of the project structure; for example, in ASP.NET MVC, nothing forbids you from creating your own virtual path provider and host data in a database rather than as files if it is more convenient and easy to understand for you and other developers who will work on your project later.

Sticking to a file structure some team invented to fit precisely their project needs is not a good idea in this regard.


问:
Is there something special about the number 65535?
2¹⁶-1 & 2⁵ = 2⁵ (or? obviously ?)

A developer asked me today what is bitwise 65535 & 32 i.e. 2¹⁶-1 & 2⁵ = ?
I thought at first spontaneously 32 but it seemed to easy whereupon I thought for several minutes and then answered 32. 32 seems to have been the correct answer but how? 65535=2¹⁶-1=1111111111111111 (but it doesn't seem right since this binary number all ones should be -1(?)), 32 = 100000
but I could not convert that in my head whereupon I anyway answered 32 since I had to answer something. Is the answer 32 in fact trivial? Is in the same way 2¹⁶-1 &
2⁵-1 =31? Why did the developer ask me about exactly 65535?

Binary what I was asked to evaluate was 1111111111111111 &
100000 but I don't understand why 1111111111111111 is not -1.
Shouldn't it be -1? Is 65535 a number that gives overflow and how do I know that?

答: It is trivial. 65535 in binary is all ones, so ANDing it with any X less than 65535 will give you X.


答:
The number is treated as an unsigned integer in this case which means all bits set will not produce -1 (if it were signed then yes, you would be correct). So all 16 bits set will give you 65535.

Interestingly enough though, signed state isn't a factor when doing logic bit-operations. Bits are themselves not signed as they are the lowest component in a computer. It's specified by the cpu operation if the bits in ex. a register will be treated signed or unsigned.

Negative numbers are produced by setting the most significant bit (MSB) to true IF the number is treated as signed (which "side", or which outer bit will be set varies depending on cpu architecture, ie. big-endian / little-endian) .

Title: Is there something special about the number 65535?

Body:
2¹⁶-1 & 2⁵ = 2⁵ (or? obviously ?)

A developer asked me today what is bitwise 65535 & 32 i.e. 2¹⁶-1 & 2⁵ = ?
I thought at first spontaneously 32 but it seemed to easy whereupon I thought for several minutes and then answered 32. 32 seems to have been the correct answer but how? 65535=2¹⁶-1=1111111111111111 (but it doesn't seem right since this binary number all ones should be -1(?)), 32 = 100000
but I could not convert that in my head whereupon I anyway answered 32 since I had to answer something. Is the answer 32 in fact trivial? Is in the same way 2¹⁶-1 &
2⁵-1 =31? Why did the developer ask me about exactly 65535?

Binary what I was asked to evaluate was 1111111111111111 &
100000 but I don't understand why 1111111111111111 is not -1.
Shouldn't it be -1? Is 65535 a number that gives overflow and how do I know that?


问:
Point me to info about constructing filters (of lists)
I would like some pointers to information which would help me understand how to go about providing the ability to filter a list of entities by their attributes as well as by attributes of related entities.

As an example, imagine a web app which provides order management of some kind. Orders and related entities are stored in a relational database. And imagine that the app has an interface which lists the orders.

The problem is: how does one allow the list to be filtered by, for example:-

order number (an attribute)

line item name (an attribute of a n-n related entity)

some text in an administrative note related to the order (text found in an attribute of a 1-1 related entity)

I'm trying to discover whether there is something like a standard, efficient way to construct the queries and the filtering form; or some possible strategies; or any theory on the topic; or some example code. My google foo fails me.

答:
You should have a look at ORM systems like Hibernate and its Criterias.

Aside from RDBMS you may look at Graph DBs like Neo4J and the Tinkerpop stack especially the Gremlin part.

For a Java solution see these two SO threads on filtering collections:

Java: Finding objects in collections

Java: What is the best way to filter a Collection?


问:
Testing vs QA - output?
I was trying to find a relevant source of information for the above, but I failed. What is the output of software testing? Some say its "list of bugs", others say "answer whether or not the software conforms to what customer wanted".
I know testing is a part of QA but not sure what is its aim and output in this context.</p>

答:
You miss the main point in the other answers:

Output of the QA is quality processes.

Output of the testing is an information about product quality.

Title: Testing vs QA - output?


问:
Quality Assurance tools discrepancies
It is a bit ironic, yesterday I answered a question related to this topic that was marked to be good and today I'm the one who asks. These are my thoughts and a question:

Also let's agree on the terms: QA is a set of activities that defines and implements processes during SW development. The common tool is the process audit. However, my colleague at work agrees with the opinion that reviews and inspections are also quality assurance tools, although most sources classify them as quality control.

I would say both sides are partially right: during inspections, we evaluate a physical product (clearly QC) but we see it as a white box so we can check its compliance with set processes (QA). Do you think it is the reason of the dichotomy among the authors? I know it is more like an academic question but it deserves the answer :)

答:
Personally, I think worrying about the distinction between quality control and quality assurance means you're more concerned about process than producing quality code. Frankly, the distinction between the words doesn't really matter.

All of the activities that relate to helping prevent defects and all of the activities that help catch defects before they go out the door are all related to quality. Call it "assurance", call it "control", it's really all the same.

Title: Quality Assurance tools discrepancies


问:
PHP frameworks - should I use them?
First of all let me explain who I am: I am a PHP Developer working for a company developing their CMS which handles online stores, data feeds and other content like blogs.  I have been programming for 6 years and 4 of those have been in PHP. (I used to be a C# developer).

My question is regarding PHP frameworks. I see so many jobs asking for zend, cakephp and other MVC types of frameworks. However, even as an experienced developer I have never used a PHP framework. Should I start learning? If so where do I even start as there are so many.

I am about to re-write so much of my work's CMS and I'm wondering whether I could help myself a lot by using a framework. What do people think? Considering I will be re-writing a lot of the online store stuff...
I am experienced in OO and I have used the .NET framework in the past.

Thanks in advance for the replies.

答:
In general, a framework is a tool which helps you to avoid reinventing the wheel, thus being more productive. In a particular case of PHP, a framework is also a way to abstract and hide some stupidities and inconsistency of PHP itself, while having a side effect to encourage some people to adhere to best practices in a context where the language itself encourages rather poorly written, poorly architectured code.

So yes, a PHP framework is definitely a thing you should learn if you want to be qualified as an experienced PHP programmer, while the choice of using it or not is up to you for every project you work on.

where do I even start as there are so many?

Learn two or three popular ones. Once you know those quite well, it wouldn't be difficult:

To know which one should fit a particular need for a given project,

To quickly discover less popular ones and see in which situations would they be more valuable compared to the ones you already know.

Title: PHP frameworks - should I use them?


答:
To my experience, there is a difference between the academic or Wikipedia definition of QA, and the way the term is used in the real world. In the real world, QA, especially software QA, is most times used synonymously with "testing", and in many companies the "QA team" is nothing than a test team. That is clearly not the definition you have in mind.

However, having worked some years in that field, I have also seen often "QA" to be meant as a generic term for all kinds of activities to ensure quality in a production process. This can be testing activities (which you would call a QC activity), constructive measures (like using the right tools for the job), or measures to inspect and improve the production process itself. By this use of term "QA", quality control is just a subset of QA.

Of course, QM systems like ISO 9000 focus only on the quality of the process, and probably your definition of QA here was inspired by a system like that. But that does not mean that this is the "only true definition" of QA; there are different definitions used in literature and between different kind of people. If I were you, I would learn to live with that. Just listen carefully when someone uses the term QA, which of the various possible definitions he has in mind.

Title: Quality Assurance tools discrepancies

Body:
It is a bit ironic, yesterday I answered a question related to this topic that was marked to be good and today I'm the one who asks. These are my thoughts and a question:

Also let's agree on the terms: QA is a set of activities that defines and implements processes during SW development. The common tool is the process audit. However, my colleague at work agrees with the opinion that reviews and inspections are also quality assurance tools, although most sources classify them as quality control.

I would say both sides are partially right: during inspections, we evaluate a physical product (clearly QC) but we see it as a white box so we can check its compliance with set processes (QA). Do you think it is the reason of the dichotomy among the authors? I know it is more like an academic question but it deserves the answer :)


问:
What core principles would you want in a library?
Theres talk about what syntax and feature you like in a programming language; i'll now ask what core principles or feature would you like in a library in your favorite (or any) language?

An example is having adding list += anotherList valid as oppose to only allowing list += listElement (although some may see this as a bad idea)

答:
Reasonable, healthy minimalism

That's all. Compare, as an example, the mechanism of pipes on Windows and UNIX. One offers a bunch of specialized API functions with a bunch of obscure, unnecessary or rarely used arguments, each of which can have one of the many macro/constant values. UNIX basically re-uses the existing open/read/write/close interface, plus a few very simple methods for some specific cases, such as socketpair() or pipe(). There is really almost, nearly nothing new you should learn in order to use pipes on UNIX. Now compare to this.

(To be fair, Microsoft originally only "borrowed" that interface from IBM's OS/2.)

ContentLicense: CC BY-SA 2.5


答:
how to go about providing the ability to filter a list of entities by their attributes as well as by attributes of related entities.

Some of the guidelines to consider are:

1 - What does the end user want and what information the end user has when she uses the system? Answering this should provide you with the primary queries to implement.

2 - Which queries are must have and which ones are nice to have. This classification would help you design your indexes better.

3 - For performance reasons, draw the line between an on-line query and a batch query (see point B below). Ask how frequent a given query is run and how often this is required. For frequent queries on large databases, you must create appropriate indexes. Some times the user may ask for statistical information on periodical basis. It is not always feasible to provide such reports on-line.

4 - Distinguish between a "search criteria" and a "filter criteria". The first could be used to generate 1 or more rows and the other is used to locate specific details within a specific result of executing a "search criteria".

In your case:

A - Order Number is good only if it is known. Ask how else could you locate an order? May be the userid of the person who placed the order with a given date range and an amount range would be good?

B - A Line item name/id, may be useful in some businesses but I can't see that it is a standard. Line item name/id is bad when you have to specify it in full, many items have the same name prefix, the item is common and appears on many orders, and so on. It may be useful as a filter argument for a specific large order (as those used in manufacturing for example). It also may be meaningful to consider searching line items appearing together with other line items. In some businesses, you could discover that certain items are always ordered together and the business could use this information to enhance their business. However, such a discovery process is best handled by off-line reports when the database is large.

C - Searching the Notes on an order is possible but ask why is there a note in the first place? May be the note is used to capture a 'reason' or a 'category' information that deserve to be placed on 1 or more separate columns. For example, the user may want to list orders that are partially delivered. Some systems use the note field to represent many unstructured information. Searching text may return inconsistent results. Some database allow you search text efficiently, but you still have to live with free form information and may cause the user to ask the system to return large amounts of data to be searched manually. To avoid this, you may want to analyze the notes contents as mentioned earlier or to use standard tags. This board uses both methods.

Title: Point me to info about constructing filters (of lists)

Body:
I would like some pointers to information which would help me understand how to go about providing the ability to filter a list of entities by their attributes as well as by attributes of related entities.

As an example, imagine a web app which provides order management of some kind. Orders and related entities are stored in a relational database. And imagine that the app has an interface which lists the orders.

The problem is: how does one allow the list to be filtered by, for example:-

order number (an attribute)

line item name (an attribute of a n-n related entity)

some text in an administrative note related to the order (text found in an attribute of a 1-1 related entity)

I'm trying to discover whether there is something like a standard, efficient way to construct the queries and the filtering form; or some possible strategies; or any theory on the topic; or some example code. My google foo fails me.


问:
What camera to choose for using with JMF (Java Media Framework)
For the past 2-3 weeks I've been searching for different ways to implement custom video streaming and in more general video capturing and manipulating, going through DVR-cards, Video Capture Cards and stuff like that.

Somehow JMF was able to stay out of my sight for all this time, but since I find out about it I'm more and more sure that this is a comfortable level for me to start playing around with video and stuff.

One major topic that occurs to me while searching for more info was the presence of many posts where people were complaining about the fact that any particular camera ( most of the time I think they mean web cameras) doesn't work with JMF. Even though there are a lot of different cameras (not necessarily a web cam) that are not that expensive I want to play it safe and buy one that is proven to work well with the JMF.

Also due to lack of experience maybe this is irrelevant but since I'll buy the camera mostly for learning and experimenting I want to have the maximum freedom possible to mess with different features, options and so on.

答:
I currently support legacy software that uses JMF to integrate a web camera into a Java based kiosk software.

While it is neat to play around with if you are learning, I would highly recommend against using it in any production application you are planning.  The following are a number of drawbacks:

It is a Dead Project

It hasn't been active for over 5 years now, meaning that there could be compatibility issues in future versions of the operating system that make it completely incompatible.  Further, any bugs that you might run into will never be fixed.

It is Closed Source

Even if you encounter a bug and feel adventurous enough to try and fix it, you will not be able to because it is closed source and Oracle has no intention of distributing it.

It is Old

It is painfully old and really is only a good solution for a Windows environment.  Perhaps you would like to run your application on a Mac or Linux, it wouldn't work very well as support for these is lacking.

It must be installed on the client

There are a number of binaries that must be installed on the client machine for it to work correctly, other libraries don't require this.

Knowing all of that I will say that I have tried JMF on a vast number of web cameras, integrated and standalone and it was perfectly compatible with them (on Windows).  I have never once encountered a webcam that it wasn't able to recognize or use.

There is the FMJ project which is an open source replacement for JMF, however it seemed a bit buggy to me and I had trouble getting it to work correctly.  It does not appear to be fully featured.

My personal recommendation is JavaCV.  It is an open source Java wrapper to the popular OpenCV framework, which wraps functionality for media devices and hardware accelerated media allowing this functionality to be easily used within a Java application that is truly Write Once, Run Anywhere.

Without having to install OpenCV, I was able to write a Java WebStart application (with full permissions of course) to utilize a webcam on multiple operating systems.  The learning curve is a bit higher though.

While JMF is easy to get started with and has a lower learning curve, JavaCV is far and away the better choice for webcam integration and capture in a Java application.


答:
It seems to me that the choice to use PHP will lead to you either using someone else's framework or building one.

"Framework hell" is a very real problem (or set of related problems) that are not unique to PHP, and there are no "silver bullet" frameworks.  In short, all frameworks are 90% solutions in the end;  Early progress in developing with a framework will almost always be faster than without.  Getting the last 10% of the way is going to be either (a) really hard or (b) consist mostly of giving in and letting the framework win, and decide some elements or limitations of your design.

I say all of the above without saying that any framework is great, or bad.  Such a question is unanswerable.  Try a framework on a small project or a small chunk of your big project, and see if it fits.  Be ready to kick it to the curb if you determine it doesn't work for you.

There are enough frameworks for PHP that you could probably evaluate them forever. But sooner or later you'll find one that's close enough.  Close enough is enough for Rock and Roll, and many PHP websites.

Title: PHP frameworks - should I use them?

Body:
First of all let me explain who I am: I am a PHP Developer working for a company developing their CMS which handles online stores, data feeds and other content like blogs.  I have been programming for 6 years and 4 of those have been in PHP. (I used to be a C# developer).

My question is regarding PHP frameworks. I see so many jobs asking for zend, cakephp and other MVC types of frameworks. However, even as an experienced developer I have never used a PHP framework. Should I start learning? If so where do I even start as there are so many.

I am about to re-write so much of my work's CMS and I'm wondering whether I could help myself a lot by using a framework. What do people think? Considering I will be re-writing a lot of the online store stuff...
I am experienced in OO and I have used the .NET framework in the past.

Thanks in advance for the replies.


答:
Testing is merely a quality control activity that is used as a measure of the suitability of the software for its purpose. As others have eluded to, testing, on its own, is not very useful. You need to have a process that describes what to do with the outputs of testing, and along with other inputs, is used to improve the product. This process of software testing / verification / validation is, although important, a small part of the Quality Assurance process.  Therefore, the output software testing is an input into the QA process.

The Quality Assurance process encompasses the entire business, and is used to drive the activities (and measure the results) that occur in the production of the product. Software is more than just a program written by programmers, and QA cannot achieved in isolation of  business  goals and non- software development activities. QA also defines such activities as code inspection, requirements management etc, that are not a part of testing, but are shown to improve product quality.

Note: Within the software community these ideas and terms are not well understood, and as a rule, we programmers naively equate QA===QC===Test. You are likely to get better and more accurate answers referring material and web sites focused on Quality Management rather than Software. Stay away from sites that use QA and Testing in the same sentence.

Title: Testing vs QA - output?

Body:
I was trying to find a relevant source of information for the above, but I failed. What is the output of software testing? Some say its "list of bugs", others say "answer whether or not the software conforms to what customer wanted".
I know testing is a part of QA but not sure what is its aim and output in this context.</p>


问:
Why shouldn't I be using public variables in my Java class?
In school, I've been told many times to stop using public for my variables. I haven't asked why yet.

This question: Are Java's public fields just a tragic historical design flaw at this point? seems kinda related to this. However, they don't seem to discuss why is it "wrong", but instead focus on how can they use them instead.

Look at this (unfinished) class:

```<code>public class Reporte {

    public String rutaOriginal;
    public String rutaNueva;
    public int bytesOriginales;
    public int bytesFinales;
    public float ganancia;

    /**
     * Constructor para objetos de la clase Reporte
     */
    public Reporte() {

    }
}
</code>```

No need to understand Spanish. All this class does is hold some statistics (those public fields) and then do some operations with them (later).

I will also need to be modifying those variables often. But well, since I've been told not to use public, this is what I ended up doing:

```<code>public class Reporte {

    private String rutaOriginal;
    private String rutaNueva;
    private int bytesOriginales;
    private int bytesFinales;
    private float ganancia;

    /**
     * Constructor para objetos de la clase Reporte
     */
    public Reporte() {

    }

    public String getRutaOriginal() {
        return rutaOriginal;
    }

    public String getRutaNueva() {
        return rutaNueva;
    }

    public int getBytesOriginales() {
        return bytesOriginales;
    }

    public int getBytesFinales() {
        return bytesFinales;
    }

    public float getGanancia() {
        return ganancia;
    }

    public void setRutaOriginal(String rutaOriginal) {
        this.rutaOriginal = rutaOriginal;
    }

    public void setRutaNueva(String rutaNueva) {
        this.rutaNueva = rutaNueva;
    }

    public void setBytesOriginales(int bytesOriginales) {
        this.bytesOriginales = bytesOriginales;
    }

    public void setBytesFinales(int bytesFinales) {
        this.bytesFinales = bytesFinales;
    }

    public void setGanancia(float ganancia) {
        this.ganancia = ganancia;
    }
}
</code>```

Looks kinda pretty. But seems like a waste of time.

Google searches about "When to use public in Java" and "Why shouldn't I use public in Java" seem to discuss about a concept of mutability, although I'm not really sure how to interpret such discussions. I do want my class to be mutable - all the time.

答:
It breaks encapsulation - the core principle here is that the fields of your class are implementation details, by exposing it as a public field, you are telling everything outside that class that it is an actual piece of data that is stored by the class - something external classes don't need to know, they just need to be able to get or set that piece of data. As soon as you make something public, external classes should be able to depend on it, and it should not change often, by implementing as a method, you are retaining the flexibility to change the implementation at a later point without affecting users of the class.

If you wanted to change one of the fields so it's calculated, or retrieved from a service when its called, you wouldn't be able to without breaking other parts of your application. Other reasons are that it allows you to control access to the variable (i.e. make it immutable as you already highlighted). In setters you can also add checking code, and you can add behaviors to getters and setters that do other things when a variable is get or set (though this may not always be a good thing). You can also override a method in a derived class, you can't override a field.

There are some very rare situations where it is better to have public field instead of a method - but this really only applies in very high performance applications (3D games & financial trading applications), unless you are writing one of these, avoid public fields - and if you do care about performance to that level, Java is probably not the best choice anyway.

Just a note on mutability - in general you should try to make things immutable until you have a genuine reason to make them mutable - the less your code exposes in its public API, the easier it is for long term maintenance, and in a multi-threaded situation, immutable objects are threadsafe, mutable objects need to implement locking.


答: Frameworks are great for reducing ramp-up time. Using a well known package and following industry-wide conventions is the difference between a developer new to the project making meaningful contributions within hours vs. days, or even weeks.</p>

Title: PHP frameworks - should I use them?


问:
As a programmer, are you required to do timesheets?
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?

答:
I have to fill out multiple timesheets.

First there's the timesheet that goes to HR.  That timesheet simply shows worked/not worked, and is used to track PTO and sick days.  So it always is filled out in multiples of 8 (out all day or working all day).

Then there's the timesheet that goes to the business.  I work software development in a large corporation; most (99%) of our projects are for internal users.  These projects are charged to the users on a by-the-hour basis;  so a project for, say, the Legal department will be charged to the Legal department's budget.  This timesheet is the most politicized;  there is pressure from the IT management to charge as much of your time as possible to the projects, and pressure from the project owners to charge as much time as possible to IT (i.e., staff meetings, informal training, etc.).  Further, before any work is done on any project, it is 'estimated' and a certain 'budget' of hours is allotted. So in order to stretch the hours, there is pressure from all parties to get creative with the timesheet; marking 8 hours in a given day to the same project sets off a red flag that triggers 3+ managers hitting up your cube.  Overtime is NEVER marked, as it serves no purpose (my pay is the same, and it decreases the available hours faster).  Accuracy in this timesheet can be detrimental to your career.

Finally, there's the project timesheet.  This is the one that goes to the project owners;  its not broken down by date, but by hour.  So this is the sheet that says "I spent 9 hours on your project this week;  tasks A and B were accomplished, and bugs X and Y were corrected.".  This timesheet is a work of complete fiction; given that it gets its hours number from the previous timesheet, the tasks-to-time ratio is completely inaccurate.  However, this timesheet is really only used to determine whether or not we've reached milestone X by a given hour usage Y, so its more a general gauge of progress than anything else.


问:
Branding/Restricting a Software by License/Serial
I have made a POS System for a client of mine using MS Access Server-Client approach.

He asked me to brand his software to allow only a certain "number" of users (cashiers) to access the POS System, and must be determined to the license his client will buy.

EX: 10 User License = 10 Cashiers ( not necessarily 10 users, it can be 30 users, shifting) = it means 10 PCs will be installed with the client software I made.

How and where do I put the logic that will determine if it is licensed or not.

What I have done:

I have created a serial key generator using Name. Problem is it can be duplicated once you give than name+serial combination, it would still work.

I am counting the number of users logged at a time. This could be problematic as I am using MSAccess and not MSSQL. I have scrapped this idea,

He also asked me if I could just put serial+mac address combination. That I could do but he will have a hard time implementing it and selling it if he needs the mac address of every computers to be installed with my POS.

I am at lost on what can I do. Would like to ask for tips and suggestions.

Thank you.

答:
Tying licencing to MAC addresses isn't perfect (since the software could run on a virtual machine or use some other kind of MAC spoofing), but it isn't necessarily unduly onerous. You just need to create a utility which he (or a reseller) can run on the target machines which harvests the MAC addresses and creates a digitally signed license file.

You could also consider using a hardware dongle.


答:
It may depend which VCS you are using.

With Git, I commit an empty directory (or with a nearly empty README file). The point is that I can go back and reset my branch to that empty state if I want to completely start over while I'm still early in the development process (before pushing upstream). I would then commit my "generated" files (e.g. visual studio solution). Then when I am actually coding I'll start committing each unit as you normally would.

With SVN, you are pushing upstream with each commit so you really don't get the luxury of starting over like you do with Git. In this case, it may not be beneficial to commit early if you think you'll be doing major revamping early on in the process. That's going to be up to the person coding though.

Title: When should I make the first commit to source control?

Body:
I'm never sure when a project is far enough along to first commit to source control. I tend to put off committing until the project is 'framework-complete,' and I primarily commit features from then on. (I haven't done any personal projects large enough to have a core framework too big for this.) I have a feeling this isn't best practice, though I'm not sure what could go wrong.

Let's say, for example, I have a project which consists of a single code file. It will take about 10 lines of boilerplate code, and 100 lines to get the project working with extremely basic functionality (1 or 2 features). Should I first check in:

The empty file?

The boilerplate code?

The first features?

At some other point?

Also, what are the reasons to check in at a specific point?


问:
Identifier for the “completed” stage of a process: 0, 99, something else?
Say, that you are handling a multi-step process (like a complex registration form, with a number of steps the user has go through in order). You need to be able to save the current state of the process (e.g. so the user can come back to that registration form later and continue form the step where they were left off).

Obviously, you’ll probably want to give each “step” an identifier you can refer to: 1, 2, 3, 4, etc. Your logic will check for this step_id (or whatever you call it) to render the appropriate data.

The question: how would you identify the stage after the final step, like the completed registration state (say, that you have to give that last “step” its own id, that’s how your logic is structured). Would it be a 0, 999, a non-integer value, something else entirely?

答:
I would consider something like a state table (or stage table (or step table)).  This table would consist of an ID and a Description, and potentially anything else you feel needs to be associated with a state/stage/step. Just try to find some sort of relevant descriptor about each step - this hopefully wouldn't be too difficult.

1 - Start

2 - Personal Info

3 - Address Info

4 - Another state

5 - Completed

Ideally, additional steps would not be added down the road, but captured up front in the design process. Just a thought.


答:
People like to count in order, so systems like this often involve sorting the pages by ID number.  Page IDs tend to go in steps of 10, though any arbitrary number can be chosen.  This allows you to later insert pages between existing pages without renumbering any existing pages.

Using an unusually high value such as 999 for the final page allows you to insert any reasonable number of pages without having to renumber your final page.  This is perfectly reasonable.

```<code> 10 Start page
 20 Welcome
 30 Select products to install
 35 Configure products          <-- Page inserted later
 40 Select folder to install to
 50 Confirm installation
 60 Display install progress
999 Finished
</code>```

Title: Identifier for the “completed” stage of a process: 0, 99, something else?

Body:
Say, that you are handling a multi-step process (like a complex registration form, with a number of steps the user has go through in order). You need to be able to save the current state of the process (e.g. so the user can come back to that registration form later and continue form the step where they were left off).

Obviously, you’ll probably want to give each “step” an identifier you can refer to: 1, 2, 3, 4, etc. Your logic will check for this step_id (or whatever you call it) to render the appropriate data.

The question: how would you identify the stage after the final step, like the completed registration state (say, that you have to give that last “step” its own id, that’s how your logic is structured). Would it be a 0, 999, a non-integer value, something else entirely?

Body:
People like to count in order, so systems like this often involve sorting the pages by ID number.  Page IDs tend to go in steps of 10, though any arbitrary number can be chosen.  This allows you to later insert pages between existing pages without renumbering any existing pages.

Using an unusually high value such as 999 for the final page allows you to insert any reasonable number of pages without having to renumber your final page.  This is perfectly reasonable.

 10 Start page
 20 Welcome
 30 Select products to install
 35 Configure products          <-- Page inserted later
 40 Select folder to install to
 50 Confirm installation
 60 Display install progress
999 Finished


问:
Which part of the Memory is used for the Garbage Collector?
I understand the Heap memory divisions such as Young, tenured and Perm Gen.
But I'm just curious from where is the memory used for performing the Garbage Collector itself? Is it from any of these memory spaces or in the thread stacks ?</p>

答: Any memory the GC itself needs to operate is either stack memory (for temporary computations it does), or from the "raw" heap, that is using the system malloc, or manually calling mmap.


答:
Whether you should 'learn frameworks' or not... no one here can tell you what you will need to know in the future.  I've been coding in PHP for over 10 years, and have never needed to use a 3rd party framework.  The types of projects I work on just dont call for it.  A lot of projects fall into that category.

That said, its important that you understand what the frameworks are doing.  Whether you do that by learning existing frameworks, or creating your own... thats what you should really be after.  Dont assume you'll be working in PHP or C#, for example, 10 years from now.  Understanding the concepts behind the frameworks will be what moves you forward.  Knowing the specifics of XYZ framework wont help you unless you expect to be locked into your current technology stack.

Title: PHP frameworks - should I use them?


答:
Whichever licensing scheme you come up with, any reasonably clever user could circumvent.

Why don't you hard code the user limit in the software, and, generate separate versions for 10,20,30 user licenses.

Title: Branding/Restricting a Software by License/Serial

Body:
I have made a POS System for a client of mine using MS Access Server-Client approach.

He asked me to brand his software to allow only a certain "number" of users (cashiers) to access the POS System, and must be determined to the license his client will buy.

EX: 10 User License = 10 Cashiers ( not necessarily 10 users, it can be 30 users, shifting) = it means 10 PCs will be installed with the client software I made.

How and where do I put the logic that will determine if it is licensed or not.

What I have done:

I have created a serial key generator using Name. Problem is it can be duplicated once you give than name+serial combination, it would still work.

I am counting the number of users logged at a time. This could be problematic as I am using MSAccess and not MSSQL. I have scrapped this idea,

He also asked me if I could just put serial+mac address combination. That I could do but he will have a hard time implementing it and selling it if he needs the mac address of every computers to be installed with my POS.

I am at lost on what can I do. Would like to ask for tips and suggestions.

Thank you.


答:
As someone who was recently in the same position, I would definitely encourage you to go with a framework. When I started with my current company a few years ago I didn't really see the point to using one - after all I was the only developer at a fairly small firm. Fast forward a few years and now I'm in charge of a team of developers, and we have a small army of websites, web apps, client projects, APIs, social apps and CMSes supporting offices in four countries. Having one or two frameworks that everyone can work from as a base makes us far more productive, and makes it easier to recruit people when we need them. It also allows us to more easily jump from one project to another when deadlines shrink or something else comes up. </p>

<p>My advice is to spend some time trying out a few frameworks. Try to make the same relatively simple site that has basic versions of the PHP functionality you need. Once you get through this with a few templates you will start to get a feel for which ones suit your needs and personality as a coder. </p>

Title: PHP frameworks - should I use them?

Body:
As someone who was recently in the same position, I would definitely encourage you to go with a framework. When I started with my current company a few years ago I didn't really see the point to using one - after all I was the only developer at a fairly small firm. Fast forward a few years and now I'm in charge of a team of developers, and we have a small army of websites, web apps, client projects, APIs, social apps and CMSes supporting offices in four countries. Having one or two frameworks that everyone can work from as a base makes us far more productive, and makes it easier to recruit people when we need them. It also allows us to more easily jump from one project to another when deadlines shrink or something else comes up.

My advice is to spend some time trying out a few frameworks. Try to make the same relatively simple site that has basic versions of the PHP functionality you need. Once you get through this with a few templates you will start to get a feel for which ones suit your needs and personality as a coder.


问:
What is the common definition of a Hacker?
I'm wondering if the term Hacker means different things to different people.  When most people hear the word hacker what are the first things that come to mind?</p>

答: Hacker is a person ( yes ! ) who has knowledge about the code more than creator itself. </p>


答:
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
Benefits of Encapsulation:

The fields of a class can be made read-only or write-only.

A class can have total control over what is stored in its fields.

The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.he public methods are the access points to this class's fields from the outside java world. Normally these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.

Title: Why shouldn't I be using public variables in my Java class?

Body:
In school, I've been told many times to stop using public for my variables. I haven't asked why yet.

This question: Are Java's public fields just a tragic historical design flaw at this point? seems kinda related to this. However, they don't seem to discuss why is it "wrong", but instead focus on how can they use them instead.

Look at this (unfinished) class:

```<code>public class Reporte {

    public String rutaOriginal;
    public String rutaNueva;
    public int bytesOriginales;
    public int bytesFinales;
    public float ganancia;

    /**
     * Constructor para objetos de la clase Reporte
     */
    public Reporte() {

    }
}
</code>```

No need to understand Spanish. All this class does is hold some statistics (those public fields) and then do some operations with them (later).

I will also need to be modifying those variables often. But well, since I've been told not to use public, this is what I ended up doing:

```<code>public class Reporte {

    private String rutaOriginal;
    private String rutaNueva;
    private int bytesOriginales;
    private int bytesFinales;
    private float ganancia;

    /**
     * Constructor para objetos de la clase Reporte
     */
    public Reporte() {

    }

    public String getRutaOriginal() {
        return rutaOriginal;
    }

    public String getRutaNueva() {
        return rutaNueva;
    }

    public int getBytesOriginales() {
        return bytesOriginales;
    }

    public int getBytesFinales() {
        return bytesFinales;
    }

    public float getGanancia() {
        return ganancia;
    }

    public void setRutaOriginal(String rutaOriginal) {
        this.rutaOriginal = rutaOriginal;
    }

    public void setRutaNueva(String rutaNueva) {
        this.rutaNueva = rutaNueva;
    }

    public void setBytesOriginales(int bytesOriginales) {
        this.bytesOriginales = bytesOriginales;
    }

    public void setBytesFinales(int bytesFinales) {
        this.bytesFinales = bytesFinales;
    }

    public void setGanancia(float ganancia) {
        this.ganancia = ganancia;
    }
}
</code>```

Looks kinda pretty. But seems like a waste of time.

Google searches about "When to use public in Java" and "Why shouldn't I use public in Java" seem to discuss about a concept of mutability, although I'm not really sure how to interpret such discussions. I do want my class to be mutable - all the time.


答:
What web frameworks do is wrapping all the request-response-cookie-session stuff into an API. So you get an easy interface to work with.

Some have more battery included and provide librairies to handle forms , databases , validation ,etc ...

My opinion :

if you have a lot of legacy code : chose a micro-framework that will help you organize php code :  slim , lavarelle , silex , ...

silex is great since it'll help you learn Symfony at the same time.

If you have time , learn big stuffs like ZF or Symfony.

A big frameworks usually means a complete stack. For instance learning symfony means learning Doctrine, Twig , Assetic, using Composer ,monolog,... so people hiring you know you know all that stuff.

Title: PHP frameworks - should I use them?


问:
Is there a study showing which agile approach is best suited for particular kind of project? (in this case a re-platforming project, Java to .NET)
It is said that the Kanban methodology is suited for software maintenance and support areas, whereas Scrum is more suited for new product development. No process or methods are complete. Using the right one will help you succeed, but they will not guarantee success.

Is there a study showing which agile approach is best suited for particular kind of project? (one with with actual project success metrics by type of project, for example, the best agile approach for project that is a a re-platforming from one technology to another, say from Java to .NET indicating that Kanban is successful more often than Scrum).

答:
It is said that kanban methodology is suited for software maintenance
  and support areas whereas scrum for new product development.

I think most people in the agile community would disagree. Both Kanban and Scrum are suited for new product development (I have worked on a greenfield project with Kanban).

It is true that they have different strenghts and weaknesses, and that Scrum in its original form is not suitable for software maintenance when quick responses are paramount, but then most teams do not use a "pure" methodology, but tailor it to their needs.

Which agile approach is best suited for a project which is basically a
  re-platforming from one technology to another(say from java to .net).

The agile answer would be: Don't. A complete rewrite is rarely a good idea, and most importantly goes against one of the fundamental ideas of agile development, namely to focus on delivering value quickly: If you do a complete rewrite, you'll probably not deliver any value until you are done (and possibly never, if you fail). See for example: to rewrite or not to rewrite, and  Joel on Software - Things You Should Never Do, Part I. It is usually better to fix the parts that cause the most pain, possibly migrating to a different technology bit-by-bit (e.g. module by module). It may look more difficult in the beginning, but will give you results much faster, and reduce risk.

That said, if you feel you must rewrite, the methodology does not depend on the fact that it is a rewrite. Rather, it should depend on how your team is composed, how they want to work, how you communicate with stakeholders, etc. Both Kanban and Scrum will be well suited.

ContentLicense: CC BY-SA 4.0


答:
Many people have already answered "Right away", and I 100% agree. I also like Xion's suggestion to start off with the VCS's ignore patterns (i. e. .gitignore or equivalent).

I guess it's pretty much agreed upon that there are no downsides to early commits. I'd like to add upsides:

You're less likely to commit stuff that you chose to discard but that's still lingering around. When I start a fresh development, I'll code and discrad stuff quickly, and when I committed later, when there's already a bunch of files, I have accidentally committed stuff only to delete it in the next commit. This, as opposed to small, or even empty, commits, is true noise in the history.

If you are a systematic type and have typical first steps in your projects, having those as commit points may be instructional to you or to others, and it might even provide an opportunity to branch off at a certain point and create a reusable project stub. I have worked on Maven-based projects where this was useful (because in setting up a Maven project, some small first steps can already define quite a substantial base, and while those steps are not much to do, they may require enough thinking to warrant reusability).


问:
Designing a plug-in system
I'm working on a Java project and I would like to add a plug-in system. More precisely, I would like to let the user design his own module, pack it into a jar, leave it in a "plugins/" subfolder of my application and be done with it. I've managed to get a child classloader to instantiate objects of classes located in external jars, but now I'm facing a design dilemma:

Say Joe makes a plug-in and he packs it in joeplugin.jar. I would really like Joe to have a class named "instantiation.Factory" and I would also like everyone to have this class with this exact location and name. (This factory class obviously implements a interface that I provide and through it I get what I want from the plug-in.) If Joe wouldn't be restricted in this way I would have to look into his entire jar for some class that implements my factory interface and I don't want to imagine how complicated things get.

So my question is: should I enforce a strict naming convention for this single class? I have no idea how plug-in systems work.

答: Look at the service locator in java. One of the main classes is java.util.ServiceLoader. It basically searches for a file named as an interface and loads the class named in this file. This is the standard way to load classes dynamically as plug-in.

Title: Designing a plug-in system


答: Answering the second part of your question. You've tagged it as 32-bit so, 65535 in 32 bits is 00000000000000001111111111111111, signed or unsigned it is not -1.


答:
I want the following:

A clearly defined name space. Since C is my primary language, I also want macros to match this. Resolving conflicts in that area sucks.

If you allocate something, give me some obvious clue that it has to be freed. This goes to my next point, which is documentation.

Document the library. Tools like Doxygen are simple and portable, there is no excuse for not giving me something I can generate and browse.

Document opaque types in public headers. I'm going to find them anyway, tell me why you don't want me messing with them and what could happen if I do. If you actually want patches, I need to know what you were thinking.

Don't drop and run. I really appreciate comments like "Please, don't contact me about this. I have no intention of maintaining it. This solved my immediate problem, maybe it will solve your problem. I don't care, I'm not going to update this and you can feel free to fork it." I can't tell you how much time that saves me.

It should add no memory leaks or errors to existing code. If you don't test prior to pushing stuff to your own code, why are you tempting me to push it to mine?

If it is indeed a library, use a permissive license and be consistent. Don't decide three months from now that you should be making more money from it. That is beyond annoying the night before you ship something and realize that you have to re-write a bunch of library code because the license changed. That is exactly the kind of thing that makes me irritated enough to re-implement your stuff under the MIT license.

Be consistent in coding style, other people have to read your code in order to figure out what it is actually doing when things don't work as expected.

Don't use more than 110 columns, your code may have to be edited in place, and I might only have an 80x25 display. If you rely on tabs to make things look more 'elegant', you have other issues to solve.

Try to at least consider ports, if not dealing with an interpreted language. Even then, try to at least consider ports.

Give me tests. I hope you have them, I might suggest them otherwise and I may actually help write them based on a call graph. If I go through all of that trouble, kindly, use them. Otherwise, you get patches that "work for me!!!" :)

Don't break the API, period. I know you may realize that you've gone about it all wrong, but make sure stuff that links to you won't break on a simple update. That may mean some cruft and kludges, welcome to the world of libraries.

Give me a roadmap so I don't duplicate your work, or the work of others.

I'll likely edit this post to add more.

Title: What core principles would you want in a library?

Body:
Theres talk about what syntax and feature you like in a programming language; i'll now ask what core principles or feature would you like in a library in your favorite (or any) language?

An example is having adding list += anotherList valid as oppose to only allowing list += listElement (although some may see this as a bad idea)


问:
null values vs "empty" singleton for optional fields
First of all I'm developing a parser for an XML-based format for 3D graphics called XGL.
But this question can be applied to any situation when you have fields in your class that are optional i.e. the value of this field can be missing.

As I was taking a Scala course on coursera there was an interesting pattern when you create an abstract class with all the methods you need and then create a normal fully functional subclass and an "empty" singleton subclass that always returns false for isEmpty method and throws exceptions for the other ones.

So my question is: is it better to just assign null if the optional field's value is missing or make a hierarchy described above and assign it an empty singleton implementation?

答: If your implementation is in Scala, it is idiomatic to use the Option[T] type.


问:
How to plan/manage multi-platform (mobile) products?
Say I've to develop an app that runs on iOS, Android and Windows 8 Mobile. Now all three platforms are technically in different program languages. The only 'reuse' that I can see is that of the boxes-and-lines drawings (UML :) charts and nothing else.

So how do companies/programmers manage the variation of the same product across different platforms especially since the implementation languages differ? It's 'easier' in the desktop world IMO given the plethora of languages and cross-platform libraries to make your life easier. Not so in the mobile world.

More so, product line management principles don't seem to be all that applicable - what is same and variant doesn't really matter - the application is the same (conceptually) and the implementation is variant.

Some difficulties that come to mind:

Bug Fixing: Applications maybe designed in a similar manner but the bug identification and fixing would be radically different. A bug on iOS may/may-not be existent for that on Android. Or a bug fix approach on one platform may not be the same on another (unless it's a semantic bug like a!=b instead of a==b which would require the same 'approach' to fixing in essence

Enhancements: Making a change on one platform would be radically different than on another

Code-Design Divergence: They way the code is written/organized, the class structures etc., could be very different given the different implementation environments - leading to further reuse of the (above) UML models.

There are of course many others - just keeping the development in sync and making sure all applications are up to the same version with the same set of features etc. Seems the effort is 3x that of a single application. So how exactly does one manage this nightmarish situation?

Some thoughts:

Split application to client/server to minimize the effect to client side only (not always doable)

Use frameworks like Unity-3D that could take care of the cross-platform problem (mostly applicable to games and probably not to other applications etc.)

Any other ways of managing a platform line? What are some proven approaches to managing/taming the effects?

答:
For starters, there are a couple more ways to run the same code on all 3 platforms:

All 3 of the platforms you mention will run C++ code. This makes it possible to have common core code. Depending on the type of app you're developing, you may only need platform-specific adapters for interfacing with things like UI, location services, etc.

Phonegap allows you to deploy the same HTML/CSS/Javascript code on many mobile platforms. You could even look into using something like GWT to generate the HTML/CSS/Javascript from Java code. (I haven't tried this, but would love to know if anyone has done so!)

For some apps though, you want to preserve the feel of the native OS and so you necessarily end up with a lot of divergent code. If this is the case, you really can't escape the fact that you are writing 3 apps, not 1.

There are a few things you can do though, to help keep things on track:

Design for all platforms: When you're looking at a new feature, you always need to keep in mind a general idea of how it's going to work on each of the platforms. This is one area where it's crucial to involve people with experience of the different platforms.

Lead development on one platform: Get each new feature implemented on one platform first, before porting it across to the others. You will get most of the kinks worked out of your design when you do the first implementation, then (providing you document the changes!) the implementation on the other platforms should be much more straightforward.

Don't force uniformity: Sometimes, things just need to work differently on different platforms. If something feels like forcing a square peg into a round hole, it's almost certainly a bad idea. If it doesn't bite you now, it likely will later.

Testing: Whenever a bug gets discovered, check for it on the other platforms.


答:
I also attended the same Scala course and I agree with e-i-s that you should use the Option[T] type for implementing an optional field. Here are some more ideas.

The pattern involving

a trait with method isEmpty

several classes or objects extending the trait

a unique object whose method isEmpty always returns true

is also used to implement sequence-like immutable structures such as lists, streams, and so on.

Compare:

An Option[T] type containing the values Some(t), for each value t in T, and the additional value None.

A List[T] type containing objects built from two subclasses (and their respective constructors) Cons[T](h: T, t: List[T]) and Nil: these represent immutable lists whose elements have type T. Note that here the method Nil.isEmpty returns true.

None indicates the absence of a value, while Nil indicates an empty list.

So an optional value None is not the same as an empty list Nil.

NOTE

If you need to test if an optional value is defined or not you can use the isEmpty method of the Option type, or pattern matching:

```<code>class MyClass(f: Option[String])
{
  val field = f
}
</code>```

and then, to test if the field of an instance obj of MyClass is defined:

```<code>if (obj.field.isEmpty)
{
}
else
{
}
</code>```

or

```<code>obj.field match
{
  case Some(s) => /* do something with s */
  case None    => /* ... */
}
</code>```

Title: null values vs "empty" singleton for optional fields

Body:
First of all I'm developing a parser for an XML-based format for 3D graphics called XGL.
But this question can be applied to any situation when you have fields in your class that are optional i.e. the value of this field can be missing.

As I was taking a Scala course on coursera there was an interesting pattern when you create an abstract class with all the methods you need and then create a normal fully functional subclass and an "empty" singleton subclass that always returns false for isEmpty method and throws exceptions for the other ones.

So my question is: is it better to just assign null if the optional field's value is missing or make a hierarchy described above and assign it an empty singleton implementation?

Body:
I also attended the same Scala course and I agree with e-i-s that you should use the Option[T] type for implementing an optional field. Here are some more ideas.

The pattern involving

a trait with method isEmpty

several classes or objects extending the trait

a unique object whose method isEmpty always returns true

is also used to implement sequence-like immutable structures such as lists, streams, and so on.

Compare:

An Option[T] type containing the values Some(t), for each value t in T, and the additional value None.

A List[T] type containing objects built from two subclasses (and their respective constructors) Cons[T](h: T, t: List[T]) and Nil: these represent immutable lists whose elements have type T. Note that here the method Nil.isEmpty returns true.

None indicates the absence of a value, while Nil indicates an empty list.

So an optional value None is not the same as an empty list Nil.

NOTE

If you need to test if an optional value is defined or not you can use the isEmpty method of the Option type, or pattern matching:

class MyClass(f: Option[String])
{
  val field = f
}

and then, to test if the field of an instance obj of MyClass is defined:

if (obj.field.isEmpty)
{
}
else
{
}

or

obj.field match
{
  case Some(s) => /* do something with s */
  case None    => /* ... */
}


答:
Garbage Collectors perform a search of the program's heap from its GC Roots in order to identify what is live.

There's a cunning trick that you can perform when undertaking this task that avoids requiring any stack memory at all for the traversal.  When doing a DFS at any given node you need to know what your predecessor node was, so your invert the pointers within the heap structure itself.  For example, if your heap looks like this:

A -> B

B -> C

B -> D

And you search from A, to B, to C.  You invert the pointers, so they'll look like this:

B -> A

C -> B

B -> D

That way when doing a garbage collection you can walk a graph of arbitrary size, whilst only needing a constant amount of memory to do so.  You only need two pointers in memory in order to walk any graph:  One to reference your current node, and one for siblings.

Its a pretty neat trick.

Title: Which part of the Memory is used for the Garbage Collector?

Body:
I understand the Heap memory divisions such as Young, tenured and Perm Gen.
But I'm just curious from where is the memory used for performing the Garbage Collector itself? Is it from any of these memory spaces or in the thread stacks ?</p>


问:
Apply WCF For Large Projects
We have a large project that has nearly 20 modules on it. We want to use WCF for the business layer.

We have thought of three ways to implement WCF our project:

Use only one datacontract and one operation contract. Send
ClassName, MethodName to operation and create class by reflection
then invoke the method in WCF side.

Put all the modules in one wcf application, and create their
data contracts, operation contracts.

Create a seperate wcf application for each module and
host them seperatly.

We use web services because, we need call business layer in java and c#.

Which one is the best way? I need your ideas.

答:
Assuming that the 20 modules are not completely unrelated, the second way is the normal approach.

Ideally, you would like calling your services via WCF to feel very similar to calling methods in a DLL. That's the whole point of the WCF (and going back to earlier days, webservice) client proxies.

The first idea - using one contract and sending the class name and method name - is just horrible.

The third idea is just more work for no apparent reason, unless the 20 modules are so unrelated that it makes no sense for them to be in a single application.

Title: Apply WCF For Large Projects


问:
When should I make the first commit to source control?
I'm never sure when a project is far enough along to first commit to source control. I tend to put off committing until the project is 'framework-complete,' and I primarily commit features from then on. (I haven't done any personal projects large enough to have a core framework too big for this.) I have a feeling this isn't best practice, though I'm not sure what could go wrong.

Let's say, for example, I have a project which consists of a single code file. It will take about 10 lines of boilerplate code, and 100 lines to get the project working with extremely basic functionality (1 or 2 features). Should I first check in:

The empty file?

The boilerplate code?

The first features?

At some other point?

Also, what are the reasons to check in at a specific point?

答:
Usually I check in whenever I add something new, but try to separate stuff in discrete commits.

That means, if I add a new dependency, I make the changes until they either compile, or they are big-enough that it would be lost time to do them again, from scratch. If I have a bigger task, I try to commit multiple times, when it makes sense (once per function, every time I make it compile and run successfully, etc).

I also commit when I want a backup point (i.e. "if what I try now won't work or becomes too complicated, I want to come back to the code as it is now", or when somebody asks me to drop what I am doing and fix some urgent issue).

If you use a centralized source control system, you cannot commit arbitrarily for backup points, because a commit that doesn't compile/work affects everybody in your team.

Usually when I start adding boilerplate code (e.g. add a new webapp in a django website), I commit every operation I do.

If I follow a tutorial to generate/write code, I use step names in the tutorial for commit messages. This way, I can diff revisions and see what a tutorial step did, at any later point.

Let's say, for example, I have a project which consists of a single code file. It will take about 10 lines of boilerplate code, and 100 lines to get the project working with extremely basic functionality (1 or 2 features).

It would depend on how difficult adding the stuff is:

if it were trivial to add the boiler plate code, I would add it and commit right before starting on the other code (this way, if I make a mistake or introduce a weird bug later, I can simply revert to the boilerplate code and start again).

If the code were non-trivial, I would commit every time I added something new (anywhere between every two lines of code changed, to a hundred or so).


问:
What should I study to 'learn' Comp Sci?
[This question was originally asked on Stack Overflow, but recommended to move the question here.]

I can't find anything quite like the question I'm about to ask, so please forgive me if there's something just like it already, please feel free to point me in the right direction. It'll take a bit of background explaining too, please forgive me for that.

[backstory]

Basically, I graduated from University about 18 months ago with a degree in Business Information Systems and Japanese. The Japanese took up half of the degree so the BIS was only joint. I only learned PHP in terms of languages and basically no computing theory - everything was vocational (Networking, programming basics, CMS development, Office and VBA and then loads of Business theory courses).

Since this, I decided to teach myself C# and ASP.Net and try to get a position as a programmer. I created an online shop style website and a small CRM application in Windows Forms to both teach myself and build a portfolio, and luckily I managed to snag a developer position.

Bad side? I'm the only developer at my company. Now don't get me wrong, in the last year I've learned loads and loads, I did some devpt. before Uni so knew the basics anyway, but it was very much a "learning from books" job - every night.

Now then... I am now at a point where I'm building software on a regular basis, making good judgements for time scales, and have even been told my code and methodology are good by other professionals that have been in the game longer than me, and they have offered me jobs.

[/backstory]

What this whole thing boils down to, is that I now want to study up on the topics I'll have missed by not doing CS. More importantly, could you recommend books / free online courses? I want to learn about Computer Science theory, not just better coding.

Thank you!

答:
The best thing you will receive out of learning Computer Science topics is problem solving skills and "attention to detail".

These things are certainly the backbone of an excellent programmer, but just be warned you wont learn very much in terms of technically skills and hands-on coding skills.

A great deal of math and theory will be thrown your way and if you think that you should improve on the two areas I listed at the top, I certainly think you will not be wasting your time.

So to best answer your question, you should study Math topics specifically Linear Algebra, Discrete Math and Computational Theory. These will all improve you significantly.


答:
I wouldn't really make a table with numeric identifiers but more something like this:

```<code>Current | Next
--------------
Start   | Page1
Page1   | Page2
Page2   | End
End     |
</code>```

This way you can easily fit a page in between. And your end page would be the one with an empty(nil) Value.

Body:
I wouldn't really make a table with numeric identifiers but more something like this:

Current | Next
--------------
Start   | Page1
Page1   | Page2
Page2   | End
End     |

This way you can easily fit a page in between. And your end page would be the one with an empty(nil) Value.


问:
How do I store an object in a way that I can use it even in a second execution of the program?
I am making program in Java in which I am making Dialog box, button, checkbox, etc. SWT widgets.

Now my problem is, I want like if in one execution button is made and in second execution checkbox is made then they both should display in one box.
So I need to store that box object.

How can I do that?

答:
Basically you have to do this yourself.  There are many ways to "persist" data and you're free to use any of them.  You have to choose where the data will be stored first:

On the local computer

On a server on the local network

On a server somewhere on the internet?

...and you have to decide what format:

CSV file

Binary serialized file (Java serialization)

Database

If you choose a Database, there are various frameworks like Hibernate that can help you.

So, when your application closes you have to hook that event and run some code that takes the program state you want to store and somehow gets it into your persistent storage.  Then when the application starts up you have to open that storage, load the data, and rebuild the GUI the way you want it to be.


答:
In general, there are two ways to go about doing what you need:

Store the state of the object, and

Store the sequence of commands that lead the object to its current state

The first way is addressed by externalization of an object's state. Essentially, you write to an external storage of some sort a file with a description of the current state of the object:

```<code>Label at 40,10 text "Are you sure?"
Button at 40,20 size 30,10 text "OK"
Button at 40,40 size 30,10 text "Cancel"
</code>```

You can read this file and restore the object to its current state.

The second way is addressed by storing commands, like this:

```<code>Add Label id 123 at 0,0
Move id 123 to 40,15
Set text id 123 "Are you crazy?"
Move id 123 to 40,10
Add Button id 124 at 0,0
Set text id 124 "Cancel"
Move id 124 to 40,40
Add Button id 125 at 0,0
Set text id 125 "OK"
Move id 125 to 40,20
Set text id 123 "Are you sure?"
</code>```

When you have a file like that, you can "replay" it to get the current state of your object. But more importantly, you can use it to implement "undo" that survives exiting the application. If you add timestamps to the events, you would also get a way to restore the state as of some time in the past.

Title: How do I store an object in a way that I can use it even in a second execution of the program?

Body:
I am making program in Java in which I am making Dialog box, button, checkbox, etc. SWT widgets.

Now my problem is, I want like if in one execution button is made and in second execution checkbox is made then they both should display in one box.
So I need to store that box object.

How can I do that?

Body:
In general, there are two ways to go about doing what you need:

Store the state of the object, and

Store the sequence of commands that lead the object to its current state

The first way is addressed by externalization of an object's state. Essentially, you write to an external storage of some sort a file with a description of the current state of the object:

Label at 40,10 text "Are you sure?"
Button at 40,20 size 30,10 text "OK"
Button at 40,40 size 30,10 text "Cancel"

You can read this file and restore the object to its current state.

The second way is addressed by storing commands, like this:

Add Label id 123 at 0,0
Move id 123 to 40,15
Set text id 123 "Are you crazy?"
Move id 123 to 40,10
Add Button id 124 at 0,0
Set text id 124 "Cancel"
Move id 124 to 40,40
Add Button id 125 at 0,0
Set text id 125 "OK"
Move id 125 to 40,20
Set text id 123 "Are you sure?"

When you have a file like that, you can "replay" it to get the current state of your object. But more importantly, you can use it to implement "undo" that survives exiting the application. If you add timestamps to the events, you would also get a way to restore the state as of some time in the past.


答:
The answer depends on what you mean by "the memory used for performing the Garbage Collect[ion]" ... and what garbage collector you are talking about.

The general answer is that different garbage collection algorithms use space differently.  This is a very high level / simplified summary:

Just about all garbage collectors make use of one or more "mark" bits in each object's header to record that the object has been processed by the GC.

Copying collectors work by copying live objects from a "from" space to a "to" space, and in the simple case don't need any extra space.

Mark / sweep collectors work by recursively walking the graph of "reachable" objects.  The recursion can be done explicitly (which requires a separate stack), or by means of a clever pointer-reversal trick (look up Cheney's algorithm).

Concurrent collectors typically require extra memory to track objects that get mutated while the garbage collector is running.

There are whole books on the topic of garbage collection.  If you want to really understand how garbage collectors work under the hood, you've got a lot of reading to do.

In general, any additional memory that the GC needs to do its job will typically be allocated outside of the live heap spaces.  Thread stack memory is not used ... apart from the thread stack for the garbage collection thread or threads themselves.

Your mention of "young", "tenured" and "permgen" suggests that you are talking about classical Java GCs.  These are generational collectors, which is a subtype of copying collectors.


答:
The task you are trying to perform is called "license management" and the tool you are looking for is a "license manager" program.

You can find a few different license manager programs out there but, even better, you can also write your own with a relativly small effort.

Most license managers are just webservices (nowadays they are almost always RESTful webservices, like the one you can esily create with Sinatra, for example) that performs these basic steps:

Accept a request for an authorization key from a client program (that resides on the same LAN or on the Internet).

Give the client an authorization key (taken from a pool of keys), if any key is available in the pool.

Get back the key (this is a metaphor. Actually, the license server just reset the key after a pre-defined period of time).

The client program, on its side, requests the key when it gets started and gives it back (deletes it) when it stops.

Of course:

You have to be able to trust both the license server and the client program. The server runs on a server machine that you control, so it is easy to trust it. The client program must be compiled (closed source) in order to keep any "hacker" from creating a new copy of the program that never deletes its keys.

Client and server must be able to communicate through a LAN or on the Internet.

The server must be under your control or must be linked to the hosting machine in some way (usually using a hardware key).

Hope this helps.


答:
The first commit can be a README file with as little as one line summary of the project, or enough information about the project's first milestone. The broad topics can also include:

Introduction

Project description

Project structure

Coding conventions

Instructions on how to:

build

test

deploy

Known issues and workarounds

todo list

Terms of use

The practice of updating the README before making changes to a project is also referred to as Readme Driven Development and it allows you to think through the changes before investing time in making those changes.

Anybody who wants to contribute to or use this software will then start with the README.


问:
How to check if 4 points form a square?
Assume I have 4 points (they are 2-dimension), which are different from each other, and I want to know whether they form a square. How to do it? (let the process be as simple as possible.)</p>

答:
Assuming that your square might be rotated against whatever coordinates system you have in place, you can't rely on there being any repetition of X and Y values in your four points.

What you can do is calculate the distances between each of the four points.  If you find the following to be true, you have a square:

There are two points, say A and C which are distance x from each other, and two other points, say B and D which are also distance x from each other.

Each point {A, B, C, D} is an equal distance from the two points which aren't x away.  i.e.: If A is x away from C, then it will be z away from both B and D.

Incidentally, the distance z will have to be SQRT((x^2)/2), but you don't need to confirm this.  If conditions 1 and 2 are true then you have a square.   NOTE: Some people are concerned about the inefficiency of square root.  I didn't say that you should do this calculation, I just said that if you did you would get a predictable result!

The bare minimum of work that you would need to do would be to pick a point, say A and calculate the distance to each of the other three points.  If you can find that A is x from one point and z from two other points, then you just need to check those two other points against each other.  If they are also x from each other then you have a square.  i.e.:

AB = z

AC = x

AD = z

Since AB = AD, check BD:

BD = x

Just to be sure, you need to check the other sides: BC and CD.

BC = z

CD = z

Since AC = BD and since AB = AD = BC = CD, this is therefore a square.

Along the way, if you find more than two distinct edge distances then the figure cannot be a square, so you can stop looking.

Working Example Implementation

I have created a working example on jsfiddle (see here).  In my explanation of the algorithm, I use arbitrary points A, B, C, and D.  Those arbitrary points happen to be in a certain order for the sake of walking through the example.  The algorithm works even if the points are in a different order, however, the example doesn't necessarily work if those points are in a different order.

Thanks to: meshuai, Blrfl, MSalters and Bart van Ingen Schenau for useful comments to improve this answer.

Title: How to check if 4 points form a square?


答:
Just before you do something silly.

For those of us without magical powers, that means little and often.

If you're working by yourself, do it everytime you get a drink, or whatever.

If you're working in a team, you probably need to make sure that the thing compiles, so that if someone else gets latest, they won't get a bag of errors. But other than that, as much as you can.


答:
Because Java was designed around the idea of having a virtual machine, there really isn't a single, correct answer for this question.

The only certainty is that the VM will implement the instruction set correctly.  There are two JVM instructions, new and newarray, that allocate space for objects and arrays.  Anything beyond that is an implementation detail which is intended to remain hidden.

AlexGaynor's malloc() answer probably holds true in most implementations for POSIX-y environments (Unix, Windows, VxWorks, etc.), where the usual practice is for dynamically-allocated memory to be put on the host system's heap.  Nothing in the JVM spec precludes implementations in other environments with other memory models:

The Java virtual machine assumes no particular type of automatic
  storage management system, and the storage management technique may be
  chosen according to the implementor's system requirements.

As long as the JVM implements something that appears to the Java program as a heap, all is good.  The spec does explicitly state that there must be garbage collection, and on a hypothetical host with infinite memory, it would be completely unnecessary.


答:
Two jobs ago I filled out timesheets.  They were done in order to record pay (we were paid overtime) and to bill the customer (a lot of work was T&M) and to check assumptions vs. actuals on fixed price projects.  I also found them useful for logging some of my own info, rather than keeping a personal log vs. a timesheet log.  It worked great.

One job ago, I tried to use timesheets the same way (the conditions were very similar), but in that case the company would question every little thing on the timesheet.  I'd have phone conversations arguing about what I put on my timesheet that lasted longer than the amount of time in question.  I stopped putting down accurate time, because it was absurd.  Other people seemed to be lying on their timesheet too, when questioned.

At this job, my time isn't directly billable to a customer, just to internal projects mostly, but I still do timesheets.  They're easy to do, and helpful, not just to myself, but to the company for accounting, etc.  Never been questioned about what I put on a timesheet here, so I keep them quite accurate.

I'd say they're great, until they start penalizing you for what you put on them.

Title: As a programmer, are you required to do timesheets?

Body:
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?


答:
Not sure if it was mentioned.

But make sure that what you commit runs/compiles! So no syntax errors, etc.

Nothing more frustrating than to checkout code that's broken.


答:
Let the four points have coordinate vectors a, b, c, d.

Then lets call their differences w=(a-d), x=(b-a), y=(c-b), z=(d-c).

Then w is orthogonal to a if you can create w from a by a 90-degree-rotation. Mathematically the 90-degree-rotation-matrix in 2-space is ( ( 0, -1 ), ( 1, 0 ) ). Thus, the condition whether w is a 90-degree-rotated a results in

( w_1 == -x_2 and w_2 == x_1 )

If this holds, then you need to check that w == -y and x == -z, or

( ( w_1 == -y_1 and w_2 == -y_2 ) and ( x_1 == -z_1 and x_2 == -z_2 ) )

If those three relations hold, a, b, c, d make an oriented square.

Title: How to check if 4 points form a square?

Body: Assume I have 4 points (they are 2-dimension), which are different from each other, and I want to know whether they form a square. How to do it? (let the process be as simple as possible.)</p>


答:
I'm sorry but some answers don't apply.

For the case you measure 3 edges (let's say AB, AC and AD) to find that two have the same size (let's say AC and AD) and one is bigger (let's say AB). Then you would measure CD to see if it's the same size of AB, and you find that it is. Instead of a square, you could have the picture below, and that makes it a wrong solution.

Then you try some other solution: measure all the distances at least once: AB, AC, AD, BC, BD, CD. Then you find that 4 of then are equal, and the other 2 are also equal among themselves. But you could just have a picture like below:

So, those answers aren't correct, despite the high upvotes they received.

One possible solution: if the two equal measures don't connect the same point. So: if AB and CD are the same lenght, all the other combinations (AC, AD, BC, BD) are also equal, you have a square. If you have the same point making the biggest length (AB and AC is the biggest, and all the others are equal), you have one of the pictures above.

Title: How to check if 4 points form a square?


答:
I wouldn't store a step_id at all, as you're just limiting yourself in the future.  Break it down into 2 groups of orders:

Incomplete order

Complete order

Just use a boolean to store that.  So you only have to worry about incomplete orders now (which are proportionately few compared to the total number of orders in your system).  Now every required detail that they have to enter has to be it's own field:

Name

Street

City

etc.

Now in the future you may want to divide your steps up in various ways.  There's a tendency now to move away from steps and towards a single long page where the user can jump around and enter it in whatever order they want, but there might be steps.

So when you reconstitute an incomplete order, you have something like:

```<code>OrderStep currentStep(Order incompleteOrder)
{
    if(!step1FieldsComplete(incompleteOrder))
    {
        return OrderStep.One; // silly naming, I know, but give it more meaningful name
    }
}

bool step1FieldsComplete(Order incompleteOrder)
{
    return
        incompleteOrder.Name != null
        && incompleteOrder.Street != null
        && ...;
}
</code>```

Now, when you want to move fields from one step to another, or merge 2 steps into one, you have lots of flexibility, and the code will even work if you add new fields in a previous step that the customer already filled out.  When they come back they'll just be bumped back to the step with the new field.

Body:
I wouldn't store a step_id at all, as you're just limiting yourself in the future.  Break it down into 2 groups of orders:

Incomplete order

Complete order

Just use a boolean to store that.  So you only have to worry about incomplete orders now (which are proportionately few compared to the total number of orders in your system).  Now every required detail that they have to enter has to be it's own field:

Name

Street

City

etc.

Now in the future you may want to divide your steps up in various ways.  There's a tendency now to move away from steps and towards a single long page where the user can jump around and enter it in whatever order they want, but there might be steps.

So when you reconstitute an incomplete order, you have something like:

OrderStep currentStep(Order incompleteOrder)
{
    if(!step1FieldsComplete(incompleteOrder))
    {
        return OrderStep.One; // silly naming, I know, but give it more meaningful name
    }
}

bool step1FieldsComplete(Order incompleteOrder)
{
    return
        incompleteOrder.Name != null
        && incompleteOrder.Street != null
        && ...;
}

Now, when you want to move fields from one step to another, or merge 2 steps into one, you have lots of flexibility, and the code will even work if you add new fields in a previous step that the customer already filled out.  When they come back they'll just be bumped back to the step with the new field.


答:
Don't, It will be a mess.

If you need all modules everytime do it.

On my side I have several services serving different usecase domain.
I want them to be injected in my app through an abstract interface so our app can use local implementation, wcf distant implementation or anyother transport.
It looks like this:

Title: Apply WCF For Large Projects

Body:
We have a large project that has nearly 20 modules on it. We want to use WCF for the business layer.

We have thought of three ways to implement WCF our project:

Use only one datacontract and one operation contract. Send
ClassName, MethodName to operation and create class by reflection
then invoke the method in WCF side.

Put all the modules in one wcf application, and create their
data contracts, operation contracts.

Create a seperate wcf application for each module and
host them seperatly.

We use web services because, we need call business layer in java and c#.

Which one is the best way? I need your ideas.


问:
Does having a higher paid technical job mean you do not get to code any more?
I work at a large company where technical people fall roughly in one of these categories:

A developer on a scrum team who develops for a single product and maybe works with other teams that are closely related to the product.

An architect who is more of a consultant on multiple teams (5-6) and tries to recognize commonalities between team efforts that could be abstracted into libraries (architects do not write the library code, however). This architect also attends many meetings with management and attempts to set technical direction.

In my company the architect role is where most technical people move into as the next step in their career.

My questions are: Do most companies work such a way that their highest paid technical people are far removed from writing code? Is this a natural tendency for a developer's career? Can a developer have it all (code AND set direction?)

答:
It depends on what your responsibilities are. If you're responsible for technical matters, then you should remain in a coding position. Splitting up the 'idea' process from the 'implementation' process is a path down the wrong road. If you ever find your self in such a position, you must resist the urge to be that genius that just doesn't have the tim to implement his brilliant ideas.

On the other hand, if your responsibility lies in management, the I don't think you should be coding. A manager should manage fill time. Such a position includes facilitating communication between different coders, and between the team and the greater bureaucratic ecosystem. The worst managers in my experience where the ones who stayed heads down coding while the team fell apart due to conflict and mis-communication.


答:
Pick three of the four points.

Figure out if it's a right isosceles triangle by checking if one of the three vectors between points is equal to another one rotated by 90 degrees.

If so, compute the fourth point by vector addition and compare it to the given fourth point.

Note that this doesn't require expensive square roots, not even multiplication.

Title: How to check if 4 points form a square?