答:
An implicit requirement might be

You shall not hit my car when I am driving

Of course this goes without saying universally but is it a requirement at all?  I would argue that it is not.  Since the nature of this specific statement is a universal truth, and the fact that in the skillset of driving this is expected as a requirement of a good driver.

The language certainly sounds like it could be a requirement but it is not a requirement in my opinion.  Any programmer or software developer should be conscious of security issues in their code just as a driver should naturally avoid accidents.

Programmers still from time to time write insecure code that puts users credit card information at risk, just as drivers occasionally get into accidents.  I view security flaws as an "accident" or "incompetence" or both.  Their are few hard and fast standards when it comes to software development and credit card security is one where there should be no debate in how user stories and features involving credit cards should be approached regardless of language platform, framework and design.

In summation, development of proper security with credit cards should be factored into a developer's estimates as an understood and known anticipation of technical work required to eventually achieve the user story or requirement.


问:
How to represent (enum) types in a public API
I am working on a simple API that I want to use for my own client, and to open to the public in the future.
I have "Item" objects which can have different "types". The type is a C "typedef enum", for the moment I have :

```<code>typedef enum {
    ItemTypeBool,
    ItemTypeNumber,
    ItemTypeDate,
} ItemType;
</code>```

(I may add some in the future)

I am wondering if I should rather transfer it as integers or as defined "strings". The JSON would be :

For integers :

```<code>{
  "name": "The name",
  "type": 0,
   ...
}
</code>```

For strings :

```<code>{
  "name": "The name"
  "type": "boolean"
   ...
}
</code>```

I'm wondering if there's a best practice for this. Keeping the integer would slightly simplify the code, and reduce the bandwidth, but strings would be easier for developers to remember. I remember I worked on a project, and I had to remember 1=image, 2=audio, 3=html,... which doesn't make any real sense.

So I'm asking you, if you know any other aspect I should consider.

答:
Best Practice depends on who is consuming your API.  If you are trying to make life easy for the consumer, you should provide sample code in C, JAVA, iOS, python, ruby that can consume your api.  In these wrappers you can include the enum, use an int in json, and then just parse your json into an object with the enum already set, and return this object to the users code.

Another thing you could do is provide both. for instance:

```<code>{
  "name": "The name",
  "typeId": 0,
  "type": "ItemTypeBool"
   ...
}
</code>```

Or you can use type, and typeStr depending on what looks best for your api.

And then clearly state in your documentation that these are redundant and it's up to the developer to choose which is best for their application.

Look at the json here: https://dev.twitter.com/docs/api/1/get/search
Twitter has an example of providing redundant data (id and id_str) , but this because some json clients cant parse long ints from a "number" in json and require a string to avoid losing digits

ContentLicense: CC BY-SA 3.0

Body:
Best Practice depends on who is consuming your API.  If you are trying to make life easy for the consumer, you should provide sample code in C, JAVA, iOS, python, ruby that can consume your api.  In these wrappers you can include the enum, use an int in json, and then just parse your json into an object with the enum already set, and return this object to the users code.

Another thing you could do is provide both. for instance:

{
  "name": "The name",
  "typeId": 0,
  "type": "ItemTypeBool"
   ...
}

Or you can use type, and typeStr depending on what looks best for your api.

And then clearly state in your documentation that these are redundant and it's up to the developer to choose which is best for their application.

Look at the json here: https://dev.twitter.com/docs/api/1/get/search
Twitter has an example of providing redundant data (id and id_str) , but this because some json clients cant parse long ints from a "number" in json and require a string to avoid losing digits


问:
Bucketing model by time
I have a model which has timestamped entities. Now I want to do bucketing - "buckets" of entities which can be reasoned about a single entity. Also I want to be able to access related entities from a bucket and get a bucket of those entities.

My main concerns are an implementation of bucketing itself and architecture of code behind this.

Should I create a separate model for bucketed data, or
should I implement tools to work with the existing model?

As I already have a metamodel with all the subclasses and relations
I'd like to be able to easily add bucketing on top.
I have been thinking about subclassing all the
entity classes to create a bucket-entity class which would
extend their common bucket functionality with traits.

答:
It seems like the buckets are very simple to calculate based on the timestamp divided by a number.  For instance timestamp/60 this would give you buckets of 1 minute long.

If you don't need to permanently store buckets, I would write a function that iterates through all the events and returns a hash of lists.  Where hash[23100517] returns a list of all events in that bucket.  Then you can just work with this hash.  Also finding the bucket of a new entity is very simple.  You could even write a member class that was like:

```<code>model.get_time_bucket(seconds)
{
  return floor(self.timestamp / seconds);
}
</code>```

and then call this with 60 or whatever your bucket size is.

Title: Bucketing model by time

Body:
It seems like the buckets are very simple to calculate based on the timestamp divided by a number.  For instance timestamp/60 this would give you buckets of 1 minute long.

If you don't need to permanently store buckets, I would write a function that iterates through all the events and returns a hash of lists.  Where hash[23100517] returns a list of all events in that bucket.  Then you can just work with this hash.  Also finding the bucket of a new entity is very simple.  You could even write a member class that was like:

model.get_time_bucket(seconds)
{
  return floor(self.timestamp / seconds);
}

and then call this with 60 or whatever your bucket size is.


答:
Provide the strings. Numbers are meaningless. You don't use them in your own code, right (you're wrapping enum values around, that are basically strings) - why punish the user with having to use these numbers?

The only pro if you do expose the numbers - easier for you to parse these. But hey, who cares about you. Take care of the API clients.

If you provide the strings - easier for the clients; won't ever have to say things like "4 had been deprecated in favor of 17"; slightly harder parsing on your behalf, but that's fine.

Do not provide both: as a user, i'm left to wonder

which one do I use? Both? [on to reading docs]

why are there two ways to say the same thing? are they subtly different? [on to reading docs]

what if I specify both and there's a mismatch? will it complain? will one take precedence? which one? [on to reading docs]

As you can see, you're having me read a lot of docs for no reason.

Title: How to represent (enum) types in a public API

Body:
I am working on a simple API that I want to use for my own client, and to open to the public in the future.
I have "Item" objects which can have different "types". The type is a C "typedef enum", for the moment I have :

```<code>typedef enum {
    ItemTypeBool,
    ItemTypeNumber,
    ItemTypeDate,
} ItemType;
</code>```

(I may add some in the future)

I am wondering if I should rather transfer it as integers or as defined "strings". The JSON would be :

For integers :

```<code>{
  "name": "The name",
  "type": 0,
   ...
}
</code>```

For strings :

```<code>{
  "name": "The name"
  "type": "boolean"
   ...
}
</code>```

I'm wondering if there's a best practice for this. Keeping the integer would slightly simplify the code, and reduce the bandwidth, but strings would be easier for developers to remember. I remember I worked on a project, and I had to remember 1=image, 2=audio, 3=html,... which doesn't make any real sense.

So I'm asking you, if you know any other aspect I should consider.


问:
Best place for a factory interface
What's the best place for a factory interface to create an instance of another interface?

OptionA: a separate class

```<code>public interface InterAFactory {
    InterA createInterA();
}

public interface InterA {
    void doStuff();
}
</code>```

OptionB: a subclass

```<code>public interface InterA {
    public interface Factory {
        InterA createInterA();
    }

    void doStuff();
}
</code>```

I notice that guava has tended to use B for the immutable collections, but that's for builders, which are slightly different to factories. I also tend towards optionB, as  it reduces the number of top-level classes in the package, and it strongly associates the factory with the thing it creates. However, implementations will not be bound or affected by this, and it will make implementations of the factory slightly more verbose. Thoughts?

答:
Guava builders are kind of different. ImmutableList.Builder only exists because ImmutableList doesn't want to open up its constructor. So the only way to create an ImmutableList is via the Builder, which is a very-closely associated inner class, which makes sense.

In your case, I think it depends on the nature of the objects we're talking about. Consider

```<code>interface Vehicle { interface Factory { createVehicle(); }}

class Bmw implements Vehicle {
  // complex code
}

class BmwFactory implements Vehicle.Factory {
  // more complex code
}

class Fiat implements Vehicle {
  public Fiat() { }
  // no need for a factory at all here, but there's still a guilty feeling
  // that inner interface had better been implemented...
}
</code>```

Which I guess is fine... You just ended up using Vehicle. as pretty much a package name. Personally, I'd go with option a)

Title: Best place for a factory interface

Body:
Guava builders are kind of different. ImmutableList.Builder only exists because ImmutableList doesn't want to open up its constructor. So the only way to create an ImmutableList is via the Builder, which is a very-closely associated inner class, which makes sense.

In your case, I think it depends on the nature of the objects we're talking about. Consider

interface Vehicle { interface Factory { createVehicle(); }}

class Bmw implements Vehicle {
  // complex code
}

class BmwFactory implements Vehicle.Factory {
  // more complex code
}

class Fiat implements Vehicle {
  public Fiat() { }
  // no need for a factory at all here, but there's still a guilty feeling
  // that inner interface had better been implemented...
}

Which I guess is fine... You just ended up using Vehicle. as pretty much a package name. Personally, I'd go with option a)


问:
Verbose or concise logging
I was wondering how much data should be logged.

I know this deeply depends on multiple factors. But it can still be hard to find the golden middle way.

Lets say I have an application where people can create and administrate a user. Furthermore they are able to create/read/update/delete other objects within the application.

If the application has many users it can be an issue if too much data is logged. If all DTO classes and their contents is logged everytime a user or any other object is edited/delete/etc. the logs could get extremely large. But if you only log a little line saying "User 'blabla' was created/edited/etc." you might have trouble debugging or recreating bugs as you dont have the exact state of the objects when the error happened.

Where I currently work we rarely log data, but instead log error messages and stack traces, but I've also previously worked at places where they logged every single bit of information that can be useful in a future debugging scenario.

I was wondering what other people do and think about this? How much data do you log for future debugging information? - is there such a thing as a "correct" amount of data logged?

答:
I'm assuming that you are using some type of third-party logging utility that supports multiple logging levels that can be changed without recompiling source code (like Log4J or SLF4J). If you're not, do yourself a favor and implement one... yesterday.

A good logging scheme should allow you to diagnose the root cause of any problem without recompiling code. Obviously, just logging the stack trace isn't going to give you much context. On the other hand, logging every logical step is going to kill application performance and eat up a ton of disk space. The trick is to default your logs to the minimal amount of detail, but allow yourself the ability to turn up the logging level in the event of a problem.

For normal processing the minimal amount of logging necessary is probably best to log at the INFO level. Think of this as a you would a Table of Contents in a book: it's not going to tell you the story, per se, but it will give you an idea on where to look to find what you want. Log your high-level process steps, services, or classes with generic informative messages like "Starting validation process" or "Retrieving query data", but use this message level sparingly (or not at all) in lower-level services, classes, or functions to avoid clutter.

I use DEBUG messages more like breadcrumbs. If the INFO level has done it's job, then I should have a pretty good idea what process broke down. From there, I should be able to turn on DEBUG level and figure out what class the offending action took place. To ensure this, I make sure I log a DEBUG level message at every entry and exit point to every method in every class. On entry, I log the name of the method, the names of the formal parameters, and the values passed in for each of those parameters. On exit I again log the method name, and provide the name and value of each variable returned or state that the method returns nothing.

If even more detail is needed, TRACE level can be turned on for the offending class. Trace level logging should allow you to follow every logical step in the class, almost as if you are stepping through the code using a debugger. Keep in mind that most live applications you will not have the luxury of using a debugger, so the TRACE level is often the closest you can get to that level of feedback. Of course, this is also the most tedious and, in my experience, most often overlooked level of logging. In TRACE logging, try to at least include critical decision points in the method (all paths in conditional statements, pointers in loops, etc) to allow you to follow the path the application took towards its demise.

Back to your example, a DTO class is what I would consider pretty low-level code. You probably don't need any INFO level logging here, but DEBUG on the entry/exit points should be added along with TRACE logging for any key processing or decision making events in the DTO. Then, make sure you turn the logging level on the DTOs to INFO so that these events normally aren't logged.

A couple of other hints:
- Default logging to INFO level
- Make sure to use a rolling appender to log your output in multiple files rather than one huge file.
- Output, at minimum, TIMESTAMP, CLASS, THREAD, LINE NUMBER your log appenders
- When adding DEBUG messages logging variable values, keep in mind that the to_string() method of many classes is not overridden so you may not get useful output. Try using the ReflectionToStringBuilder.toString(Object object) static method.

Title: Verbose or concise logging


问:
State design pattern: best implementation for my case?
Me and a mate have a discussion about what would be the best way to implement the pattern state for managing several screens for an application we are developing.

We have a ScreenManager (I guess the Context class according some books) which looks like this (some irrelevant code has been removed to ease understanding) :

```<code>public class ScreenManager : DrawableGameComponent
{

    #region Fields

    List<GameScreen> screens = new List<GameScreen> ();
    List<GameScreen> screensToUpdate = new List<GameScreen> ();

    InputState input = new InputState ();

    #endregion

    /// <summary>
    /// Constructs a new screen manager component.
    /// </summary>
    public ScreenManager (Game game)
        : base(game)
    {
        content = new ContentManager (game.Services, "Content");

        graphicsDeviceService = (IGraphicsDeviceService)game.Services.GetService (
                                                    typeof(IGraphicsDeviceService));

        if (graphicsDeviceService == null)
            throw new InvalidOperationException ("No graphics device service.");
    }

    public override void Update (GameTime gameTime)
    {
        // Read the keyboard and mouse.
        input.Update ();

        // Make a copy of the master screen list, to avoid confusion if
        // the process of updating one screen adds or removes others
        // (or it happens on another thread)
        screensToUpdate.Clear ();

        foreach (GameScreen screen in screens)
            screensToUpdate.Add (screen);

        while (screensToUpdate.Count > 0) {
            // Pop the topmost screen off the waiting list.
            GameScreen screen = screensToUpdate [screensToUpdate.Count - 1];

            screensToUpdate.RemoveAt (screensToUpdate.Count - 1);

            // Update the screen.
            screen.Update (gameTime);
            screen.HandleInput (input);
        }
    }

    public void AddScreen (GameScreen screen)
    {
        screen.ScreenManager = this;

        if ((graphicsDeviceService != null) &&
            (graphicsDeviceService.GraphicsDevice != null)) {
            screen.LoadContent ();
        }

        screens.Add (screen);
    }

    public void RemoveScreen (GameScreen screen)
    {
        screens.Remove (screen);
        screensToUpdate.Remove (screen);
    }
}
</code>```

As you can see, the screenmanager has a list of GameScreens which are updated every time the Update method is called.

Then here we have a couple of screens + base Screen class. At the base class, we create a coupling between GameScreen and ScreenManager, while there also exist a coupling between ScreenManager and GameScreen:

```<code>public abstract class GameScreen
{
    ScreenManager screenManager;

    public ScreenManager ScreenManager {
        get { return screenManager; }
        internal set { screenManager = value; }
    }

    public virtual void HandleInput (InputState input)
    {
    }

    public virtual void LoadContent ()
    {
    }

    public virtual void UnloadContent ()
    {
    }

    public virtual void Update (GameTime gameTime)
    {
    }
}

public class TitleScreen : GameScreen
{
    public Texture2D titleScreen;

    public TitleScreen ()
    {
    }

    public override void HandleInput (InputState input)
    {
        if (input.MenuSelect) {
            ScreenManager.AddScreen (new PlayingScreen ());
    }

}

public class PlayingScreen : GameScreen
{
//...... Irrelevant implementation details for my question
}
</code>```

As you can see there, TitleScreen knows about PlayingScreen, creates it and adds it to ScreenManager (creating a dependency between TitleScreen and PlayingScreen). Although this kind of implementation has been seen in books (as far as I've read), my companion proposes me another kind of implementation: He proposes to create an Observer approach, replacing in TitleScreen the whole PlayingScreen management with an event, which would then be suscribed by the ScreenManager, and then the ScreenManager would orchestrate all the management of screens.

With this approach, he says TitleScreen could be reused in other applications and decouple screens among them, but create a big ScreenManager class who would be coupled with everyone.

I'm not sure whether the State approach or the Observer approach is better for my specific case. Which would be the best implementation?

Thank you

答:
I agree with Hans that observer can make the maintenance more nightmare. What I can suggest is separating the concern (delegating the responsibility) of opening playing screen into another class, to follow Single Responsibility Principle.

Currently, your title class has at least 2 responsibility, that is:

rendering the title page and menus

add screen related to menu selected

(handle input such as arrow keys, etc)?

The add screen responsibility can be delegated to another class. Let's say it TitleAddScreenHandler.

```<code>public class TitleAddScreenHandler{
    public TitleAddScreenHandler(ScreenManager screenManager){
        // property assignments
    }
    private ScreenManager screenManager;

    public void AddScreen(InputState input){
        if (input.MenuSelect) {
            screenManager.AddScreen (new PlayingScreen ());
        }
    }
}
</code>```

Then in your TitleScreen, you can has one instance of TitleAddScreenHandler or injected in constructor. It will limit the dependency only to one class.

OwnerDisplayName: David Jiménez Martínez

Body:
I agree with Hans that observer can make the maintenance more nightmare. What I can suggest is separating the concern (delegating the responsibility) of opening playing screen into another class, to follow Single Responsibility Principle.

Currently, your title class has at least 2 responsibility, that is:

rendering the title page and menus

add screen related to menu selected

(handle input such as arrow keys, etc)?

The add screen responsibility can be delegated to another class. Let's say it TitleAddScreenHandler.

public class TitleAddScreenHandler{
    public TitleAddScreenHandler(ScreenManager screenManager){
        // property assignments
    }
    private ScreenManager screenManager;

    public void AddScreen(InputState input){
        if (input.MenuSelect) {
            screenManager.AddScreen (new PlayingScreen ());
        }
    }
}

Then in your TitleScreen, you can has one instance of TitleAddScreenHandler or injected in constructor. It will limit the dependency only to one class.

OwnerDisplayName: Fendy


问:
Why shouldn't I use the repository pattern with Entity Framework?
During a job interview, I was asked to explain why the repository pattern isn't a good pattern to work with ORMs like Entity Framework. Why is this the case?</p>

答:
The single best reason to not use the repository pattern with Entity Framework? Entity Framework already implements a repository pattern. DbContext is your UoW (Unit of Work) and each DbSet is the repository. Implementing another layer on top of this is not only redundant, but makes maintenance harder.

People follow patterns without realizing the purpose of the pattern. In the case of the repository pattern, the purpose is to abstract away the low-level database querying logic. In the old days of actually writing SQL statements in your code, the repository pattern was a way to move that SQL out of individual methods scattered throughout your code base and localize it in one place. Having an ORM like Entity Framework, NHibernate, etc. is a replacement for this code abstraction, and as such, negates the need for the pattern.

However, it's not a bad idea to create an abstraction on top of your ORM, just not anything as complex as UoW/repostitory. I'd go with a service pattern, where you construct an API that your application can use without knowing or caring whether the data is coming from Entity Framework, NHibernate, or a Web API. This is much simpler, as you merely add methods to your service class to return the data your application needs. If you were writing a To-do app, for example, you might have a service call to return items that are due this week and have not been completed yet. All your app knows is that if it wants this information, it calls that method. Inside that method and in your service in general, you interact with Entity Framework or whatever else you're using. Then, if you later decide to switch ORMs or pull the info from a Web API, you only have to change the service and the rest of your code goes along happily, none the wiser.

It may sound like that's a potential argument for using the repository pattern, but the key difference here is that a service is a thinner layer and is geared towards returning fully-baked data, rather than something that you continue to query into, like with a repository.

OwnerDisplayName: StringBuilder


问:
Is securing the credit card data is considered a requirement from the customer
I'm taking an Introduction to Agile Software Development course, The instructor was discussing an example about online store and asked us to write the User Stories and the Conditions of satisfactions and one story was As a user I can commit for marketing card that was selected previously in order to buy my goods, the conditions of satisfactions in this case contained some conditions in addition to The system must secure the Credit Card data across the internet connection using https

I disagreed with that and said this is a thing that must be done, not just in case the user asked me to protect it, and it is a fatal threat like or more important than SQl Injections and this is a non-functional requirement at the technical level and if the user mention it or didn't this must be taken in our development, some project managers in the course showed their disagreement and said this is a time wast on features that the user didn't ask for!, the instructor didn't give my comment any attention and didn't reply to me.

I really think I'm true and not convinced, but all of those trained people disagreed with me[I'm new in the software engineering field but used always to work as a developer], so I'm asking you about this.

答:
I think you are correct.

The Credit Card issuer/authorizer is an Actor in this senario. You absolutly need to secure/encrypt the customers data or you will be cut off from the payments system and stuck with paypal and postal orders.

In a similar situation you do not deduct sales tax because the user and the customer request it, but because the State absolutely requires you to do so. In this case the State tax collection agency should be explicitly defined as an Actor/Stakeholder with there own set of requirements and conditions.


问:
What do programmers "micro-optimize" for today?
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.

答:
I think I've wasted weeks worth of time fiddling with Java exception handlers.

This is a lot of work for code that fails two or three times per year. Should this be a warning or an info? Error or fatal? Is it really fatal is the process will be re-spawned in five minutes? Is it really a warning if everything is still in default state?

Lots of navel gazing and discussion about the nature of an IO error. If you can't read a file over the network, is it a file error or a network error? And so on.

At one point I replaced all the concat strings with String.format so the yearly file error doesn't result in extra objects in the heap. That was a waste.

ContentLicense: CC BY-SA 2.5


问:
Is logging hours for software work a good idea?
An employer I'm interviewing for does this, I have never heard of anyone doing it before and honestly I don't like the idea of being micromanaged. How does the community feel about this? </p>

答:
It is very common in medium+ sized companies. Almost every company I have worked with does this. There are a multitude of reasons:

billing external clients (self explanatory)

billing internal clients. In some companies (like the one I'm in now), IT has to earn its own budget. It does this by cross-charging other divisions.

cost tracking. It helps to know how much a product is costing.

tax reasons. In Australia, a company can claim an R&D tax break based upon the money spent and the nature of the work. Obliviously, the tax department wont take your word for it.

because other (non-IT) divisions have to do it, it may just be part of the way the company works.

Telling the company where your effort (and their dollars) has gone hardly counts are micro-management.


答: My company does it. We have time reporting for every employee from the receptionist (who also does job-specific project work) to everyone on the shop floor to the software and engineering departments. I dislike the tedium required for keeping accurate records, but I understand and support why it has to be done. If you wish to run a profitable company you have to have some reference for how much it costs you to do business. If you quote a job at $10K with a $100/hr burden and it takes you 200 hours to complete the job, then you are going to go out of business pretty darn quick.</p>

Title: Is logging hours for software work a good idea?

Body: An employer I'm interviewing for does this, I have never heard of anyone doing it before and honestly I don't like the idea of being micromanaged. How does the community feel about this? </p>


答:
I actually log all my work even though I'm not required, but not on an hourly basis.

I used to log hours in a response to justifying time spent on various proojects, there is no need for that now and presently I only log the tasks that I have completed or worked on throughout the day. This just helps me to keep track of when I worked on one of my hundreds of tasks and mean I can easily justify project time when pulled onto another project or give status reports to my manager.

In my day-to-day work logging the hours is only necessary when I work on a project that requires billing and is one of the reasons dave gives.


答:
Even if you're not required to do it, it's a good idea to do it anyway. Not down to the minute but down to the hour is good. Just write down at the end of every week roughly what you spent your time on. (I just look at my SVN logs and sent emails and it reminds me what I did.)

Why? In four months time someone is going to say to you "Who are you and what have you been spending your time on?". If your boss doesn't want to know then I would put a bet that your bosses boss will want to know. If your boss doesn't know what you're spending your time on, it also couldn't hurt to remind him/her occasionally.


问:
How should I go about bringing this code under test?
I'm working on an open-source test framework.

90% of my codebase has good test coverage. My main problem area is the command-line entry point. This module began life as a very short script for calling into the domain model (see the call to _run_impl()) and exit with code 1 if the test run failed.

It didn't feel necessary to test that script at the time that I wrote it, but as the project has sprouted features, a number of small changes to the logic in this file have led it to become quite long:

```<code>import argparse
import os
import sys
from . import _run_impl  # a function, in __init__.py, which calls into the domain model
from . import reporting  # a sub-package concerned with writing output to the console

import colorama; colorama.init()

def cmd():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--no-capture',
        action='store_false',
        dest='capture',
        default=True,
        help="Disable capturing of stdout during tests.")
    parser.add_argument('-v', '--verbose',
        action='store_true',
        dest='verbose',
        default=False,
        help="Enable verbose progress reporting.")
    parser.add_argument('--teamcity',
        action='store_true',
        dest='teamcity',
        default=False,
        help="Enable teamcity test reporting.")
    parser.add_argument('--no-random',
        action='store_false',
        dest='shuffle',
        default=True,
        help="Disable test order randomisation.")
    parser.add_argument('path',
        action='store',
        nargs='?',
        default=os.getcwd(),
        help="Path to the test file or directory to run. (default current directory)")
    args = parser.parse_args()

    if args.teamcity or "TEAMCITY_VERSION" in os.environ:
        reporters = (reporting.teamcity.TeamCityReporter(sys.stdout),)
    elif args.verbose:
        reporters = (reporting.cli.ColouredReporter(sys.stdout),)
    elif args.capture:
        reporters = (
            reporting.cli.DotsReporter(sys.stdout),
            type("ColouredCapturingReporter", (reporting.cli.ColouredReporter, reporting.cli.StdOutCapturingReporter), {})(sys.stdout),
            reporting.cli.TimedReporter(sys.stdout)
        )
    else:
        reporters = (
            reporting.cli.DotsReporter(sys.stdout),
            type("ColouredCapturingReporter", (reporting.cli.ColouredReporter, reporting.cli.SummarisingReporter), {})(sys.stdout),
            reporting.cli.TimedReporter(sys.stdout)
        )

    reporter = reporting.shared.ReporterManager(*reporters)

    _run_impl(os.path.realpath(args.path), reporter, args.shuffle)

    if reporter.failed:
        sys.exit(1)
    sys.exit(0)

if __name__ == "__main__":
    cmd()
</code>```

I know that this code has bugs (for example, it should be possible to capture stdout from tests when running in verbose mode), and I've lost confidence in my ability to change this module without breaking something. So I want to write some tests for it - but I only really have experience with test-first development, so I don't really know where to start.

Should the tests be at the unit or integration level? Should I mock the ArgumentParser? Should I mock the reporting module? Should I mock _run_impl? Should I try to bring the whole module under test at the start, or just add tests as I add features? Do I need to refactor to make this method more testable?

Addendum: I think a part of my confusion is due to the fact that this is a relatively thin layer on top of the business logic - it's just there to make it possible to kick-off the test runner from the command line. So I'm feeling confused about what constitutes the service boundary here - in particular, what I should and shouldn't mock.

答:
Testing is usually hard when several ideas are coupled together in the same code; it means testing a lot of things at the same time.  Breaking code apart into smaller chunks usually solves that problem.

In that vein, I would rewrite this slightly by extracting some methods:

```<code>def cmd(arguments):
    args = parse(arguments)
    reporter = create_reporter(args)

    _run_impl(os.path.realpath(args.path), reporter, args.shuffle)

   return not reporter.failed

if __name__ == "__main__":
   if cmd(sys.argv)
       sys.exit(0)
   sys.exit(1)
</code>```

This has several benefits:

The code in cmd is not coupled to sys.argv and sys.exit(), which are both hard to deal with in a unit testing context

cmd is now simple to test if you mock out parse, create_reporter, and _run_impl

parse, create_reporter are simple and isolated enough to test easily on their own.

Python is not my primary language, so I can't recall if you'll need to create some classes to enable clean mocking, but if so do it.  It's just a little bit of typing for a lot of value.

OwnerDisplayName: Benjamin Hodgson

Body:
Testing is usually hard when several ideas are coupled together in the same code; it means testing a lot of things at the same time.  Breaking code apart into smaller chunks usually solves that problem.

In that vein, I would rewrite this slightly by extracting some methods:

def cmd(arguments):
    args = parse(arguments)
    reporter = create_reporter(args)

    _run_impl(os.path.realpath(args.path), reporter, args.shuffle)

   return not reporter.failed

if __name__ == "__main__":
   if cmd(sys.argv)
       sys.exit(0)
   sys.exit(1)

This has several benefits:

The code in cmd is not coupled to sys.argv and sys.exit(), which are both hard to deal with in a unit testing context

cmd is now simple to test if you mock out parse, create_reporter, and _run_impl

parse, create_reporter are simple and isolated enough to test easily on their own.

Python is not my primary language, so I can't recall if you'll need to create some classes to enable clean mocking, but if so do it.  It's just a little bit of typing for a lot of value.


问:
We have a custom program that generates all the stored procs and classes for the Data Tier. Where will I put the generated classes?
This is more of an architectural question regarding MVC and Data Access:

We have a custom program that generates all the stored procs and classes for the Data Tier from the MS SQL database. It's pretty nice as it generates a base class with the basic CRUD operations which includes ForeignKey reads. It also generates the plural version of the class to return the collections of objects.

For the next phase of our application we are planning on using MVC but we were hoping to continue using this great tool. Where will I put the generated classes in my new MVC application? I have seen people create an Infrastructure folder for their data access logic.

Is it a good idea to continue using this tool or should we be converting to the Entity Framework?

Also if the DAL is returning my objects and lists of objects what will I put in my Model layer?

答:
Tool that you are using generates entities. Entity is a domain model that gets persisted. We have a similar tool and it resides in the entity framework project as it uses T4 templates. It needs to be part of entity framework project because it requires EDMX to run T4 templates.

Once the tool generates entities, we copy them into the domain layer project. I would never put entities into the DAL layer - it doesn't make sense in a domain driven design. How you wire things up is entirely up to you. If your entities are coupled to the data access framework (such as LINQ-to-SQL in old days), then you have a problem as all of a sudden your data access logic is leaking into your domain layer.

Once the tool generates stored procedures, tables and supporting components we move them into the ADO project. We are happy doing it manually. When the need comes, we might automate it.

With regards to your MVC application, domain models, and especially entities shouldn't be leaked into presentation layer. MVC should be working with view models. In some cases your view model will be an identical copy of a domain model, but don't be fooled - it might not always be the case.

Normally you would query the data through ADO or entity framework. You would then take the result and pass it to your presentation layer. When you do this you might want to convert result into DTO or pass the domain model directly (I normally avoid second option). Then in your presentation layer you take the DTO or domain model and convert it to the view model. Finally, M in MVC normally means view model, as opposed to domain model.


问:
How to refactor a Java singleton to Clojure?
I'm writing a simple game in Java and I want to learn Clojure, so I've decided to refactor my current Java code to Clojure. The problem is that I've coded so much in object-oriented languages that I cannot see how to do it functionally.

To be concrete, I have a Map<String, Country> inside a singleton class that can be accessed from anywhere to get a Country instance, update it, and put it back into the map. I implemented this the same way in Clojure. For example, to update a country:

```<code>(def countries (do-get-countries))

(defn update-country
    [country]
    (def countries (assoc countries (get country :name) country)))
</code>```

Also I've created a defrecord Country, but I actually modify these records like

```<code>(assoc country :name "New name")
</code>```

These two examples don't look idiomatic in my opinion. Is this actually the correct way to do it in Clojure? If not how would it be more idiomatic?

Thanks in advance!

答:
Here's a step-by-step guide to getting from your Java example to some decent Clojure:

recognize that your singleton is just global, mutable state.  The singleton may work fine but it's not necessary.  So we've moved from Java: singleton  ->  Java: global, mutable state

refactor your Java example to use local mutable state instead of global mutable state, by passing the map to the methods that modify it.  So let's move from Java: global, mutable state  ->  Java: local, mutable state

*now, instead of destructively updating the map every time, find/write a Java library (such as the one the Clojure implementation uses) that does not mutate when adding/removing key/value pairs to/from maps.  Remember to return values that have been "updated", otherwise, the changes won't be visible to other code.  So we've just moved from Java: local, mutable state  ->  Java: local, immutable state

at this point, you have an FP solution, but it's coded in Java.  Your initial Clojure solution could end up as a nearly 1:1 translation, but as you learn more Clojure you'll figure out how to take advantage of its strengths and improve and shorten the code.  Plus, you might learn some cool patterns for dealing with "mutable" state in a purely functional way.  So it's up to you to make the leap from Java: local, immutable state  ->  Clojure: local, immutable state

From point 3 above: one of the major points of FP is "same thing in, same thing out".  Mutable state totally destroys this concept, and with it, the advantages of pure code.  Clojure doesn't force you to be pure, but it certainly makes it easy to do so.  So if you want to learn how to write good Clojure code, you'll have to learn how to avoid (most) mutable state at some point.


问:
Why the Scala fascination with flatmap? (This doesn't seem to be the same for mapcat in the Clojure world)
In the Scala community - there is an apparent fascination with the FlatMap function.

Now I understand that FlatMap is significant because it is used for the bind part of a Monad. (and that the Clojure community hasn't dived into Monads yet, with some wonderful exceptions).

Now in the Clojure Community - there is no corresponding cultural idiom, eg "MapCat that S***".

My theory on the difference between the two communities and the reason for this difference is that the concurrency primitives in Clojure lend it towards solving problems on a single machine, in a single instance. (Ie Clojure is good at concurrency). Whereas in the Scala World, with the rise of the Actor model, Scala is a little more focused on solving multi-machine problems. This focus on multi-machine problems has a higher focus on breaking problems down into their parts, and a greater focus on what can be broken down and Scale. (eg Monoids) (Now I realise there is an STM in Scala, and that Actor models, Avout and Cascalog are wonderful exceptions to this - I'm making a generalization)

My question is, why the Scala fascination with flatmap?

(I'm not trying to start a flamewar - I think both communities have benefited from each others existence - I'm trying to understand a cultural behaviour).

答:
Now I understand that FlatMap is significant because it is used for the bind part of a Monad. (and that the Clojure community hasn't dived into Monads yet, with some wonderful exceptions).

I think that's pretty much the entire explanation. Many Scala idioms and approaches are derived from Haskell, and so it pays a lot of attention to type-safety, monads, etc.

Now in the Clojure Community - there is no corresponding cultural idiom, eg "MapCat that S***".

mapcat only works with collections, unlike flatMap.

This focus on multi-machine problems has a higher focus on breaking problems down into their parts, and a greater focus on what can be broken down and Scale. (eg Monoids) (Now I realise there is an STM in Scala, and that Actor models, Avout and Cascalog are wonderful exceptions to this - I'm making a generalisation)

Better example of this in Clojure core is Reducers.


问:
Deprecation considered harmful?
I've just been compiling some of my own code with the -std=c++0x flag in GCC, as I want to vaguely keep up with what all the young folks are doing (provided they stay of my lawn), and I ended up with a load of warnings about auto_ptr being deprecated. Of course, I knew that auto_ptr was deprecated in C++0x, but...

Isn't deprecation a waste of time and effort? Reasons for not deprecating (with auto_ptr as an example):

there is an ocean of code out there that still needs to be supported, producing millions of warnings will only tempt people to turn warnings off.

auto_ptr is a bit naff, but it does actually do what it says on the tin.

if we really want to deprecate things, I nominate printf(). But just imagine the squeals that would ensue. auto_ptr doesn't have too many friends, but in at least my C++ code it is used more than printf, which isn't used at all.

the committee have a bad record of getting this right - they deprecated static at namespace scope, and now it seems to have been undeprecated  - I wouldn't be surprised if auto_ptr made a similar come-back

lastly, whatever the committee say, the compiler implementers ignore them - they simply can't risk breaking their customers code, all they can do is issue irritating warnings.

So my question - do you consider deprecation (of anything, not just auto_ptrs, and not just in C++) a good idea, and if so, why?

答:
Deprecation is not harmful if moving to an alternative can be done in 1 work day: eg. simple search/replace of the old function with the new, or a compatibility layer is easy to set up.

If you need to rewrite large parts of the software because of the deprecation, then it's harmful.

A good example would be probably the PHP's mysql API, basically you simply need to replace all mysql_* with mysqli_* and provide a link id to them and it's done.

One bad example is the deprecation and removal glBegin, glEnd, and all matrix computation stuff from OpenGL, if you want your code work on OpenGL3 or above, you'll need to rewrite the whole rendering code to use vertex buffers.

Title: Deprecation considered harmful?


问:
Algorithm for recursive evaluation of postfix expressions
I'm reading Sedgewick's book on algorithms in C and I'm looking for an algorithm to evaluate postfix expressions (addition and multiplication only) without using a stack. I tried to implement one but I always get nowhere.

I have a simple C implementation for prefix evaluation

```<code>int eval()
{
  int x = 0;

  while (a[i] == ' ')
    i++;
  if (a[i] == '+')
    {
      i++;
      return eval() + eval();
    }
  if (a[i] == '*')
    {
      i++;
      return eval() * eval();
    }
  while ( (a[i] >= '0') && (a[i] <= '9'))
    x = 10*x + (a[i++]-'0');
  return x;
 }
</code>```

and I was wondering if it's possible to do something as elegant as this but for postfix evaluation.

答: I wouldn't exactly call using a global variable as a string index counter 'elegant', but in a nutshell: No, you can't, because you have no idea how to combine the various numbers you find until you get to the operators. Until you do, you have to store them somewhere - and to get the right result, whatever your storage strategy is will ultimately boil down to stack semantics.</p>


答:
you pass the top 2 in the stack as parameter at each point, this way when you get to an operator you go up the stack when you see a value you go down the stack and when you get back you try again:

here is the magic:

```<code>eval(int x1, int x2)
{
 do{
   int x = 0;
   while (a[i] == ' ')
     i++;
   if (a[i] == '+')
    {
      i++;
      return x2+x1;// go up the stack with the resulting value
    }
   if (a[i] == '*')
    {
      i++;
      return x1*x2;
    }
   while ( (a[i] >= '0') && (a[i] <= '9'))
      x = 10*x + (a[i++]-'0');
   x2 = eval(x2, xt); // replace the old top with the result and try again
 }while(true);
}
</code>```

you just need to add 2 functions to handle the errors when operators appear as the first 2 terms:

```<code>eval()
{
 int x = 0;
  while (a[i] == ' ')
    i++;
 if (a[i] == '+')
    {
      i++;
      return ERROR;
    }
  if (a[i] == '*')
    {
      i++;
      return ERROR;
    }
  while ( (a[i] >= '0') && (a[i] <= '9'))
    x = 10*x + (a[i++]-'0');
  return eval(x);
}

eval(int x1)
{
 int x = 0;
  while (a[i] == ' ')
    i++;
 if (a[i] == '+')
    {
      i++;
      return ERROR;
    }
  if (a[i] == '*')
    {
      i++;
      return ERROR;
    }
  while ( (a[i] >= '0') && (a[i] <= '9'))
    x = 10*x + (a[i++]-'0');
  return eval(x1, x);
}
</code>```

Title: Algorithm for recursive evaluation of postfix expressions

Body:
I'm reading Sedgewick's book on algorithms in C and I'm looking for an algorithm to evaluate postfix expressions (addition and multiplication only) without using a stack. I tried to implement one but I always get nowhere.

I have a simple C implementation for prefix evaluation

```<code>int eval()
{
  int x = 0;

  while (a[i] == ' ')
    i++;
  if (a[i] == '+')
    {
      i++;
      return eval() + eval();
    }
  if (a[i] == '*')
    {
      i++;
      return eval() * eval();
    }
  while ( (a[i] >= '0') && (a[i] <= '9'))
    x = 10*x + (a[i++]-'0');
  return x;
 }
</code>```

and I was wondering if it's possible to do something as elegant as this but for postfix evaluation.

Body:
you pass the top 2 in the stack as parameter at each point, this way when you get to an operator you go up the stack when you see a value you go down the stack and when you get back you try again:

here is the magic:

eval(int x1, int x2)
{
 do{
   int x = 0;
   while (a[i] == ' ')
     i++;
   if (a[i] == '+')
    {
      i++;
      return x2+x1;// go up the stack with the resulting value
    }
   if (a[i] == '*')
    {
      i++;
      return x1*x2;
    }
   while ( (a[i] >= '0') && (a[i] <= '9'))
      x = 10*x + (a[i++]-'0');
   x2 = eval(x2, xt); // replace the old top with the result and try again
 }while(true);
}

you just need to add 2 functions to handle the errors when operators appear as the first 2 terms:

eval()
{
 int x = 0;
  while (a[i] == ' ')
    i++;
 if (a[i] == '+')
    {
      i++;
      return ERROR;
    }
  if (a[i] == '*')
    {
      i++;
      return ERROR;
    }
  while ( (a[i] >= '0') && (a[i] <= '9'))
    x = 10*x + (a[i++]-'0');
  return eval(x);
}

eval(int x1)
{
 int x = 0;
  while (a[i] == ' ')
    i++;
 if (a[i] == '+')
    {
      i++;
      return ERROR;
    }
  if (a[i] == '*')
    {
      i++;
      return ERROR;
    }
  while ( (a[i] >= '0') && (a[i] <= '9'))
    x = 10*x + (a[i++]-'0');
  return eval(x1, x);
}


问:
How do I comply to GPL in case of Appliance?
We are developing an enterprise network appliance which has got some GPL softwares like linux and apache and some others with APL license.

But the core of the service is proprietary software and access is provided only via a web interface.

My query is what all I need to do in order to comply with GPL license in this scenario. Would providing a list of Third party softwares used in the appliance in the web interface be sufficient?

答:
If you are selling the appliance to your customers you are "conveying" the software to your customers and will need comply with the licenses (GPL or otherwise) for all software installed on the device.

For all of the common licenses this means you must include the Copyright and license details for all packages in your documentation. For the GPL this means you must provide the source or an offer to provide the source to your customers.

If you have included modified GPL code you must make the modified sources available.

If your proprietary software could be considered a derived work of GPL software you will need to provide the source for your proprietary software.  However, just installing it on a linux machine and using the standard libraries does not make your software a derived work.


问:
Modelling Login and Authentication on an iOS mobile client
I'm about to start working on a V2 of a mobile application and I'd like to adopt  a more object-centric approach.  Primarily because I think it makes for more maintainable code, but a secondary benefit is easier testability.

V1 of the app is pretty controller-centric.  The Login ViewController has its login fields and it hits the backend via AFNetworking, reports errors if necessary, and receives a token which gets stored away securely for later use.

There's only ever a single user.  When the user logs out, all local data is deleted, so essentially the current user is 'global' and can either be nil (need a login) or not (doesn't).

The situation is complicated of course by the idea of token expiry.  Essentially any network request (either explicit GETs or asynchronous, delayed POSTs) can fail because the token expired and we want the user to re-authenticate.

The V1 model of a login screen at startup if there's no current user doesn't easily extend to this model, and I feel,I'm missing an object somehow I'd route everything through.  An Authenticator that provides a token, or throws up the login screen if it doesn't have one.

Then we could do something like - when any request fails, we delete the current token and retry the request.  The request asks the authenticator for the token, and the authenticator asks the user.

Or something.

How this could be better modelled?

I feel like the code needs to be centralised, but that's hard as requests are used throughout the apps.  Its almost like a filter layer is needed to handle auth errors centrally, but other errors / successes wherever they're needed (in a success/fail block).

答:
I see no problem with a "controller centric" way.

Let's start with a Root View Controller, who owns a "User" object.

```<code>- (void)viewDidAppear
{
    if (self.user && self.user.isAuthenticated) {
        [self showSensitiveData];
    } else {
        [self getAuthenticatedUserWithModal];
    }
}
</code>```

This is simple enough, but of course if the user becomes unauthenticated at any point, then your Root View Controller needs to know about it. I like to use Reactive Cocoa, but you could also do this with KVO or delegation:

```<code>- (void)authenitcationViewControllerDidFinishWithUser:(User *)user
{
    self.user = user;
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)setUser:(User *)
{
    _user = user;
    if (user) {
        @weakify(self);
        [RACObserve(self.user.isAuthenticated) subscribeNext:(id) x ^{
            @strongify(self);
            if(!self.user.isAuthenticated) {
                [self hideSensitiveData];
                [self getAuthenticatedUserWithModal];
            }
        }];
    }
}
</code>```

How does the user know whether or not they are authenticated? Apple suggests putting your networking code in your models. If your user object is responsible for dispatching and responding to requests, you can set the authenticated property whenever you receive a callback.

Body:
I see no problem with a "controller centric" way.

Let's start with a Root View Controller, who owns a "User" object.

- (void)viewDidAppear
{
    if (self.user && self.user.isAuthenticated) {
        [self showSensitiveData];
    } else {
        [self getAuthenticatedUserWithModal];
    }
}

This is simple enough, but of course if the user becomes unauthenticated at any point, then your Root View Controller needs to know about it. I like to use Reactive Cocoa, but you could also do this with KVO or delegation:

- (void)authenitcationViewControllerDidFinishWithUser:(User *)user
{
    self.user = user;
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)setUser:(User *)
{
    _user = user;
    if (user) {
        @weakify(self);
        [RACObserve(self.user.isAuthenticated) subscribeNext:(id) x ^{
            @strongify(self);
            if(!self.user.isAuthenticated) {
                [self hideSensitiveData];
                [self getAuthenticatedUserWithModal];
            }
        }];
    }
}

How does the user know whether or not they are authenticated? Apple suggests putting your networking code in your models. If your user object is responsible for dispatching and responding to requests, you can set the authenticated property whenever you receive a callback.


问:
I want to publish an android app, but I'm afraid of software patents
I wrote an application that helps you to save energy. Actually it is very simple. I check the current location of the phone and I make some changes to the configuration like "sound off, dark display, wifi off...", depending on the location of the user. Sony just released a new phone including one of my apps features (actually they have an extra entry in the options menue for this). I have no idea whether there is a patent for this function.

Can I even release this app without risking to be sued some day?

I'm very confused about the whole "patent" situation.

I'm about 20 years old and I can't even write a simple app, without investing lots of money for a lawyer.

Edit: I don't ask for legal advice. I wanted to receive an overview about how developers see or handle the whole situation.

答:
This is an appropriate situation for some basic game-theoretical analysis.

First, you should ignore anyone advising you to not worry about it because you're unlikely to get sued unless you're successful. This is absolutely false. You can and will be sued if you present a strategic threat to someone. The case of FlightPrep vs RunwayFinder is typical.

Despite the fact that RunwayFinder had no money whatsoever and the author gave away his hobby project software free of charge, FlightPrep still sued him out of business.

http://www.techdirt.com/blog/?company=runway+finder

RunwayFinder did try to fight back, btw, but found the costs staggering, even though donations were solicited to help defray legal expenses. If you care to see how that strategy actually plays out in the real world, consult Google, it's well documented.

Assertions on this topic that begin citing probabilities or risk analysis are entirely bogus. First, what methodological process was used to collect the data that any such risk-based analysis is founded on? Most companies and products patent trolls destroy never generate any court records because things never get that far. The majority of companies that have met their fate at the hands of trolls leave no official record to be accumulated into a meaningful statistic.

Consider also that trolls engage in mass threats via attorney letters. What are you going to do if you get one of these? Ignore it? In fact you'll compelled to answer it, which is to say you'll be compelled to start spending money on lawyers. If a lawsuit is merely filed, a relatively cheap thing to do, in some far flung courthouse- typically in the Eastern district of Texas :

http://www.technologyreview.com/news/405259/a-haven-for-patent-pirates/

you'll fold because while the other side may or may not be ready to take you to trial, you know you can't afford to defend yourself in some far distant state having been served with documents you can barely read.

By similar analysis, as soon as a troll gets a reputation for going after small developers, all other small developers will be forced to take them seriously- a fact that isn't lost to trolls. This is similar to a drug dealer capping, say, a ten year old he finds selling on his turf. The 10 year old wasn't a real threat and had no business to speak of, but all the other drug dealers now take him seriously.

Just as the possible threat of a lawsuit is sufficient to make you think twice about entering the market, the mere sight of just one dev in your product space being sued is enough to make anyone fold. Those who stay must be staying because they're making money and now the troll knows who to go after in earnest.

If you lose a patent lawsuit in the US, you also lose your rights to sell that software anywhere the US has the typical international IP agreement with because while a country may not recognize foreign software patents, they all agree to enforce any IP judgments issuing from a reciprocal nation's jurisdiction. So if you're sued in the US, you can't run to the EU at a future time with your software and start making money, you effectively lost that right when you were sued in the US for selling a product which infringes by US law. IN the eyes of the law, your software is someone else's property and you're trying to sell the stolen goods in the EU. The EU authorities are obliged to pursue.

One other note. The US Supreme Court decided in 2007 that creating software in the US and shipping a "golden master disk" to another nation's jurisdiction did NOT constitute infringement if the software was never sold here:

http://www.siliconvalleywatcher.com/mt/archives/2007/04/supreme_court_n.php

So it appears to be safe to write software here and then sell it there.

What game theoretical analysis suggests to us then is, just avoid the US market. Avoiding the US market for most app developers has no real downside. Although theoretical profits are left on the table,  if your app was going to make you a millionaire in the US market, it's probably going to do the same for you in the combined markets of EU NZ and other developer friendly markets.

Publishing software in the US is a kind of Russian roulette.  If you care about your future, then you don't play. If you're immune to fear of death for some reason, then by all means, pull the trigger. There is just no economic reason to conduct business in the US given the finality of a judgment against you. In effect, the threat of a lawsuit issuing from any old  IP lawyer functions just like a letter from some medieval king before the Magna Carta, decreeing you to be an enemy of the crown. There will be no trial. There will be no appeal. You're just dead, 'cause you are, 'cause someone (the troll) said something to someone (the court). Just cuz.

You can make all the money you need and more selling into the EU, NZ and other developer-friendly nations.


问:
Is it best practice to create a back door for testing a web service?
We have a public RESTful web service which exposes functionality to third parties. We are writing automated tests against it. In order to set up all scenarios on it we need to change the data behind it.

We also have a private RESTful web service which exposes functionality to other systems owned by us. However, this web service does not expose endpoints required to set up all the scenarios for the public web service.

In this circumstance is it best to create extra endpoints, not needed in normal operational behaviour, on the private web service in order to support the testing of the public one? Or should we set up our data using other means such as sending SQL commands?

答:
I don't see a need to create back doors for testing.

If you're making use of repo pattern or something similar then test you data access logic separately, and mock your repo in services when testing (I assume you're unit-testing them?). This way you can validate if service calls the correct repo methods with correct inputs.

This was working out pretty well for us.


问:
How to represent (enum) types in a public API
I am working on a simple API that I want to use for my own client, and to open to the public in the future.
I have "Item" objects which can have different "types". The type is a C "typedef enum", for the moment I have :

```<code>typedef enum {
    ItemTypeBool,
    ItemTypeNumber,
    ItemTypeDate,
} ItemType;
</code>```

(I may add some in the future)

I am wondering if I should rather transfer it as integers or as defined "strings". The JSON would be :

For integers :

```<code>{
  "name": "The name",
  "type": 0,
   ...
}
</code>```

For strings :

```<code>{
  "name": "The name"
  "type": "boolean"
   ...
}
</code>```

I'm wondering if there's a best practice for this. Keeping the integer would slightly simplify the code, and reduce the bandwidth, but strings would be easier for developers to remember. I remember I worked on a project, and I had to remember 1=image, 2=audio, 3=html,... which doesn't make any real sense.

So I'm asking you, if you know any other aspect I should consider.

答:
Strings.

One of Json's strengths is that its human-readable. When debugging the output half a year from now "0" will tell you nothing.

Some frameworks will do auto-conversion too. If you're not using one - you can create a converter yourself to keep your code dry.

This turns in a vote casting, though.


问:
Is it common to print out code on paper?
I like to keep my lines of code under 80 characters because:

I don't have to do any horizontal scrolling;

I know the line is probably too complicated if it exceeds this limit; and

it prints out nicely on paper.

Concerning the latter, I've met only a few who actually print out code to look at (I'm one of them). So how common is it to print out code?

答:
I print out my code all the time, but only because I'm a student who needs to do it to turn it in to the instructor.

However, because I have access to multiple monitors (like any good developer), I haven't had many situations where I need to print out source code for reference.  I once printed out one of the scripts I used to populate a database so that I can see the schema at a glance, but I don't seem to use it much.


答:
I used to print out code fairly often, but do so less now that I have multiple monitors on my desk -- I will often keep one part of a listing which I am using as a reference on my right monitor (which is somewhat off to the side), and my current work in front of me.

If I do print out ode, it is almost always code from someone or somewhere else (library) that I want to study, and need to flip pages back and forth.

I almost always print out code in landscape mode, because of the tendancy to use long lines.

Title: Is it common to print out code on paper?

Body:
I like to keep my lines of code under 80 characters because:

I don't have to do any horizontal scrolling;

I know the line is probably too complicated if it exceeds this limit; and

it prints out nicely on paper.

Concerning the latter, I've met only a few who actually print out code to look at (I'm one of them). So how common is it to print out code?


问:
How should I specify locations where clients can resolve authorization problems in a REST API?
I'm working through an API design where a user's authentication will be verified by the presence of a valid forms authentication ticket in a session cookie.  However, there are additional levels of access that can exist for particular resource URLs.  When attempting to access those, it seems like returning a 401 would be the most appropriate response.

However, generally we handle 401s by redirecting to a sign-in page.  That would not be a valid course of action for clients on certain resources, where there's an additional step required (e.g., email validation, signing up for a particular role).

Is there a standard way to communicate where to go next when responding with a 401?  I'm tempted to include something in the Location header, but that seems only appropriate for 302s after a POST.  I'm also reluctant to use URLs to specify where to go, since clients may not be restricted to browsers.

Any good examples or standards docs I can refer to on this?

答:
I've always considered redirects to be part of the convenience for the UI or UI agent.  Whereas REST API is more like a normal function API intended for clients that were coded specifically to communicate with it.

Just like many OS functions might fail with "access denied" and not redirect you to an authentication resource, I wouldn't expect REST API to redirect me either.  If someone codes the client to talk to your REST server, that client should also be coded to perform proper authentication in the first place.

So my take would be to reply with 401, or maybe even 403 Forbidden to distinguish between clients that are not authenticated vs. those that are authenticated but do not have correct permissions.  And possibly include human-readable text string indicating the reason for authentication/authorization failure, but don't worry about any redirects.


问:
Web App vs. Desktop App Regarding Deployment
I'm taking on an opportunity for a local business to develop a small, simple timesheet manager (they still record time by hand) and am currently in the planning phases. It will include basic functionality such as managing employee information, logging time worked on a weekly basis for payroll, and generating reports for administration.

I've developed Windows Forms applications for a while and am fairly confident my coding skills are where they need to be for this project, but I'm fairly new to both ASP.NET and the concept of developing a full desktop system as opposed to individual applications, so my questions will probably sound very elementary. I'm mainly struggling with understanding how to choose between ASP.NET and Windows Forms with regard to deployment down the road. Hopefully you guys can offer some insight.

I'm still a bit fuzzy on how database/web application hosting works. If I develop for desktop, will the database need a physical server if more than one workstation/client wants access? Could one of the workstations act as a server (there are under 20-30 employees at any given time, so data size shouldn't be an issue)? Would an ASP.NET system require purchasing a web host? Or, can the web files be hosted on a local computer/server with IIS as an intranet? Can virtualization fit somewhere in all this?

I guess it boils down to: Can I get them up and going for free, or is a server/hosting cost implied either way?

Thanks in advance!

答:
You should try a RAD platform for desktop databases, they hide the complexity of building and deploying database solutions, something like alpha5, brilliantdb, lyterad. They all have their own limitations but they will get you started with a ready to use database app in minutes.

But then you dont need these if you're already a db expert.


答:
I think you should test the command-line interface as part of integration testing.

Change your main function to:

```<code>def cmd(args=None):
    ...
    args = parser.parse_args(args=args)
    ...
</code>```

...so that you can easily pass in a list of arguments in your tests.

If running the entire program during testing is unreasonable, mock out _run_impl.

You might also want to look at something like scripttest to help capture output.

Title: How should I go about bringing this code under test?

Body:
I'm working on an open-source test framework.

90% of my codebase has good test coverage. My main problem area is the command-line entry point. This module began life as a very short script for calling into the domain model (see the call to _run_impl()) and exit with code 1 if the test run failed.

It didn't feel necessary to test that script at the time that I wrote it, but as the project has sprouted features, a number of small changes to the logic in this file have led it to become quite long:

```<code>import argparse
import os
import sys
from . import _run_impl  # a function, in __init__.py, which calls into the domain model
from . import reporting  # a sub-package concerned with writing output to the console

import colorama; colorama.init()

def cmd():
    parser = argparse.ArgumentParser()
    parser.add_argument('-s', '--no-capture',
        action='store_false',
        dest='capture',
        default=True,
        help="Disable capturing of stdout during tests.")
    parser.add_argument('-v', '--verbose',
        action='store_true',
        dest='verbose',
        default=False,
        help="Enable verbose progress reporting.")
    parser.add_argument('--teamcity',
        action='store_true',
        dest='teamcity',
        default=False,
        help="Enable teamcity test reporting.")
    parser.add_argument('--no-random',
        action='store_false',
        dest='shuffle',
        default=True,
        help="Disable test order randomisation.")
    parser.add_argument('path',
        action='store',
        nargs='?',
        default=os.getcwd(),
        help="Path to the test file or directory to run. (default current directory)")
    args = parser.parse_args()

    if args.teamcity or "TEAMCITY_VERSION" in os.environ:
        reporters = (reporting.teamcity.TeamCityReporter(sys.stdout),)
    elif args.verbose:
        reporters = (reporting.cli.ColouredReporter(sys.stdout),)
    elif args.capture:
        reporters = (
            reporting.cli.DotsReporter(sys.stdout),
            type("ColouredCapturingReporter", (reporting.cli.ColouredReporter, reporting.cli.StdOutCapturingReporter), {})(sys.stdout),
            reporting.cli.TimedReporter(sys.stdout)
        )
    else:
        reporters = (
            reporting.cli.DotsReporter(sys.stdout),
            type("ColouredCapturingReporter", (reporting.cli.ColouredReporter, reporting.cli.SummarisingReporter), {})(sys.stdout),
            reporting.cli.TimedReporter(sys.stdout)
        )

    reporter = reporting.shared.ReporterManager(*reporters)

    _run_impl(os.path.realpath(args.path), reporter, args.shuffle)

    if reporter.failed:
        sys.exit(1)
    sys.exit(0)

if __name__ == "__main__":
    cmd()
</code>```

I know that this code has bugs (for example, it should be possible to capture stdout from tests when running in verbose mode), and I've lost confidence in my ability to change this module without breaking something. So I want to write some tests for it - but I only really have experience with test-first development, so I don't really know where to start.

Should the tests be at the unit or integration level? Should I mock the ArgumentParser? Should I mock the reporting module? Should I mock _run_impl? Should I try to bring the whole module under test at the start, or just add tests as I add features? Do I need to refactor to make this method more testable?

Addendum: I think a part of my confusion is due to the fact that this is a relatively thin layer on top of the business logic - it's just there to make it possible to kick-off the test runner from the command line. So I'm feeling confused about what constitutes the service boundary here - in particular, what I should and shouldn't mock.

Body:
I think you should test the command-line interface as part of integration testing.

Change your main function to:

def cmd(args=None):
    ...
    args = parser.parse_args(args=args)
    ...

...so that you can easily pass in a list of arguments in your tests.

If running the entire program during testing is unreasonable, mock out _run_impl.

You might also want to look at something like scripttest to help capture output.


答:
I don't see anything in the RFC-2616 Location header definition that limits it's use to 3xx or 201 HTTP status responses. I agree the 401 response would be appropriate since the HTTP 403 status response implies there is no recourse even when subsequent authentication is possible. What you're suggesting is an application specific variation on the established HTTP Basic authentication protocol.

This StackOverflow answer to a similar question gives an example which includes the location as part of the required WWW-Authenticate header contents in a 401 response instead of in the separate Location header. I believe either approach respects the RFC-2616 & RFC-2617 specs but I'd would choose embedding the location in the WWW-Authenticate header contents due to its simplicity of implementation since it keeps all the application specific authentication information in a single place.

Title: How should I specify locations where clients can resolve authorization problems in a REST API?

Body:
I'm working through an API design where a user's authentication will be verified by the presence of a valid forms authentication ticket in a session cookie.  However, there are additional levels of access that can exist for particular resource URLs.  When attempting to access those, it seems like returning a 401 would be the most appropriate response.

However, generally we handle 401s by redirecting to a sign-in page.  That would not be a valid course of action for clients on certain resources, where there's an additional step required (e.g., email validation, signing up for a particular role).

Is there a standard way to communicate where to go next when responding with a 401?  I'm tempted to include something in the Location header, but that seems only appropriate for 302s after a POST.  I'm also reluctant to use URLs to specify where to go, since clients may not be restricted to browsers.

Any good examples or standards docs I can refer to on this?


答:
and I was wondering if it's possible to do something as elegant as this but for postfix evaluation.

Postfix notation isn't meant to be processed with a call stack or recursion or really anything of that nature.  Its designed for nice, tight implementations that just have a simple loop and a stack next to it.  These fall into the realm of stack machines and are often found in embedded systems because of their simplicity.  You find things like forth, postscript and the jvm as very successful stack machines (see Wikipedia - Category stack based virtual machines) along with venerable HP rpn calculator.

The elegance of postfix can be seen in the simple loop:

```<code>while not end of file
    read into var
    if var is not operand
        push var
    else if var is '+'
        pop into v1
        pop into v2
        push v1 + v2
    else if var is '*'
        pop into v1
        pop info v2
        push v1 * v2
</code>```

And thus you go through and implement all the operands and you're done.  dc has 27 operands (things like print (pop and print) P, print (just print) p, print the stack f, clear the stack c, etc...).  You can read them at dc.1 man page.  I will admit there are some more elegant structures for implementing the operands rather than a huge if else if cascade depending on the language... but you get the idea.

The elegance of the system is its simplicity.  You don't have to worry about stack frames, calling conventions, and the like when implementing it.  You've got a stack and a variable or two.

Body:
and I was wondering if it's possible to do something as elegant as this but for postfix evaluation.

Postfix notation isn't meant to be processed with a call stack or recursion or really anything of that nature.  Its designed for nice, tight implementations that just have a simple loop and a stack next to it.  These fall into the realm of stack machines and are often found in embedded systems because of their simplicity.  You find things like forth, postscript and the jvm as very successful stack machines (see Wikipedia - Category stack based virtual machines) along with venerable HP rpn calculator.

The elegance of postfix can be seen in the simple loop:

while not end of file
    read into var
    if var is not operand
        push var
    else if var is '+'
        pop into v1
        pop into v2
        push v1 + v2
    else if var is '*'
        pop into v1
        pop info v2
        push v1 * v2

And thus you go through and implement all the operands and you're done.  dc has 27 operands (things like print (pop and print) P, print (just print) p, print the stack f, clear the stack c, etc...).  You can read them at dc.1 man page.  I will admit there are some more elegant structures for implementing the operands rather than a huge if else if cascade depending on the language... but you get the idea.

The elegance of the system is its simplicity.  You don't have to worry about stack frames, calling conventions, and the like when implementing it.  You've got a stack and a variable or two.


问:
Why is FRACTRAN turing complete?
I've tried to google for explanation but most links only say things like "FRACTRAN is turing complete. As an example, let's look at multiplication."

I remember seeing an xkcd forum post say that FRACTRAN helped the poster understand Turing Completeness. I am looking for an intuitive explanation as to why this esolang is Turing complete, as it's not very obvious looking at the language mechanics.

答:
For an imperative language to be Turing complete it must have:

Conditional loop

Arbitrary number of variables

FRACTRAN is a language that is made up of a series of fractions that stores its data in the exponents of primes.

Lets say you want to add two numbers: 2a3b becomes 5ab

```
455   11    1   3   11   1
--- , -- , -- , - , -- , -
 33   13   11   7    2   3
```

That's a FRACTRAN program for doing that above change.

You start off with a number like 72 (2332).  The program goes 'forward' until it finds a number that when multiplied by the instruction is another integer (no remainders allowed).

72 will run forward until it gets to 11/2. It then will divide the number by 2 and multiply it by 11 (the power in 11 is a variable).  This gives 396.  396 is divisible by 33 (reducing the 3 power and the 11) and multiply by 455 (incrementing 5, 7 and 13 variables).  And so on.  The full description of this program and its state table can be read at FRACTRAN wikipedia page, including a really nice animated gif of the above program.

Other FRACTRAN material on Stack Exchange that touches on the Turing completeness can be found at: Convert Fractran into Brainfuck (ok, that's a really productive use of one's time)

The reason that Fractran is Turing-complete is because it simulates a register machine. The number's prime factorization stores the contents of the registers, while the division and multiplication is a way to conditionally add and subtract from the registers.

Part of the trick here (and this starts straying into theory) is that behind the scenes, this is a Minsky register machine for which it was proved that certain tapes (programs) are Turing machines IF the tape is represented as a Gödel number which is exactly what the FRACTRAN number is (from the linked wikipedia page):

Gödel used a system based on prime factorization. He first assigned a unique natural number to each basic symbol in the formal language of arithmetic with which he was dealing.

So, we've got conditional loops, arbitrary variables stored as Gödel numbers, we've got a Turing machine.

Some other fun reading that touches on the Collatz like nature of FRACTRAN can be read at Can’t Decide? Undecide! that relate the Collatz conjecture to FRACTRAN and the halting problem.

FRACTRAN is a bit difficult to get one's head around.

Consider the program something like:

```<code>LABEL: start
    block1
    block2
    block3
    ...
END
</code>```

In this, each block is of the form:

```<code>IF(registers X >= a, Y >= b)  # or any combination of registers
THEN
    X -= a
    Y -= b

    I += n
    J += m

    goto start
</code>```

The first statement from the multiplication program above:

```
455
---
 33
```

Would be written in this form as:

```<code>IF(register `3` >= 1 && `11` >= 1)
THEN
     `3` -= 1
    `11` -= 1

     `5` += 1
     `7` += 1
    `13` += 1

    goto start
</code>```

And thus you can clearly see the data storage and the looping constructs necessary for Turing completeness.  Its very rudimentary, but it exists and runs as a simple register machine - but then thats all that you really need to be able to do.

Still not convinced?

This largely borrows from a lecture by Dimitri Hendricks on Models of Computation

This takes the very simple program (2/3) which is an adder (2a3b --> 3a+b) But it is destructive - the value in 2 is cleared as part of the process.

Lets write a higher level FRACTRAN that makes it easy to not do such destruction.

The original program could be thought of as:

```
   2
α: - → α
   3
```

In F2, one can specify 'functions' of a sort.

```
   10       1
α: -- → α , - → β
    3       1

   3
β: - → β
   5
```

To convert an F2 program (P) into a standard FRACTRAN program, one does:

Clear P of loops of length 1

Replace greek letters (functions) with fresh prime numbers

Replace the transitions:

```
   a      c      e
p: - → q, - → r, - -> s, ...
   b      d      f
```

becomes:

```
aq   cr   es
-- , -- , -- , ...
bp   dp   fp
```

What this has done is used the primes p, q, r, and s to store the state of the program.

And then we've got the register machine... it has a finite number of registers that store arbitrary large numbers and two instructions:

inc(xi, m) - increment register i and go to line m

jzdec(xi, m1, m2) - if register i is 0 go to line m, else decrement i, and go to line m2.

This register machine has been shown to be Turing complete.

It then goes to show the process over several slides of compiling a register machine program into a FRACTRAN program as part of a mechanical process.

Basically:

```
                       p(i)
inc(x(i), m)        =  ---- → m
                        1

                        1          1
jzdec(x(i), m1, m2) =  ---- → m2,  - → m1
                       p(i)        1
```

And thus because of the equivalence between these two models of computing, FRACTRAN is Turing complete.

Btw, if you really want to have your mind blown, read Code Golf: Fractran in which some people wrote a FRACTRAN program to run another FRACTRAN program.

OwnerDisplayName: mage

Title: Why is FRACTRAN turing complete?

Body:
For an imperative language to be Turing complete it must have:

Conditional loop

Arbitrary number of variables

FRACTRAN is a language that is made up of a series of fractions that stores its data in the exponents of primes.

Lets say you want to add two numbers: 2a3b becomes 5ab

455   11    1   3   11   1
--- , -- , -- , - , -- , -
 33   13   11   7    2   3

That's a FRACTRAN program for doing that above change.

You start off with a number like 72 (2332).  The program goes 'forward' until it finds a number that when multiplied by the instruction is another integer (no remainders allowed).

72 will run forward until it gets to 11/2. It then will divide the number by 2 and multiply it by 11 (the power in 11 is a variable).  This gives 396.  396 is divisible by 33 (reducing the 3 power and the 11) and multiply by 455 (incrementing 5, 7 and 13 variables).  And so on.  The full description of this program and its state table can be read at FRACTRAN wikipedia page, including a really nice animated gif of the above program.

Other FRACTRAN material on Stack Exchange that touches on the Turing completeness can be found at: Convert Fractran into Brainfuck (ok, that's a really productive use of one's time)

The reason that Fractran is Turing-complete is because it simulates a register machine. The number's prime factorization stores the contents of the registers, while the division and multiplication is a way to conditionally add and subtract from the registers.

Part of the trick here (and this starts straying into theory) is that behind the scenes, this is a Minsky register machine for which it was proved that certain tapes (programs) are Turing machines IF the tape is represented as a Gödel number which is exactly what the FRACTRAN number is (from the linked wikipedia page):

Gödel used a system based on prime factorization. He first assigned a unique natural number to each basic symbol in the formal language of arithmetic with which he was dealing.

So, we've got conditional loops, arbitrary variables stored as Gödel numbers, we've got a Turing machine.

Some other fun reading that touches on the Collatz like nature of FRACTRAN can be read at Can’t Decide? Undecide! that relate the Collatz conjecture to FRACTRAN and the halting problem.

FRACTRAN is a bit difficult to get one's head around.

Consider the program something like:

LABEL: start
    block1
    block2
    block3
    ...
END

In this, each block is of the form:

IF(registers X >= a, Y >= b)  # or any combination of registers
THEN
    X -= a
    Y -= b

    I += n
    J += m

    goto start

The first statement from the multiplication program above:

455
---
 33

Would be written in this form as:

IF(register `3` >= 1 && `11` >= 1)
THEN
     `3` -= 1
    `11` -= 1

     `5` += 1
     `7` += 1
    `13` += 1

    goto start

And thus you can clearly see the data storage and the looping constructs necessary for Turing completeness.  Its very rudimentary, but it exists and runs as a simple register machine - but then thats all that you really need to be able to do.

Still not convinced?

This largely borrows from a lecture by Dimitri Hendricks on Models of Computation

This takes the very simple program (2/3) which is an adder (2a3b --> 3a+b) But it is destructive - the value in 2 is cleared as part of the process.

Lets write a higher level FRACTRAN that makes it easy to not do such destruction.

The original program could be thought of as:

   2
α: - → α
   3

In F2, one can specify 'functions' of a sort.

   10       1
α: -- → α , - → β
    3       1

   3
β: - → β
   5

To convert an F2 program (P) into a standard FRACTRAN program, one does:

Clear P of loops of length 1

Replace greek letters (functions) with fresh prime numbers

Replace the transitions:

   a      c      e
p: - → q, - → r, - -> s, ...
   b      d      f

becomes:

aq   cr   es
-- , -- , -- , ...
bp   dp   fp

What this has done is used the primes p, q, r, and s to store the state of the program.

And then we've got the register machine... it has a finite number of registers that store arbitrary large numbers and two instructions:

inc(xi, m) - increment register i and go to line m

jzdec(xi, m1, m2) - if register i is 0 go to line m, else decrement i, and go to line m2.

This register machine has been shown to be Turing complete.

It then goes to show the process over several slides of compiling a register machine program into a FRACTRAN program as part of a mechanical process.

Basically:

                       p(i)
inc(x(i), m)        =  ---- → m
                        1

                        1          1
jzdec(x(i), m1, m2) =  ---- → m2,  - → m1
                       p(i)        1

And thus because of the equivalence between these two models of computing, FRACTRAN is Turing complete.

Btw, if you really want to have your mind blown, read Code Golf: Fractran in which some people wrote a FRACTRAN program to run another FRACTRAN program.


问:
best way to send messages to all subscribers with multiple subscriptions and multiple providers
I'm writing an application in which -

Many users can subsribe to posts made by another users.

So for a single publisher there can be many subscribers.

When a message is posted by an user X, all users who have subscribed to messages of User X will be sent an email.

How to achieve this ? I'm thinking of using publish-subscribe pattern.

And then I came through JMS. Which is the best JMS implementation to use according to your experience ?

Or else what else solution do you propose to the given problem ?

Shall I go for a straight-forward solution ?:
User x posts a message, I find all users (from database) who subscribe to user x
and then for every user, I call the sendEmail() method.

[EDIT]
My intention here is not to send-emails. I'm really sorry if it wasn't clear.
I also have to send kind of system-notifications apart from Email to all subscribers.

Right now, I've implemented the email-sending as a threadPool

答:
Hope you are not looking for a platform specific solution

If Yes, your requirement highlights a pub/sub pattern. I handled the same using RabbitMQ which has specific support for Pub/Sub scenario.

Without going in to granular details, to give you an idea on RabbitMQ's pub/sub model

It has something called "exchange" in addition to "producer","queue", & "consumer"

The core idea on this messaging model is that the producer never sends any messages directly to a queue. A quite often the producer doesn't even know if a message will be delivered to any queue at all. The producer can only send messages to an exchange. An exchange receives messages from producers and the other side it pushes them to queues.

It supports different exchange types to satisfy your various needs - direct, topic, headers and fanout.

This means greater flexibility to de-couple core MQ functionality from the business logic, which you may want to impose on message formats/delivery/retry logic

I used "topic" exchange type which supports message routing/filtering just by looking at message name/title.

To give you a best use of this logic - I had a weird requirement (on pub/sub model) to maintain the list of active subscribers , which I managed to get it done by introducing a heartbeat (topic based) message on the same queue

For the said reasons, and high accuracy on message delivery, and good performance results of supported AMQP protocol, I felt quite happy about my choice

Disclaimer : I am not advocating here that RabbitMQ is the only choice, but sharing this as my nice experience with a smart solution. There are quite few pub/sub solutions out there in the market.

I also found WAMP interesting while exploring various options,but didn't use it for any commercial implementation


问:
Using raw types in Java method signatures
In general I try to avoid using raw types in the signature of methods in the libraries I develop.
However, lately I am starting to relax this (self-adopted) rule-of-thumb, and I am starting to write raw types more often than before.

For example, assuming a method receiving any list as parameter (i.e., the type of the list members is not important), I was tempted before to declare it as:

```<code>void myMethod(List<?> list) {...}
</code>```

But now I am starting to write more and more:

```<code>void myMethod(List list) {...}
</code>```

Because it is shorter.

My concrete question is:
In the scenario where type parameters are not important, is using raw types in method parameters considered a good practice ?
If not, why not ?

The only problem I see is being condemned to see an eternal warning in the IDE I use (although probably that can be deactivated somewhere), but I would like to be sure I am not missing something else.

Update:

Got fully convinced I should use generics everywhere after reading the paragraph below here:

Use of raw types is discouraged.  The Java Language Specification even
  states that it is possible that future versions of the Java
  programming language will disallow the use of raw types.

答:
Yes, you are. Generic wildcards enforce that the container contains "something, but we're not sure what" and raw types are just "the container contains objects".

So you can get some counterintuitive results,

```<code>List<?> wild = new ArrayList<String>();
List    raw  = new ArrayList<String>();
wild.add(1); // Compile time error
raw.add(1);
raw.add("Foo");
wild.add("string"); // Still a compile time error
</code>```

Wild cards are represented as the same as raw at run time, but they are typechecked to make sure you never do something silly, like adding random objects to it.

So if you don't care about type safety, then yes, you can go ahead and use List, but for 3 characters, I'd just use the parameterized type.

Body:
Yes, you are. Generic wildcards enforce that the container contains "something, but we're not sure what" and raw types are just "the container contains objects".

So you can get some counterintuitive results,

List<?> wild = new ArrayList<String>();
List    raw  = new ArrayList<String>();
wild.add(1); // Compile time error
raw.add(1);
raw.add("Foo");
wild.add("string"); // Still a compile time error

Wild cards are represented as the same as raw at run time, but they are typechecked to make sure you never do something silly, like adding random objects to it.

So if you don't care about type safety, then yes, you can go ahead and use List, but for 3 characters, I'd just use the parameterized type.


问:
What do programmers "micro-optimize" for today?
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.

答:
Time complexity. I spend way too much time optimizing things for worst case performance on a scale that is orders of magnitude larger than anything I know the program will realistically encounter.

I'm just too obsessive to let go of the 'but it could grow that big' bone, even when other design decisions preclude that from realistically happening.

However, in my defense, should the unrealistic become reality .. the optimization really isn't 'micro' any longer. Note, I didn't say impossible, but unrealistic.

Of course, requirements take precedence.