问:
How to get money from reluctant client?
I completed this website 4 months ago. (I would like to keep the website anonymous - if this post comes up on google search by customers, it will have a negative impact on their business). We did several iterations, the client was very demanding (and nosy), I complied with every single thing that was wanted, including the font-size of the footer which destroyed the aesthetic looks by quite a bit; (and they messed with the colours too, making it look dangerously childish and unprofessional).

Anyway, the client was very friendly during the whole process. After getting all the requirements I accepted to build the website for £950 and I charged him £150 in advance so he wouldn't want to bail out after I started the work. The requirements kept changing quite a lot, I made adjustments as and completed the website just 5 days late, w.r.t. the agreed date, in-spite all the changes in requirements.

That was four months ago. They have never returned my calls nor replied to my emails since then. How do I get the money back from them? I really need some advice on this, this is the second time someone has not paid me.

Points to be noted:

We did not sign any contract - the client was a friend of a friend.

I still hold the passwords for ftp, cpanel and everything. I don't want to bring the site down; somehow it doesn't seem ethical to me.

I posted this on Stack Overflow and it was closed, I was redirected here.

EDIT

Thank you everyone, for your enormous support. I thought I should include some more details: The client is hosting the site; as in, I made them register and use their own debit card to buy the domain name, webspace and everything, I just have the passwords for his cpanel, and ftp (well, I have access to cpanel that pretty much gives me access to many things).

Now, if I give them a warning, he might change the password to cpanel, but I am fairly sure they doesn't know about ftp's.

UPDATE

I followed Anna Lear's advice and sent the final invoice, on Saturday, with a warning that I will take the site down if he doesn't respond to my email before this Tuesday. They havn't replied to my emails yet, but I will let you know how this goes. Thanks much for your support. I plan to put up a holding page as Darknight suggested after Tuesday.

Points

I don't have a server space of my own, however I have few web spaces of my clients but I don't want to use them for this kind of purpose.

RESULTS

After my follow up of final invoice and warning, the client refused to anything. workman's advice seemed to be the most sensible to me. I mirrored the site to my own webspace, logged into his CPanel and forwarded the website to my site. Once that was done, I put up a holding page on my site so anyone going to the website would see a holdup page (nothing fishy, just an Under Construction page). Of course, this was all very weak in the sense that if my client knew about CPanel he could just remove the redirection. But, I had this second chance to get back to him and I was relying on him not knowing anything.

Two hours later, I got a call from the said client, (and  acting as if they did not get any of my voice mails or emails) and asked me to get the site back up. I, of-course, said I had to be paid and two days after that I received a bank transfer. The site's back up and running now.

Just wanted to say thank you all very much, I was very desperate when I had started this question. You are the best, not only you told me to learn the lesson (which I did) you also gave me a very very good solution that seemed to be very ethical (almost) to me.

A BIG thank you to workman!

If I could choose more than once answer, I would have chosen Anna Lear  too, but since I followed workman's advice I had to pick that up. People who made a point about not taking the site down without consulting a lawyer, thanks a lot.

答:
Speak with your solicitor about this, as soon as you possibly can.  £800 is a bit too much money to let it slide.  (The FIRST thing your solicitor will say will likely be "Next time, put it in writing.")

Speak with your tax advisors, and make certain that you are not liable for taxes on the full £950, even though it has not been paid.

Someone else suggested talking with your mutual friend.  I second this advice.  If they attend the same church (yes, it is a long shot), you might consider speaking with the pastor of the church, and asking him to speak with the two of them.

If the hosting company is run by friends of yours, you MIGHT be able to get some traction by talking with them about the issue.  Officially, they won't be able to do anything, since he is paying them, not you, but they MIGHT be able to put some pressure on him.

If there is a formal or informal professional association of web designers in your area, by all means put the word out about him.  Sooner or later, he's going to need a modification to the site.  You of course are going to refuse to touch it, until he pays you the disputed amount, and then you will negotiate a written contract.  It would really help if everyone else he contacts says "I heard from Miss Understood about her problem with you, and, under the circumstances, I'm sure you will understand that I have to insist on a written, enforceable contract" or, better yet, "I heard from Miss Understood about her problem with you, and, under the circumstances, I'm sure you will understand when I suggest you go see her for maintenance."

Title: How to get money from reluctant client?


问:
Two closely related projects -- Two repositories or one?

Background

I am coding two closely related Java projects.
The first project is Single Facility Simulator,
which simulates a very simple supply chain with a single facility.
The second project is Supply Chain Simulator,
which simulates more complex supply chain networks,
i.e. multiple facilities arranged as a graph
with directed edges between some pairs of facilities.

The first project is a "toy" project in the sense that
I am using it to test and refine the high-level design of the project.
The second project is the "real" project that I am interested in for work purposes.
The high-level design of the two projects is the same,
although there are some differences,
for example a Demand object in the "toy" project only needs to generate a demand value per time period,
whereas a Demand object in the "real" project needs to generate a demand value per facility per time period.

Question

Currently, the "toy" project lives in its own Git repository.
As I begin implementing the "real" project,
should I fork the "toy" project,
or should I implement the "real" project as different packages in the same space as the "toy" project?

答: IMHO this decision should depend on the intended life cycle of your projects. If you are going to develop your "toy" project further, in parallel to your "real" project, and if you want to create a combined release of your both projects whenever you create a release of your "real" project, then one repository is better. But if you want to decouple the life cycle of your real project (almost) completely from your toy project, then two separate repositories will most probably be the better alternative.</p>

ContentLicense: CC BY-SA 3.0


问:
How to handle or prevent all Admins and users being removed
I have a website that stores all users in a database. A user can log on to the website and if they have sufficient privileges can add/delete users, as well as change their privileges.

How do I ensure there is always at least one Administrator (to create/edit/delete users) in the system or that an administrator can easily be added to the system.

Surely I can put rules in place so that the Admin can't delete himself, or other rules like that. But what if someone deletes all the users in the SQL table. The passwords are hashed so it's not as if the DBA can just go in and add a new user with Admin rights.

Do I hardcode some special username/password that automatically gets added to the system if no Admin exists?

答: Rather than focus on preventing people from circumventing the system I would focus on giving users a way to right the ship. In this case is it as simple as a command line app that lets them create an admin user in a pinch?</p>


问:
Help with design structure choice: Using classes or library of functions
So I have GUI Class that will call another class called ImageProcessor that contains a bunch functions that will perform image processing algorithms like edgeDetection, gaussianblur, contourfinding, contour map generations, etc. The GUI passes an image to  ImageProcessor, which performs one of those algorithm on it and it returns the image back to the GUI to display. So essentially ImageProcessor is a library of independent image processing functions right now.

It is called in the GUI like so

```<code>Image image = ImageProcessor.EdgeDetection(oldImage);
</code>```

Some of the algorithms procedures require many functions, and some can be done in a single function or even one line.

All these functions for the algorithms jam packed into ImageProcessor can be pretty messy, and ImageProcessor doesn't sound it should be a library. So I was thinking about making every algorithm be a class with a shared interface say IAlgorithm. Then I pass the IAlgorithm interface from the GUI to the ImageProcessor.

```<code>public interface IAlgorithm{
   public Image Process();
}
public class ImageProcessor{

  public Image Process(IAlgorithm TheAlgorithm){
        return IAlgorithm.Process();
  }
}
</code>```

Calling in the GUI like so

Image image = ImageProcessor.Process(new EdgeDetection(oldImage));

I think it makes sense in an object point of view, but the problem is I'll end up with some classes that are just one function. What do you think is a better design, or are they both crap and you have a much better idea? Thanks!

答:
I don't know if my solution could help you, but I think I'll create an abstraction:

```<code>interface ImageEffect {

    Image apply(Image source);

}
</code>```

and then:

```<code>class EdgeDetection implements ImageEffect {
    ...
}

class GaussianBlur implements ImageEffect {
    ...
}
</code>```

But, if you have only 2 or 3 effects I think you could simply create an object:

```<code>class Picture {

    private Image image;

    public Picture(Image image) {
        this.image = image;
    }

    public Picture edgeDetection() {
        this.image = [...]
    }

    public Picture gaussianBlur() {
        this.image = [...]
    }

    public Image toImage() {
        return image;
    }

}
</code>```

so that in the end you can call something like this:

```<code>[...]
new Picture(myimage)
    .edgeDetection()
    .gaussianBlur()
    .toImage();
[...]
</code>```

Why I suggest 2 ways to solve the same problem? The reason is that the solution you need depends on what "forces" are engaged in your software. You are the only one that can manage this "forces" and the design you'll create it will be simply a "side effect". I suggest you to use TDD to find the design good for you.

Body:
I don't know if my solution could help you, but I think I'll create an abstraction:

interface ImageEffect {

    Image apply(Image source);

}

and then:

class EdgeDetection implements ImageEffect {
    ...
}

class GaussianBlur implements ImageEffect {
    ...
}

But, if you have only 2 or 3 effects I think you could simply create an object:

class Picture {

    private Image image;

    public Picture(Image image) {
        this.image = image;
    }

    public Picture edgeDetection() {
        this.image = [...]
    }

    public Picture gaussianBlur() {
        this.image = [...]
    }

    public Image toImage() {
        return image;
    }

}

so that in the end you can call something like this:

[...]
new Picture(myimage)
    .edgeDetection()
    .gaussianBlur()
    .toImage();
[...]

Why I suggest 2 ways to solve the same problem? The reason is that the solution you need depends on what "forces" are engaged in your software. You are the only one that can manage this "forces" and the design you'll create it will be simply a "side effect". I suggest you to use TDD to find the design good for you.


问:
Object-Oriented Class Design
I was wondering about good object oriented class design. In particular, I have a hard time deciding between these options:

static vs instance method

method with no parameters or return value vs method with parameters and return value

overlapping vs distinct method functionality

private vs public method

Example 1:

This implementation uses instance methods, with no return value or parameters, with no overlapping functionality, and all methods public

```<code>XmlReader reader = new XmlReader(url);
reader.openUrl();
reader.readXml();
Document result = reader.getDocument();
</code>```

Example 2:

This implementation uses static methods, with return values and parameters, with overlapping functionality and private methods

```<code>Document result = XmlReader.readXml(url);
</code>```

In example one, all methods are public instance, which makes them easy to unit test. Although all methods are distinct, readXml() is dependent on openUrl() in that openUrl() must be called first. All data is declared in instance fields, so there's no return values or parameters in any method, except in the constructor and accessors.

In example two, only one method is public, the rest are private static, which makes them hard to unit test. Methods are overlapping in that readXml() calls openUrl(). There's no fields, all data is passed as parameters in methods and the result is returned immediately.

What principles should I follow to do proper object oriented programming?

答:
I won't answer to your question, but I think that an issue is created by the terms you have used. E.g.

```<code>XmlReader.read => twice "read"
</code>```

I think you need an XML so I'll create an object XML that can be created from a textual type (I don't know C#... in Java it's called String). E.g.

```<code>class XML {
    XML(String text) { [...] }
}
</code>```

You can test it and it's clear. Then if you need a factory, you can add a factory method (and it can be static like your 2nd example).
E.g.

```<code>class XML {
    XML(String text) { [...] }

    static XML fromUrl(url) { [...] }

}
</code>```

Title: Object-Oriented Class Design

Body:
I won't answer to your question, but I think that an issue is created by the terms you have used. E.g.

XmlReader.read => twice "read"

I think you need an XML so I'll create an object XML that can be created from a textual type (I don't know C#... in Java it's called String). E.g.

class XML {
    XML(String text) { [...] }
}

You can test it and it's clear. Then if you need a factory, you can add a factory method (and it can be static like your 2nd example).
E.g.

class XML {
    XML(String text) { [...] }

    static XML fromUrl(url) { [...] }

}

ContentLicense: CC BY-SA 4.0


问:
Object model design: collections on classes
Consider Train.Passengers, what type would you use for Passengers where passengers are not supposed to be added or removed by the consuming code?

I'm using .NET Framework, so this discussion would suit .NET, but it could apply to a number of modern languages/frameworks.

In the .NET Framework, the List<Person> is not supposed to be publicly exposed. There's Collection<Person> and ICollection<Person> and guidance, which I tend to agree with, is to return the closest concrete type down the inheritance tree, so that'd be Collection<Person> since it is already an ICollection<Person>.

But Collection has read/write semantics and so possibly it should be a ReadOnlyCollection<Person>, but its arguably common sense not to alter the contents of a collection that you don't have intimate knowledge about so is it necessary?

And it requires extra work internally and can be a pain with (de)serialization.

At the extreme ends I could just return Person[] (since LINQ now provides much of the benefits that previously would have been afforded by a more specified collection) or even build a strongly-typed PersonCollection or ReadOnlyPersonCollection!

What do you do?

答:
I would consider the behaviours of passengers.
E.g. if you don't want behaviours provided by basic types it's better to create custom types...

In Object Oriented an object should exists only if it has "behaviours" (see for example what says about this Allen Holub). So, my answer means that in my application I will design Passengers as a collection of Passenger if I don't have any additional behaviour. But once I found I need a behavoiur like "remove all Passengers under 10 years old", I'll create Passengers as a custom object with an internal collection showing a message "removePassengersYoungerThan(int years)".

I think each collection need a specific design. In the same application, too.

I hope this will be more clear than previous answer.


问:
Are there more efficient ways to search for help/documentation than Google/SO/...?
Google sometimes come up with irrelevant links, not everything is available on SO, there are cases where the local documentation is also annoying to look through... Are there other efficient ways you use to search?</p>

答: I honestly just use google with enough keywords to get the directly to the documentation without having to pull up giant RAM eating pages like the entire Java 6 class list. </p>

ContentLicense: CC BY-SA 2.5


问:
What would you add in this Software Development Project Checklist?
I'm a big fan of checklists. There is Travel Checklist, Moving Checklist and even a Scrum Checklist.

Context: you have been hired by a large corporation and given the mission to setup the whole software development environment, processes, team, etc. You have "carte blanche". You will be responsible for the creation of the working increments of the software. Project size: 2000 man/days.

What items would you add to the following (intentionally small and incomplete) checklist:

Install a Continuous Integration Server

Write a DoD

Write a one page coding guidelines

Create a product backlog

Install a Bug Tracking System

Schedule Regular Face Time

答:
Seeing as I've had the most problem with 3rd party libraries and their usage:

Determine the libraries and versions you're going to be using.

Create the process of integrating library updates to your project.

Make sure the developers are all on board the library choices.

Create a beneficial channel for open discussion on technologies being used.

Why?  I can't tell you the number of times 3rd party libraries (proprietary) have had henious bugs which sent us back weeks of development time because we had no process for moving up or back down.  Or dealing with developers saying "which version did you use?  Why did you use functions marked deprecated?"


问:
Making a sldprt to PDB file converter?
I wanted to create a parser that can read a solidworks file and turn it into a protein data bank file.  This has already been done in a program called DiamondCAD. http://www.zyvex.com/Research/DiamondCAD.html

I waant to make a parser that can parse the data and then visualize it the same way as DiamondCAD.  I have downloaded and opened solidworks files before and they make no sense to me with never before seen symbols and looks like ancient writing.

Does anyone know how a sldprt. file is structured and how it can be parsed into a PDB file? (A  software called VMD converts a PDB to Obj. file so it is proof of concept)

答:
Solidworks can save the .sldprt to many other formats.  .stp may be the easiest to work with, as it is just text.

.sldprt format is proprietary and changes every year.

Good luck!

Title: Making a sldprt to PDB file converter?


问:
Blocks of Javascript in Web Pages
I'm trying to find the best patterns for javascript usage in my sites, and in doing so I tend to look at source code at some sites (meetup.com, facebook.com, etc).  One thing that sticks out at me is the fact these sites seem to compress all of their javascript and place it in the actual page rather than using a

答:
How are they compressing (or how would one compress) the javascript? Should I use YUIcompress on every page call?

I usually use something like UglifyJS prior to uploading my script files. Doing it every single time you have a page call doesn't seem very efficient. It's preferable to already have the JavaScript minified/compressed before you make it available as a resource on the page.

What is the benefit of doing things this way rather than importing separate scripts? I would think the separate scripts would make the page itself load quicker.

There is some debate about whether loading an external script file vs having the script inline is faster or slower. If you have the script inline it's one less resource that needs to be loaded before the page is loaded. Typically, if your script is small (less than 10-15 lines), it's better to just have it in a  block on the page rather than an external file.

Google has a plugin called PageSpeed that will analyze your site and show you some ways that you can optimize it. They have a number of articles that touch on JavaScript optimization.

Title: Blocks of Javascript in Web Pages


答:
What is the benefit of doing things this way rather than importing separate scripts? I would think the separate scripts would make the page itself load quicker.

In a word "caching" your browser can cache the downloaded script file and use it again and again without recourse to the network. If you embed your javascript in HTML then it gets downloaded with every page request.

But that's just the beginning. Modern browsers will also cache the parser's results so the script needs to be parsed only once, some will even compile snippets to machine code and cache the resulting executable. All these aggressive optimizations depend on having a recognizable static source, its much harder to do when the javascript is mixed in with random web pages.

Title: Blocks of Javascript in Web Pages

Body: I'm trying to find the best patterns for javascript usage in my sites, and in doing so I tend to look at source code at some sites (meetup.com, facebook.com, etc).  One thing that sticks out at me is the fact these sites seem to compress all of their javascript and place it in the actual page rather than using a


问:
How to choose between different open-source libraries?
Recently, I found multiple GitHub repositories that would allow me to perform the same task. (In my case, assess the readability of text strings.)

It made me wonder, what are the best practices for programmers to choose between different open-source libraries, and in particular, libraries hosted on GitHub?

GitHub statistics of users who watch, star, or fork a repository are one option, but are there others?

答:
If I had the choice between two pieces of software with identical functionality, I'd choose the one with more recent commit activity. This indicates the software is being worked on at the moment and the original author is probably still around and might be willing to help fix any bugs you find.

If the functionality isn't identical, here are some other metrics to consider:

The language of the library is the same (or compatible with) the language you are using for your software.

Which is simpler (or looks simpler) to implement into your project?


问:
Zero behavior objects in OOP - my design dilemma
The basic idea behind OOP is that data and behavior (upon that data) are inseparable and they are coupled by the idea of an object of a class. Object have data and methods that work with that (and other data). Obviously by the principles of OOP, objects that are just data (like C structs) are considered an anti-pattern.

So far so good.

The problem is I have noticed that my code seems to be going more and more in the direction of this anti-pattern lately. Seems to me that the more I try to achieve information hiding between classes and loosely coupled designs, the more my classes get to be a mix of pure data no behavior classes and all behavior no data classes.

I generally design classes in a way which minimizes their awareness of other classes' existence and minimizes their knowledge of other classes' interfaces. I especially enforce this in a top-down fashion, lower level classes don't know about higher level classes. E.g.:

Suppose you have a general card game API. You have a class Card. Now this Card class needs to determine visibility to players.

One way is to have boolean isVisible(Player p) on Card class.

Another is to have boolean isVisible(Card c) on Player class.

I dislike the first approach in particular as it grants knowledge about higher level Player class to a lower level Card class.

Instead I opted for the third option where we have a Viewport class which, given a Player and a list of cards determines which cards are visible.

However this approach robs both Card and Player classes of a possible member function. Once you do this for other stuff than visibility of cards, you are left with Card and Player classes which contain purely data as all functionality is implemented in other classes, which are mostly classes with no data, just methods, like the Viewport above.

This is clearly against the principal idea of OOP.

Which is the correct way? How should I go about the task of minimizing class interdependencies and minimizing assumed knowledge and coupling, but without winding up with weird design where all the low level classes contain data only and high level classes contain all the methods? Does anyone have any third solution or perspective on class design which avoids the whole problem?

P.S. Here's another example:

Suppose you have class DocumentId which is immutable, only has a single BigDecimal id member and a getter for this member. Now you need to have a method somewhere, which given a DocumentId returns Document for this id from a database.

Do you:

Add Document getDocument(SqlSession) method to DocumentId class, suddenly introducing knowledge about your persistence ("we're using a database and this query is used to retrieve document by id"), the API used to access DB and the like. Also this class now requires persistence JAR file just to compile.

Add a some other class with method Document getDocument(DocumentId id), leaving DocumentId class as dead, no behavior, struct-like class.

答:
However this approach robs both Card and Player classes of a possible member function.

And how is that bad/ill-advised?

To use a similar analogy to your cards example, consider a Car, a Driver and you need to determine if the Driver can drive the Car.

OK, so you decided that you don't want your Car to know if the Driver has the right car key or not, and for some unknown reason you also decided you don't want your Driver to know about the Car class (you didn't fully flesh this out in your original question as well). Hence, you have an intermediary class, something along the lines of an Utils class, which contains the method with business rules in order to return a boolean value for the question above.

I think this is fine. The intermediary class may only need to check for car keys now, but can be refactored to consider if the driver has a valid driving license, under the influence of alcohol, or in a dystopian future, check for DNA biometrics. By encapsulation, there is really no big problems having these three classes co-existing together.


答:
I am not sure the question at hand is being answered at the right level. I had urge the wise in the forum to actively think on the core of the question here.

U Mad is bringing up a situation where he believes that programming as per his understanding of OOP would generally result in a lot of leaf nodes being data holders while his upper level API is comprises of most of the behavior.

I think the topic went slightly tangential into whether isVisible would be defined on Card vs Player; it was a mere example illustrated, albeit naive.

I had push the experienced here to look at the problem at hand though. I think there is a good question that U Mad has pushed for. I understand that you would push the rules and the concerned logic to an object of its own; but as I understand the question is

Is it OK to have simple data holder constructs (classes / structs ; I don't care about what they are modeled as for this question) which do not really offer much functionality ?

If yes, What is the best or preferred way to model them?

If no, how do we incorporate this data counter parts into higher API classes (including behavior)

My view:

I think you are asking a question of granularity that is hard to get right in object oriented programming. In my little experience, I would not include an entity in my model that does not include any behavior by itself. If I have to, I had probably use a construct a struct that is designed to hold such abstraction unlike a class that has the idea of encapsulating data and behavior.

Title: Zero behavior objects in OOP - my design dilemma

Body:
The basic idea behind OOP is that data and behavior (upon that data) are inseparable and they are coupled by the idea of an object of a class. Object have data and methods that work with that (and other data). Obviously by the principles of OOP, objects that are just data (like C structs) are considered an anti-pattern.

So far so good.

The problem is I have noticed that my code seems to be going more and more in the direction of this anti-pattern lately. Seems to me that the more I try to achieve information hiding between classes and loosely coupled designs, the more my classes get to be a mix of pure data no behavior classes and all behavior no data classes.

I generally design classes in a way which minimizes their awareness of other classes' existence and minimizes their knowledge of other classes' interfaces. I especially enforce this in a top-down fashion, lower level classes don't know about higher level classes. E.g.:

Suppose you have a general card game API. You have a class Card. Now this Card class needs to determine visibility to players.

One way is to have boolean isVisible(Player p) on Card class.

Another is to have boolean isVisible(Card c) on Player class.

I dislike the first approach in particular as it grants knowledge about higher level Player class to a lower level Card class.

Instead I opted for the third option where we have a Viewport class which, given a Player and a list of cards determines which cards are visible.

However this approach robs both Card and Player classes of a possible member function. Once you do this for other stuff than visibility of cards, you are left with Card and Player classes which contain purely data as all functionality is implemented in other classes, which are mostly classes with no data, just methods, like the Viewport above.

This is clearly against the principal idea of OOP.

Which is the correct way? How should I go about the task of minimizing class interdependencies and minimizing assumed knowledge and coupling, but without winding up with weird design where all the low level classes contain data only and high level classes contain all the methods? Does anyone have any third solution or perspective on class design which avoids the whole problem?

P.S. Here's another example:

Suppose you have class DocumentId which is immutable, only has a single BigDecimal id member and a getter for this member. Now you need to have a method somewhere, which given a DocumentId returns Document for this id from a database.

Do you:

Add Document getDocument(SqlSession) method to DocumentId class, suddenly introducing knowledge about your persistence ("we're using a database and this query is used to retrieve document by id"), the API used to access DB and the like. Also this class now requires persistence JAR file just to compile.

Add a some other class with method Document getDocument(DocumentId id), leaving DocumentId class as dead, no behavior, struct-like class.


问:
Design Pattern for Data Validation
What would be the best design pattern for this problem:

I have an Object A. Object A can either be registered or deleted from the database depending on the user request.

Data validation is performed before registration or deletion of the object. There are a set of rules to be checked before the object can be registered and another set of rules for deletion. Some of these rules are common for both operations.

So far, I think the Chain of Responsibility design pattern fits the most but I'm having trouble implementing it.

答:
As described, I would probably implement an option type. That way I could return a "None" or a validated value (perhaps lazily) but that's an implementation detail and leads nicely to the idea of using a Decorator.

Of course if the interface becomes ugly I would use a facade.

Title: Design Pattern for Data Validation


问:
What is the benefit of Continuous Integration over make?
We are evaluating and setting up Continuous Integration for our PHP project. Each of the Continuous Integration tools has their own proprietary "build language" which will run many commands and check the return status of these commands.

Here is an example of a .travis.yml configuration:

```<code>language: php

php:
  - "5.3"
  - "5.4"
  - "5.5"

script: phpunit test

notifications:
  email:
    - sourcespeak@phor.net
</code>```

A Jenkins configuration will be in XML and is too long to paste here.

Here is an example of a circle.yml configuration:

```<code>dependencies:
  override:
    - bundle install:
        timeout: 240
        environment:
          foo: bar
          foo2: bar2
        pwd:
          test_dir
</code>```

My question is: what is the benefit of using all these popular, proprietary configurations languages for CI instead of using a Makefile to set up your test environment and have whatever CI server just run make test?

答:
travis-ci is designed to take your script file ( in your case a makefile) and set it up to run on many different versions of your language (in your case php) with minimal setup.

The .travis.tml file is designed to setup everything to run your tests and to run them, in about 5 lines!

It's also designed to be set it and forget it, copy the five lines or so from the documentation, modify them slightly for your needs, and you never have to worry about your CI setup again.

If you run your own CI server it's a lot more difficult to test on different language versions (or change versions on a whim
), see the results in the GitHub UI, and you have to worry about maintaining and updating the server, instead of the 5 minutes setup of a cloud CI service like Travis.

OwnerDisplayName: Full Decent


问:
Relevance of HTML5: Is now the time?
It seems like most of the jobs I'm receiving, and most of the Internet, is still using standard HTML (HTML 4, let's say) + CSS + JS. Does anyone have any vision on where HTML5 is as a standard, particularly regarding acceptance and diffusion? It's easy to find information about inconsistencies between implementations of HTML5 and so forth. What I want to know about is relevance of HTML5.

答:
If you want to be on the next wave of development, I believe HTML5 will be the next one.

Why?

It doesn't require a plugin, and

It will work on all browser-enabled mobile devices.

Coding on mobile devices (i.e. phones) is a huge pain.  It's not hard to see why.  If you've ever owned more than one phone, you know why, because your old charger won't work with the new phone.

Phones are made to be deliberately incompatible with each other.  This is changing with the emergence of iPhone and Droid, but still...

Microsoft has highlighted this philosophy by throwing its weight behind HTML5 for future phone development.

Title: Relevance of HTML5: Is now the time?


问:
Comparing absolute values when determining zero crossing in 2D image
I am trying to implement an algorithm for finding the zero crossing (check that the signs of all the entries around the entry of interest are not the same) in a two dimensional matrix, as part of implementing the Laplacian of Gaussian edge detection filter for a class,

I understand everything up to step 3 of page 25 of this PDF. Why do I have to compare the absolute values of my neighbouring entries? It doesn't seem logical to me. If I have a matrix that looks like this:

```<code>[1 1 -2],
[2 -4 -1],
[1 -2 -2]
</code>```

Why isn't the value of -4 a valid zero crossing?

答:
According to this website, this comparison is used to determine where exactly the zero crossing is if it seems to occur between two pixels. If there are multiple valid edges, which one is closest to the boundary? Obviously, the one with the smallest absolute value is the one closest to the zero crossing! There are many other ways to localize the edge, some of them summarized on the website I linked and probably many others found at your local library in an image processing textbook.

That being said, please note that the algorithm for edge detection in the previous OP actually will give you very sparse edges, as I've demonstrated by implementing the algorithm here. If you want continuous edges, although admittedly with a lot of false detections, you can use the following simplified algorithm.

Check if all the pixels around you have the same sign.

If they don't have the same sign, then you are a zero crossing.

The code where I implement this is here.

In the end, if you want really good localization, you're going to have to go to the sub-pixel scale, which unfortunately, I can't help you with, but is covered in this paper. Alternatively, you might want to also try increasing the size of your zero-crossing detection range of consideration. In the end, the one thing to take away from all this, is that if you're going to do edge detection, just stick with Canny.


问:
Compatibility between Class Diagram and Sequence Diagram
Do the message being passed between objects in Sequence Diagram match with the methods in Class Diagram?

答:
In theory, yes. Each message in a Sequence Diagram corresponds to a method in the Class Diagram.

In practice, showing everything in your Class Diagrams tends to make them unmanageable and hard to understand. For that reason, it is often best to leave out all the little details that aren't needed to bring your point across and that often includes some or all of the methods and/or properties that a class has.


问:
Test Doubles, Mocks and Stubs - when not to use & why, for Ruby, Rspec
I've learned about mocking and stubbing and I've seen how they can help me create great test suites that run blindingly fast and thus speed up my development process hugely.

However I've also seen the downside when there is an issue that is database centred and wasn't tested for (test doubles or not).

So should I have a subset of tests that do test such connectivity at least and some simple operations, for example creating a record in the primary transaction detail table, even if most of the foreign keys are stubbed out?

What experience have people found with this issue and what balance has worked in various situations?

I normally post on Stack Overflow but this seemed much more conceptual.  It might still be a bit subjective so maybe the question can be improved.

The closest similar question I could find was When should I use mock objects? but it didn't feel like it was really the same question and the answers felt further off.  Perhaps my question is more about when NOT to mock.  ...yeah, so I've updated my title.

I also found this helpful: TDD: Mocking out tightly coupled objects

答:
So should I have a subset of tests that do test such connectivity at least and some simple operations, for example creating a record in the primary transaction detail table, even if most of the foreign keys are stubbed out?

Unit tests can and should never replace integration tests. That is, when testing the data layer you should always use integration tests as there is no fake/stub in the world that can act as the database server do.

So the answer is yes, you should always have tests that make sure that your code access the database in a correct way.


问:
Developing an big system in a a small company
I'm doing this one anonymously.

Our company manufactures some kind of machines and also has a software department, which I'm part of. Our philosophy is mostly to have in-house software and components of the machine instead of third-party where reasonable, so we can quickly implement customer requirements.

Most recently, there has been a decision to implement a small Manufacturing resource planning system (with Bill of materials, Material requirements planning, Capacity planning,  etc, all integrated with our machines.

In a nutshell, the customer will enter all of his worker schedule, different manufacturing operations and their capacities,  transportation capabilities between them, operations in order and time required for manufacturing a certain item or assembly, deadlines for the internal orders, etc. and then the system will tell the customer a production plan - what the operators at any mfg. post are supposed to do, with reports on over- and under-capacity, time estimates, and so on.

I suppose there is also a vision that we'll make this software universal to be able to adapt to different customer requirements, so we'll sell a lot of them.

We're trying to add value to the machine, so the customers will only need to buy this stuff from us and won't need to pay some big software house tens/hundreds of thousands for a real ERP. We'll be mostly selling this to smaller companies (tens of employees), which cannot afford a real ERP and will have all of the of benefits of automated production planning for a fraction of the cost.

But I have a sinking feeling that there is a reason on why this kind of software does cost so much instead of the common greediness of the suppliers - it is complex, takes time to develop. I'm also worried about the "garbage in, garbage out" factor - that the system will not be able to produce any reasonable output unless the inputs are almost perfectly correct, and I'm not sure you can enforce this level of bureaucracy and overhead in smaller companies.

The powers that be think that all parts of this system are manageable (and have already drawn user interface mockups for the screens) and there will be no problem. Maybe I'm the one overestimating, but I don't know... We already have a small part of this implemented and it took about 2 years to get it to acceptable level.

My biggest concern is the underestimation of development time for this kind of system. In reality, we have about 3 developers, one under a part-time contract, and we'll maybe hire one more full-time developer, so about 3 and a half guys in total. No one has any prior experience with something of this scale, we'll have a lot more data, we'll need more customization options, bigger databases and better algorithms so there will be traps waiting around everywhere.

Is all of this unreasonable? How should I voice my concern to my superiors? Will opposing this kind of project look bad and make me seem unwilling or afraid?

答:
It is not possible to give a perfect answer without specific details. However, I could make some general remarks.

Yes, software of this kind is complex to implement. It takes lots of programmer time, but even more so it will require a business process analyst type of role that can map your processes to the software. This is often the meat of the work and where most of the complexity hides. Nowadays the decision is usually made to minimize modifications to the software to fit your processes, in favor of modifying processes to fit the software. The reasoning is that this will greatly simplify future upgrades of the software. So be prepared to change the way you do things.

Based on the fact that it took you 2 years to stabilize a small part of this system it is (probably) reasonable to extrapolate that implementing a much bigger part of this system will take much longer.

Sometimes it is better to live with an imperfect system that works.


答:
At first you could try to collect the different requirements from all stakeholder in a brainstorming workshop. Normally this is a good starting point to get a first overview about all the different expectations and use cases. With this you can start to develop a first global picture of the system.
It is much easier to discuss your concerns when you know some more fact about the system you should build.

And try to avoid a waterfall model. Try to learn as much as possible about Agile development, test-driven-development and continuous integration. Why?

Using an agile approach like Scrum will force you to iterations with a fixed timeline (  we are using 3 weeks for instance ).

After three weeks you have to show your results to your customers and they are hopefully happy about the results

It is much easier to react on new incoming requirements of your stakeholder because you will meet them after each sprint ( it is easier to change your focus after 3 weeks than after half of a year ).

You can get feedback fast from your stakeholders when their change their mind ( and normally they will ).

When doing so the tests will give you an answer which part of your system is broken after implementing the new requirements / user stories.

The continuous integration approach can help you to see if your build is broken, the unittests are red or other stuff went wrong after each commit / baseline.

This makes your system much more stable and you will not be scared to change things.

All these points helps you to have a working system all the time. Even if you have to deploy something you know your system has already value.

Title: Developing an big system in a a small company

Body:
I'm doing this one anonymously.

Our company manufactures some kind of machines and also has a software department, which I'm part of. Our philosophy is mostly to have in-house software and components of the machine instead of third-party where reasonable, so we can quickly implement customer requirements.

Most recently, there has been a decision to implement a small Manufacturing resource planning system (with Bill of materials, Material requirements planning, Capacity planning,  etc, all integrated with our machines.

In a nutshell, the customer will enter all of his worker schedule, different manufacturing operations and their capacities,  transportation capabilities between them, operations in order and time required for manufacturing a certain item or assembly, deadlines for the internal orders, etc. and then the system will tell the customer a production plan - what the operators at any mfg. post are supposed to do, with reports on over- and under-capacity, time estimates, and so on.

I suppose there is also a vision that we'll make this software universal to be able to adapt to different customer requirements, so we'll sell a lot of them.

We're trying to add value to the machine, so the customers will only need to buy this stuff from us and won't need to pay some big software house tens/hundreds of thousands for a real ERP. We'll be mostly selling this to smaller companies (tens of employees), which cannot afford a real ERP and will have all of the of benefits of automated production planning for a fraction of the cost.

But I have a sinking feeling that there is a reason on why this kind of software does cost so much instead of the common greediness of the suppliers - it is complex, takes time to develop. I'm also worried about the "garbage in, garbage out" factor - that the system will not be able to produce any reasonable output unless the inputs are almost perfectly correct, and I'm not sure you can enforce this level of bureaucracy and overhead in smaller companies.

The powers that be think that all parts of this system are manageable (and have already drawn user interface mockups for the screens) and there will be no problem. Maybe I'm the one overestimating, but I don't know... We already have a small part of this implemented and it took about 2 years to get it to acceptable level.

My biggest concern is the underestimation of development time for this kind of system. In reality, we have about 3 developers, one under a part-time contract, and we'll maybe hire one more full-time developer, so about 3 and a half guys in total. No one has any prior experience with something of this scale, we'll have a lot more data, we'll need more customization options, bigger databases and better algorithms so there will be traps waiting around everywhere.

Is all of this unreasonable? How should I voice my concern to my superiors? Will opposing this kind of project look bad and make me seem unwilling or afraid?


问:
How Do You Determine Your Hourly Rate?
In pricing a service or product it is general practice to not merely charge for the effort spent and the costs involved + margin but from the value delivered down. As an independent consultant, how do you set the price of your work?

What is the process of determining your hourly rate as an independent software developer? If you have one, what is your hourly rate and how did you arrive at that figure?

What factors would you take into account.  Is the process of setting a hourly rate only based on balancing demand with supply so that supply (you and your time) doesn't get overwhelmed?

When are the good times to raise your rates?

Are there projects in which you have had to charge higher than other projects? If so, please cite examples.

Do you change your hourly rate based on what kind of development you are doing? (for example, .net programming more, and lesser for php programming)

Do you set hourly rates based on what type of business the client is? If so how?

If you know of any relevant articles or material on the topic of charging for programming services, please post the same.

答:
Primarily the market for the work in question dictates the rates you can charge.

The work in question will be defined by the skills you're using (technical), the industry the client is in and the value the work will deliver to them, any specific knowledge which may be needed to carry out the work and any reputation (good or bad) you may have.  Essentially the fewer people who can compete with you for the work, the more you're going to get away with charging.

So understand the market is the main thing.

As the market rises you can raise your rates.  If it falls then I wouldn't necessarily volunteer to drop them but be aware so if a client starts negotiating you know whether he really has other options - obviously if you're trying to charge $1000 a day and there are good programmers who can and will do the work for $500 you've got a tough sell on your hands.  Similarly if everyone else is charging $1000 a day you'd be missing a trick charging much less.

The key thing in doing this is to understand who your competitors and therefore the people you can compare yourself to are.

Title: How Do You Determine Your Hourly Rate?


问:
Why can't the IT industry deliver large, faultless projects quickly as in other industries?
After watching National Geographic's MegaStructures series, I was surprised how fast large projects are completed. Once the preliminary work (design, specifications, etc.) is done on paper, the realization itself of huge projects takes just a few years or sometimes a few months.

For example, Airbus A380 "formally launched on Dec. 19, 2000", and "in the Early March, 2005", the aircraft was already tested. The same goes for huge oil tankers, skyscrapers, etc.

Comparing this to the delays in the software industry, I can't help wondering why most IT projects are so slow, or more precisely, why they cannot be as fast and faultless, at the same scale, given enough people?

Projects such as the Airbus A380 present both:

Major unforeseen risks: while this is not the first aircraft built, it still pushes the limits of the technology and things which worked well for smaller airliners may not work for the larger one due to physical constraints; in the same way, new technologies are used which were not used before, because for example they were not available in 1969 when the Boeing 747 was certified.

Risks related to human resources and management in general: people quitting in the middle of the project, inability to reach a person because she's on vacation, ordinary human errors, etc.

With those risks, people still achieve projects like those large airliners in a very short period of time, and despite the delivery delays, those projects are still hugely successful and of a high quality.

When it comes to software development, the projects are hardly as large and complicated as an airliner (both technically and in terms of management), and have slightly less unforeseen risks from the real world.

Still, most IT projects are slow and late, and adding more developers to the project is not a solution (going from a team of ten developers to two thousand will sometimes make it possible to deliver the project faster, sometimes not, and sometimes will only harm the project and increase the risk of not finishing it at all).

Those which are still delivered may often contain a lot of bugs, requiring consecutive service packs and regular updates (imagine "installing updates" on every Airbus A380 twice a week to patch the bugs in the original product to prevent the aircraft from crashing).

How can such differences be explained? Is it due exclusively to the fact that the software development industry is too young to be able to manage thousands of people on a single project in order to deliver large scale, nearly faultless products very fast?

答:
Software engineer here, with an engineering background, and a wife who works in construction. We've had long discussions (and arguments) on the differences of our jobs.

Software engineering is about designing new things. Almost everything basic has been done in an open source library somewhere. In almost any job where a software engineer is hired, she has to design something that doesn't exist.

In something like construction and most forms of engineering, things that would otherwise be in a 'library' in software are already fully designed. Want to build a tower? Just copy and paste the plans from an existing structure, with a few modifications.

In fact, one of the main reasons I decided not to become an engineer is that you spend most of your time designing a 10% improvement to an existing invention, when that same time could be used to program something more visible, like a social network.

There are not many new designs in engineering; an extremely skilled engineer is someone who can manipulate an existing design into something new or improve on it. But almost every programmer is expected to modify designs, hack them, or create something new.

Look back at how far the standards have changed completely, from assembly to C to C++ to Java, JavaScript, C#, PHP, and so on. There's not a lot of code that can be recycled from 10 or 20 years ago. This is very different to say... the automotive or aeronautics industry when you can keep improving on designs from decades back.

Project management is notoriously difficult in software. Time estimates are best done by people doing the work, but when they're busy making estimates, they're not writing code. This tempts people to avoid any project management at all.

Often, a lot of code depends on specific people, and if these people are late or unable to perform, the code does not move ahead. In contrast, if you wanted to build a car, you can simply hire different people to assemble the tires, the chassis, the battery, the engine, and so on. Object oriented and existing frameworks makes this possible, but it may not be practical when you're designing everything from scratch.

Failures may be allowed in software. Testing can be costly. In software, it's very tempting to skip all that testing, when you can just fix a crash. In most forms of engineering, a 'crash' can be fatal.

You do have programming methods that use extensive testing, like extreme programming (which was actually used on software megaprojects). But with tight deadlines (that can be made tighter on purpose), it's tempting to skip all that programming and launch with bugs. The Joel Spolsky style of "always fixing all bugs" will save more time in the long run, but the undisciplined will skip this and fail.

Small projects are better. My wife once asked me to get a job in a big company. It ended up in an argument that big companies are bad companies... to her, a big company had a lot of resources, experience, functional project management, and the right procedures. To me, a big company is a dinosaur, where most of your time is spent on fixing code, testing it, and documentation.

I've seen million-dollar IT projects worked on by less than 10 people. More people would have slowed down the project and added unnecessary bureaucracy. WhatsApp is an example of a 'small' project that's worth billions of dollars. It's not that big projects aren't possible, but you simply don't need thousands of people to produce billions of dollars worth in software.


问:
CakePHP: Automation triggers after save - best done as component or behavior?
Folks, first time on CodeReview - just looking for some input in creating some automation in CakePHP, wondering if this is best used a component or a behavior. It's model driven but involves logic and processing. Here's the scoop:

The app I'm creating requires the user to be notified when a model meets certain conditions - additionally data in the affected model or a related model might need to be changed. For example, if a customer model is saved with a certain state/province, assign that customer to a sales rep (by changing a relational field) and notify them through a Growl or an Email. So it's data driven, for sure, suggesting behavior, presumably afterSave()

But it also requires logic and other utilities not typically used in the model or behavior (email, for example and Session/system configuration/user preferences) - functionality typically found in a controller/component and not readily available to a model or behavior.

So is this best developed as a behavior or a component?

Any tips on how to approach by Cake Guru's this would be much appreciated.

Thanks in advance.

答:
Model and behaviour are quite the same thing. A behaviour extends the functionality of a model. The choice between that lies in complexity and re-usability. If you don't know what's best you could post a separate question on that with corresponding code to define what's the best solution.

The app I'm creating requires the user to be notified when a model
  meets certain conditions

For this kind of notifications you should look at the Events system of CakePHP. That will create the separation you want to have.

In general it means that you check the condition in your model (or behaviour) and throw an Event when the conditions is met. Other code will respond to that event and handle sending out the notification etc.

The Event listener could then also be modified, for example: For performance reasons you might want to put the notification in a queue to offload the work so the response becomes faster.

additionally data in the affected model or a related model might need to be changed.
  assign that customer to a sales rep (by changing a relational field)

This is more something to do directly in the model or behaviour. I would not implement an Event here directly. You could hook this up for example in beforeValidate. Make sure the salesrep_id is required. Then in your code you check which one you should select and enter the right ID.

That way a client is aways assigned to a sales rep and that is being validated.

If the code for selecting a sales rep is complex or has to be re-used you can separate that out into a behaviour as well.

[edit] more on the events system: http://book.cakephp.org/2.0/en/core-libraries/events.html

OwnerDisplayName: optimumdarren


问:
Colons in internationalized UI
When using gettext or a similar framework, should the translation strings include ':' (like "Label:") for generating labels for UI or should I add ':' in UI code itself?

答:
It may depend on the localization system that you use, but having other things equal, I would personally avoid adding any punctuation (unless within a phrase of course, where its use is dictated by the grammar), because I feel they're part of the presentation, like font size etc., and not really the content. So we're mixing different things with this approach.

After all, the same words and phrases may be needed both with punctuation and without. Eg. you can have "Enter subject:" caption next to a textbox, but also "Enter subject" as a window title.

Does it make sense to have both of them translated separately?

When you decide that colons actually look bad and redundant in the UI, you'll have to retranslate all language versions. Which is a bit silly.

PS. The "ground rules" given by @bartc are valid either way - whether or not you include punctuation marks in translated strings.

PPS. @paulkayuk, too, raises a good point (in his comment) - that culture specifics should be taken into consideration as well. If you've got things like mirrored question marks in Spanish, include them in your translation of course. My answer assumes uniform, language-agnostic punctuation, because that seems to be the debatable bit.

Title: Colons in internationalized UI


问:
OO Design when using communication
I have 2 applications one is written in C++ and one is written in Java. the applications communicate by passing byte arrays which represent a serialized object.

each communication object represent a Command and holds the command id and the associated data.

I will use an example to describe my problem.
Let's say I have 3 components. one is responsible for the data storage and file system, one is responsible for presenting UI , and one is responsible for security and authorizing users.

One way to access a specific component is by having one entry point that will do a switch case on all the possible commands ids.

pseudo:

```<code>    switch(commandId)
{
case SAVE_FILE:
DATASTORAGE::Save();
break;
case LOAD_FILE:
 DATASTORAGE::Load();
 break;
case AUTHORIZE:
 SECURITY_CONTROLLER::authorize();
 break;
case DENY_ACCESS:
 SECURITY_CONTROLLER::denyAccess();
 ...
}
</code>```

In this case if I need to change the security controller, I need to change this main entry point.

so instead I added an extra field to the communication object, that holds the id of the component that need to process the command.
In this case if I want to preform authorize I will do the following:

```<code>communicationObject.commandId = AUTHORIZE;
communicationObject.target = SECURITY_CONTROLLER_ID;
</code>```

And the main will switch case on the possible targets and pass the command id to the specfic component which is responsible for that command.

```<code>   switch(target)
{
case SECURITY_CONTROLLER_ID:
SECURITY_CONTROLLER::Process(commandId);
break;
case DATASTORAGE_ID:
 DATASTORAGE::Process(commandId);

 ...
}
</code>```

I also don't like this new design since it requires that the sender will know the inner structure of the receiver.

on the other hand, if I had direct access to the other application classes (not using byte [] for communication) then the second option will be mapped to something like:  SECURITY_CONTROLLER::Authorize(); while the first option will be mapped to something like Main.AUTHORIZE(), which is definitely not the way to go!

what is the best approach in this case?

答:
The most modular way is to let each receiving module register itself with the main command handler for receiving the commands that it can handle.

Assuming that there is at most one handler for each command, you would get something like this (pseudo code)

```<code>class MainCommandHandler
{
public:
    RegisterCommandHandler(CommandID, ICommandHandler*);
    ProcessCommand(Command cmd)
    {
        if (commandHandlers.contains(cmd.id))
        {
            // delegate to the registered handler for this command
            commandHandlers.get(cmd.id)->HandleCommand(cmd);
        }
        else
        {
            // handle unknown commands
        }
    }
private:
    map<CommandID, ICommandHandler*> commandHandlers;
};

class SECURITY_CONTROLLER : public ICommandHandler
{
    someMethodOrConstructor() {
        mainCommandHandler.RegisterCommandHandler(AUTHORIZE, this);
        //... more registrations
    }
    HandleCommand(Command cmd)
    {
        switch(cmd.id)
        {
        case AUTHORIZE: authorize(); break;
        //... other *registered* commands
    }
};
</code>```

You still have the switch-case on the command ID, but now it is in the components that actually handle the command. If there are additional commands, those components would have to be changed anyway, so the main drawback of your case #1 doesn't exist anymore.

Title: OO Design when using communication

Body:
The most modular way is to let each receiving module register itself with the main command handler for receiving the commands that it can handle.

Assuming that there is at most one handler for each command, you would get something like this (pseudo code)

class MainCommandHandler
{
public:
    RegisterCommandHandler(CommandID, ICommandHandler*);
    ProcessCommand(Command cmd)
    {
        if (commandHandlers.contains(cmd.id))
        {
            // delegate to the registered handler for this command
            commandHandlers.get(cmd.id)->HandleCommand(cmd);
        }
        else
        {
            // handle unknown commands
        }
    }
private:
    map<CommandID, ICommandHandler*> commandHandlers;
};

class SECURITY_CONTROLLER : public ICommandHandler
{
    someMethodOrConstructor() {
        mainCommandHandler.RegisterCommandHandler(AUTHORIZE, this);
        //... more registrations
    }
    HandleCommand(Command cmd)
    {
        switch(cmd.id)
        {
        case AUTHORIZE: authorize(); break;
        //... other *registered* commands
    }
};

You still have the switch-case on the command ID, but now it is in the components that actually handle the command. If there are additional commands, those components would have to be changed anyway, so the main drawback of your case #1 doesn't exist anymore.


答:
I see unit tests as routines that test pieces of code that are in a code base that you manage. Mocking and stubbing helps focus only on the flow and logic of your code, which is what you are testing in your unit tests.

Whether or not an outside service like a database (which is not inherently part of your code) actually works is not important for unit tests, but rather for integration tests.

So should I have a subset of tests that do test such connectivity at least and some simple operations, for example creating a record in the primary transaction detail table, even if most of the foreign keys are stubbed out?

Only if you have implemented routines to do simple database operations, should you tests whether those routines work like you expect them to, in unit tests. But then you would still stub out the database because you are not particularly interested in whether the database actually works, you are testing whether the logic in your code works.

Title: Test Doubles, Mocks and Stubs - when not to use & why, for Ruby, Rspec

Body:
I've learned about mocking and stubbing and I've seen how they can help me create great test suites that run blindingly fast and thus speed up my development process hugely.

However I've also seen the downside when there is an issue that is database centred and wasn't tested for (test doubles or not).

So should I have a subset of tests that do test such connectivity at least and some simple operations, for example creating a record in the primary transaction detail table, even if most of the foreign keys are stubbed out?

What experience have people found with this issue and what balance has worked in various situations?

I normally post on Stack Overflow but this seemed much more conceptual.  It might still be a bit subjective so maybe the question can be improved.

The closest similar question I could find was When should I use mock objects? but it didn't feel like it was really the same question and the answers felt further off.  Perhaps my question is more about when NOT to mock.  ...yeah, so I've updated my title.

I also found this helpful: TDD: Mocking out tightly coupled objects


问:
As a programmer, are you professionally obliged to offer ongoing support after you've left a company?
I've had a few programming jobs in the past where I was the only developer working on a project. After I've left, I typically get several emails a week from these companies, usually from the developer(s) who's replaced me there. These emails are usually asking for details about how things work and how I'd best go about implement feature x based on the existing system.

I'm usually polite and helpful, but these kind of communications really start to eat into my time making every job I work on another weight around my ankle. Not to mention they're projects that I chose to leave behind me for a good reason.

My question is, would it be professionally 'ok' to tell them I'm just not going to offer support any more and refuse and answer inquiries?

NB. None of these companies are paying me any type of retainer and the inquiries are often informal questions from developers and not management.

答:
If you havent signed a contract with the company/clients about offering help to them in future, then you can say no to such calls.
There is generally a agreed support time between client and developer. The developer is supposed to help the client till the support time is breached.</p>


答:
Since what you're doing is write a custom binary protocol for performing cross-language RPCs, it makes sense to have separate IDs for the components and their commands.

For example: a fixed number of bytes in the beginning of the byte array could be used to specify the component, while the following bytes (another fixed number) would represent the component-specific command. Finally, all of the remaining bytes would represent the associated data.

Your top-level switch would be used to find the component for the component ID. If all components have the same superclass, you can even replace that switch with an std::map that would assing actual objects (components) to component IDs.

But each component would need to have a switch to map command IDs to actual methods.

Note that, in this solution, you can use the same command ID to represent different operations, if they aren't in the same component. This way, you are less likely to need too many bytes for the command-id section of the byte array.

Title: OO Design when using communication

Body:
I have 2 applications one is written in C++ and one is written in Java. the applications communicate by passing byte arrays which represent a serialized object.

each communication object represent a Command and holds the command id and the associated data.

I will use an example to describe my problem.
Let's say I have 3 components. one is responsible for the data storage and file system, one is responsible for presenting UI , and one is responsible for security and authorizing users.

One way to access a specific component is by having one entry point that will do a switch case on all the possible commands ids.

pseudo:

```<code>    switch(commandId)
{
case SAVE_FILE:
DATASTORAGE::Save();
break;
case LOAD_FILE:
 DATASTORAGE::Load();
 break;
case AUTHORIZE:
 SECURITY_CONTROLLER::authorize();
 break;
case DENY_ACCESS:
 SECURITY_CONTROLLER::denyAccess();
 ...
}
</code>```

In this case if I need to change the security controller, I need to change this main entry point.

so instead I added an extra field to the communication object, that holds the id of the component that need to process the command.
In this case if I want to preform authorize I will do the following:

```<code>communicationObject.commandId = AUTHORIZE;
communicationObject.target = SECURITY_CONTROLLER_ID;
</code>```

And the main will switch case on the possible targets and pass the command id to the specfic component which is responsible for that command.

```<code>   switch(target)
{
case SECURITY_CONTROLLER_ID:
SECURITY_CONTROLLER::Process(commandId);
break;
case DATASTORAGE_ID:
 DATASTORAGE::Process(commandId);

 ...
}
</code>```

I also don't like this new design since it requires that the sender will know the inner structure of the receiver.

on the other hand, if I had direct access to the other application classes (not using byte [] for communication) then the second option will be mapped to something like:  SECURITY_CONTROLLER::Authorize(); while the first option will be mapped to something like Main.AUTHORIZE(), which is definitely not the way to go!

what is the best approach in this case?


答:
Yes

Despite warnings from the W3C and the media privacy concern scare I think that pushing forward with new technology is key to staying ahead of the curve. What fun is playing with non-alpha software? Get your feet wet now rather then later when the people that did are leading the pack.

There is a ton of great features HTML5 specs bring, the least of which is video and multimedia. You also have WebSockets which are a huge advancement in async. server communication. Now you can stream real time live data as simply as writing a quick JavaScript Node server and a few lines of client side JS.

Why delay in starting? Balance where you can leverage existing technology for backwards support and new specs to gain access to the advanced feature set supported by modern browsers.

Title: Relevance of HTML5: Is now the time?

Body: It seems like most of the jobs I'm receiving, and most of the Internet, is still using standard HTML (HTML 4, let's say) + CSS + JS. Does anyone have any vision on where HTML5 is as a standard, particularly regarding acceptance and diffusion? It's easy to find information about inconsistencies between implementations of HTML5 and so forth. What I want to know about is relevance of HTML5.


答:
I use most recent commit and overall age as  good indicator.

If there are a couple that are established, active, and have the functionality you need, try them both.  That's the only real "metric" to use.

Title: How to choose between different open-source libraries?

Body:
Recently, I found multiple GitHub repositories that would allow me to perform the same task. (In my case, assess the readability of text strings.)

It made me wonder, what are the best practices for programmers to choose between different open-source libraries, and in particular, libraries hosted on GitHub?

GitHub statistics of users who watch, star, or fork a repository are one option, but are there others?


答:
You are in no way obligated to help them.

Whether or not your former employer have realized it, they have taken a low cost/high risk decision by having only one developer work on the software. That was their (perhaps uninformed) decision, and now they are paying the price - you should not.

If you feel like helping them, you should make a support agreement where they pay you for the time spent helping the new developer, in order for you to be compensated properly for your time.

Title: As a programmer, are you professionally obliged to offer ongoing support after you've left a company?

Body:
I've had a few programming jobs in the past where I was the only developer working on a project. After I've left, I typically get several emails a week from these companies, usually from the developer(s) who's replaced me there. These emails are usually asking for details about how things work and how I'd best go about implement feature x based on the existing system.

I'm usually polite and helpful, but these kind of communications really start to eat into my time making every job I work on another weight around my ankle. Not to mention they're projects that I chose to leave behind me for a good reason.

My question is, would it be professionally 'ok' to tell them I'm just not going to offer support any more and refuse and answer inquiries?

NB. None of these companies are paying me any type of retainer and the inquiries are often informal questions from developers and not management.


问:
Java code quality in methods calling methods
I am currently working with an "interesting" code-base and see the following type of thing alot in the code.

```<code>public Object doSomething()
{
    Object obj = new Object();

    // Do some stuff to the object

    obj = doSomthingElse(obj);

    return obj;
}
</code>```

I always feel when looking at this kind of code that it is somewhat incorrect to have an object be passed into a method as a parameter but also set the object returned by the method to the same variable that was referencing the passed object. I would usually do something like the following, where I create a new variable to avoid any confusion.

```<code>public Object doSomething()
{
    Object obj = new Object();

    // Do some stuff to the object

    Object anotherObj = doSomthingElse(obj);

    return anotherObj;
}
</code>```

Am I wrong in thinking the second code snippet is more readable/correct?

答:
If the method call is transforming the object without creating a copy of it (and then returning the same object, with the changes), the statement obj = doSomthingElse(obj); has no effect (you could just perform doSomthingElse(obj); instead).

If the method creates and returns another object (that is a modified copy of the original), then what the statement obj = doSomthingElse(obj); does is called variable reuse. To say that it is a good or a bad practice would be nothing more than an opinion.

Sticking to your abstract example, my opinion would be that you need to add some comments to the code explaining what the obj variable represents. Then, reusing it or not, you should try to stick to what is documented (the variable's role in the code).

If the result of doSomthingElse(obj) is another object and represents something different from the documented role of the variable obj, then you should use another variable (as you did), IMHO.


答:
Here's a potential e-mail to craft*;

Sorry, I'm very busy right now with my existing contracts and not
  regularly checking my e-mails. If you have a support request for a
  product I used to work on, send a message to
  "support@mattharrison.com", so that we can discuss setting up a
  support agreement. If it's urgent, be sure to prefix the subject with
  'URGENT:' and I'll move it to the top of my priority support list.

Kind Regards,

Matt Harrison

Send this in response to any support request, even if you're sitting in bed eating a sammich and checking your e-mails. If it actually does look like the kind of thing where you'd want to help them immediately because it's a big deal, still send this, but immediately follow up with an e-mail saying "Just saw this, I'll help as soon as I can".

The idea here is to put them in the mindset that this is a service you provide as an extra, and if they want it, it's a chargeable service. The word discuss means that you haven't committed to anything, and by allowing them to specify 'URGENT:', if you've actually put them in a bad position (e.g. some mistake you'd happily fix just to maintain your reputation and because it's the right thing to do), you can approach these with a different mindset. "That website you made for us just lost us $50,000" is something I'd approach very differently to "we need you to change the position of the logo on the 'About Us' page".

This means that if you do make time to help (because being helpful is a good thing), then they're aware that there's been a cost to you. And if you don't, then they're aware of your reasons.

As someone mentioned, if you have an existing support agreement, or if they're under the impression that you do, you'd have to provide service anyway, but this response covers this (and they should have your support number anyway). Also, you should go into any job negotiation with the intention of clearly specifying your support terms up front, especially when it's a solo project and thus you're not working off a standard template contract for all devs, and even more especially as this has come up for you before.

How do you know if you're professionally obliged to do something? Because your professionally drawn up contract obliges you to do it. How do you know that you're not? Because the limits of that obligation are specifically mentioned in your contract (e.g. 'The employee shall provide support on all aspects of the work until the termination of employment by either party, as described in section 3'*).

*: Anyone has any improvements to the wording, please leave them in the comments


答:
The first and most important test of a component is to test the external interfaces. Write those tests first, and make sure they are comprehensive. Then add some more. Then review them, find out which cases are missing, and add them.

Then add some more.

Write lower level (i.e. class-as-unit) tests only when:

your higher-level (i.e. component-as-unit) tests are failing, and you can't figure out why.

you have some budget left after you have written every possible external interface test.

you have a resuable, generic or just plain over-engineered utility class or function.

it is explicitly required by the customer.

For testing external interfaces, every interface is going to be either an input, an output, or a collaborator (like a database).

For a component-as-unit test:

test the input interfaces; call the methods, assert the return values.

mock the output interfaces; verify the expected methods are called for a given test case.

fake the collaborators; provide a simple but working implementation

If you do that properly and cleanly, you barely need a mocking tool; it only gets used a few times per system. And unit tests should run in milliseconds (at least unless your code is horrendously slow, in which case perhaps you should fix it). Integration test then replace the fakes and mocks, one by one when you first do it, or all except user interfaces for a regression test.


问:
Overcoming slow problem solving due to increased knowledge of what might go wrong
This has been troubling me for some time, and I'd really appreciate the input of other professionals.

Short background: I started programming when my parents bought me my first computer in 1988 (at age 14, I'm 39 now). I followed a couple of other career paths before finally becoming a professional programmer in 1997. Late bloomer, perhaps, but that's how it was. I'm still happy with my choice, I love programming, and I consider myself good at what I do.

Lately, I've been noticing that the more experience I gain, the longer it takes me to complete projects, or certain tasks in a project. I'm not going senile yet. It's just that I've seen so many different ways in which things can go wrong. And the potential pitfalls and gotchas that I know about and remember are just getting more and more.

Trivial example: it used to be just "okay, write a file here". Now I'm worrying about permissions, locking, concurrency, atomic operations, indirection/frameworks, different file systems, number of files in a directory, predictable temp file names, the quality of randomness in my PRNG, power shortages in the middle of any operation, an understandable API for what I'm doing, proper documentation, etc etc etc.

In short, the problems have long since moved from "how do I do this" to "what's the best/safest way of doing it".

The upshot is that it takes me longer to finish a project than a novice. My version may be rock solid, and as impenetrable as I know how to make it, but it takes longer.

The "create file" example above was just that, an example. Real tasks are obviously more complex, but less suited for a generic question like this one. I hope you understand where I'm going with this. I have no problem coming up with efficient algorithms, I love math, I enjoy complex subjects, I have no difficulties with concentration. I think I do have a problem with experience, and consequently with a fear of errors (intrinsic or extrinsic).

I spend almost two hours a day reading up on new developments, new techniques, languages, platforms, security vulnerabilities, and so on. The conundrum is that the more knowledge I gain, the slower I am in completing projects.

How do you deal with this?

答:
Just like you, I started programming at the age of 14, also when I got my first computer (although I had been studying for a few months at that point).
However, I am "only" 33 now. :-)

My suggestion is that, when developing something, you take each one of those worries (file permissions, number of files in a directory, etc.) and then use all of your vast experience to answer a few questions about it, in this spirit:

How long would it take to handle that issue properly in your code?

If you don't handle it properly, how likely it is that this thing will bite you later?

If it does bite you, what are the consequences?

Armed with those answers, such an experienced guy will not have problems to make a wise decision. ;-)

It is the responsibility of "veterans" like you to come up with this type of requirement, and that involves both identifying what can go wrong and deciding which potential problems you should give attention to.


问:
Why is "Select * from table" considered bad practice
Yesterday I was discussing with a "hobby" programmer (I myself am a professional programmer). We came across some of his work, and he said he always queries all columns in his database (even on/in production server/code).

I tried to convince him not to do so, but wasn't so successful yet. In my opinion a programmer should only query what is actually needed for the sake of "prettiness", efficiency and traffic. Am I mistaken with my view?

答:
Think about what you're getting back, and how you bind those to variables in your code.

Now think what happens when someone updates the table schema to add (or remove) a column, even one you're not directly using.

Using select * when you're typing queries by hand is fine, not when you're writing queries for code.


答:
because if the table gets new columns then you get all those even when you don't need them. with varchars this can become a lot of extra data that needs to travel from the DB

some DB optimizations may also extract the non fixed length records to a separate file to speed up access to the fixed length parts, using select* defeats the purpose of that

Title: Why is "Select * from table" considered bad practice

Body:
Yesterday I was discussing with a "hobby" programmer (I myself am a professional programmer). We came across some of his work, and he said he always queries all columns in his database (even on/in production server/code).

I tried to convince him not to do so, but wasn't so successful yet. In my opinion a programmer should only query what is actually needed for the sake of "prettiness", efficiency and traffic. Am I mistaken with my view?


答:
This is what I do; it is by no means the only way or even the best way!

set your normal rate based on your income needs, relative value, market rates, a rational (40-hour) work week, and allow for taxes; if you're self-employed in the USA, figure taxes will take almost half of your income

if the project adds tremendous value, charge a percentage of the ROI, say 2%, as long as this is more than your normal long-term hourly rate

if the project is short-term and rush, charge 50%-100% more than your normal rate for schedule disruption and overtime

if the project is short-term, charge 25% more than your normal rate

alternately, you can bid on projects for a fixed fee (half up front!) as long as the scope is set and the schedule is reasonable. Beware the unknowns, mitigate risks, plan for interruptions and "gotcha!" bugs

Title: How Do You Determine Your Hourly Rate?

Body:
In pricing a service or product it is general practice to not merely charge for the effort spent and the costs involved + margin but from the value delivered down. As an independent consultant, how do you set the price of your work?

What is the process of determining your hourly rate as an independent software developer? If you have one, what is your hourly rate and how did you arrive at that figure?

What factors would you take into account.  Is the process of setting a hourly rate only based on balancing demand with supply so that supply (you and your time) doesn't get overwhelmed?

When are the good times to raise your rates?

Are there projects in which you have had to charge higher than other projects? If so, please cite examples.

Do you change your hourly rate based on what kind of development you are doing? (for example, .net programming more, and lesser for php programming)

Do you set hourly rates based on what type of business the client is? If so how?

If you know of any relevant articles or material on the topic of charging for programming services, please post the same.


问:
How can I improve my problem-solving ability?
Everyone says the same thing: "a real programmer knows how to handle real problems." But they forget how they learned this ability or where: it's not taught in schools.

What can I do to improve my ability to tackle complex programming problems? What strategies have worked for you? Are there specific areas I should be focusing on, like algorithms or design patterns?

答:
For newbies in programming like myself I recommend the book "Think Like a Programmer". In the first chapter it covers such problem solving techniques as  restating and dividing the problem, starting with what you know, reducing, analogies and experimenting. </p>

<p>Then there are more advanced techniques with examples in C++: solving problems with  arrays, pointers and dynamic memory, classes, recursion, code reuse. I cannot comment on this part because it's too hard for me yet.  </p>

Body:
For newbies in programming like myself I recommend the book "Think Like a Programmer". In the first chapter it covers such problem solving techniques as  restating and dividing the problem, starting with what you know, reducing, analogies and experimenting.

Then there are more advanced techniques with examples in C++: solving problems with  arrays, pointers and dynamic memory, classes, recursion, code reuse. I cannot comment on this part because it's too hard for me yet.


答:
The short answer is: it depends on what database they use. Relational databases are optimized for extracting the data you need in a fast, reliable and atomic way. On large datasets and complex queries it's much faster and probablly safer than SELECTing * and do the equivalent of joins on the 'code' side. Key-value stores might not have such functionalities implemented, or might not be mature enough to use in production.

That said, you can still populate whatever data structure you're using with SELECT * and work out the rest in code but you'll find performance bottlenecks if you want to scale.

The closest comparison is sorting data: you can use quicksort or bubblesort and the result will be correct. But won't be optimized, and definitely will have issues when you introduce concurrency and need to sort atomically.

Of course, it's cheaper to add RAM and CPUs than investing in a programmer that can do SQL queries and has even a vague understanding of what a JOIN is.


答:
Querying every column might be perfectly legitimate, in many cases.

Always querying every column isn't.

It's more work for your database engine, which has to go off and rummage around its internal metadata to work out which columns it needs to deal with before it can get on with the real business of actually getting the data and sending it back to you.  OK, it's not the biggest overhead in the world, but system catalogs can be an appreciable bottleneck.

It's more work for your network, because you're pulling back any number of fields when you might only want one or two of them.  If somebody [else] goes and adds a couple of dozen extra fields, all of which contains big chunks of text, you're throughput suddenly goes through the floor - for no readily apparent reason.  This is made worse if your "where" clause isn't particularly good and you're pulling back lots of rows as well - that's potentially a lot of data tromping its way across the network to you (i.e. it's going to be slow).

It's more work for your application, having to pull back and store all of this extra data that it quite probably doesn't care about.

You run the risk of columns changing their order.  OK, you shouldn't have to worry about this (and you won't if you select only the columns you need) but, if you go get them all at once and somebody [else] decides to rearrange the column order within the table, that carefully crafted, CSV export that you give to accounts down the hall suddenly goes all to pot - again, for no readily apparent reason.

BTW, I've said "someone [else]" a couple of times, above.  Remember that databases are inherently multi-user; you may not have the control over them that you think you do.


答: Apart from overhead, something you want to avoid in the first place, I would say that as an programmer you don't depend on column order defined by the database administrator. You select each column even if you need them all.</p>


答:
Another concern: if it's a JOIN query and you're retrieving query results into an associative array (as could be the case in PHP), it's bug-prone.

The thing is that

if table foo has columns id and name

if table bar has columns id and address,

and in your code you are using SELECT * FROM foo
JOIN bar ON foo.id = bar.id

guess what happens when someone adds a column name to the bar table.

The code will suddenly stop working properly, because now the name column appears in the results twice and if you're storing the results into an array, data from second name (bar.name) will overwrite the first name (foo.name)!

It's quite a nasty bug because it's very non-obvious. It can take a while to figure out, and there's no way the person adding another column to the table could have anticipated such undesirable side effect.

(True story).

So, don't use *, be in control of what columns you are retrieving and use aliases where appropriate.


答:
No, you are not professionally obliged to provide support for a previous employer.

If you want to do this, make sure there's a contract in place to compensate you for the time you spend.

It may also be that you could offer to come back for 1-2 weeks and train your replacement (as it were), naturally at a suitable fee.

What I would say, though, is that leaving a project should involve leaving clear documentation behind, in a suitable form.


答: It depends on the application and who would be using it and what your timeline is for development. There is not much point in writing software that most of your potential customers cannot run.</p>

Title: Relevance of HTML5: Is now the time?


问:
Is there a problem holding large numbers of open socket connections for lengthy periods of time?
The application we have in mind is a relay server. The aim is to accept large numbers of incoming socket connections (at least thousands) that will stay open for lengthy periods (hours or maybe days). They will exchange modest quantities of data and they need reasonably low latency.

The technical design is straightfoward and we have a test implementation. Our preference is to use Windows hosting and .NET, because that's the technology we know. However, this kind of usage is well outside what we are familiar with.

The question is whether there are specific limits or constraints to be aware of that are inherent in or common to software that does this, and that we should allow for in our design and/or test for before a roll-out.

I found this question (Handling large amounts of sockets) and this link (http://www.metabrew.com/article/a-million-user-comet-application-with-mochiweb-part-1), which tend to suggest that our solution should work.

--

Commenters have suggested opening and closing ports, or using some kind of protocol, without suggesting how. The problem is that at any time a message might be relayed to an individual known destination with the expectation that it be received quickly (say 1 second at most, preferably sooner). The destination is (in general) behind a firewall with unknown properties, so cannot (in general) run a server or accept incoming connections. It can only make outgoing connections. We think it needs a persistent outgoing connection in order to receive packets at any time without notice. Alternative suggestions would be of interest, although strictly off topic for this question.

Other commenters have suggested there are OS limits, but not specified any. Assuming that this is some version of Windows server and some (perhaps large) amount of memory, are the limits likely to be a problem? Roughly what will they be? Is Windows a bad idea?

答:
computers have a hard limit of how many connections can be open at the time (decided by the OS). Programs see a subset of that.

each open socket requires some resources and a network-timeout heartbeat so disconnections can be detected. Having a lot of sockets sending those heartbeats will start to fill the bandwidth.

my suggestion is to close the connections as needed and just accept that you will need to reopen them.


答:
I don't see any reason why you shouldn't use for the purpose it's build - retrieve all the columns from a database. I see three cases:

A column is added in the database and you want it in code also.
a) With * will fail with a proper message.
b) Without * will work, but won't do what you expect which is pretty bad.

A column is added in database and you do not want it in code.
a) With * will fail; this means that * does no longer applies since it's semantics means "retrieve all".
b) Without * will work.

A column is removed
Code will fail either way.

Now the most common case is case 1 (since you used * which means all you most probably want all); without * you can have code that works fine but doesn't do what expected which is much, much worst that code that fails with a proper error message.

I'm not taking into consideration the code which retrieves the column data based on column index which is error-prone in my opinion. It's much more logic to retrieve it based on column name.