问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
I tend to install NoScript and only whitelist sites that I trust. Otherwise I use the "allow temporarily" for specific domains when I need to.

This is just good security. Otherwise you're allowing an arbitrary amount of code to run on your machine! Even if it's sandboxed... there's always vulnerabilities.

Beyond my own habits, even if most people do browse with JavaScript, it's still useful to develop sites with progressive enhancement in mind. If your site is functional at the baseline it can service the largest audience. It also means that you separate your data from visual design and from business logic. Most of what you do with JavaScript on the client side should be done on the server side anyway -- doing it client side should just be a convenience given to a user of the site.

Of course there are exceptions that are going to require JavaScript, but generally there's an expectation involved. For example, there's an expectation to enable JavaScript for BioLab Disaster, a game, but none for a site like A List Apart, mostly just text.

When I'm filling out a form, should there really be an expectation that I have JavaScript enabled to submit the form? Why? So that the JavaScript code can check to make sure that I didn't enter a number instead of a letter?


问:
Can I use MIT code within a MS-PL project?
I would like to modify and use code of a MIT project within a MS-PL project. Am I allowed to do that?

I've already searched for it with Google and Bing, but I could not find anything like "Yes (No) you can (not) use MIT code within a MS-PL project". I am no jurist, so it is quite hard to interpret any license.

答:
I am not a lawyer, but this is how these licenses are usually interpreted in my experience:

The MIT license is a so-called permissive license. It explicitely allows merging and sublicensing. That means you can use MIT-licensed code and relicense it under a different license. This allows you to use the code in any project regardless of the license.

The only condition you have to fulfill is that you need to include the copyright notice and permission notice of the MIT-licensed component in your project. You don't present this notices in a way that it looks as if it applies to your whole project. You should just make clear that your product includes MIT-licensed code, who made it and what licenses apply to the code you used. Common practice is to put these in the readme-file of a non-gui application or the about-section of a GUI application.

The Microsoft Public License is a lot more convoluted than MIT, but similar in spirit. It is also a permissive license which also allows to merge and sublicense the resulting product. The MS-PL puts an additional restriction for sublicensing: "If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license". Whether or not a license complies with the MS-PL is a topic you can debate about (The GNU-GPL does not, but I am quite sure the MIT does), but in your case it's irrelevant. You intend to license the resulting software under the MS-PL. That means it does not concern you, because the MS-PL code retains its license.

ContentLicense: CC BY-SA 3.0


问:
Is NoSQL a better choice when working with OOP?
This might be a silly question, but I've reading a little bit about NoSQL databases on the past few days and I'm trying to understand when really they help us. One thing I've realized though is that it seems that NoSQL databases are closer to OOP than RDBMS.

I say that because usually when we deal with OOAD we don't get a finished version of the model upfront. The model changes lots of times before getting to the real thing. I've even questioned about this here on Programmers.SE. With NoSQL, however, this seems the most natural thing, since the database can also change without much trouble.

Also, for a first try with this kind of technology I've created one MongoDB database and the data was being saved like POJO, so that it seemed much more close to object oriented design.

In that setting, NoSQL is really a good idea when working with OOP or it's just a good idea in cases where we need the database to scale, to be accessed by many users and all of that stuff?

答:
There is no such thing as NoSQL. There is a myriad of new database technologies grouped under that label, and they all work completely different.

But when you are talking about document-oriented, schemaless databases like MongoDB, which are one subset of NoSQL, then yes, these are often more suitable for modeling object-oriented hierarchies than relational databases, because they are usually less affected by the Object-relational impedance mismatch problem. When you have a class hierarchy with classes inheriting from other classes, these classes usually have some fields in common, but other fields which are unique to certain subtypes. When you try to cram all of these objects in one relational database table, you will have to create lots of columns for fields which only apply to a small subset of entries and will be NULL for all others. An alternative would be to use a separate table for each subtype, but this will become ugly when you try to query all objects of a certain base-class regardless of what their sub-class is.

An even better match than schemaless databases are pure object-databases, but these are usually quite exotic technologies without widespread use. Also, they are often bound to a specific programming language which hinders interoperability with systems programmed in other languages.

But how well you can model your data is only one aspect which should be taken into account when choosing a database technology. There are often a lot of other requirements in a project which give reason to favor one database technology or the other.


问:
Testing C# Eventhandler Subscription
I want my unit tests to be able to verify that some events were subscribed or unsubscribed at specific points. Currently, I see two options.

VerifiableEventHandler

Each client subscribes using the common += and -= notation. Each class that has a verifiable eventhandler needs to implement IsSubscribed(), which can query the eventhandler using GetInvocationList().

```<code>public interface IVerifiableEventHandler<T>
{
    event EventHandler<T> EventHandler;
    bool IsSubscribed(Delegate d);
}

// impl
public bool IsSubscribed(Delegate d)
{
    return EventHandler.GetInvocationList().Contains(d);
}
</code>```

Custom subscription interface

The actual C# event handler would be hidden, and clients can only subscribe using the Subscribe / Unsubscribe function.

```<code>public interface IEventSource<T>
{
    void Subscribe(EventHandler<T> func);
    void Unsubscribe(EventHandler<T> func);
    void Raise(object sender, T event_args);
}
</code>```

Pros and Contras

To me, the advantage of the first approach is that the principle of least surprise is not violated. A .Net programmer will expect events to be subscribed to using the += notation.

The advantage of the second approach is that it's very easy to test, as the functions are nothing special and can be verified easily if the class containing the eventhandler is mocked.

Is there a better way to solve this problem? If not, which of the two variants should be preferred, and why?

答:
Is there a better way to solve this problem?

Yes!

C# allows you to override the += and -= syntax. I'm not sure how easy it is to supply in common mocking frameworks like Moq, but it should be trivial to build your own fake object that has hooks into the subscribe and unsubscribe methods of your interface:

```<code>    private Action foo = () => {};
    public event Action Foo
    {
        add
        {
            Console.WriteLine("Subscribe called with value: {0}", value);
            foo += value;
        }

        remove
        {
            Console.WriteLine("Unsubscribe called with value: {0}", value);
            foo -= value;
        }
    }
</code>```

(though you'll likely to want to do something more interesting in the properties)

Title: Testing C# Eventhandler Subscription

Body:
Is there a better way to solve this problem?

Yes!

C# allows you to override the += and -= syntax. I'm not sure how easy it is to supply in common mocking frameworks like Moq, but it should be trivial to build your own fake object that has hooks into the subscribe and unsubscribe methods of your interface:

    private Action foo = () => {};
    public event Action Foo
    {
        add
        {
            Console.WriteLine("Subscribe called with value: {0}", value);
            foo += value;
        }

        remove
        {
            Console.WriteLine("Unsubscribe called with value: {0}", value);
            foo -= value;
        }
    }

(though you'll likely to want to do something more interesting in the properties)


问:
How do you explain agile process tool (like Scrum or Kanban) to a (traditional) project manager?
I am sure many people involved in the software development projects came up with this question, but I could not actually come up with satisfying answer.

How to explain to a manager used to having a huge gantt-chart, resource allocation, critical-paths (etc) benefits of using agile process tool such as Scrum or Kanban?

A typical problem is explaining why testing sometimes takes longer than the actually coding...

答:
I'm not sure this is the right forum for this question, but since similar questions are already here, my advice (out of experience) is:

Don't bother explaining. Rather, show him.

In particular, if you want to introduce agile or scrum processes, you'll have to do two jobs: on one side, report him the data he wants (Gantt charts, estimates). On the other, let your team work Scrum without interference. When things go well (they will if your team is with you) you can turn over and say "by the way, this time I managed things this way" and introduce him to agile.

A "traditional" PM is not opposed to process: however, they have probably been around long enough to survive most PM fads and would rather see results than babble.


问:
OO design choice and single responsibility principle
I'm currently refactoring an application which periodically downloads content from various sources (http, ftp, sql, etc). There is a schedule which controls the times during which the application can be active. For example, it can download content between 8AM and 16PM. The application has been written in an object oriented language (C#).

This is the general design I came up with in my first iteration:

The Scheduler class will be responsible for keeping to the general schedule. It starts the downloading at the start of the scheduled period, and stops it at the end. The Scheduler contains a number of ITask implementations, each of which have their own bit of downloading to do. I've created an abstract base class implementation which periodically calls the protected abstract method "StartDownload". Subclasses of Task will only implement this method, and won't have to worry about timing and scheduling.

So far, so good. But while TDD'ing the Task baseclass, I realised that it was actually difficult to mock the behaviour of StartDownload. When the Task's timer ticks, it should only call StartDownload if it has finished the previous download iteration. But since these are implementation details, it's hard to mock.

This made me wonder if the Task class isn't actually violating the Single Responsibility Principle. After all, it's taking care of the periodical invocation of StartDownload. And the StartDownload method is responsible for the actual downloading. So I came up with a more separated design:

Here the responsibility of the Task class is limited to just periodically calling the Client. And the Client's only responsibility is downloading content. Testing the Task class will now be easier, because I can just inject an IDownloadClient mock.
The Task and Download have a 1 to 1 relationship. So each Task performs one download, so to speak. In practice, all Task instances will be added to a single Scheduler instance and started/stopped from there.

I do wonder if this is actually a clearer design though... The Task class now seems a bit odd, being just a single implementation without any subclasses. What do you guys think?

答:
This is basically question of Composition vs. inheritance. In your first case, you use inheritance as way to share behavior. In second instance, you use composition. Also, in second case, it is easy to identify a Strategy pattern in IDownloadClient. So some would say the second case is better.

But there is also KISS and YAGNI. Your second case is already getting complicated for function it is supposed to do. It is questionable if you really need such abstract design.

If it was me, I would use the first one, but keep the second one in mind if more requirements come in, that might require complication of the whole design.

OwnerDisplayName: PJanssen


问:
What hat should a programmer not wear?
In my experience, software developers tend to wear multiple hats and fill multiple roles with different responsibilities.  From not only coding, but sometimes also writing SQL, designing the user-interface, designing the database, graphics manipulation, to even QA testing.

If the primary role is to write software/code, what roles should the developer not take on?  Are there any?

The intention of this question is not because a developer is incapable of filling another role-- but having the additional role actually works against the primary role, or should really be a dedicated role of someone who does not primarily program.

答: Any role that makes him manage himself. In small teams, there is often a tendency to make one of the senior developers the project manager, but also keep him in the team as a programmer. This leads to all kinds of problems, since this guy, as a programmer, is basically unmanaged. Instead of delegating all tasks to the other team members, he will often be tempted to assign many of them to himself, especially the most difficult tasks. So the most difficult tasks, those who are most likely to cause problems, are assigned to a person who is only 50% available as a programmer and as such reports to no-one. When other team members are unable to deliver, instead of kicking their ass, he will try to do their tasks, to, because as a project manager, he is responsible for the success and the safest way to get it done is to do it himself, isn't it?

ContentLicense: CC BY-SA 2.5

Title: What hat should a programmer not wear?


问:
Designing tables for recording rounds in a game
I'm working on website for the game of bridge and I am process to designing the table to store the bidding.

Shortly about the bidding. 4 people at a table will bid clockwise until 3 players has passed so it could be many rotations of bidding with a one of the four to start the bidding like this:

```<code>North East South West
Pass  1H   Pass  1NT
Pass  3H   Pass  3NT
Pass  Pass Pass

North East South West
                 1C
1S    Pass 3S    Pass
4S    Pass Pass  Pass
</code>```

So obviously I need save each bid in sequence but I have a few options how to design this.

Could have a table like this and just keep adding an entry per round needed:
Round, NorthBid, EastBid, SouthBid, WestBid

Or:
Sequence Number, Who, Bid

Might be some other alternatives but I would like to get some input on the best approach designing the table structure for data like this.

答:
If this is only for presentation, then the first one is probably easier to work with.

```
 +----------+
 | bids     |
 |----------|
 | game     |
 | round    |
 | north    |
 | south    |
 | east     |
 | west     |
 +----------+
```

And you are done.  Easy to insert, easy to extract for presentation.

However, this table isn't normalized and thus some queries against it will be more difficult.

Consider asking the question of the table "when is a 3NT the accepted bid?"  The query for this question becomes quite convoluted to the point of someone will hunt you down and say nasty things about your table structure.  If this is for presentation only, people likely won't do that... but for any other use... ug.

I was going to try to write that query to demonstrate the issue but then it got more ugly than I really wanted to try to present in here... and I've got a fair bit of tolerance for ugly queries.  Seriously, its bad if you want to ask that question.

On the other hand, if its a one row per bid...

```
 +----------+
 | bids     |
 |----------|
 | game     |
 | order    |
 | seat     |
 | bid      |
 +----------+
```

Well, now I can do a query such as:

```<code>select game
from
  bids NT, bids NT1, bids NT2, bids NT3
where
  NT.bid = '3NT'
  and NT1.order = NT.order +1 and NT1.bid = 'pass'
  and NT2.order = NT.order +2 and NT2.bid = 'pass'
  and NT3.order = NT.order +3 and NT3.bid = 'pass'
  and NT.game = NT1.game and NT.game = NT2.game and NT = NT3.game
</code>```

And that would do it.  Its not the cleanest one (I didn't do nice joins)... but it works.

You might consider making another table that contains the order of bids (since it is an enumerable list) so that the bid itself could be a number and you could do comparisons based on numbers rather than strings (foo.bid = bar.bid + 5 would say that the bid was raised to the N+1 value in the same suit such as a bid if 2H was raised to 3H).

It really boils down to what you want to do with the data.  For presentation, a simple demoralized schema works nicely.  For analysis, you need something else that looks at the bids as individual rows.

Body:
If this is only for presentation, then the first one is probably easier to work with.

 +----------+
 | bids     |
 |----------|
 | game     |
 | round    |
 | north    |
 | south    |
 | east     |
 | west     |
 +----------+

And you are done.  Easy to insert, easy to extract for presentation.

However, this table isn't normalized and thus some queries against it will be more difficult.

Consider asking the question of the table "when is a 3NT the accepted bid?"  The query for this question becomes quite convoluted to the point of someone will hunt you down and say nasty things about your table structure.  If this is for presentation only, people likely won't do that... but for any other use... ug.

I was going to try to write that query to demonstrate the issue but then it got more ugly than I really wanted to try to present in here... and I've got a fair bit of tolerance for ugly queries.  Seriously, its bad if you want to ask that question.

On the other hand, if its a one row per bid...

 +----------+
 | bids     |
 |----------|
 | game     |
 | order    |
 | seat     |
 | bid      |
 +----------+

Well, now I can do a query such as:

select game
from
  bids NT, bids NT1, bids NT2, bids NT3
where
  NT.bid = '3NT'
  and NT1.order = NT.order +1 and NT1.bid = 'pass'
  and NT2.order = NT.order +2 and NT2.bid = 'pass'
  and NT3.order = NT.order +3 and NT3.bid = 'pass'
  and NT.game = NT1.game and NT.game = NT2.game and NT = NT3.game

And that would do it.  Its not the cleanest one (I didn't do nice joins)... but it works.

You might consider making another table that contains the order of bids (since it is an enumerable list) so that the bid itself could be a number and you could do comparisons based on numbers rather than strings (foo.bid = bar.bid + 5 would say that the bid was raised to the N+1 value in the same suit such as a bid if 2H was raised to 3H).

It really boils down to what you want to do with the data.  For presentation, a simple demoralized schema works nicely.  For analysis, you need something else that looks at the bids as individual rows.


问:
Should I use inheritance or an interface?
So in a nutshell I have an abstract class :

```<code>public abstract class Member
{
public string PCode { get; set; }
public string Reference { get; set; }
public DateTime? ElectedDate { get; set; }
}
</code>```

And this is inherited by 3 other classes:

```<code>public class Fellow : Member
{
 // some class level properties here
}
public class ForeignMember : Member
{
 // some class level properties here
}
public class HonoraryMember : Member
{
 // some class level properties here
}
</code>```

And the usual CRUD operations are done through using a generic repository pattern:

Interface

```<code>public interface ICRMRepository<T>
{
    List<T> GetAll();
    T GetById(int id);
    T GetByPCode(string pcode);
}
</code>```

Class

```<code>public class CRMRepository<T> : ICRMRepository<T> where T : class
{

   public List<T> GetAll()
   {
    //actions go here
   }

   public T GetById(int id)
   {
    //actions go here
   }

   public T GetByPCode(string pcode)
   {
    //actions go here
   }
}
</code>```

The question is if I wanted to do a query that would bring back all the Fellows, HonoraryMembers and ForeignMembers in one result set, how would I do this?

Would it be better to have an interface instead of inheritance e.g. IMember, and then the three classes use that interface? Or some solution that uses both?

答:
Typically you would get ahold of an ICRMRepository<Member> and query against that if you wanted all Members and within your loop you'd check their actual type:

```<code>foreach(Member member in memberRepository.GetAll())
{
    // do stuff here that you can do for all Members, then...
    if(member is HonoraryMember)
    {
        var honoraryMember = member as HonoraryMember;
        // do stuff here that you only do to HonoraryMembers...
    }
}
</code>```

In order for this to work, it's dependent on the capabilities of your repository.  Your generic Member repository has to actually return instances of the correct class.  Not all repository implementations do this, but yours could.

Most implementations use concrete types for entities, but your idea of using interfaces (IMember) is actually worth looking into.  I wrote a small application that used interfaces for my entities and I really liked it.  You end up with some interesting benefits, like your Insert method can take an instance of NewMember and your queries can return instances of ExistingMember (which tracks changes to itself) and both could implement the IMember interface.

Body:
Typically you would get ahold of an ICRMRepository<Member> and query against that if you wanted all Members and within your loop you'd check their actual type:

foreach(Member member in memberRepository.GetAll())
{
    // do stuff here that you can do for all Members, then...
    if(member is HonoraryMember)
    {
        var honoraryMember = member as HonoraryMember;
        // do stuff here that you only do to HonoraryMembers...
    }
}

In order for this to work, it's dependent on the capabilities of your repository.  Your generic Member repository has to actually return instances of the correct class.  Not all repository implementations do this, but yours could.

Most implementations use concrete types for entities, but your idea of using interfaces (IMember) is actually worth looking into.  I wrote a small application that used interfaces for my entities and I really liked it.  You end up with some interesting benefits, like your Insert method can take an instance of NewMember and your queries can return instances of ExistingMember (which tracks changes to itself) and both could implement the IMember interface.


问:
How do I explain to non-programers what .NET is?
I don't work at a software company, and I'm one of a small handful of people in the company that know anything about programming. I spend a lot of time automating other programs that are used in the office through public APIs, and I've also created a few stand alone applications. I work almost entirely in C#.NET as every application we seem to use in the office seems to have some form of .NET API.

I've had a few people here ask me about learning "how to program", and where they should start. I think it makes a lot more sense to learn a .NET language as nearly all the programs they would want to automate have a .NET API, and it sounds like VBA is on it's way out and being replaced by VSTA.

However, I'm trying to figure out how to explain what .NET is and why they should learn it to a someone that doesn't know anything about programming. It's not really a language, as there are a number of languages that are considered .NET languages. Plus I think there is a distinction between ".NET" and "The .NET framework" as the latter is more about the libraries provided by Microsoft.

答: "It makes it easier for programmers/software developers make applications for Microsoft products and even some other platforms like Linux."</p>


问:
Design Pattern: Algorithm varies according to the input arguments
I will give a simple example to help you understand my question. Suppose we have a rectangle and a Utility class with a method that creates a buffer arround a shape.

The .createBuffer method has required and optional arguments:

required: radius

optional: direction (for example "inside" or "outside", default is "outside")

... maybe more arguments ...

Every combination of arguments needs a different algorithm.

Which design pattern is appropriate for solving similar problems?

答:
I would go with a builder pattern.
Where shape is the shape to be buffered, 5 is the required radius, I made up some other things that you may want your buffer to have.

```<code>var bufferedShape = new BufferBuilder(shape, 5)
                     .Inside()
                     .SinglePixel()
                     .DropShadow(10)
                     .CreateBuffer();
</code>```

A bit more detail in this post.

Edit: The builder pattern addresses the need for different algorithms in that each call to the different methods of the builder class builds up the final buffered shape class that knows how to draw itself based on the methods called during the building phase.

Body:
I would go with a builder pattern.
Where shape is the shape to be buffered, 5 is the required radius, I made up some other things that you may want your buffer to have.

var bufferedShape = new BufferBuilder(shape, 5)
                     .Inside()
                     .SinglePixel()
                     .DropShadow(10)
                     .CreateBuffer();

A bit more detail in this post.

Edit: The builder pattern addresses the need for different algorithms in that each call to the different methods of the builder class builds up the final buffered shape class that knows how to draw itself based on the methods called during the building phase.


答:
There's a third option: mock the object with the event and use behavior testing to verify the mock's subscriptions at given points.  Several mocking frameworks allow for this.

```<code>public interface INeedToBeMocked
{
    public event EventHandler EventRaised;
}
</code>```

NSubstitute

```<code>var mockedItem = Substitute.For<INeedToBeMocked>();
mockedItem.Received().EventRaised += Arg.Any<EventHandler>();
</code>```

Rhino Mocks

```<code>var mockedItem = MockRepository.GenerateMock<INeedToBeMocked>();
mockedItem.AssertWasCalled(x => x.EventRaised += Arg.Is.Anything);
</code>```

Title: Testing C# Eventhandler Subscription

Body:
I want my unit tests to be able to verify that some events were subscribed or unsubscribed at specific points. Currently, I see two options.

VerifiableEventHandler

Each client subscribes using the common += and -= notation. Each class that has a verifiable eventhandler needs to implement IsSubscribed(), which can query the eventhandler using GetInvocationList().

```<code>public interface IVerifiableEventHandler<T>
{
    event EventHandler<T> EventHandler;
    bool IsSubscribed(Delegate d);
}

// impl
public bool IsSubscribed(Delegate d)
{
    return EventHandler.GetInvocationList().Contains(d);
}
</code>```

Custom subscription interface

The actual C# event handler would be hidden, and clients can only subscribe using the Subscribe / Unsubscribe function.

```<code>public interface IEventSource<T>
{
    void Subscribe(EventHandler<T> func);
    void Unsubscribe(EventHandler<T> func);
    void Raise(object sender, T event_args);
}
</code>```

Pros and Contras

To me, the advantage of the first approach is that the principle of least surprise is not violated. A .Net programmer will expect events to be subscribed to using the += notation.

The advantage of the second approach is that it's very easy to test, as the functions are nothing special and can be verified easily if the class containing the eventhandler is mocked.

Is there a better way to solve this problem? If not, which of the two variants should be preferred, and why?

Body:
There's a third option: mock the object with the event and use behavior testing to verify the mock's subscriptions at given points.  Several mocking frameworks allow for this.

public interface INeedToBeMocked
{
    public event EventHandler EventRaised;
}

NSubstitute

var mockedItem = Substitute.For<INeedToBeMocked>();
mockedItem.Received().EventRaised += Arg.Any<EventHandler>();

Rhino Mocks

var mockedItem = MockRepository.GenerateMock<INeedToBeMocked>();
mockedItem.AssertWasCalled(x => x.EventRaised += Arg.Is.Anything);


问:
Inventory Management System Design Problem "Items Packages"
I am developing a retail management system with inventory management module, I am facing a logic design problem and I don't really know how to address the problem in an easy way, so I wrote an example which illustrates that problem:

Let's say I have an item (e.g. Cola Can), this item have a Barcode (11...1), this is so good until now and we can sell the item smoothly using the Cola Can barcode(11...1). However, when the warehouse buys cola can they buy with larger package for simplicity 6 cans packages which have different barcode(11...2), after that the 6 packages is braked down into 1-1 cans and sold per item of barcode (11...1).

The problem is that you buy with package and sell per item which will make the reports for the inventory incorrect, and the inventory stock will never match.

How to control this packages problem or should the system deals with the smallest package only (e.g. when I buy 6 cans package, the warehouse should enter 6 items of single can barcode)?

答:
You're going to need to bust the assembly when an item within it is sold.  Add the remaining items from the assembly to inventory and subtract the case.  This will effectively balance out your inventory.

As per request via comments, I will adjust my answer accordingly.

We can use your 'Cola Can' example to help us visualize.  We all know that you can buy 12 can cases of Cola 'Case Upc (11..2)', but lets say we want to sell them individually 'Unit Upc (11..1)'.  In addition for clarification, let's say that your physical and logical inventory match in that all Single Cans have been sold.  The process would go something along the lines of this.

```<code>if (inventory of single cola == 0) and (inventory of case cola > 0) then
    subtract 1 case from inventory of case cola.
    add the number of cola in 1 case of cola to single cola inventory
    subtract 1 single cola from single cola inventory
</code>```

While the code is a bit rough, the example should show you how to effectively get your result.

Body:
You're going to need to bust the assembly when an item within it is sold.  Add the remaining items from the assembly to inventory and subtract the case.  This will effectively balance out your inventory.

As per request via comments, I will adjust my answer accordingly.

We can use your 'Cola Can' example to help us visualize.  We all know that you can buy 12 can cases of Cola 'Case Upc (11..2)', but lets say we want to sell them individually 'Unit Upc (11..1)'.  In addition for clarification, let's say that your physical and logical inventory match in that all Single Cans have been sold.  The process would go something along the lines of this.

if (inventory of single cola == 0) and (inventory of case cola > 0) then
    subtract 1 case from inventory of case cola.
    add the number of cola in 1 case of cola to single cola inventory
    subtract 1 single cola from single cola inventory

While the code is a bit rough, the example should show you how to effectively get your result.


答:
It's not clear to me that you need any design pattern -- at least not in the sense of the "Gang of Four" book.

From your description of the problem:

Every combination of arguments needs a different algorithm

what you need is some way to get from input -> output where input is "combination of arguments" and output is "algorithm".  This is essentially just a hash table (or a function), in which:

keys: some property of the specific arguments present

values: algorithms (the exact implementation could be functions, objects, etc. depending on which language you're using and how convenient each choice is).

The second part of your problem -- "The .createBuffer method has required and optional arguments" -- isn't well-specified enough to give a sure answer, and will also depend on your choice of language.  If your language supports optional arguments and default values, this problem nearly solves itself:

```<code>def createBuffer(self, radius, direction="outside")
    ...
</code>```

If you're in Java, you can use reference types and check for null, converting them to default values where necessary.  Or even better, try this -- it helps clarify your intention to use nullable types to other programmers!

```<code>public void createBuffer(float radius, Optional<Direction> direction) {
    if ( direction.isAbsent() ) {
        direction = new Direction("outside");
    }
    ....
}
</code>```

As others mentioned, you could also throw the Builder pattern at it, but personally I wouldn't unless I was sure that I needed it, because a single method with a single type signature is simpler and easier to use.

Title: Design Pattern: Algorithm varies according to the input arguments

Body:
I will give a simple example to help you understand my question. Suppose we have a rectangle and a Utility class with a method that creates a buffer arround a shape.

The .createBuffer method has required and optional arguments:

required: radius

optional: direction (for example "inside" or "outside", default is "outside")

... maybe more arguments ...

Every combination of arguments needs a different algorithm.

Which design pattern is appropriate for solving similar problems?

Body:
It's not clear to me that you need any design pattern -- at least not in the sense of the "Gang of Four" book.

From your description of the problem:

Every combination of arguments needs a different algorithm

what you need is some way to get from input -> output where input is "combination of arguments" and output is "algorithm".  This is essentially just a hash table (or a function), in which:

keys: some property of the specific arguments present

values: algorithms (the exact implementation could be functions, objects, etc. depending on which language you're using and how convenient each choice is).

The second part of your problem -- "The .createBuffer method has required and optional arguments" -- isn't well-specified enough to give a sure answer, and will also depend on your choice of language.  If your language supports optional arguments and default values, this problem nearly solves itself:

def createBuffer(self, radius, direction="outside")
    ...

If you're in Java, you can use reference types and check for null, converting them to default values where necessary.  Or even better, try this -- it helps clarify your intention to use nullable types to other programmers!

public void createBuffer(float radius, Optional<Direction> direction) {
    if ( direction.isAbsent() ) {
        direction = new Direction("outside");
    }
    ....
}

As others mentioned, you could also throw the Builder pattern at it, but personally I wouldn't unless I was sure that I needed it, because a single method with a single type signature is simpler and easier to use.


问:
Is it common for the founder of a web app to lack technical expertise to scale it?
When I look at things like Twitter, it seems like the idea is so simple to implement initially that the founder does not have to be very technically talented. Basically it's just a guy with a good idea. But when an app / software blows up and entails much harder engineering problems, how does the founder deal with it?

Have we seen cases in which the original guy with the good idea somehow falls off the enterprise as it becomes more about technical challenges and less about ideas?

答:
The founders of the company can come from a lot of different backgrounds: they might be marketing folks, or sales folks, or just someone in a different industry altogether who want to build their own organization. They might be money guys trying to cash in on a hot industry idea. So it's pretty common in the early days of a startup to have a huge disconnect between the organizational vision and actual technical capabilities.

On the other hand, sometimes the founders are very technically savvy. The best situation is when the founders have both strong technical skills as well as "business" skills.

In the early days of a startup, the technical resources can get stretched very thin. So they may be playing lots of technical roles compared to working in a big shop where people can focus on a smaller set of tasks. Also, startups are typically short of cash and sensitive to how much runway they have, so it's common for them to pay less. This means that they bring in people who are building their technical skills, or trying to prove themselves in the industry.

The stereotype is young guys who want to program all day in the office, working for peanuts, sleeping under their desks at night.

As an organization grows, there is potential for people with real talent on both the technical side and on the "business" side to emerge. But sometimes the organization needs to add the talent they need as they grow and get more money.

Scaling is just one aspect of that growth. There are other important technical capabilities, such as harnessing advanced technologies, creating a compelling user experience, and (nowadays) handling huge amounts of data.


问:
How much time do you spend on design before coding?
In my experience, it is useful to spend a little while sketching plans for a project before getting into code. Such planning usually includes choosing frameworks/tools, writing requirements and expectations, and doing mockups.

I usually only do this for serious projects though, not so much for one-off or short-lived attempts.

I'd be interested to hear how much time you spend on planning/designing projects before starting to do the coding. Do you do it for every project, or just the "serious" ones?

答:
It depends greatly on the project.

If the project is based on a specification that has been already written (e.g. a binary data file specification), then there may not be much design involved.

If the project is highly speculative or research oriented, I might spend more time writing throwaway code to formulate a design than I will on creating a design up-front.

If the project is a large one, it will need more up-front thinking about high-level architecture.


问:
What is "condition testing" (as defined by the ISTQB Syllabus) actually good for?
I am currently checking through the syllabus for the ISTQB "Technical Test Analyst" certification. This syllabus (henceforth called "TTA syllabus") contains a chapter dedicated to "condition testing" (apparently this is also called "condition coverage" or "condition coverage testing".)

Condition testing as defined in the TTA syllabus strikes me as an exceedingly strange and possibly anachronistic thing that has more to do with Grandma's Ham Story than with software testing. Let me explain...

What is "condition testing" according to the TTA syllabus?

Referring to the "Advanced Level Syllabus - Technical Test Analyst, Version 2012" of the ISTQB, available here, "condition testing" is defined as follows on page 12:

Compared to decision (branch) testing, which considers the entire
  decision as a whole and evaluates the TRUE and FALSE outcomes in
  separate test cases, condition testing considers how a decision is
  made. Each decision predicate is made up of one or more simple
  “atomic” conditions, each of which evaluates to a discrete Boolean
  value. These are logically combined to determine the final outcome of
  the decision. Each atomic condition must be evaluated both ways by the
  test cases to achieve this level of coverage.

Applicability

Condition testing is probably interesting only in the abstract because
  of the difficulties noted below. Understanding it, however, is
  necessary to achieving greater levels of coverage that build upon it.

So let's clarify the words

Suppose we have some software-under-test on which we want to do whitebox testing (i.e. we have the source code). The code naturally contains many of those decision predicates that we all know and love and that show up after strings like if, while, until etc.

An example of the decision predicate might be:

((x>y+z) AND (y<-3)) OR ((z²+x²<4) AND (z≤y))

This decision predicate accepts a triple (x,y,z) of integer values (say) and outputs a boolean, b_out.

The first-level functions which map (x,y,z) to {TRUE,FALSE} are called conditions (also atomic conditions) in the TTA syllabus.

Condition testing coverage

One attains "condition testing coverage" by running test cases until all the conditions found in the decision yielded at least once true and at least once false.

One can thus achieve condition testing coverage by running the following five test cases (for example):

Each of the the b0, b1, b2, b3 shows up at least once with true and at least once with false. In some test cases, we do not care about a given value as it has no influence on the condition whose output we want to get right.

Addendum: Decision coverage

Incidentally, the truth table shows also that "decision coverage" has been attained for this decision, as b_out shows up at least once with true and at least once with false, so both branches of any code would be covered.

And now the question

What is "condition testing" as defined above actually good for?

It won't help you ascertain the correctness of the decision predicate at all.

That is best done by a code inspection, letting a second team write the same expression and comparing outputs or running test cases at "boundary values" (e.g. here, for y = -4, -3, -2).

Checking the individual conditions strikes me to be more about testing the CPU's ALU or maybe testing the compiler output. It is certainly suitable for checking manually written assembler code or verifying manually assembled logic.

And this makes me think that "condition testing" could well be a leftover from the days where conditions were actually wired up on panels  (for example in the ENIAC) and might thus be subject to wiring bugs. These days, the condition is written in high-level code and is exactly the one you conceptually want. While review might be useful, a testing of the condition is just a waste of time.

Or am I missing something?

Addendum: Literature Search

A search of the IEEE Xplore library for "condition testing" yields only two papers relevant to software (all the others seem relevant to hardware only), both by K.C. Tai of the Department of Computer Science of North Carolina State University.

Checking one of those, Condition-based software testing strategies reveals that the author uses the term condition in the sense of decision above, i.e. in this paper "condition testing" is actually "decision testing". The condition as used in the TTA syllabus is called simple condition. It seems the TTA syllabus definitions are not widely used.

From the abstract:

A computer program consist of statements, such as IF and WHILE statements, that contain conditions, which are combinations of Boolean and relational expressions. A testing approach, referred to as condition testing, is to test a program by focusing on testing the conditions in this program. A number of condition testing strategies have been developed, but they are not effective for detecting errors in complicated conditions. In this paper, we define two condition testing strategies, based on the detection of Boolean and relational expression [i.e. expression of the form E1 op E2, where E1 and E2 are arithmetic expressions and op is one of six possible relational operators: < <=, =, !=, >, >=] errors in a condition. For these two condition testing strategies, we show some theoretical properties and explain why they are practical and effective for testing programs containing complicated conditions.

答:
Condition testing is a direct consequence of the fact that each if in your software creates a "bifurcation" (essentially breaking your code up into two separate bits of code), thereby increasing the overall cyclomatic complexity of your code.

In order to get full code coverage in a white box testing scenario, you need to have some knowledge of the if conditions, so that you can make sure that each code branch is being exercised during testing.

As to the "correctness" of the code, that can be ascertained by writing meaningful unit tests.  That is, for each input that exercises a particular path in the code, you can expect some output, the result of which demonstrates that the correctness that you are after has been achieved.

By "meaningful," I mean that, generally your unit tests will demonstrate that some contract or requirement has been fulfilled.  But you still need to make sure you exercise all code paths, so that there are no unpleasant surprises later.

OwnerDisplayName: David Tonhofer


问:
Why must directories be empty before being deleted?
As far as I know, deleting a non empty directory could work the same way as deleting an empty directory: by removing the pointer to the directory's metadata there would be no pointers to the items it contained, effectively deleting all its children recursively.

If that's true, then why must directories be empty before being deleted? Is it just a safeguard to prevent erasing many files at once, or a technical limitation of some (possibly ancient) file system?

答:
Many file systems work with a reference count system for files.

```
~/foo$ ls -l
total 312
-rwxr-xr-x  2 shagie  staff  14884 Jan 24 10:35 a.out*
-rwxr-xr-x  1 shagie  staff    379 Apr 10 13:56 alias.pl*
-rw-r--r--@ 1 shagie  staff  14236 Apr 10 13:50 aliases.csv
-rwxr-xr-x  2 shagie  staff  14884 Jan 24 10:35 b.out*
-rw-r--r--  1 shagie  staff    137 Feb 17 15:30 f.pl
-rwxr-xr-x  1 shagie  staff    616 Mar 24 15:19 file*
```

You've got permissions, and then the reference count.  Note that a.out and b.out are the same file.  Once all references to a file are deleted it can be reclaimed.  But files and directories are different.

In POSIX, you've got files which are removed by unlink - which removes them from a directory entry.

The unlink function deletes the file name filename. If this is a file's sole name, the file itself is also deleted. (Actually, if any process has the file open when this happens, deletion is postponed until all processes have closed the file.)

And you've got directories which are removed with rmdir.

The rmdir function deletes a directory. The directory must be empty before it can be removed; in other words, it can only contain entries for . and ...

These are separate checks and rmdir can't remove a file nor can unlink remove a directory.  That's just the way it works.

This makes the code much simpler and fewer error messages involved.  A function does one and only one thing.  From Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?

If, when describing the activity of the code to another programmer you use the word 'and', the method needs to be split into at least one more part.

For rmdir to behave this way the description would be:

Remove the directory entry, and any files if any are contained within the directory.

Note the and.  By making rmdir non-atomic this means there are many more situations where a partial process could be done without clearly saying if it was done or not.  If you hit files you cannot delete as part of the hypothetical rmalldir is it a success? failure? what error message?

And thus, each function call does one and only one thing - remove a file.  remove a directory.  Any errors are specifically applicable to that operation.

The code is simpler and there are fewer possible situations for error either in the library or people using the library.

Body:
Many file systems work with a reference count system for files.

~/foo$ ls -l
total 312
-rwxr-xr-x  2 shagie  staff  14884 Jan 24 10:35 a.out*
-rwxr-xr-x  1 shagie  staff    379 Apr 10 13:56 alias.pl*
-rw-r--r--@ 1 shagie  staff  14236 Apr 10 13:50 aliases.csv
-rwxr-xr-x  2 shagie  staff  14884 Jan 24 10:35 b.out*
-rw-r--r--  1 shagie  staff    137 Feb 17 15:30 f.pl
-rwxr-xr-x  1 shagie  staff    616 Mar 24 15:19 file*

You've got permissions, and then the reference count.  Note that a.out and b.out are the same file.  Once all references to a file are deleted it can be reclaimed.  But files and directories are different.

In POSIX, you've got files which are removed by unlink - which removes them from a directory entry.

The unlink function deletes the file name filename. If this is a file's sole name, the file itself is also deleted. (Actually, if any process has the file open when this happens, deletion is postponed until all processes have closed the file.)

And you've got directories which are removed with rmdir.

The rmdir function deletes a directory. The directory must be empty before it can be removed; in other words, it can only contain entries for . and ...

These are separate checks and rmdir can't remove a file nor can unlink remove a directory.  That's just the way it works.

This makes the code much simpler and fewer error messages involved.  A function does one and only one thing.  From Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?

If, when describing the activity of the code to another programmer you use the word 'and', the method needs to be split into at least one more part.

For rmdir to behave this way the description would be:

Remove the directory entry, and any files if any are contained within the directory.

Note the and.  By making rmdir non-atomic this means there are many more situations where a partial process could be done without clearly saying if it was done or not.  If you hit files you cannot delete as part of the hypothetical rmalldir is it a success? failure? what error message?

And thus, each function call does one and only one thing - remove a file.  remove a directory.  Any errors are specifically applicable to that operation.

The code is simpler and there are fewer possible situations for error either in the library or people using the library.


答: Don't forget cookies. I consider cookies to be more dangerous than JavaScript. I used to be a NoScript user, but I have turned it off in favor of whitelisting cookie sites.</p>

Title: How important is graceful degradation of JavaScript?

Body:
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?


问:
Inheritance: Is code from superclass virtually *copied* to subclass, or is it *referred-to by subclass*?
Class Sub is a subclass of class Sup. What does that mean practically? Or in other words, what is the practical meaning of "inheritance"?

Option 1: The code from Sup is virtually copied to Sub. (as in 'copy-paste', but without the copied code visually seen in the subclass).

Example: methodA() is a method originally in Sup. Sub extends Sup, so methodA() is (virtually) copy-pasted to Sub. Now Sub has a method named methodA(). It is identical to Sup's methodA() in every line of code, but entirely belongs to Sub - and doesn't depend on Sup or is related to Sup in any way.

Option 2: The code from Sup isn't actually copied to Sub. It's still only in the superclass. But that code can be accessed through the subclass and can be used by the subclass.

Example: methodA() is a method in Sup. Sub extends Sup, so now methodA() can be accessed through Sub like so: subInstance.methodA(). But that will actually invoke methodA() in the superclass. Which means that methodA() will operate in the context of the superclass, even if it was called by the subclass.

Question: Which of the two options is really how things work? If none of them is, than please describe how these things actually work.

答:
the code is not copied, it is accessed by reference:

the subclass references its methods and the superclass

the superclass references its methods

compilers may optimize how this is represented/executed in memory, but that's basically the structure


答:
Option 2.

The bytecode is referenced dynamically at runtime: this is why, for example, LinkageErrors occur.

For example, assume you compile two classes:

```<code>public class Parent {
  public void doSomething(String x) { ... }
}

public class Child extends Parent {
  @Override
  public void doSomething(String x) {
    super.doSomething(x);
    ...
  }
}
</code>```

Now modify and recompile the parent class without modifying or recompiling the child class:

```<code>public class Parent {
  public void doSomething(Collection<?> x) { ... }
}
</code>```

Finally, run a program that uses the child class. You will receive a NoSuchMethodError:

Thrown if an application tries to call a specified method of a class
  (either static or instance), and that class no longer has a definition
  of that method.

Normally, this error is caught by the compiler; this error can only
  occur at run time if the definition of a class has incompatibly
  changed.

Title: Inheritance: Is code from superclass virtually *copied* to subclass, or is it *referred-to by subclass*?

Body:
Class Sub is a subclass of class Sup. What does that mean practically? Or in other words, what is the practical meaning of "inheritance"?

Option 1: The code from Sup is virtually copied to Sub. (as in 'copy-paste', but without the copied code visually seen in the subclass).

Example: methodA() is a method originally in Sup. Sub extends Sup, so methodA() is (virtually) copy-pasted to Sub. Now Sub has a method named methodA(). It is identical to Sup's methodA() in every line of code, but entirely belongs to Sub - and doesn't depend on Sup or is related to Sup in any way.

Option 2: The code from Sup isn't actually copied to Sub. It's still only in the superclass. But that code can be accessed through the subclass and can be used by the subclass.

Example: methodA() is a method in Sup. Sub extends Sup, so now methodA() can be accessed through Sub like so: subInstance.methodA(). But that will actually invoke methodA() in the superclass. Which means that methodA() will operate in the context of the superclass, even if it was called by the subclass.

Question: Which of the two options is really how things work? If none of them is, than please describe how these things actually work.

Body:
Option 2.

The bytecode is referenced dynamically at runtime: this is why, for example, LinkageErrors occur.

For example, assume you compile two classes:

public class Parent {
  public void doSomething(String x) { ... }
}

public class Child extends Parent {
  @Override
  public void doSomething(String x) {
    super.doSomething(x);
    ...
  }
}

Now modify and recompile the parent class without modifying or recompiling the child class:

public class Parent {
  public void doSomething(Collection<?> x) { ... }
}

Finally, run a program that uses the child class. You will receive a NoSuchMethodError:

Thrown if an application tries to call a specified method of a class
  (either static or instance), and that class no longer has a definition
  of that method.

Normally, this error is caught by the compiler; this error can only
  occur at run time if the definition of a class has incompatibly
  changed.


问:
How to find number of points with same minimal distances on matrix
I'm trying to find the number of points in a matrix with the same minimal distances.

Start with a MxN matrix, where M and N < 50000.  There is given a set of fixed points, with their respective coordinates.

The problem is to find the number of points in the matrix such as the minimal distance from any point in the set can be reached for at least two point in the set. The distance is measured by moving one units a time horizonatally or vertically. You can't move diagonally.

An example would make things clearer.

Let's say we have 3 fixed point: (1,3), (3,1) and (3,6). Here the point (3,3) would be one point since the minimal distance is 2 units and it can be reached for the first two fixed points in the set. However, the point (4,4) doesn't satisfy the requirements. Although the distance from (1,3) and (3,1) is same, 4 units, the minimal distance is 3 units.

My idea was to use any point with integer coordinates that lies on the bisector of a segment joining each par as a point that would fill our requirements. But I find a lot of false positives were a point satisfies the requirements, but doesn't lie on the perpendicular bisector.

Brute-force methods won't work, because we need too check a billion of distance for each point and that one heck of a job to do.

How should I go about solving this problem?

答:
As depicted here, what you are looking for is the 1st-order 2-dimensional Voronoi diagram under the Manhattan, or L1-metric. This is a quite non-trivial problem (to solve efficiently), fortunately with many existing algorithms and software.

You actually want the subset of the Voronoi diagram that coincides with the discrete grid defined by your matrix coordinates, but it is straightforward to find which points of the diagram happen to have integral coordinates.

The "fixed points" are called sites, seeds, generators, or source points in different contexts. Since the number of sites is small, it is more appropriate to use a computational geometry algorithm, that is, find a vector representation of the line segments the diagram consists of, independently of the size of your matrix (for 10 sites, it should be extremely fast).

A highly recognized library is CGAL, which includes a large number of computational geometry algorithms in C++, and in particular 2D segment Delaunay graphs (Voronoi diagrams). The user manual talks only about Euclidean distance, but there is also an L1 Voronoi diagram demo, so I hope you'll find your way.

Another perspective is a raster representation, using algorithms that sweep the entire plane (your matrix) once, in a particular order similar to wave propagation. This is recommended if the number of sites is large, forming arbitrary shapes on the plane. It is related to the distance transform, the medial axis and the topological skeleton. The latter two are generalizations of the Voronoi diagram, in that they consist of curves rather than line segments in general, regardless of the metric.

A very good solution under this perspective is distance transforms of sampled functions, also giving source code. This is limited to computing the distance transform and to separable distance metrics for instance squared Euclidean or L1 (your case).

To find the medial axis given the distance transform, a good choice is my own medial feature detector, with binary code available. This work also uses an alternative method for distance transform computation that has no limitation on the distance metric. It is slower than the previous one but still linear-time on the size of domain (your matrix). Computation of the medial axis itself is extremely fast (linear-time on the number of points of the medial axis).

As an example, you can have a look at this image, where white points are the sites (actually forming a closed curve on the plane), and red-yellowish curves are the (Euclidean) medial axis. Note that the latter have sub-pixel accuracy, i.e. appear as 1-pixel-wide anti-aliased curves, although the input sites do not. This illustrates that you have the required information (exact position) to find out whether a candidate point on the medial axis has integral coordinates or not. To get an idea of speed, this result was generated in around 300ms.

If you care about efficiency, my advice is to look for existing algorithms or code. If you insist on your own implementation, you will have to read a lot first, so that you have a good understanding of the problem.

ContentLicense: CC BY-SA 4.0


问:
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.

答:
Before I get in to anything else or in details, I will start by saying - DO NOT PULL THE SITE, but if possible, encrypt / obfuscate / similar to the original source code. If you have the ability to, but this is risky, put in a fail safe / on application start that simply looks for a web service / xml feed or whatever is quickest in webspace that you control and make it that if this feed is not found and / or a "special" code is returned, the application fails to start.

If they specifically said they want a site that does xxx - but do not actually mention source code or the ability to extend in the future without you, technically there is nothing forcing you to give the source code as long as the site lives up and does what was originally agreed upon.

There was a verbal contract to provide a service (Website Creation) in return for payment (£950).

If you were late or not by a few days, that does not really matter unless it was part of the original contract e.g. penalty clause. "I will not pay you / I will give you a reduced rate if you finish by xx/xx/2010".

Remember that a contract has two sides Pulling the content may mean you are £150 up, but it would also mean breaking your side of the contract for supplying the service - even if he has not lived up to his side of paying for it.

(This is unless either of you discussed any sort of cancellation agreement in advance... Remember)

Also, pulling content will mean very risky ground, I guarantee that any legal body (lawyer, judge, arbiter etc.) will not look favourably at you and it may affect getting any money in the future.

What I have said here is to protect you, if you were to pull the content, you should not get in to any further trouble, but it certainly would not advance your case anywhere. At worst, he may try to sue you (for either money or an action of restoring the site) - in which case you can issue a counter claim for the amount owed.... but again, any legal body will probably think you are being petty for taking it down.

I don't mean to be rude, but in the future, have a contract - it does not need to be legally written or have technical terms, it can be on a napkin - just make sure you write in plain English - I <their name / company> agree to pay <your name/company> for a website. All content of the website remains <your name/company>'s property until it is paid in full.

People always try to write cancellation clauses, extra stuff that just confuses matters - just remember, a contract is for products/services, and you don't have to have a cancellation clause or anything complicated (when B2B).

At this point, there may be a perfectly reasonable explanation for what is happening - ask your friend, or try going around/asking this person. If it fails, send one recorded letter (about 50p) stating - I have tried to contact you many times for the money owed on completion of the website. Please pay either cash, cheque or money transfer **within** one week of receipt of this letter and contact immediately upon doing it, otherwise I will have no choice other than to proceed with legal action.

Again, remember, there is no sort of clause that protects you from non payment, therefore if you delete the site, you are also in breach of contract and a few judges may just throw it out as a deal that went wrong for both sides.

If he does not respond to the letter, you have to follow it up. As long as you have a bit of history - emails, phone records (if not full recordings), your friend, etc, take him to court. It is not complicated or scary - you can do it yourself. The website is www.moneyclaim.gov.uk (Money Claim Online (MCOL)), it is part of Her Majesty's Courts Service (HMCS) and they will set the claim up, forward it to your local court and everything. - It does cost, but it is not a lot.

I have only used the service twice, one time the person just ignored me - it was only over something costing £50 and I got a default judgement against him - he never paid so in total I was £80 out of pocket (£30 fee), but I never chased it up as bailiffs would of cost a lot more.  The next was a lying, dishonest company (would say a lot more and wondering if I should hyperlink to their website!) that basically took £1468.75 from me and refused to provide me with the product I bought (Opposite to you!) I am an email hoarded and was able to produce messages going back 5 years previous to the date but they kept refusing to either give the product or pay up. The even filed a counter claim against me, but then I sent one last email stating my point and the day before documents had to be filled for trial, they paid out every penny including my legal fees (around £300)

Again, contract for supply of product/services in return for money - I lived up to my point, they didn't... if they provided the service the contract would of been completed, if they returned the money, officially they are still in breach - I could of got compensation, but I really just wanted it to be over with.

When it all comes to an end - do not mess around with their site, it will just make you look petty - you are safe in the knowledge that you have a "kill switch", but right now they will have a site that does what they wanted, but can not be improved / changed without you (If you followed my advise).

P.S. As you can guess, I am in England as well - I have access to a few excellent legal resources through my business, if you want to talk to a lawyer, email me and I will happily send you the details of someone who will be willing to talk to you/give you advise for free.

Written a lot here and taken longer than I thought it would! I have edited it over and over again - if any spelling/grammar or flow problems, feel free to edit.

Title: How to get money from reluctant client?


问:
Are VB.NET and C#.NET projects created from Microsoft Visual Studio "Open Source" safe?
I'm developing software in VB.NET and C#.NET and planning to release their source codes as fully open source. Are these projects "open-source" safe?

My doubts are:

VB.NET and C#.NET are using the .NET framework which is not open source.

The source codes depends on the compiler and the IDE, although there's 100% open source and compatible alternatives provided, it is confirmed to be buggy and incompatible with my project.

My projects were using the Jet 4.0 OLE DB, which is not open source either.

Files like .Designer.vb, Microsoft ResX Schema, the Solution file, or the .vbproj etc that are generated by the Visual Studio

Maybe I didn't have enough knowledge on open-source in the field where the codes released can be mixed with non open-source, or the codes can be released as open source even though developed and generated on a non open-source IDE.

Am I still eligible to hold the "open-source project" title? Can the codes be released as open-source? If so, what kind of open source license that are compatible based on the criteria above?

答:
Your code is your own.

Generated code is also your code. While Microsoft may have built the mechanism to output it, it is no more owned by them than a brochure your company prints is owned by HP. Using an IDE to write your code does not make the IDE developers own it.

Note, however, that your code is, more accurately, your employer's if you create it on the job.

On Licensing

Only a lawyer can truly explain exactly what is covered or not in a specific license, but the matters mentioned in your question aren't too difficult.

There are various kinds of licenses. Anything stricter than LGPL will not allow you to reference compiled assemblies that are not under the same (or compatible) license. Anything less, and you can. You may not be able to package proprietary software with your own, depending on the license, but you could still use it.

That should be everything you need to do the rest of the research into the license you want. Mostly, read the terms. They tell you exactly what's allowed.


答:
I think it's mostly for your protection, to avoid deleting a lot of files you don't mean to.  You potentially could have lots of directories and files directories under the top=level one, and not know especially when working from the command line, which is where this convention started back before there were GUIs.  Furthermore, I don't there is the concept of a Trask or Recycle bin available for files and folders deleted using the rm command.

As someone already pointed out, you can get around this behavior on Linux and Unix by providing a "-r" flag to the remove command, or even mask it by making rm a alias for "rm -r".

On GUI-based systems, it's much easier to see if you have folders or files underneath the one you are about to delete, plus you can recover files easier.

If you try to delete a folder on Windows, it asks first (like it does for any deletion), but then goes ahead and deletes the folder and all files and folders underneath without any further prompting.  If you make a mistake, it's pretty trivial to restore your folders/files from the Recycle bin.

Title: Why must directories be empty before being deleted?

Body:
As far as I know, deleting a non empty directory could work the same way as deleting an empty directory: by removing the pointer to the directory's metadata there would be no pointers to the items it contained, effectively deleting all its children recursively.

If that's true, then why must directories be empty before being deleted? Is it just a safeguard to prevent erasing many files at once, or a technical limitation of some (possibly ancient) file system?


问:
Why returning XML/JSON for API requests, can't we just directly process request and return the modified web page (HTML/CSS/JS)?
Let's say that a user requests for some piece of data. Usually the data is processed via a server and then returned in XML/JSON format. Im guessing another piece of processing happens to convert it into HTML/CSS so that it could be displayed on a browser.

Why do we bother returning XML/JSON for API requests? Why can't we just directly process whatever the user wants and just return the modified web page (HTML/CSS/JS)?

答:
Because you can do many more things with real data besides display it in a web page.

HTML is just a type of output that web browsers recognize, and it's not really useable as data in a meaningful way, because its metadata is about structure and form, not about the data itself.  It also contains all sorts of things that have nothing to do with data output, such as the <input> tag.

XML and JSON, on the other hand, can be used to create dynamic HTML web pages by simply binding to it.  In addition, you can create reports with it, you can analyze it with programs and algorithms, you can meaningfully put it in a database and process it further.

None of these things are really practical with HTML, since HTML is a markup language, not a data transport mechanism.


答:
HTML is used for presentation in browsers, but it adds a lot of display artifacts (like
, <input>,  tags, etc.)

XML and JSON aren't concerned with the display ... they can just send a plain representation of the data. How the user sees that data separate concern.

By separating the two, you can use the same JSON in a lot of different HTML pages.

Title: Why returning XML/JSON for API requests, can't we just directly process request and return the modified web page (HTML/CSS/JS)?

Body:
Let's say that a user requests for some piece of data. Usually the data is processed via a server and then returned in XML/JSON format. Im guessing another piece of processing happens to convert it into HTML/CSS so that it could be displayed on a browser.

Why do we bother returning XML/JSON for API requests? Why can't we just directly process whatever the user wants and just return the modified web page (HTML/CSS/JS)?

Body:
HTML is used for presentation in browsers, but it adds a lot of display artifacts (like <div>, <input>, <img> tags, etc.)

XML and JSON aren't concerned with the display ... they can just send a plain representation of the data. How the user sees that data separate concern.

By separating the two, you can use the same JSON in a lot of different HTML pages.


问:
How do I go about writing a programming language specification?
I really enjoy programming language design. Sometimes I think my language projects and their potential users would benefit from a comprehensive standards document. I've looked at many language standards, ranging from the very formal (C++) to the rather informal (ECMAScript), but I can't really get a handle on how I should break things down and organise such a document, even though I think I'm pretty good at technical writing in general.

Should I write it like a long tutorial, or more like a formal math paper? How do I keep it up to date if I'm developing it alongside a reference implementation? Should I just give up and treat the implementation and documentation as the de facto standard? Further, is there really any significant benefit to having a standard? Does requiring a standard mean that the language is needlessly complex?

答:
any specification should be terse and able to stand the test of time

this is why you see an abstraction like BNF used for many language standards...its terse and will still be understood long after many of our current tools have been left behind.

of course there's more to it than just a grammar. look at what others have done...perl6, scheme, C...they address issues that implementor also care about.


答:
In addition to the answers provided, there's also the fact that in an MVC or MVP front-end, you separate the data from the view. Plus it allows the backend to be useful for multiple projects.

You can provide the same data, and have, for example, one application that displays it as a graph, one that uses it in its logic (e.g. a stock market analyser that doesn't show the stock data but uses it to predict future prices), and one that just displays it directly to the user (perhaps prettified in some way) that can be used as an internal debugging tool for the developers.

If you had the server return HTML, only the last one would be practical. If it returned all kinds of different code depending on the client, then you're bleeding design into function, which should be avoided.

As a general rule, presentation should never be mixed with logic. Thats the philosophy of MVC. The server deals in data and logic. It receives raw data, processes raw data, and returns raw data. It should never care what that data will look like to the user. The client's job is to format and process the data in order to make it presentable to the user in whatever way is specified.


答:
There are many advantages to returning JSON or XML or returning HTML:

JSON (or XML) is typically more compact, so you get better performance throughout the entire system. This matters a lot on mobile.

Different browsers have different bugs. If you return JSON or XML, then you only need to handle the bugs in one place, rather than on every page that generates output.

Sometimes you have a web service where the output is for humans, other times its a remote function call. If you download JSON, then you only need a single implementation on the server to handle both web pages and API calls.

It is easier to partition the problem, which makes it easier to have a group of people working on it. So breaking down your problem this way makes it easier for a team to develop and deploy a system.

Likewise, it's easier to test the server when your tester doesn't need to figure out what to do with the HTML.

If the HTML is being generally locally, it's generally easier to style it with CSS.

I could probably come up with more.


问:
How to make my code decide which class to instantiate based on a parameter?
I have a system in which I will perform queries to a database. I want Query1, Query2 and Query3 to use the same methods in their way to the data source layer.

To do that I would like to make something similar to Strategy or Template Patterns, where I have a part of the code which is a default behavior for all queries (getting to the database layer, connection, executing the query and so on) and a variable part (building the query itself).

I think this idea is good and feasible. I would receive a parameter from the client specifying the query to be built, build it and run. The only question is: given this parameter, how can I decide which method to call to build the query? This is my current solution: (is this solution a pattern?)

```<code>public Query QueryFactory(string queryIdentifier){
   if(queryIdentifier == "query1")
      return BuildQuery1();
   else if(queryIdentifier == "query2")
      return BuildQuery2();
}
</code>```

It works, but I don't think this is "pretty enough", I would like something nicer. It would be perfect if it didn't require the developer to add a new if statement when he created a new query.
Is there any way to improve this if/else chain? And to make this decision automatic?

Edit:
The problem I want to solve is: I have queries that are going to be called against a database. I want to have the same flow so I don't have duplicated code for the queries that do not have any business logic applied to it (ex: get all users, get all students, and so on)

答:
As Steve Evers states, using an enumeration as a key and either a Class to instantiate (or an instance of Query pre-built) to return.  If you don't like the if/else pattern, I know Java has Map implementations, of which the EnumMap would be a good fit (where it optimizes the utilization of Enumerations as the key values in the map.

Then your code looks something like

```<code>public Query QueryFactory(QueryType type){
   return localMap.get(type);
}
</code>```

With the assumption that you define an enumeration named QueryType, and your localMap contains the appropriate Query instances for each type.

If you didn't want to pre-instantiate the queries, the code would use the map to store the Class, which would allow the object to be instantiated then and there

```<code>public Query QueryFactory(QueryType type){
   Class queryClass = localMap.get(type);
   return (Query) queryClass.newInstance();
}
</code>```

Again, this is all using Java as an example.  Just realized you didn't mention which language.  But it can be cleaned up the way it sounds like you would prefer.

Body:
As Steve Evers states, using an enumeration as a key and either a Class to instantiate (or an instance of Query pre-built) to return.  If you don't like the if/else pattern, I know Java has Map implementations, of which the EnumMap would be a good fit (where it optimizes the utilization of Enumerations as the key values in the map.

Then your code looks something like

public Query QueryFactory(QueryType type){
   return localMap.get(type);
}

With the assumption that you define an enumeration named QueryType, and your localMap contains the appropriate Query instances for each type.

If you didn't want to pre-instantiate the queries, the code would use the map to store the Class, which would allow the object to be instantiated then and there

public Query QueryFactory(QueryType type){
   Class queryClass = localMap.get(type);
   return (Query) queryClass.newInstance();
}

Again, this is all using Java as an example.  Just realized you didn't mention which language.  But it can be cleaned up the way it sounds like you would prefer.


答:
Lets start out with two simple classes:

```<code>package com.michaelt.so.supers;

public class Sup {
    int methodA(int a, int b) {
        return a + b;
    }
}
</code>```

and then

```<code>package com.michaelt.so.supers;

public class Sub extends Sup {
    @Override
    int methodA(int a, int b) {
        return super.methodA(a, b);
    }
}
</code>```

Compiling methodA and looking at the byte code one gets:

```<code>  methodA(II)I
   L0
    LINENUMBER 6 L0
    ALOAD 0
    ILOAD 1
    ILOAD 2
    INVOKESPECIAL com/michaelt/so/supers/Sup.methodA (II)I
    IRETURN
   L1
    LOCALVARIABLE this Lcom/michaelt/so/supers/Sub; L0 L1 0
    LOCALVARIABLE a I L0 L1 1
    LOCALVARIABLE b I L0 L1 2
    MAXSTACK = 3
    MAXLOCALS = 3
</code>```

And you can see right there with the invokespecial method it does the lookup against the Sup class methodA().

The invokespecial opcode has the following logic:

If C contains a declaration for an instance method with the same name and descriptor as the resolved method, then this method will be invoked. The lookup procedure terminates.

Otherwise, if C has a superclass, this same lookup procedure is performed recursively using the direct superclass of C. The method to be invoked is the result of the recursive invocation of this lookup procedure.

Otherwise, an AbstractMethodError is raised.

In this case, there is no instance method with the same name and descriptor int his class so the first bullet is not going to fire. The second bullet however will - there is a superclass and it invokes the super's methodA.

The compiler doesn't inline this and there is no copy of the source of Sup in the class.

However the story isn't finished yet.  This is just the compiled code.  Once the code hits the JVM, HotSpot can get involved.

Unfortunately, I don't know that much about it, so I will appeal to authority on this matter and go to Inlining in Java where it is said that HotSpot can inline methods (even non-final methods).

Going to the docs it is noted that if a particular method call becomes a hot spot instead of doing that lookup each time, this information can be inlined - effectively copying the code from Sup methodA() into Sub methodA().

This is done at runtime, in memory, based on how the application is behaving and what optimizations are necessary to speed up performance.

As stated in HotSpot Internals for OpenJDK "Methods are often inlined.  Static, private, final, and/or "special" invocations are easy to inline."

If you dig into the options for the JVM you will find an option of -XX:MaxInlineSize=35 (35 being the default) which is the maximum number of bytes that can be inlined.  I'll point out that this is why Java likes to have lots of little methods - because they can be easily inlined.  Those small methods become faster when they are called more because they can be inlined.  And while one can play with that number and make it bigger it may cause other optimizations to be less effective. (related SO question: HotSpot JIT inlining strategy which points out a number of other options to peek at the internals of inlining that HotSpot is doing).

So, no - the code is not inlined at compile time.  And, yes - the code could very well be inlined at runtime if performance optimizations warrant it.

And all of what I've write about HotSpot inlining only applies to HotSpot JVM distributed by Oracle.  If you look at wikipedia's list of Java virtual machines there are many more than just HotSpot and the way those JVMs handle inlining can be completely different than what I've described above. Apache Harmony, Dalvik, ART - things may work differently there.

Body:
Lets start out with two simple classes:

package com.michaelt.so.supers;

public class Sup {
    int methodA(int a, int b) {
        return a + b;
    }
}

and then

package com.michaelt.so.supers;

public class Sub extends Sup {
    @Override
    int methodA(int a, int b) {
        return super.methodA(a, b);
    }
}

Compiling methodA and looking at the byte code one gets:

  methodA(II)I
   L0
    LINENUMBER 6 L0
    ALOAD 0
    ILOAD 1
    ILOAD 2
    INVOKESPECIAL com/michaelt/so/supers/Sup.methodA (II)I
    IRETURN
   L1
    LOCALVARIABLE this Lcom/michaelt/so/supers/Sub; L0 L1 0
    LOCALVARIABLE a I L0 L1 1
    LOCALVARIABLE b I L0 L1 2
    MAXSTACK = 3
    MAXLOCALS = 3

And you can see right there with the invokespecial method it does the lookup against the Sup class methodA().

The invokespecial opcode has the following logic:

If C contains a declaration for an instance method with the same name and descriptor as the resolved method, then this method will be invoked. The lookup procedure terminates.

Otherwise, if C has a superclass, this same lookup procedure is performed recursively using the direct superclass of C. The method to be invoked is the result of the recursive invocation of this lookup procedure.

Otherwise, an AbstractMethodError is raised.

In this case, there is no instance method with the same name and descriptor int his class so the first bullet is not going to fire. The second bullet however will - there is a superclass and it invokes the super's methodA.

The compiler doesn't inline this and there is no copy of the source of Sup in the class.

However the story isn't finished yet.  This is just the compiled code.  Once the code hits the JVM, HotSpot can get involved.

Unfortunately, I don't know that much about it, so I will appeal to authority on this matter and go to Inlining in Java where it is said that HotSpot can inline methods (even non-final methods).

Going to the docs it is noted that if a particular method call becomes a hot spot instead of doing that lookup each time, this information can be inlined - effectively copying the code from Sup methodA() into Sub methodA().

This is done at runtime, in memory, based on how the application is behaving and what optimizations are necessary to speed up performance.

As stated in HotSpot Internals for OpenJDK "Methods are often inlined.  Static, private, final, and/or "special" invocations are easy to inline."

If you dig into the options for the JVM you will find an option of -XX:MaxInlineSize=35 (35 being the default) which is the maximum number of bytes that can be inlined.  I'll point out that this is why Java likes to have lots of little methods - because they can be easily inlined.  Those small methods become faster when they are called more because they can be inlined.  And while one can play with that number and make it bigger it may cause other optimizations to be less effective. (related SO question: HotSpot JIT inlining strategy which points out a number of other options to peek at the internals of inlining that HotSpot is doing).

So, no - the code is not inlined at compile time.  And, yes - the code could very well be inlined at runtime if performance optimizations warrant it.

And all of what I've write about HotSpot inlining only applies to HotSpot JVM distributed by Oracle.  If you look at wikipedia's list of Java virtual machines there are many more than just HotSpot and the way those JVMs handle inlining can be completely different than what I've described above. Apache Harmony, Dalvik, ART - things may work differently there.


问:
Are there any valid uses for the System.Collections.Specialized classes any more?
Are there any valid uses for the classes in the System.Collections.Specialized namespace any more or are they all superseded by the classes in the System.Collections.Generic, System.Collections.Concurrent and System.Collections.ObjectModel namespace now?

The classes in the namespace are:

```<code>HybridDictionary
ListDictionary
NameValueCollection
OrderedDictionary
StringCollection
StringDictionary
StringEnumerator
</code>```

Similarly, are there any real reasons why one might use the non-generic System.Collections namespace classes such as:

```<code>ArrayList
BitArray
Hashtable
Queue
SortedList
Stack
</code>```

答:
For new code there isn't any particular value -- by and large they are around for backwards compatibility concerns -- NameValueCollection is deeply embedded in significant parts of ASP.NET for example. Many venerable libraries are using the non-generic and specialized collections internally. Some of the specialized collections don't have a direct generic equivalent though one can usually get there without too much trouble.

From a maintenance overhead point of view they aren't maintenance hassles, once you've got a working ListDictionary implementation how much is it going to change with updates to the CLR?


问:
Dealing with co-workers who do not have a consistent coding style?
What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just looks ugly. We've got:

Mixture of different naming conventions and titles (underscore_style and camelCase and UpperCamel and CAPS all applied more or less at random to different variables in the same function)

Bizarre and inconsistent spacing, e.g. Functioncall  (arg1 ,arg2,arg3 );

Lots of misspelled words in comments and variable names

We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc."

How would you encourage this person to be more careful and consistent with these kinds of details?

答: How hard is it to follow style conventions? I understand the spelling errors but the rest is an indicator of sloppy thinking and coding. Tell the person that they need to be more consistent when it comes to production code because they are not the only ones that will be looking at it. It's just plain rude, selfish, and inconsiderate to write production code in an inconsistent style.</p>


问:
Static classes and/or singletons -- How many does it take to become a code smell?
In my projects I use quite a lot of static classes. These are usually classes that naturally seem to fit into a single-instance type of thing. Many times I use static classes and recently I've started using some singletons.

How many of these does it take to become a code smell? For instance, in my recent project which has a lot of static classes is an Authentication library for ASP.Net.

I use a static class for a helper class that fixes ASP.Net error codes so it can be used like

```<code>CustomErrorsFixer.Fix(Context);
</code>```

Or my authentication class itself is a static class

```<code>//in global.asax's begin_application
Authentication.SomeState="blah";
Authentication.SomeOption=true;
//etc

//in global.asax's begin_request
Authentication.Authenticate();
</code>```

When are static or singleton classes bad to use? Am I doing it wrong, or am I just in a project that by definition has very little per-instance state associated with it?

The only per-instance state I have is stored in HttpContext.Current.Items like so:

```<code>    /// <summary>
    /// The current user logged in for the HTTP request. If there is not a user logged in, this will be null.
    /// </summary>
    public static UserData CurrentUser{
        get{
            return HttpContext.Current.Items["fscauth_currentuser"] as UserData; //use HttpContext.Current as a little place to persist static data for this request
        }
        private set{
            HttpContext.Current.Items["fscauth_currentuser"]=value;
        }
    }
</code>```

答:
Static classes almost always a bad smell because they make unit testing hard. You can't make mock or make test versions of a static class. If any of your code is a client of a static class, then there is tight coupling between the two classes.

Instead of static classes, you should be using a normal object but manage it with an Inversion of Control container.