答:
Depending on the type and size of your project, at least do "unit testing" of individual functions, then try to do some "system testing" i.e. put test data in the database, start the application like it would be done in production and compare the output with a saved copy of what you would expect. Between those ends there's "integration testing" where you test e.g. if some classes work together.
Despite the name, you can do every kind of testing with the "junit" tool.</p>

Title: Testing From A Developer's Perspective

Body:
I have a book which mentions:

"There are many types of testing, including unit testing, integration testing, functional testing, system testing, performance testing, and acceptance testing".

It is often noted that many developers carry out unit-testing only, or no testing at all. From the types of testing above, which ones are to be conducted by the developer? What are the responsibilities of a developer when it comes to testing?


问:
Testing From A Developer's Perspective
I have a book which mentions:

"There are many types of testing, including unit testing, integration testing, functional testing, system testing, performance testing, and acceptance testing".

It is often noted that many developers carry out unit-testing only, or no testing at all. From the types of testing above, which ones are to be conducted by the developer? What are the responsibilities of a developer when it comes to testing?

答:
"What are the responsibilities of a developer when it comes to testing?"

The explicit responsibility is:

write tests that exercise your code and ensure that it returns the expected output.

However I have found that the implicit responsibilities are:

ensure that the tests themselves don't have false positives - make them fail first.

make sure that the business owners know 'what' is being tested.

make sure that testing covers the users platform and not just the developers 'hot' machine.

make testing a part of features and aim to start getting some tests written before writing the code.

tell management that the tests are part of the software.

tell management that the writing the tests is what a professional developer does.

when bugs arrive, point to any lack of tests that would have prevented it

find stories about failures that reflected a lack of testing.

when bugs are found, write tests to reproduce & fix them and add them to your regression suite.

ContentLicense: CC BY-SA 3.0

Title: Testing From A Developer's Perspective


答:
Boris Bezier says this:

"Programmers are responsible for software quality – quality in their
  own work, quality in the products that incorporate their work, and
  quality at the interfaces between components. Quality has never been
  and will never be tested in. The responsibility is both moral and
  professional."

If you are responsible for delivering quality software, how are you going to do that? The software must be tested. If you are in an organization that doesn't have dedicated testing resources, it is up to you. Even if your team does have testing resources, it's up to you to make sure testing happens. That may mean writing tests, or it may mean you follow up with whomever is responsible for writing the tests.

Bottom line: you and your team are responsible for the quality of your code.

Title: Testing From A Developer's Perspective


问:
What is better making a separate temporary table or inserting directly to big table?
I have a big table with 1,400,000 rows, and I need to insert 3000 rows daily in it.

When I insert 3000 rows daily should

I first insert to a temporary table than dump that temporary table to the main table.

insert directly to the big table.

Which approach is fast and why?

答:
I would suggest you to go by the batch insert way of storing data in SQL. I assume that you are having a front application that is interacting with the user and sending the data to the database for storing.

In the previous answer's one suggested you to go for the batch mode of data insertion and the other suggested to use secondary table for data cleaning or structuring. I would suggest you to structure the data and then send it to database for storing. ie do the cleaning and data structuring part in your server side language and use the database for data insertion and retrieval only. More over considering having 3000 rows to insert I would have defined a for loop to loop in data. then I would have first processed 500 rows, structured and cleaned them and then put them into batch insert.

In the same iteration I would have processed next 500 rows and created another batch for insert. So basically while my previous 500 rows are being inserted in database I would have been working to insert next 500 rows. Of course these is a brief overview and requires proper work around on it to be implemented.

I see that these thread pretty old so I am little late for the party. never the less just wanted to share my opinion. Do reply with how did you solve the issue. Will be useful for us in future.

Cheers

ContentLicense: CC BY-SA 2.5


问:
Why the current enthusiasm for Functional Programming?
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?

答:
Todays need for distributed computing.

FP uses functions as building blocks, which don't have state, so invoking them n  times with the same parameters should return the same value always, they don't have side effects.

Thus, you can send the same function to a bunch of machines to perform and have the doing the work in parallel.

In OO paradigm, this is a bit harder, because the building blocks are objects, which are almost by definition stateful.  If you invoke several times the same method, you have to be careful in synchronizing the internal data, to avoid data corruption. While still possible, the FP paradigm works better than the OO in some scenarios where computation has to be distributed.

The advent of FP ( and NoSQL at some extent ) comes after the stories about amazing computing results in hundreds of thousands of computers working in parallel, and how easy it is.

But probably this is only a niche the kind of applications that need this kind of setup. For many, many other applications/systems, procedural and OO work just fine.

So is all about to expand our programming horizons and re-take these concepts we once thought wouldn't go beyond academia.

I learned to program in Lisp years ago, and back then I didn't knew that was even FP. By now I have forgotten almost everything about it, but certainly help me to understand concepts like recursion very easily.


问:
Code formatting for variable declarations
Is it looked down upon or bad to write multiple variable declarations on the same line? As in:

```<code>    boolean playMoreGames = true;           int length;
    boolean win;                            int bodyparts;
    boolean contains;                       char blank = '-';
    String word;                            Scanner fileIn;
    String guess;                           Scanner keyboard = new Scanner(System.in);
</code>```

vs (standard):

```<code>    boolean playMoreGames = true;
    boolean win;
    boolean contains;
    int length;
    int bodyparts;
    char blank = '-';
    String word;
    String guess;
    StringBuilder sb_word;
    Scanner fileIn;
    Scanner keyboard = new Scanner(System.in);
</code>```

答:
Style is always different everywhere. I've never seen this style that I can recall, but that doesn't matter.

I think it might be seen as pretty strange by many but again, it's subjective and really doesn't matter so long as your style doesn't get in your (or anyone elses) way.

Though I would think this style might get in your way, but if it doesn't, and you like it, have a ball.

Bad design is looked down upon, style is looked at mostly with curiosity. Though if you're in a team, style that isn't uniform with the others is (rightly) looked down upon.

The only other thing to note about style is that while it's subjective and everyone's may be different outside of collaborative works, there are often common subsets of style among language communities. While there's no necessity to follow any of these common styles, there can be benefit in that your code will be easier to digest to more people. As many people are used to seeing style X, if you code in style X, more developers will be able to understand and work with your code if you ever share it.


答:
I really like the readability of that style, and might use it in a publication, but a good programming style should also be easily editable.  It would be very annoying to insert or delete a declaration in the middle of the list, especially if you're accustomed to being able to do so using your editor's linewise shortcuts, like vim's dd.

The other reason people generally stick to one statement per line is that compilers report errors by line number and version control diffs and merges by line.  While it's not that hard to deal with, it makes interacting with your tools that much more convenient.

Title: Code formatting for variable declarations

Body:
Is it looked down upon or bad to write multiple variable declarations on the same line? As in:

```<code>    boolean playMoreGames = true;           int length;
    boolean win;                            int bodyparts;
    boolean contains;                       char blank = '-';
    String word;                            Scanner fileIn;
    String guess;                           Scanner keyboard = new Scanner(System.in);
</code>```

vs (standard):

```<code>    boolean playMoreGames = true;
    boolean win;
    boolean contains;
    int length;
    int bodyparts;
    char blank = '-';
    String word;
    String guess;
    StringBuilder sb_word;
    Scanner fileIn;
    Scanner keyboard = new Scanner(System.in);
</code>```


问:
Is every object rounded to the same size in Java?
According to this answer every object in Java is of the same size? Is the answer talking about the object itself or the reference to the object?

Here's the statement:

every object size is rounded to 16 bytes in Hotspot, so an object with
  a single byte field will take up precisely the same space as a single
  object with a long or double field;

I am completely baffled by the claim in this statement. So many upvotes to this answer further befuddled me.

Can some one please explain what is meant by the above statement?

答: Rounded to a multiple of 16 bytes. Objects can be 16B, 32B, 48B, etc</p>


问:
Over thinking development
I've been working as an app developer for a year and a half now (not long I know), and I've just been given my first big project.

Needless to say it didn't go very smoothly, so I sought advice from a senior programmer involved in the project about how to approach it.

He said that I had drastically been over thinking the task at hand, and that because I had never tackled a project of this scale before I'd been spending too much time over thinking design patterns. In his wise words, he told me "F*ck the future, build for now".

Is this a trend programmers typically follow when going about a project like this? For example, if you were asked to do a proof of concept model, is it a typical trend just to mash a workable example out as soon as possible?

Edit: In light of the debate this has sparked, I'd like to mention that this situation is fairly extreme: we have very tight deadlines due to factors beyond our control (i.e. the market we're aiming for will lose interest if we don't show them something) and his advice proved to be very effective for this particular task.

答:
He said that I had drastically been over thinking the task at hand, and that because I had never tackled a large project like this I'd been spending too much time over thinking design patterns. In his wise words, he told me "F*ck the future, build for now".

I think that's a bit of a cowboy mentality from the other developer. The modern day's version of a tough nerd who just "does it now". It's become a popular theme among startups and no thanks to people at Facebook for starting the phrase "getting it done is better than doing it right".

It's appealing. It's encouraging and offers visions of developers standing around a console clapping their hands as they launch their big project into the world on time, on budget and all because they did not over engineer anything.

It's an idealistic fantasy and life doesn't work this way.

A fool will rush into a project thinking he can just "do it" and get it done. Success will favor the developer who prepares for the unseen challenges, and treats his profession like fine craftsmanship.

Any senior developer can criticize, condemn and complain - and most do!

While he/she tells you that you are "over thinking" the project. I congratulate you on actually "thinking" first. You have taken your first steps in being a better developer then the other guy.

Is this a trend programmers typically follow when going about a project like this? For example, if you were asked to do a proof of concept model, is it a typical trend just to mash a workable example out as soon as possible?

That's exactly what a proof of concept is. It's an attempt to mash something out as quickly as possible so that people can take a step back and look at it. It's done to prevent mistakes, misdirection and wasted time/money.

There are many different kinds of proof of concepts. You can build something that is thrown away in the garbage when done, or you can build something that represents a starting point for the project. That all depends upon what you need, and how close the concept is to the final product.

It's also an opportunity to demonstrate your ideas. There have been times when I've presented a prototype that took things to a level they didn't expect.

Title: Over thinking development


问:
Is imposing the same code format for all developers a good idea?
We are considering to impose a single standard code format in our project (auto format with save actions in Eclipse). The reason is that currently there is a big difference in the code formats used by several (>10) developers which makes it harder for one developer to work on the code of another developer. The same Java file sometimes uses 3 different formats.

So I believe the advantage is clear (readability => productivity) but would it be a good idea to impose this? And if not, why?

UPDATE

We all use Eclipse and everyone is aware of the plan. There already is a code format used by most but it is not enforced since some prefer to stick to their own code format. Because of the above reasons some would prefer to enforce it.

答: For me, the main advantage of a common format automatically applied is that it helps our change tracking  & code reviews. git (and most other source control tools) can show diffs of previous versions of the files. By enforcing a common style, it minimizing programmer preference diffs.</p>


答:
Style guides also enable easier programmatic parsing of code for various analytical purposes.

Google has published a paper about this called "Searching for Build Debt:
Experiences Managing Technical Debt at Google".

Title: Is imposing the same code format for all developers a good idea?

Body:
We are considering to impose a single standard code format in our project (auto format with save actions in Eclipse). The reason is that currently there is a big difference in the code formats used by several (>10) developers which makes it harder for one developer to work on the code of another developer. The same Java file sometimes uses 3 different formats.

So I believe the advantage is clear (readability => productivity) but would it be a good idea to impose this? And if not, why?

UPDATE

We all use Eclipse and everyone is aware of the plan. There already is a code format used by most but it is not enforced since some prefer to stick to their own code format. Because of the above reasons some would prefer to enforce it.


问:
Is it okay to call a model method in my view?
In the interest of keeping my Controller's skinny, I put a headline method in a Model.

```<code># My Model
class Property
  def headline
    "#{name} | #{address}"
  end
end
</code>```

(Then, Property Controller for context...)

```<code># My Controller
class PropertyController
  def show
    @property = Property.find(params[:id])
  end
end
</code>```

Question: As far as MVC is concerned, is it okay to call that Model method from my View, like so?

```<code># My View
<h1><%= @property.headline %></h1>
</code>```

答:
The whole point of MVC, or any other programming paradigm, is to get good separation of concerns.  Slavish adherence to your paradigm's principles should be insisted upon only when you can specify a greater benefit to doing so than not.

If you're willing to accept the need to possibly edit your View when a new headline rule comes along, skipping an empty property on the PropertyController is probably fine.  Especially if your View already has an included dependency to the model.

On the other hand, if your View has no other direct reference to the model, you'd probably be better off just defining the "empty" parameter on the PropertyController, so you can change or move the logic without having to worry about the View.

(If you have a lot of these, you may want to explore a generic get function on the controller, and have the view call that instead of direct property or method references.)


答:
Generally, assuming you hire reasonable developers, it is a bad idea to impose a universal code format.  It is however a good idea to adopt code guidelines.

I've never seen a set of code formatting rules that optimizes readability in all cases.  Likewise there are no 100% applicable grammar rules in English: our brains just aren't wired that way.  So use guidelines, but give developers the freedom to override them as they see fit.

That being said, a harder rule of "follow the code convention that already exists in the file/project" is a good one.

But keep in mind that the formatting contributes much less to the readability than simply how logically organized the code is.  I've seen plenty of unreadable spaghetti code w/ perfect formatting!


问:
Reason for placing function type and method name on different lines in C
I just started at a company and one of the style comments at my first code review was that the return type and method name should be on different lines. For example, this

```<code>void foo() {
}
</code>```

should be this

```<code>void
foo() {
}
</code>```

I've always used the first style, and I was wondering if there is any reason other than personal preference why people use the second style? I don't think the first one hurts readability at all. Is one more common than the other with C programmers and large open source projects?

答:
This is pretty much the only code formatting rule that I have found actually makes a noticeable impact on readability and it takes almost no effort (assuming your code editor doesn't start a fight with you over it).

It is good programming language design to have names appear in a consistent position in declarations/definitions. The rationale is straightforward: you have a nice visual anchor (a curly brace or just a hanging indentation) that you can use to immediately find the start of the name. You don't have to actually parse the language when scanning through a file the find the name.

It's the same as when you are formatting a document: when you start a new section you put the name up front in boldface--often on its own line--not buried somewhere, undifferentiated, in a long sentence.

Early C had very terse signatures: return types were optional and argument types were declared after the signature. Names also tended to be very short. This mitigated the impact of having an occasional return type offsetting the name.

```<code>double dot(x, y);
</code>```

Is still pretty digestible.

C++ made this a bit worse. It moved argument type specifications into signatures making signatures longer. This syntax was later adopted during the standardization of C.

```<code>static struct origin *find_origin(struct scoreboard *sb,
                  struct commit *parent,
                  struct origin *origin)
</code>```

is less digestible, but not too bad. (Excerpt from Git)

Now consider modern programming practices with long, descriptive names and parametrized types and see how this choice has become disastrous. An example from a Boost header:

```<code>template <class A1, class A2, class A3, class A4, class A5, class A6>
inline typename normalise<policy<>, A1, A2, A3, A4, A5, A6>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&)
{
   typedef typename normalise<policy<>, A1, A2, A3, A4, A5, A6>::type result_type;
   return result_type();
}
</code>```

If you are writing generic code, signatures like that aren't even out of the ordinary. You can find examples of much worse cases than this without trying too hard.

C, C++, and their derivatives, Java and C#, seem to be the exceptions to having readable declarations/definitions. Their popular predecessors and peers (Fortran, ALGOL, Pascal) placed names before result types and, thankfully, many of their successors (Go, Scala, TypeScript, and Swift to name a few) have chosen more readable syntaxes as well.

Body:
This is pretty much the only code formatting rule that I have found actually makes a noticeable impact on readability and it takes almost no effort (assuming your code editor doesn't start a fight with you over it).

It is good programming language design to have names appear in a consistent position in declarations/definitions. The rationale is straightforward: you have a nice visual anchor (a curly brace or just a hanging indentation) that you can use to immediately find the start of the name. You don't have to actually parse the language when scanning through a file the find the name.

It's the same as when you are formatting a document: when you start a new section you put the name up front in boldface--often on its own line--not buried somewhere, undifferentiated, in a long sentence.

Early C had very terse signatures: return types were optional and argument types were declared after the signature. Names also tended to be very short. This mitigated the impact of having an occasional return type offsetting the name.

double dot(x, y);

Is still pretty digestible.

C++ made this a bit worse. It moved argument type specifications into signatures making signatures longer. This syntax was later adopted during the standardization of C.

static struct origin *find_origin(struct scoreboard *sb,
                  struct commit *parent,
                  struct origin *origin)

is less digestible, but not too bad. (Excerpt from Git)

Now consider modern programming practices with long, descriptive names and parametrized types and see how this choice has become disastrous. An example from a Boost header:

template <class A1, class A2, class A3, class A4, class A5, class A6>
inline typename normalise<policy<>, A1, A2, A3, A4, A5, A6>::type make_policy(const A1&, const A2&, const A3&, const A4&, const A5&, const A6&)
{
   typedef typename normalise<policy<>, A1, A2, A3, A4, A5, A6>::type result_type;
   return result_type();
}

If you are writing generic code, signatures like that aren't even out of the ordinary. You can find examples of much worse cases than this without trying too hard.

C, C++, and their derivatives, Java and C#, seem to be the exceptions to having readable declarations/definitions. Their popular predecessors and peers (Fortran, ALGOL, Pascal) placed names before result types and, thankfully, many of their successors (Go, Scala, TypeScript, and Swift to name a few) have chosen more readable syntaxes as well.


问:
How do you demo software with No UI in the Sprint Review?
We are doing agile software development, basically following Scrum.   We are trying to do sprint reviews but finding it difficult.  Our software is doing a lot of data processing and the stories often are about changing various rules around this.

What are some options for demoing the changes that occurred in the sprint when there isn't a UI or visible workflow change, but instead the change is a subtle business rule on a processing job that can take 10s of minutes or even a couple of hours?

答:
How do you know that a feature is working yourself?
When you deploy it how do you make sure its actually working?

If you can't answer those questions then you have bigger problems than a Sprint Review. You should be able to show that in your demo.

In Scrum, during a demo, the Product Owner is review each of the stories under development and either accept them or return them to development.
You need to be able to prove that a feature is working; this is normally best done with an automated test. Can you pick out the automated tests that correspond to the acceptance tests and highlight the key changes?

Your Product Owner should also be able to help; they should have a detailed understanding the product under development. They don't need understand the full implementation details but they do need to understand it well enough to be able to stand up an explain the purpose (or business value) of each feature. After all, the Product Owner is the person who asked you to implement the story in the first place!


答: In my opinion it's a good solution for observer pattern (your model can be observable object which will notify its observers that data has changed). For example model (ex. Human) has changed its property (ex. weight) so he notifies its registered observers about it (ex. views). After receiving that information all observers (ex. view) can change its data.</p>

Title: Is it okay to call a model method in my view?

Body:
In the interest of keeping my Controller's skinny, I put a headline method in a Model.

```<code># My Model
class Property
  def headline
    "#{name} | #{address}"
  end
end
</code>```

(Then, Property Controller for context...)

```<code># My Controller
class PropertyController
  def show
    @property = Property.find(params[:id])
  end
end
</code>```

Question: As far as MVC is concerned, is it okay to call that Model method from my View, like so?

```<code># My View
<h1><%= @property.headline %></h1>
</code>```


问:
Tracking progress via a burndown chart when sprints overlap
Our team has adopted some agile practices to help us develop and deliver our software to our client. We adopt practices as needed (as problems/challenges were identified) rather than jumping wholesale into the agile camp. The big ones for us are maintaining a product and sprint backlog and developing and delivering new versions in roughly one month sprints. We do estimate the items in our sprint backlog to guesstimate what we can deliver within a sprint. However we do not track progress very well so it's difficult to know whether or not we are on target.

The next step in our evolution appears to be to improve our progress tracking ability. We are looking at using burn down charts to aid us. However, our sprints overlap significantly due to established and procedures for our software promotion schedule. We have the following established events:

Development begins on Sprint 1 and continues until code freeze. That said we do test our software throughout this phase with the development and test groups.

Code freeze stops development on Sprint 1 functionality. We have a small window to finish or fix any issues before the next event acceptance promotion 1. In addition development begins on Sprint 2.

Acceptance promotion 1 promotes the application to the client's acceptance environment where it is tested by our test group. Issues identified in testing may be fixed during a small window before acceptance promotion 2. Meanwhile Sprint 2 development continues.

Acceptance promotion 2 promotes the application one last time to the client's acceptance environment to validate any issues identified during acceptance promotion 1. Sprint 2 development continues.

Production promotion promotes the application to production and it is tested by our test group and Sprint 1 is officially completed. This is when it is truly done.

A visual depiction of this can be seen below. The average calendar time between development begins and code freeze is four weeks. The average time between code freeze and production promotion is two weeks.

larger resolution version

This schedule of events is not within our control. Client policy dictates when application software is promoted from Test to Acceptance to Production. No application code may be modified beyond our second fix window. We do not perform the promotions. This is accomplished by '3rd' parties at the client's site, again, due to policy.

In addition, some tasks such as data updates, can and do happen outside of this schedule. Certain data updates follow the code (for instance, when there is a schema dependency) but others such as data bugs or new data can and do occur outside of this schedule. This is due to fewer restrictions as to what may be modified on the clients environment and when. Only application code is restricted to these specific milestones. Data and configuration are exempt and technically may be modified as needed. We are considering tightening this up so that data updates follow the same schedule as the code.

Given this scenario, our overlapping sprints, I have a several questions?

What is the proper way to create/handle a burn down chart when we burn development, testing, and data hours from the previous sprint while also working towards the next one?

I think we have 2 concurrent burn down charts on for each sprint.

Assuming we at most have two burn down charts how do we best display the cumulative burn down when the sprints overlap so as to understand our actual workload progress on each so as to best set us up for success?

If items are found in Sprint 1 after code freeze that need to be addressed in Sprint 2 how does that our Sprint 2 backlog and burn down?

I assume that for critical items we need to bump out less critical Sprint 2 items to make room for the incomplete Sprint 1 items. Non critical items will be bumped to Sprint 3 or later.

What would be the proper start and end dates for the burn down chart?

It seems the best option would be to reflect reality. Sprint 1 is not truly done (including testing and data updates) until production promotion and its final testing. So the start date would be development begins
and the end date be production promotion despite any overlap.

What else am I missing? What else could or will bite us?

答:
The Sprint is an name taken from Scrum. At the end of a Sprint your software should be "potentially shippable".

During a Sprint your team should be free from interference but committed to delivering the software at the end of the sprint.

What you are doing would not normally be described as a sprint.

It looks like during your 4 week iteration you have a couple of days for bug fixing from the release branch.

You have many options, my preferred choice would be to reduce the iteration length to 1 week long, and when you need to do work on the release branch, introduce that to the appropriate sprint backlog. Issues identified in UAT should be fixed in iteration/week 5. To avoid waste, I would try to line up the start of an iteration with this window for fixes. The acceptance testing should not be considered special compared to any other bug fix. The bugs they discover should just go into the backlog and be prioritised as appropriate.

Alternatively as if it is a relatively fixed amount of work, that is, it always takes a certain numer of days, then I would time box the activities of bug fixing and not consider it as part of the burn down. You need ensure that time taken and pts/estimate are tracked for these issues.

Another option is to put in some placeholder stories for the work that will likely result from the acceptance testing. You can work out the points to assign them by using the amount of effort that they have taken historically.


问:
Difference between mutex in windows and linux
Is that correct that a mutex object in Linux cannot be used for cross process synchronization as opposed to its Windows counterpart?

If that is true - what was the idea to limit mutex synchronisation functionality on Linux?

答: The difference is kind of "made up", on windows MUTEX is very rarely used, and even then no really for sync but to discover already runnin instance of the program. What has wide use is CRITICAL_SECTION, and it is close equivalent of recursive mutex on linux, solaris and others. </p>


问:
Making subclass more type-specific with accessors
I have a super class: TriggerManager with a subclass TimedTriggerManager. NOTE: I'm working in java

TimedTriggerManager only deals with TimedTrigger s, a subclass of Trigger. TriggerManager references all Trigger objects. To modify the subclass (TimedTriggerManager) to only accept TimedTriggers into its accessors and mutators (getters and setters) I have the following questions:

1) I have in TriggerManager the following public void addTrigger(Trigger t). In TimedTriggerManager should I just override the method to throw an error if the argument (t) is not a TimedTrigger. If so, What error should I throw? If not, what should I do?

2) Should I add another method getTimedTrigger to work alongside the supper class's getTrigger so that I don't have to keep type casting? (Since the latter would return a Trigger object)

3) Is there anything else I'm forgetting, or some common practice that I'm not doing?

答:
1) Yes. Unless you have a common interface for both Trigger and TimedTrigger, which means the TimedTriggerManager does not require any special functionality from TimedTrigger, you should check the type of the received Trigger and ensure its a TimedTrigger.

2) It doesn't seem a good idea to me. The base class usually should not know anything about the the derived classes. So I think casting is not a big problem here. It results in a cleaner design in my opinion.

3) Do you actually use a concrete TriggerManager class directly? One think that you may want to consider is to use an interface instead of a base object for the specialized managers.


问:
Dollar Sign Blues: Javascript and PHP
I grew up programming C++ and Java where everything was safe and beautiful. Compilers made sure to keep me in check if I ever strayed. Of course, everyone did a little Perl in college, but I didn't inhale. Kids these days are all about PHP on the backend and Javascript on the front. In trying to be hip, I do the same (for web development). The problem I keep running into is I accidentally add a dollar sign ($) in front of regular variables in Javascript and of course no one says anything because that's legal syntax often used for jQuery objects.

Are there any debugging tools or dev tricks to catch this dollar sign confusion? Do you often make the same mistake, and how do you deal with it emotionally? Chrome dev tools don't always see this is a Javascript error. I use PhpStorm and Emacs for development, but those don't catch my stupidity, although I suspect Emacs does but chooses to not tell me about it out of spite.

If you think this question is ridiculous, I think you are right. But we live in a world where a variable has a dollar sign in front of it. In such a world, nothing is ridiculous.

答:
There is nothing wrong in using $ in variables. I wouldn't do it on purpose on every variable, but it's still a valid syntax. jQuery is one of the examples where $ is used as a variable name. That's also why "Chrome dev tools don't always see this is a Javascript error", because there is no error in the first place.

If you are afraid of writing code like:

```<code>var demo = function demo() {
    var a = 123;
    ...
    $a = 456; // A new variable is created in global scope.
}
</code>```

then you have to use a style checker, like jsLint, jsHint or Google Closure Linter. Which one of those? It's up to you to make a choice. To help you with that, here are a few notes:

Style

Google Closure Linter follows Google JavaScript Style Guide, known to be cleverly done. Using a well-known style for JavaScript or any of six other languages is a good idea: when you share your code or hire a new developer, chances are they are already familiar with this style.

Many developers are familiar with Douglas Crockford style as well. This style is explained in detail in JavaScript: The Good Parts, a book worth be bought by anyone who works with JavaScript.

As for jsHint, I can't really find what conventions are used, and the website itself seems to avoid talking about that subject. Maybe I missed something.

Support by IDEs

Both jsLint and jsHint are supported by PhpStorm. This is also the case of Google Closure Linter.

Environment

Google Closure Linter is one of a series of tools. If you're already using Google Closure Compiler or Google Closure Library, it would be preferable to chose Closure Linter above other tools.

Strictness

jsLint is known to be strict. jsHint is more permissive, which is not always a good thing. For example, one of the reasons to fork jsLint for jsHint is explained in an article which shows bad code which will produce a error in jsLint, but not in jsHint:

```<code>/*global jQuery */

// Example taken from jQuery 1.4.2 source
jQuery.extend({
    /* ... */

    isEmptyObject: function( obj ) {
        for ( var name in obj ) {
            return false;
        }
        return true;
    }

    /* ... */
});
</code>```

The code is bad, because it looks like JavaScript has block scope, while it hasn't. See JavaScript: The Good Parts, p. 102, Appendix A: Awful Parts, Scope. In other words, looking at the code without knowing the language, we expect name to not being visible outside the loop, while it will remain visible.

As for Google Closure Linter, I believe that it's somewhere in the middle between jsLint and jsHint, but I haven't enough information to support that.

Conclusion

I would avoid jsHint: it's too permissive, meaning that it would not find potential bugs the other linters would detect. The style guide which is used is difficult to find.

Among jsLint and Google Closure Linter, the choice isn't obvious. Both are written by experts, both follow strict, well described style guide already followed by thousands of developers. Use both for some time, then pick one which is more practical for you.

Title: Dollar Sign Blues: Javascript and PHP

Body:
There is nothing wrong in using $ in variables. I wouldn't do it on purpose on every variable, but it's still a valid syntax. jQuery is one of the examples where $ is used as a variable name. That's also why "Chrome dev tools don't always see this is a Javascript error", because there is no error in the first place.

If you are afraid of writing code like:

var demo = function demo() {
    var a = 123;
    ...
    $a = 456; // A new variable is created in global scope.
}

then you have to use a style checker, like jsLint, jsHint or Google Closure Linter. Which one of those? It's up to you to make a choice. To help you with that, here are a few notes:

Style

Google Closure Linter follows Google JavaScript Style Guide, known to be cleverly done. Using a well-known style for JavaScript or any of six other languages is a good idea: when you share your code or hire a new developer, chances are they are already familiar with this style.

Many developers are familiar with Douglas Crockford style as well. This style is explained in detail in JavaScript: The Good Parts, a book worth be bought by anyone who works with JavaScript.

As for jsHint, I can't really find what conventions are used, and the website itself seems to avoid talking about that subject. Maybe I missed something.

Support by IDEs

Both jsLint and jsHint are supported by PhpStorm. This is also the case of Google Closure Linter.

Environment

Google Closure Linter is one of a series of tools. If you're already using Google Closure Compiler or Google Closure Library, it would be preferable to chose Closure Linter above other tools.

Strictness

jsLint is known to be strict. jsHint is more permissive, which is not always a good thing. For example, one of the reasons to fork jsLint for jsHint is explained in an article which shows bad code which will produce a error in jsLint, but not in jsHint:

/*global jQuery */

// Example taken from jQuery 1.4.2 source
jQuery.extend({
    /* ... */

    isEmptyObject: function( obj ) {
        for ( var name in obj ) {
            return false;
        }
        return true;
    }

    /* ... */
});

The code is bad, because it looks like JavaScript has block scope, while it hasn't. See JavaScript: The Good Parts, p. 102, Appendix A: Awful Parts, Scope. In other words, looking at the code without knowing the language, we expect name to not being visible outside the loop, while it will remain visible.

As for Google Closure Linter, I believe that it's somewhere in the middle between jsLint and jsHint, but I haven't enough information to support that.

Conclusion

I would avoid jsHint: it's too permissive, meaning that it would not find potential bugs the other linters would detect. The style guide which is used is difficult to find.

Among jsLint and Google Closure Linter, the choice isn't obvious. Both are written by experts, both follow strict, well described style guide already followed by thousands of developers. Use both for some time, then pick one which is more practical for you.


问:
Should I write a wrapper within a manager object?
I have three classes that work together to do one function (from the perspective of the rest of my program). There is a little bit of set up between them, so, to make it easier for the rest of my program, I grouped them into:

ListManager: object, which initializes them to the right values when it is constructed. The three objects it stores are:

Timer:

TriggerManager: basically a wrapper around an ArrayList that manages Trigger objects

CueList: a linked list with the usual getters and setters that come with that.

Since the rest of my program is only interacting/referencing the TriggerManager class, should I write wrapper methods for the objects it manages?

So should I make ListManager.add(Cue c) as a wrapper for CueList.add(Cue c).

OR should I just add getters for the three objects and let the rest of my program use that to manipulate them.

I tend to think that the later option is far more maintainable, but at the same time, the code produced if I make the wrapper just seems... prettier...

What's the best practice in situations like this?

答:
It depends on the kind of abstraction you want to achieve with your ListManager. If your ListManager is just a data tuple of 3 independent objects, the "wrapper" approach is pointless. If it provides an abstraction on it's own, because the the 3 objects are not independent from each other, then you should use specific accessor methods.

For example, do you want the rest of your program to get full control over the ListManager.CueList?  And does this not introduce any specific pitfalls for the user of your ListManager? Then add a public getter for the CueList.

Or is it better when the rest of your program gets only restricted access to ListManager.CueList (for example, to allow only a specific subset of the CueList methods to be called like CueList.add)? Might this prevent any unintentional errors? For example, must CueList.add be always called in conjunction with some additional operations? Then use the ListManager.add(Cue c) approach.


答:
Testing is about verifying the correctness of your work. I think it's every developer's responsibility to do that.

I suspect that the author of that quote was primarily talking about automated testing. There's also manual testing, which is probably something that you're doing already.

What steps to you perform to verify that the code you wrote works? If those steps can only be performed with your participation, then you're performing a manual test. If those steps can be run while you check twitter, then you're performing an automated test.

If I assume that your question is actually:

What are the responsibilities of a developer when it comes to [automated] testing?

Then my answer is that you've got to make that decision for yourself. The rule I follow is based on "3 or more use a for". I'll tolerate running a manual test twice, but the third time that I go to run it, I force myself to take the time to write an automated test. I recommend developing a similar rule that you can follow.

Title: Testing From A Developer's Perspective


问:
Inserting validation in Data Driven Tests
I am working on a testing tool that provides image comparisons. For test data insertions, I am using excel and csv files that supply the tests with text that is used by the tool to mock actual user interactions - in filling up of forms/screens in the tests.
After the insertion, there is a need for verification to ascertain whether the test has functioned properly or not.

What mechanism should I apply to ensure proper validation for the tests ?
As the screens will differ widely, I cannot use a hard coded error/success validation string/image.

One approach that I am considering is generation of images based on inputs(OCR) for different tests, which will be used to validate the instance of test where the specified input was executed.

Can anyone comment/share any other technique for doing this ?

答:
I suggest developing (or even better finding) an algorithm to compute how different the images are. Then have the assertion specify the maximum tolerance for how different those images are. It's not a fool proof approach, but I suspect it'll work pretty well. Similar to the tolerance that can be set by many tools when comparing two floating point values.

Another thing to try would be to allow your tool to define a rectangle within the images that the test cares about. That might help tests specify the exact area that's being evaluated by the test.


问:
Freelancing and GPL?
Is it possible for a freelance programmer to use Open Source products under GNU Public License and make money given that he cannot stop his customers from freely distributing his products?</p>

答:
IANAL (I am not a lawyer):  Freelancing and GPL are very compatible -- if the client is a company that wants something done, rather than a product they can sell, the fact that it is GPL is actually a bonus.  It clearly establishes the copyright situation.

It can also be used effectively when what you are selling is a service.  Only when you are developing something that is going resold to others would the GPL be a possible obstacle.

Title: Freelancing and GPL?


答:
What mechanism should I apply to ensure proper validation for the tests ?

That depends entirely on what toolkit and language you're using, and on how portable you need the test to be.  Were I going to build such an approach, I'd create at least two parts, one of which runs the test and one of which pre-builds an image of what I expect the test to be, and then I'd do a straight equality test between my generated image and an image of the form post-test.  No OCR, no tolerance for variation -- the test suite would build an image itself, and compare it to the image from the actual app.

(I'd also likely kick up a storm if I was asked to do image-based testing, and explore using or building a UI-aware test framework instead.)

Title: Inserting validation in Data Driven Tests

Body:
I am working on a testing tool that provides image comparisons. For test data insertions, I am using excel and csv files that supply the tests with text that is used by the tool to mock actual user interactions - in filling up of forms/screens in the tests.
After the insertion, there is a need for verification to ascertain whether the test has functioned properly or not.

What mechanism should I apply to ensure proper validation for the tests ?
As the screens will differ widely, I cannot use a hard coded error/success validation string/image.

One approach that I am considering is generation of images based on inputs(OCR) for different tests, which will be used to validate the instance of test where the specified input was executed.

Can anyone comment/share any other technique for doing this ?


问:
Using NSpec at various architectural layers
Having read the quick start at nspec.org, I realized that NSpec might be a useful tool in a scenario which was becoming a bit cumbersome with NUnit alone.

I'm adding an OAuth (or, DotNetOpenAuth) to a website and quickly made a mess of writing test methods such as

```<code>[Test]
public void UserIsLoggedInLocallyPriorToInvokingExternalLoginAndExternalLoginSucceedsAndExternalProviderIdIsNotAlreadyAssociatedWithUserAccount()
{
...
}
</code>```

... and I wound up with maybe a dozen permutations of this theme, for the user already being logged in locally and not locally, the external login succeeding or failing, etc.  Not only were the method names unwieldy, but every test needed a setup that contained parts in common with a different set of other tests.

I realized that NSpec's incremental setup capabilities would work great for this, and for a while I was trucking a long wonderfully, with code like

```<code>  act = () => { actionResult = controller.ExternalLoginCallback(returnUrl); };

            context["The user is already logged in"] = () =>
            {
                before = () => identity.Setup(x => x.IsAuthenticated).Returns(true);
                context["The external login succeeds"] = () =>
                {
                    before = () => oauth.Setup(x => x.VerifyAuthentication(It.IsAny<string>())).Returns(new AuthenticationResult(true, providerName, "provideruserid", "username", new Dictionary<string, string>()));
                    context["External login already exists for current user"] = () =>
                    {
                        before = () => authService.Setup(x => x.ExternalLoginExistsForUser(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(true);
                        it["Should add 'login sucessful' alert"] = () =>
                        {
                            var alerts = (IList<Alert>)controller.TempData[TempDataKeys.AlertCollection];
                            alerts[0].Message.should_be_same("Login successful");
                            alerts[0].AlertType.should_be(AlertType.Success);
                        };
                        it["Should return a redirect result"] = () => actionResult.should_cast_to<RedirectToRouteResult>();
                    };
                    context["External login already exists for another user"] = () =>
                    {
                        before = () => authService.Setup(x => x.ExternalLoginExistsForAnyOtherUser(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(true);
                        it["Adds an error alert"] = () =>
                        {
                            var alerts = (IList<Alert>)controller.TempData[TempDataKeys.AlertCollection];
                            alerts[0].Message.should_be_same("The external login you requested is already associated with a different user account");
                            alerts[0].AlertType.should_be(AlertType.Error);
                        };
                        it["Should return a redirect result"] = () => actionResult.should_cast_to<RedirectToRouteResult>();
                    };
</code>```

This approach seemed to work magnificently until I prepared to write test code for my ApplicationServices layer, to which I delegate viewmodel manipulation from my MVC controllers, and which coordinates the operations of the lower data repository layer:

```<code>public void CreateUserAccountFromExternalLogin(RegisterExternalLoginModel model)
{
    throw new NotImplementedException();
}

public void AssociateExternalLoginWithUser(string userName, string provider, string providerUserId)
{
    throw new NotImplementedException();
}

public string GetLocalUserName(string provider, string providerUserId)
{
    throw new NotImplementedException();
}
</code>```

I have no idea what in the world to name the test class, the test methods, or even if I should perhaps include the testing for this layer into the test class from my large code snippet above, so that a single feature or user action could be tested without regard to architectural layering.

I can't find any tutorials or blog posts which cover more than simple examples, so I would appreciate any recommendations or pointing in the right direction.  I would even welcome "your question is invalid"-type answers as long as some explanation is provided.

答:
Beware: I've never actually used NSpec, but I use it's cousin RSpec all the time. It's my experience with that tool that leads me to the following answer.

I suggest using this naming convention:

```<code>class describe_your_class : nspec
{
  void instance_method_CreateUserAccountFromExternalLogin()
  {
    before = () =>
    {
      account_repository = new AccountRepository();
      fixture = new YourClass(account_repository);
    }
    context["with a valid external login model"] = () =>
    {
      before = () =>
      {
        account = CreateValidAccountForTesting();
        fixture.CreateUserAccountFromExternalLogin(account);
      }
      it["creates a user account"] = () => account_repository.count.should_be(1);
    }
    context["with a null external login model"] = () =>
    {
      before = () =>
      {
        fixture.CreateUserAccountFromExternalLogin(null);
      }
      it["silently does not create a user"] = () => account_repository.count.should_be(0);
    }
  }
}
</code>```

In RSpec this would look like:

```<code>describe YourClass do
  # "#method_name" is a convention that's used in Ruby docs to refer to an
  # instance method. ".method_name" would refer to a class method
  describe '#create_user_account_from_external_login' do
    before do
      # the "@" here indicates that these are instance variables
      @account_repository = AccountRepository.new
      @fixture = YourClass.new(@account_repository)
    end

    context 'with a valid external login' do
      before do
        account = create_valid_account_for_testing()
        @fixture.create_user_account_from_external_login(account)
      end
      it 'creates a user account' do
        @account_repository.count.should == 1
      end
    end

    context 'with a nil external login' do
      before do
        @fixture.create_user_account_from_external_login(nil)
      end
      it 'silently does not create a user account' do
        @account_repository.count.should == 0
      end
    end
  end
end
</code>```

There are other constructs that RSpec provides, so I probably wouldn't write my spec exactly like the one above, but I would be able to understand someone else's that I came across. There's a great RSpec focused site called Better Specs that might give you more inspiration. You'll have to translate some of the syntax, of course.

Body:
Beware: I've never actually used NSpec, but I use it's cousin RSpec all the time. It's my experience with that tool that leads me to the following answer.

I suggest using this naming convention:

class describe_your_class : nspec
{
  void instance_method_CreateUserAccountFromExternalLogin()
  {
    before = () =>
    {
      account_repository = new AccountRepository();
      fixture = new YourClass(account_repository);
    }
    context["with a valid external login model"] = () =>
    {
      before = () =>
      {
        account = CreateValidAccountForTesting();
        fixture.CreateUserAccountFromExternalLogin(account);
      }
      it["creates a user account"] = () => account_repository.count.should_be(1);
    }
    context["with a null external login model"] = () =>
    {
      before = () =>
      {
        fixture.CreateUserAccountFromExternalLogin(null);
      }
      it["silently does not create a user"] = () => account_repository.count.should_be(0);
    }
  }
}

In RSpec this would look like:

describe YourClass do
  # "#method_name" is a convention that's used in Ruby docs to refer to an
  # instance method. ".method_name" would refer to a class method
  describe '#create_user_account_from_external_login' do
    before do
      # the "@" here indicates that these are instance variables
      @account_repository = AccountRepository.new
      @fixture = YourClass.new(@account_repository)
    end

    context 'with a valid external login' do
      before do
        account = create_valid_account_for_testing()
        @fixture.create_user_account_from_external_login(account)
      end
      it 'creates a user account' do
        @account_repository.count.should == 1
      end
    end

    context 'with a nil external login' do
      before do
        @fixture.create_user_account_from_external_login(nil)
      end
      it 'silently does not create a user account' do
        @account_repository.count.should == 0
      end
    end
  end
end

There are other constructs that RSpec provides, so I probably wouldn't write my spec exactly like the one above, but I would be able to understand someone else's that I came across. There's a great RSpec focused site called Better Specs that might give you more inspiration. You'll have to translate some of the syntax, of course.


问:
How Do You Organize Your Methods in OO Progamming
Whenever I am programming in an object-oriented language, I am always faced with what order and how to group the methods for an object. Are there any standards for this, or any suggestions?</p>

答:
I don't know of any standard, but when I write an object I like to write out the method names first in a functional grouping, in coarse order of execution, with internal methods immediately after the method they were first written to be called by.

Were I asked to re-organize an existing class, of my own or someone else's, my first concern would be to group similar methods together, and have them in rough order of execution frequency.  Different method signatures, if allowed, would always be listed together and in order of increasing complexity.

So, if I had a Box class with a constructor and methods to move the box or add contents to it, I might organize them as follows.

Constructors first

new Box()

new Box(contents)

Main functional group second.

getContents

addItem

removeItem

Secondary functional group third.

pickUp

putDown

move

moveLeft

moveRight

moveUp

moveDown

Of course, this is just a style question.  Anyone using your code won't see the public methods or properties in internal source order, and anyone having to maintain your code will hopefully use a tool that guides them through it.


答:
@jmoreno's answer is spot on.  And another good thing about GPL (or open source in general) is that it frees you from worrying about what the customer might do with your "proprietary" code after you have moved on to the next job.  If you've given it to them, you don't need to worry about them stealing it.

However, if you are concerned about them attempting to resell it (in some form), then you may need to keep an eye out for signs that this has happened.  Depending on how they did that, it could be a breach of the GPL (and your copyright) and potential grounds to sue them.

But if you simply don't care about that (and you are happy for them to try to make a buck from "your" code) then maybe something like the Bsd or Apache licenses would be more appropriate.

But note that you need to deal with these issues at the point where you sign the initial agreement with your client.  They need to sign off on you releasing the relevant part of your work for them under the GPL ... and on who will own the copyright.  You can only release something as GPL (or under some other open source license) if you actually own the copyright.  And the fact that you wrote it doesn't necessarily mean that you do.  (In some legal jurisdictions, the entity that is paying the bills for the work may own the copyright on work product ... by default.)

Title: Freelancing and GPL?

Body: Is it possible for a freelance programmer to use Open Source products under GNU Public License and make money given that he cannot stop his customers from freely distributing his products?</p>


答:
I don't think there's a simple answer to this. It's not a yes or no question. While I believe that style and naming conventions are important to an extent, it's also pretty easy to waste too much time thinking about it. It's best to answer by example.

On one particular project I was on, there were no conventions at all. Every developer did things in their own way. Because of the relative inexperience of this team, going from one class to the next was really jarring. The style was less of an issue than the naming conventions problem. One developer would reference UI elements with awful Hungarian notation (a silly practice in the age of modern IDE's), one would name private members one way, another would name them differently. You just never knew what you were looking at.

At the opposite extreme, one team used StyleCop (this was a .Net project) as part of their build process. What's worse, is that they also used most of the default rules. So you would do something totally normal in terms of line spacing or curly bracket placement, and the build would puke because of it. So much time was wasted just adding spaces and lines to stuff, and everyone, including the dudes who insisted using StyleCop, ended up doing it almost every commit. It was an enormous waste of time and money.

So the point I'm making here is that being inflexible isn't the answer, but being in the Wild West isn't either. The real answer is to find the place that makes the most sense, which in my opinion is to not have automated tools checking stuff, but not throwing convention to the wind, either.


问:
Why do C# and Java use reference equality as the default for '=='?
I've been pondering for a while why Java and C# (and I'm sure other languages) default to reference equality for ==.

In the programming I do (which certainly is only a small subset of programming problems), I almost always want logical equality when comparing objects instead of reference equality. I was trying to think of why both of these languages went this route instead of inverting it and having == be logical equality and using .ReferenceEquals() for reference equality.

Obviously using reference equality is very simple to implement and it gives very consistent behavior, but it doesn't seem like it fits well with most of the programming practices I see today.

I don't wish to seem ignorant of the issues with trying to implement a logical comparison, and that it has to be implemented in every class. I also realize that these languages were designed a long time ago, but the general question stands.

Is there some major benefit of defaulting to this that I am simply missing, or does it seem reasonable that the default behavior should be logical equality, and defaulting back to reference equality it a logical equality doesn't exist for the class?

答: C# does it because Java did.  Java did because Java does not support operator overloading.  Since value equality must be redefined for each class, it could not be an operator, but instead had to be a method.  IMO this was a poor decision. It is much easier to both write and read a == b than a.equals(b), and much more natural for programmers with C or C++ experience, but a == b is almost always wrong.  Bugs from the use of == where .equals was required have wasted countless thousands of programmer hours.


答:
For Java and C# the benefit lies in their being object oriented.

From a performance point of view - the easier to write code should also be quicker: since OOP intends for logically distinct elements to be represented by different objects, checking reference equality would be quicker, taking into consideration that objects can become quite large.

From a logical point of view - equality of an object to another does not have to be as obvious as comparing to object's properties for equality (ex. how is null==null logically interpreted? this can differ from case to case).

I think what it boils down to, is your observation that "you always want logical equality over reference equality". The consensus amongst the language designers was probably the opposite. I personally find it hard to evaluate this, since I lack the broad spectrum of programming experience. Roughly, I use reference equality more in optimisation algorithms, and logical equality more in handling data-sets.

Title: Why do C# and Java use reference equality as the default for '=='?

Body:
I've been pondering for a while why Java and C# (and I'm sure other languages) default to reference equality for ==.

In the programming I do (which certainly is only a small subset of programming problems), I almost always want logical equality when comparing objects instead of reference equality. I was trying to think of why both of these languages went this route instead of inverting it and having == be logical equality and using .ReferenceEquals() for reference equality.

Obviously using reference equality is very simple to implement and it gives very consistent behavior, but it doesn't seem like it fits well with most of the programming practices I see today.

I don't wish to seem ignorant of the issues with trying to implement a logical comparison, and that it has to be implemented in every class. I also realize that these languages were designed a long time ago, but the general question stands.

Is there some major benefit of defaulting to this that I am simply missing, or does it seem reasonable that the default behavior should be logical equality, and defaulting back to reference equality it a logical equality doesn't exist for the class?


问:
Why do many PHP Devs hate using isset() and/or any of PHP's similarly defensive functions like empty()?
Over on stackoverflow, I see this issue crop up all the time:

E_NOTICE ?== E_DEBUG, avoiding isset() and @ with more sophisticated error_handler

How to set PHP not to check undefind index for $_GET when E_NOTICE is on?

How to stop PHP from logging PHP Notice errors

How do I turn off such PHP 5.3 Notices ?

Even Pekka (who offers a lot of solid PHP advice) has bumped against the dreaded E_NOTICE monster and hoped for a better solution than using isset(): isset() and empty() make code ugly

Personally, I use isset() and empty() in many places to manage the flow of my applications.  For example:

```<code>public function do_something($optional_parameter = NULL) {
    if (!empty($optional_parameter)) {
        // do optional stuff with the contents of $optional_parameter
    }
    // do mandatory stuff
}
</code>```

Even a simple snippet like this:

```<code>if (!isset($_REQUEST['form_var'])) {
    // something's missing, do something about it.
}
</code>```

seems very logical to me.  It doesn't look like bloat, it looks like stable code.  But a lot of developers fire up their applications with E_NOTICE's enabled, discover a lot of frustrating "uninitialized array index" notices, and then grimace at the prospect of checking for defined variables and "littering" their code with isset().

I assume other languages handle things differently.  Speaking from experience, JavaScript isn't as polite as PHP.  An undefined variable will typically halt the execution of the script.  Also, (speaking from inexperience) I'm sure languages like C/C++ would simply refuse to compile.

So, are PHP devs just lazy?  (not talking about you, Pekka, I know you were refactoring an old application.)  Or do other languages handle undefined variables more gracefully than requiring the programmer to first check if they are defined?

(I know there are other E_NOTICE messages besides undefined variables, but those seem to be the ones that cause the most chagrin)

Addendum

From the answers so far, I'm not the only one who thinks isset() is not code bloat.  So, I'm wondering now, are there issues with programmers in other languages that echo this one?  Or is this solely a PHP culture issue?

答: I use isset and empty plenty. But mostly it's places that you mention, like $_REQUEST processing, in case anyone's been messing with the parameters. In cases where I have control over all the variables flying around, I find that I usually don't need them.</p>


问:
Are unused CSS rules so costly that they must be removed?
I have been reading various Web application optimizing articles and many of them suggest to remove unused CSS rules. Currently, I have a page which has jQueryUI css, Bootstrap CSS, Datatables CSS and couple of more. All together they translate to about couple of thousands of rules ( my estimate ) and am quite sure I am using only 20-30%

I asked my friend in UK who has very high speed broadband, to check the page load time and he says, like for every other page on his connection this one too loaded in a second which is quite suggestive that rendering time seems insignificant to the page load time. How much improvement is expected in removing unused CSS rules? Is it really worth it?

答:
I think there is an impact although fairly small in terms of page loading times. If for example you had developers who never follow best practices and don't try and keep CSS clean etc then the impact can start building up. Ultimately, if you have well structured, organised and clean CSS, the users experience is generally improved and they can navigate the site quicker.

In addition to removing unused CSS, another way to improve page loading times is to use  minification of your CSS (and javascript):
http://www.minifycss.com/, http://cssminifier.com/

Similar question: https://stackoverflow.com/questions/6669672/what-is-the-performance-impact-of-having-many-unused-css-selectors-rules


答:
I asked my friend in UK who has very high speed broadband, to check the page load time

This is not the right way to measure performance. It cannot be automated, it's not a precise metric, it cannot be reliably reproduced and is inherently subjective. The right way is to:

Determine non-functional requirements specifying the expected performance for page rendering under strict conditions.

Ask yourself if you have performance concerns, i.e. whether those non-functional requirements are not matched by the actual code.

If there is actually a problem with performance, run a profiler to determine the bottleneck. Most browsers have one, showing the details about what is really happening. If JavaScript processing takes 1 300 ms. and CSS processing - 25 ms., don't care about CSS right now.

If you've found, according to the benchmarks and the profiler, that the difference between the expected rendering time (specified in the requirements) and the actual tested time is due to CSS, then use several techniques to optimize your CSS. Google documentation is a good start.

Here's a test done on the home page of Programmers.SE. CSS selector profile took 59 ms. with following details:

```<code>Selector                                                         Total  Matches   Source
―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
.widget_ad_rotator, .widget_adrotate_widgets, .widget_ads [...]  57.6%        0
html, body, div, span, applet, object, iframe, h1, h2, h3 [...]  11.9%     3862   all.css
a:-webkit-any-link                                                5.1%      913
:focus                                                            3.4%        0
input[type=button], input[type=submit], input[type=reset] [...]   3.4%        4
div                                                               3.4%     2101
.badge:hover                                                      1.7%        0   all.css
a:visited                                                         1.7%      913   all.css
</code>```

As you can see, most performance loss comes from the fact that I'm using an add blocker in my browser. That sucks, since I don't want to block ads on Stack Exchange. Now that I whitelisted Stack Exchange, the CSS selector time went from 59 ms. down to 23 ms.

The second most expensive selector is a global one which takes on elements identified by their tag names. This is expensive given the number of matches, and there is probably nothing one can do to optimize that, without getting being too much hurt from browser inconsistencies.

The next four are related to Webkit, not the CSS written for the web page.

Starting from the seventh selector, the percentage is too low to care. The actual one, .badget:hover, is not used, but removing it on this page while it's used on other ones would create code difficult to maintain, and especially would represent a gain inferior to 100 microseconds.

From my experience (of a developer who works only on small to medium scale web apps, and not the apps which are accessed thousands of times per second), what you should take care of is the complexity of CSS. Selectors like:

```<code>body.en-us div#sidePanel.moveable div:first-child input[type=submit]:hover,
*.lang.en-us div#sidePanel.moveable div:first-child input[type=submit]:hover {
    color:#59a;
}
</code>```

are both unreadable for developers and slow for browsers. Avoiding feature creep in the website and simplifying the styles to:

```<code>#sidePanel .top-submit:hover {
    color:#59a;
}
</code>```

worth the effort. In the same way:

```<code>.style {
    background-color: #000000;
    background-image: url('im/fade.jpg');
    background-repeat: repeat-x;
    background-position: top left;
}
</code>```

by:

```<code>.style {
    background: #000 url(im/fade.jpg) repeat-x top;
}
</code>```

is not too difficult, and largely simplifies the maintenance (see also Google CSS Style Guide).

But I wouldn't spend hours removing 20% of styles just because they are not used, in order to gain a few milliseconds. Especially when using LESS/Sass.

Title: Are unused CSS rules so costly that they must be removed?

Body:
I have been reading various Web application optimizing articles and many of them suggest to remove unused CSS rules. Currently, I have a page which has jQueryUI css, Bootstrap CSS, Datatables CSS and couple of more. All together they translate to about couple of thousands of rules ( my estimate ) and am quite sure I am using only 20-30%

I asked my friend in UK who has very high speed broadband, to check the page load time and he says, like for every other page on his connection this one too loaded in a second which is quite suggestive that rendering time seems insignificant to the page load time. How much improvement is expected in removing unused CSS rules? Is it really worth it?

Body:
I asked my friend in UK who has very high speed broadband, to check the page load time

This is not the right way to measure performance. It cannot be automated, it's not a precise metric, it cannot be reliably reproduced and is inherently subjective. The right way is to:

Determine non-functional requirements specifying the expected performance for page rendering under strict conditions.

Ask yourself if you have performance concerns, i.e. whether those non-functional requirements are not matched by the actual code.

If there is actually a problem with performance, run a profiler to determine the bottleneck. Most browsers have one, showing the details about what is really happening. If JavaScript processing takes 1 300 ms. and CSS processing - 25 ms., don't care about CSS right now.

If you've found, according to the benchmarks and the profiler, that the difference between the expected rendering time (specified in the requirements) and the actual tested time is due to CSS, then use several techniques to optimize your CSS. Google documentation is a good start.

Here's a test done on the home page of Programmers.SE. CSS selector profile took 59 ms. with following details:

Selector                                                         Total  Matches   Source
―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――
.widget_ad_rotator, .widget_adrotate_widgets, .widget_ads [...]  57.6%        0
html, body, div, span, applet, object, iframe, h1, h2, h3 [...]  11.9%     3862   all.css
a:-webkit-any-link                                                5.1%      913
:focus                                                            3.4%        0
input[type=button], input[type=submit], input[type=reset] [...]   3.4%        4
div                                                               3.4%     2101
.badge:hover                                                      1.7%        0   all.css
a:visited                                                         1.7%      913   all.css

As you can see, most performance loss comes from the fact that I'm using an add blocker in my browser. That sucks, since I don't want to block ads on Stack Exchange. Now that I whitelisted Stack Exchange, the CSS selector time went from 59 ms. down to 23 ms.

The second most expensive selector is a global one which takes on elements identified by their tag names. This is expensive given the number of matches, and there is probably nothing one can do to optimize that, without getting being too much hurt from browser inconsistencies.

The next four are related to Webkit, not the CSS written for the web page.

Starting from the seventh selector, the percentage is too low to care. The actual one, .badget:hover, is not used, but removing it on this page while it's used on other ones would create code difficult to maintain, and especially would represent a gain inferior to 100 microseconds.

From my experience (of a developer who works only on small to medium scale web apps, and not the apps which are accessed thousands of times per second), what you should take care of is the complexity of CSS. Selectors like:

body.en-us div#sidePanel.moveable div:first-child input[type=submit]:hover,
*.lang.en-us div#sidePanel.moveable div:first-child input[type=submit]:hover {
    color:#59a;
}

are both unreadable for developers and slow for browsers. Avoiding feature creep in the website and simplifying the styles to:

#sidePanel .top-submit:hover {
    color:#59a;
}

worth the effort. In the same way:

.style {
    background-color: #000000;
    background-image: url('im/fade.jpg');
    background-repeat: repeat-x;
    background-position: top left;
}

by:

.style {
    background: #000 url(im/fade.jpg) repeat-x top;
}

is not too difficult, and largely simplifies the maintenance (see also Google CSS Style Guide).

But I wouldn't spend hours removing 20% of styles just because they are not used, in order to gain a few milliseconds. Especially when using LESS/Sass.


答:
When you are freelancing, copyright usually reverts to the company for which you are doing the work. Which means that you need to clear your use of GPL'd code with them, as they will have to comply with it when distributing their product.

If you retain all rights to your software, you would be selling a license to use your product to your customer(s) and that license needs to be compatible with the licenses of whatever libraries you used to create the product. Your customer needs to accept that license and make their customers accept it as well when the license you sold to them included re-distribution rights.

TL DR: when you use GPL'd code to create software for a customer, you need to make your customer aware of the consequences and they need to accept those consequences. If they are not willing to accept the consequences of GPL'd code, you should not use any GPL'd code in the solution you are building for them.

Title: Freelancing and GPL?


问:
Why the current enthusiasm for Functional Programming?
I've been hearing a lot of enthusiasm about functional programming languages lately, with regards to Scala, Clojure, and F#.  I've recently started studying Haskell, to learn the FP paradigm.

I love it, it's really fun, and fits my math background.

But will it ever really matter?  Obviously, it's hardly a new idea.

Here's my questions:

What has contributed to the recent FP enthusiasm?  Is is merely boredom with OO, or has something changed to make FP more needed than before?

Is this indicative of a FP future?  Or is this a fad, like object orient databases?

In other words, can anyone help me understand where this comes from and where it might be going?

答:
One of the major innovations in FP that has resulted in the "explosion" of interest is monads.

In January of 1992, Philip Wadler wrote a paper called The Essence of Functional Programming which introduced monads into functional programming as a way to deal with IO.

The major problem with pure, lazy, functional programming languages was utility in dealing with IO.  It's one of member of the "Awkward Squad" in programming, because "laziness and side effects are, from a practical point of view, incompatible.  If you want to use a lazy language, it pretty much has to be a purely functional language; if you want to use side effects, you had better use a strict language." Reference

The issue with IO before monads was that maintaining purity was not possible for programs that were actually useful for anything.  By IO, we mean anything that deals with changing state, including getting input and output from the user or environment.  In pure functional programming, everything is immutable, to allow laziness and purity (free from side effects).

How do monads solve the problem of IO?  Well, without discussing monads too much, they basically take the "World" (the runtime environment) as input to the monad, and produce a new "World" as output, and the result:  type IO a = World -> (a, World).

FP has therefore entered more and more into the mainstream, because the biggest problem, IO (and others) has been solved.  Integration into existing OO languages has also been happening, as you know.  LINQ is monads, for example, through and through.

For more information, I recommend reading about monads and the papers referenced in my answer.


答:
What the other answers have not touched upon: There is a huge difference between using a GPL library in your product or using a GPL tool in your toolchain to build the product.

If you just use a GPL editor or compiler (or other tool) to create your product, then this has no influence whatever on the licenses you can use for your product. It is perfectly well possible to use a GPL editor or other tool (such as GCC or Make) to create a closed-source application and you will not be violating any license terms in doing so.

If you use a GPL library in your product, or in some other way incorporate GPL code in the product, then you need to apply the GPL license to your code as well. Note that this situation can also occur if you use a tool that generates code for you.

As for making money from GPL software, the GPL does not forbid this so you are perfectly within your rights to charge a customer for the code you write for them or the maintenance you perform afterwards.
You can't forbid the customer from giving the source away, but then, why would they if they paid hard-earned cash for it themselves?

Title: Freelancing and GPL?


答:
Your situation reeks of the classic Shape hierarchy where a Square inherits from Rectangle (and adds the constraint that both dimensions are the same). This is generally regarded as failing the Liskov Substitution Principle (LSP), because the added constraint makes that the base-class operations are not always appropriate for the derived class.

If the getTrigger method is only meant for use within the hierarchy, then you could turn the inheritance between TriggerManager and TimedTriggerManager around (making TimedTriggerManager the base class), as a derived class may weaken the requirements placed on method parameters but not strengthen them.

If getTrigger is also meant for outside use, then TriggerManager and TimedTriggerManager can't have an inheritance relation with each other without violating the LSP.
In that case, it might be best to make TriggerManager and TimedTriggerManager sibling-classes that both inherit from a AbstractTriggerManager. The AbstractTriggerManager provides all the common functionality, but no public methods where TriggerManager and TimedTriggerManager place different requirements on the parameters (such as addTrigger).

Title: Making subclass more type-specific with accessors

Body:
I have a super class: TriggerManager with a subclass TimedTriggerManager. NOTE: I'm working in java

TimedTriggerManager only deals with TimedTrigger s, a subclass of Trigger. TriggerManager references all Trigger objects. To modify the subclass (TimedTriggerManager) to only accept TimedTriggers into its accessors and mutators (getters and setters) I have the following questions:

1) I have in TriggerManager the following public void addTrigger(Trigger t). In TimedTriggerManager should I just override the method to throw an error if the argument (t) is not a TimedTrigger. If so, What error should I throw? If not, what should I do?

2) Should I add another method getTimedTrigger to work alongside the supper class's getTrigger so that I don't have to keep type casting? (Since the latter would return a Trigger object)

3) Is there anything else I'm forgetting, or some common practice that I'm not doing?


问:
Why don't public web applications use ini files for configuration
Almost every public CMS out there uses a .php configuration file for the database settings and so on. For example WordPress automatically creates a .php config file when you install it.

Why don't they just use a .ini file? PHP already has parse_ini_file() and I'm sure other languages have similar functions.

答: Speed without caching can also be the reason. PHP config can be opcode-cached transparently if needed. Whereas INI file needs to be text-parsed every time it's read and you need to create the cache yourself. For small files it's ok, but with hundreds of lines parsed on every request it can raise to tens of miliseconds, which is quite a lot for 200ms optimized web. </p>


问:
Is imposing the same code format for all developers a good idea?
We are considering to impose a single standard code format in our project (auto format with save actions in Eclipse). The reason is that currently there is a big difference in the code formats used by several (>10) developers which makes it harder for one developer to work on the code of another developer. The same Java file sometimes uses 3 different formats.

So I believe the advantage is clear (readability => productivity) but would it be a good idea to impose this? And if not, why?

UPDATE

We all use Eclipse and everyone is aware of the plan. There already is a code format used by most but it is not enforced since some prefer to stick to their own code format. Because of the above reasons some would prefer to enforce it.

答:
My main argument against common coding style is that an experienced programmer is used to read his own style. You can train the hand to write a specific style but it is nearly impossible to train the eye to understand a style that you hate. A programmer writes some piece of code once and then reads it again and again during development and debugging. If every time he reads his own code he struggles to understand it since he was forced to write it in a BAD style he will be very unhappy and less productive. This is from my on experience.

I am not too familiar with Eclipse but auto format on save sounds like an horrific idea.
A developer must have complete control over his code regardless of whether coding style is imposed or not. 'save' operation must not change a single character without explicit consent from the user.

If your company sells source code then coding style is more important but if you sell compiled code then it is much less relevant.

Hoping that coding style will make the original coder less distinguishable and prevent ego wars is bullshit in the best case and plain stupid in the worst case. Great programmers will always produce elegant code regardless of the style.

I am also strongly pro giving every developer ownership of specific code units and against letting everyone touch every piece of code freely. Developing whole units in the code and being responsible for them allow the developer to grow pride in his work and prevent him from developing crappy code knowing that bugs will return to hunt him.

Finally, anyone who is pro coding style always assume that his own coding style will be selected and everyone else will follow. Imagine that the coding style you least like from all of your co-developers being selected as standard. Are you still in favor of imposing coding style?


答: It's languages not codes. We humans have more than 6000 languages so we translate them. So if you want your "codes" to communicate you'll have to make your adjustments. You see we users have to change our data formats so we won't loose our data.</p>


问:
How were the first compilers made?
I always wonder this, and perhaps I need a good history lesson on programming languages.
But since most compilers nowadays are made in C, how were the very first compilers made (AKA before C) or were all the languages just interpreted?

With that being said, I still don't understand how even the first assembly language was done, I understand what assembly language is but I don't see how they got the VERY first assembly language working (like, how did they make the first commands (like mov R21) or w/e set to the binary equivalent?

答:
The first compilers were implemented using assembly language.  And the first assemblers were implemented by coding programs in binary ...

It is not THAT long ago that programming in binary was still a skill that people used.

When I was an undergraduate, I remember doing a programming exercise that entailed writing a tiny program in PDP-8 (I think) machine code, entering it via the front panel switches, and running it.  I couple of years later, I bought myself a 6502 system development kit that had a hex keypad for entering programs ... and 4k bytes of RAM.

Title: How were the first compilers made?


问:
How do I convince my company to contribute towards Open-Source?
I'm trying to convince the company I work for to contribute towards open-source software, specifically building a library/component for ASP.NET web apps. We have an 'Innovation Day' coming up where we can work on our own personal pet projects at work, similar to Google's one day a week policy, except ours is once a month :-), and I have an idea that I want to open-source.

Other companies do this, eg. Headspring Systems (http://automapper.codeplex.com - see banner at top).

What do I tell them? What benefits can I convey to them that would be beneficial to the company? I've already mentioned possible exposure for our company and reputation etc. as well as attracting top software developers when we next go on a hiring spree. But what other arguments could I make?

Update: The company I work for is a software company that mainly builds web applications in ASP.NET and the MS Stack. Our clients are mainly the NHS (public health sector of the UK).

答:
You have to make a business case.  I've done this before by making the case that the intellectual property we'd be open sourcing wasn't a core business asset (didn't differentiate us), but by releasing the code we'd be creating a marketing channel to the users of that open source code, who just also happen to be our target audience.

You can use this theory: "Commoditize Your Complements"


问:
Is it okay to call a model method in my view?
In the interest of keeping my Controller's skinny, I put a headline method in a Model.

```<code># My Model
class Property
  def headline
    "#{name} | #{address}"
  end
end
</code>```

(Then, Property Controller for context...)

```<code># My Controller
class PropertyController
  def show
    @property = Property.find(params[:id])
  end
end
</code>```

Question: As far as MVC is concerned, is it okay to call that Model method from my View, like so?

```<code># My View
<h1><%= @property.headline %></h1>
</code>```

答:
In certain MVC variants, the view gets notified of changes in the model via the controller: the view registers as a listener on model-changed notifications, but the view never calls methods of the model (see e.g. the diagram in the wikipedia article).

In another variant, the view queries (calls getter methods of) the model directly to get the data to be displayed. However, the view should only be able to query the model, not to change its contents. To my knowledge, this is the JSP approach: the view (a JSP page) can contain queries that get data from the model to be rendered with the rest of the page.

As far as I understand, your example follows the second approach and it is therefore OK since the view is only querying the model via @property.headline.