答:
1) Do you really manage (and how) to predict possible future problems?

Look at the level of maturity of a technology in question, and consider how widespread is its use. You can predict with reasonable certainty that the number of non-intuitive places in a technology stack drops as the technology gets more mature.

2) How much time do you spend for finding the workaround/fix/solution before you leave it and switch to other problems.

It depends on the need for a fix: I've spent nearly two weeks researching a rare but persistent bug on an obscure platform that we needed to support, because the platform was required by the contract. This was when Experts Exchange was in its infancy, and Stack Overflow did not exist.

3) What are the criteria for you to think about yourself as experienced in the tecnology. Do you take these gotchas into account?

Absolutely, I do! In fact, it's pretty much the only thing that makes up the "experience" (as opposed to "knowledge" that can be learned from books and tutorials).

The biggest criteria is how long you can go without hitting one of these "gotchas": what's gotcha for one developer, may be a known limitation to another developer, and a feature to yet another one. The more you use a technology, the more "gotchas" sort themselves out into your "feature" and "limitation" boxes, letting you work without discovering a new one for days and months.

Title: Does the term "Learning Curve" include the knowing of the gotchas?

Body:
When you learn new technology you spend time understanding its concepts and tools.
But when technology meets real life strange and not pleasant things happen.
Reuqirements are often far from ideal and differ from 'classic' scenario.
And soon I find myself bending  the technology to my real needs. At this point I begin to know bugs of the system or that is is not so flexible as it seemed at the very begining.
And this 'fighting' with technology consumes a great part of the time while developing.
What is more depressing is that the bunch of such gotchas and workarounds are not concentrated at one place (book, site, etc.) And before you really confront it you cannot really ask the correct question because you do not even suspect the reason for the problem to occur (unknown-unknown).

So my question consiststs of three:

1) Do you really manage (and how) to predict possible future problems?

2) How much time do you spend for finding the workaround/fix/solution before you leave it and switch to other problems.

3) What are the criteria for you to think about yourself as experienced in the tecnology. Do you take these gotchas into account?


问:
How do I trust an off site application
I need to implement something similar to a license server. This will have to be installed off site at the customers' location and needs to communicate with other applications at the customers' site (the applications that use the licenses) and an application running in our hosting center (for reporting and getting license information).

My question is how to set this up in a way I can trust that:

The license server is really our application and not something that just simulates it; and

There is no "man in the middle" (i.e. a proxy or something that alters the traffic).

The first thing I thought of was to use with client certificates and that would solve at least 2. However, what I'm worried about is that someone just decompiles (this is build in .NET) the license server, alters some logic and recompiles it. This would be hard to detect from both connecting applications.

This doesn't have to be absolutely secure since we have a limited number of customers whom we have a trust relationship with. However, I do want to make it more difficult than a simple decompile/recompile of the license server. I primarily want to protect against an employee or nephew of the boss trying to be smart.

答: I am unsure this is actually truly possible. A bit of a stretch but a similar question I posted came to the that conclusion. You may want to try utilizing the OS for achieving what you want, perhaps store a cert in a folder only your application has access to. That way any non-administrator would not be able to get to it and thus could never represent themselves as your application.</p>

ContentLicense: CC BY-SA 3.0

Title: How do I trust an off site application


问:
How do you handle objects that need custom behavior, and need to exist as an entity in the database?
For a simple example, assume your application sends out notifications to users when various events happen.  So in the database I might have the following tables:

```<code>TABLE Event
    EventId uniqueidentifier
    EventName varchar

TABLE User
    UserId uniqueidentifier
    Name varchar

TABLE EventSubscription
    EventUserId
    EventId
    UserId
</code>```

The events themselves are generated by the program.  So there are hard-coded points in the application where an event instance is generated, and it needs to notify all the subscribed users.

So, the application itself doesn't edit the Event table, except during initial installation, and during an update where a new Event might be created.

At some point, when an event is generated, the application needs to lookup the Event and get a list of Users.  What's the best way to link the event in the source code to the event in the database?

Option 1:

Store the EventName in the program as a fixed constant, and look it up by name.

Option 2:

Store the EventId in the program as a static Guid, and look it up by ID.

Extra Credit

In other similar circumstances I may want to include custom behavior with the event type.  That is, I'll want subclasses of my Event entity class with different behaviors, and when I lookup an event, I want it to return an instance of my subclass.

For instance:

class Event
{
    public Guid Id { get;  }
    public Guid EventName { get;  }
    public ReadOnlyCollection<EventSubscription> EventSubscriptions { get; }
    public void NotifySubscribers()
    {
        foreach(var eventSubscription in EventSubscriptions)
        {
            eventSubscription.Notify();
        }
        this.OnSubscribersNotified();
    }
    public virtual void OnSubscribersNotified() {}
}

class WakingEvent : Event
{
    private readonly IWaker waker;
    public WakingEvent(IWaker waker)
    {
        if(waker == null) throw new ArgumentNullException("waker");
        this.waker = waker;
    }

    public override void OnSubscribersNotified()
    {
        this.waker.Wake();
        base.OnSubscribersNotified();
    }
}
```

<p>So, that means I need to map <code>WakingEvent</code> to whatever key I'm using to look it up in the database.  Let's say that's the <code>EventId</code>.  Where do I store this relationship?  Does it go in the event repository class?  Should the <code>WakingEvent</code> know declare its own ID in a static member or method?</p>

<p>...and then, is this all backwards?  If all events have a subclass, then instead of retrieving events by ID, should I be asking my repository for the <code>WakingEvent</code> like this:</p>

<pre class="lang-cs prettyprint-override"><code>public T GetEvent<T>() where T : Event
{
    ... // what goes here?
}
</code>```

I can't be the first one to tackle this.  What's the best practice?

答:
I assume data in Event is truly static, not dynamic. If that's the case an enum could represent the event types. Have both the name and ID match that of the database if possible. At least 1 should match.

```<code>enum EventType
{
    Waking = 1, //it would be nice if both enum's name/int matched DB name/ID
    Sleeping,
    FooBar
}
</code>```

To get the Event object pass an enum to a factory method.

```<code>IEvent getImp(EventType type)
{
    IEvent imp = null;

    switch (type)
    {
        case EventType.Waking:
            imp = new WakingEvent();
            break;
        case EventType.Sleeping:
            imp = new SleepingEvent();
            break;
        case EventType.FooBar:
            imp = new FooBarEvent();
            break;
    }
    return imp;
}
</code>```

It may feel "wrong" because everything is hard-coded into the app. But this is assuming the behavior cannot be data driven. Random complex behavior cannot be defined as data unless the data itself is imperative code.

Body:
I assume data in Event is truly static, not dynamic. If that's the case an enum could represent the event types. Have both the name and ID match that of the database if possible. At least 1 should match.

enum EventType
{
    Waking = 1, //it would be nice if both enum's name/int matched DB name/ID
    Sleeping,
    FooBar
}

To get the Event object pass an enum to a factory method.

IEvent getImp(EventType type)
{
    IEvent imp = null;

    switch (type)
    {
        case EventType.Waking:
            imp = new WakingEvent();
            break;
        case EventType.Sleeping:
            imp = new SleepingEvent();
            break;
        case EventType.FooBar:
            imp = new FooBarEvent();
            break;
    }
    return imp;
}

It may feel "wrong" because everything is hard-coded into the app. But this is assuming the behavior cannot be data driven. Random complex behavior cannot be defined as data unless the data itself is imperative code.


问:
Syntax Memorization

Possible Duplicate:

  Programmers forgetting syntax

  Do programmers need a good memory?

I'm a new web developer.  I began learning HTML/CSS around June of this year.  I picked them up easily, now I'm moving on to Javascript.  My problem is this.  I understand the concepts that the training material are teaching but I find myself coming up short when it's time to apply those lessons.  Mainly it's due in part to the syntax.  I memorize a function, apply it, test it, move on then forget it a few days later (the syntax, not the concept).  My question is this.  Should I be spinning my wheels trying to remember everything, or is knowing the concept enough.

I know this has been addressed before but I couldn't find any real definitive real world answers.  Feel free to discuss what methods worked for you when you started out.

答:
Correct syntax is only a Google away, proper application of concepts is the important part that can take a lifetime to master. It is far more important to know what you want and need than how to type it with correct syntax.

Remembering syntax will come with time and repetition, the more stuff you do the more you will understand which things are commonly used and worth remembering.

Title: Syntax Memorization


问:
Data structure for pattern matching
Let's say you have an input file with many entries like these:

```<code>date, ticker, open, high, low, close, <and some other values>
</code>```

And you want to execute a pattern matching routine on the entries(rows) in that file, using a candlestick pattern, for example. (See, Doji) And that pattern can appear on any uniform time interval (let t = 1s, 5s, 10s, 1d, 7d, 2w, 2y, and so on...).

Say a pattern matching routine can take an arbitrary number of rows to perform an analysis and contain an arbitrary number of subpatterns. In other words, some patterns may require 4 entries to operate on others may require more or less.

Say also that the routine (may) later have to find and classify extrema (local and global maxima and minima as well as inflection points) for the ticker over a closed interval, for example, you could say that a cubic function (x^3) has the extrema on the interval [-1, 1]. (See link)

Given that I don't know the size of the input file upon reading? What would be the most natural choice in terms of a data structure?  What about an interface that conforms a Ticker object containing one row of data to a collection of Ticker so that an arbitrary pattern can be applied to the data. For example, let's say I have a pattern that requires n elements to form a match, I need to apply the pattern to those elements and then analyze each one of those chunks.

What's the first thing that comes to mind?

I chose a doubly-linked circular linked list that has the following methods:

```<code>push_front()
push_back()
pop_front()
pop_back()
[] //overloaded, can be used with negative parameters
</code>```

But that data structure seems very clumsy, since so much pushing and popping is going on, I have to make a deep copy of the data structure before running an analysis on it.

So, I don't know if I made my question very clear -- but the main points are:

What kind of data structures should be considered when analyzing sequential data points to conform to a pattern that does NOT require random access?

What kind of data structures should be considered when classifying extrema of a set of data points?

Updated

Here's the main analyzer loop for my program (in some pseudocode that's a polyglot of a few languages)

```<code>data = new circular_linkedList()
// in my case, data is a circular linked list of elements.
foreach(element in dataFeed) {
    data.push_front(element)
}

step_value = Pattern.numberRequiredElementsForMatch()
buffer = new circular_linkedList()
// at this point, you'll have a circular linked list
// where pop_back() will return the oldest entry and
// entry, and pop_front() will return the newest

// initialize the buffer
for(value in range(step_value()) {
    buffer.push_back(data.pop_back())
    // fill a buffer with the number of
    // values required for a match.
    // so now buffer will contain
    // [elementk, ... , elementk+n]
    // where buffer[0] < ... < buffer[n]
}
do {
    last = buffer[len(buffer)]
    ...
    first = buffer[0]

    Pattern.match(first, ... , last)
    buffer.pop_front() // remove the first element
    buffer.push_back(data.pop_back()) //add another element to the back

} while (!data.isEmpty())

...
</code>```

Anyway, that's a basic idea of what I have going on. The problem is that the way I'm doing it now, I have to reiterate through the loop to apply another pattern. (buffer sizes differ) It just seems inefficient to do that. Also, what happens when there's no more data in the buffer and it's not evenly divisible by the number of elements needed by a match?

答:
Vector instead of Linked List

Whatever you do, don't use a doubly linked list for this. It has a lot of allocation and space overhead. The data is read and appended sequentially, there is no random access or random removal of items, so a vector-like data structure would be much more suitable to store data. But even that is overkill for the raw data, as you'll see below.

Data flows through Listeners, then disappears

To do linear pattern matching you don't have to store the data at all, and you'll only have to traverse it once. The idea is to have several matchers listening for their patterns as the data hums along. These store only the data needed to detect a pattern. Any items that cannot be part of a pattern anymore will be forgotten.

I'll describe one way of achieving that. I must warn you that the task you want to perform is not trivial to do efficiently. Judging from your proposal of using a linked list, it may take some time to wrap your head around the principles involved.

Continuously register Matchers listening to the data

Let's start by adding some entities to listen for your patterns in the data. Register a matcher factory for every  combination you want to recognize. Typically each pattern would be in its own matcher class, parametrized by the resolution it is looking for.

Now start reading in the data, and feed each item to each matcher factory as you read it. Then have that factory instantiate/reuse a matcher for every place that could be the starting point of a pattern. For example, a matcher with a 7 day resolution could be instantiated each time the first data point for the new week comes in.

Matchers update internal state until they reject/accept a pattern

The ticker items are also fed to each active matcher. Each matcher should track its own internal matching state. For example, a matcher with a 7 day resolution may be accumulating ticker values to calculate the 7 day average. After each 7 days pass, it stores the average in the next position of an array, starting a new average accumulation for subsequent incoming ticker items. This continues until it has seen enough weeks to either reject the or confirm the presence of the pattern. To get some ideas on how to do this, look into 'Finite State Machines'.

Efficiency gains by eliminating duplicate calculations

Of course, if there are multiple matchers that need the data on a 7-day resolution it is not efficient to have each one calculate it on its own. You may build a hierarchy of matchers so intermediate patterns only have to be calculated once. Look into ring buffers for ideas on how to maintain rolling averages (or other aggregate functions)

Related: Parser Generators

So-called 'Parser Generators' do a similar thing automatically for formal grammars. The generated parsers employ a finite state machine to detect hundreds of patterns with about the same effort it would take to recognize just one, and in just one pass of the source data. I imagine such tools may also exist for continuous time-series data, or you could transform their ideas to apply them to your problem.

Hope this helps!

Title: Data structure for pattern matching


答: As long as you know the concept you'll be fine. Programming is all about these concepts, and syntax is just a way of expressing them. Learning a new language, we all face a hard time remembering syntax, but that's what reference material is for. And now that we have the Internet (you younglings have no idea how good you have it!), moderate Google skills can get you the syntax of pretty much anything you might ever need. With time, and expereince, you'll find yourself retaining more and more of that syntax in your head so coding will get faster and faster. But you'll never get everything in your head, so don't worry about it.

Title: Syntax Memorization

Body:
Possible Duplicate:

  Programmers forgetting syntax

  Do programmers need a good memory?

I'm a new web developer.  I began learning HTML/CSS around June of this year.  I picked them up easily, now I'm moving on to Javascript.  My problem is this.  I understand the concepts that the training material are teaching but I find myself coming up short when it's time to apply those lessons.  Mainly it's due in part to the syntax.  I memorize a function, apply it, test it, move on then forget it a few days later (the syntax, not the concept).  My question is this.  Should I be spinning my wheels trying to remember everything, or is knowing the concept enough.

I know this has been addressed before but I couldn't find any real definitive real world answers.  Feel free to discuss what methods worked for you when you started out.


答:
No this is a common subsystem of larger applications, I call it Alerts and Notifications. The Event and Subscriber entities you mentioned are a starting point.

Here we have a simple diagram for the core of the system. You have an EventType, which just describes the various events that can be raised by the system. A subscription (which may have hanging off of it various subscription types, e.g. Email, SMS, etc.). When an event is generated, the system looks at that event's type and generates an alert for each subscription.

The tricky part is like you said, how to create a hierarchy of events. Event Type is what is known in the Object Modeling world as a Descriptor. Descriptors have an inherent knowledge of how to generate the type of object they are describing. That is, they act as object factories. We used an ORM trick where we stored the fully qualified name of the Event subclasses in the EventType table for each type. Thus when we had an instance of an EventType, it would return subclass of the Event via Reflection.

Most O/RMs support mapping a hierarchy of classes to a database (at least in the .NET world).

There is a lot more that could be said about implementing an alert and notification system. But I'll leave the discussion open for you to ask any follow-up questions.

Title: How do you handle objects that need custom behavior, and need to exist as an entity in the database?

Body:
For a simple example, assume your application sends out notifications to users when various events happen.  So in the database I might have the following tables:

```<code>TABLE Event
    EventId uniqueidentifier
    EventName varchar

TABLE User
    UserId uniqueidentifier
    Name varchar

TABLE EventSubscription
    EventUserId
    EventId
    UserId
</code>```

The events themselves are generated by the program.  So there are hard-coded points in the application where an event instance is generated, and it needs to notify all the subscribed users.

So, the application itself doesn't edit the Event table, except during initial installation, and during an update where a new Event might be created.

At some point, when an event is generated, the application needs to lookup the Event and get a list of Users.  What's the best way to link the event in the source code to the event in the database?

Option 1:

Store the EventName in the program as a fixed constant, and look it up by name.

Option 2:

Store the EventId in the program as a static Guid, and look it up by ID.

Extra Credit

In other similar circumstances I may want to include custom behavior with the event type.  That is, I'll want subclasses of my Event entity class with different behaviors, and when I lookup an event, I want it to return an instance of my subclass.

For instance:

class Event
{
    public Guid Id { get;  }
    public Guid EventName { get;  }
    public ReadOnlyCollection<EventSubscription> EventSubscriptions { get; }
    public void NotifySubscribers()
    {
        foreach(var eventSubscription in EventSubscriptions)
        {
            eventSubscription.Notify();
        }
        this.OnSubscribersNotified();
    }
    public virtual void OnSubscribersNotified() {}
}

class WakingEvent : Event
{
    private readonly IWaker waker;
    public WakingEvent(IWaker waker)
    {
        if(waker == null) throw new ArgumentNullException("waker");
        this.waker = waker;
    }

    public override void OnSubscribersNotified()
    {
        this.waker.Wake();
        base.OnSubscribersNotified();
    }
}
```

<p>So, that means I need to map <code>WakingEvent</code> to whatever key I'm using to look it up in the database.  Let's say that's the <code>EventId</code>.  Where do I store this relationship?  Does it go in the event repository class?  Should the <code>WakingEvent</code> know declare its own ID in a static member or method?</p>

<p>...and then, is this all backwards?  If all events have a subclass, then instead of retrieving events by ID, should I be asking my repository for the <code>WakingEvent</code> like this:</p>

<pre class="lang-cs prettyprint-override"><code>public T GetEvent<T>() where T : Event
{
    ... // what goes here?
}
</code>```

I can't be the first one to tackle this.  What's the best practice?


答:
I want to dissent with some of the other posters. The concepts are most important, but I question your grasp of the concept if you can't even remember the syntax.

Beyond that, you'll run into issues as a programmer if every few days you're looking up syntax details rather than getting things done. Retaining syntax is a matter of practice and usage. So is program design skill, debugging skill, and tons of other things programmers need.

So while you don't need to worry so much about the syntax, you should maybe worry that if you're not retaining the syntax you've learned then maybe you're not spending enough time actually writing code to properly learn the other things that do matter. You should maybe worry that looking up syntax isn't the best use of your time.

Title: Syntax Memorization


问:
To write or not to write: Frameworks
Today some friends and I started discussing frameworks..

Some of us strongly believe that in 99.9% of cases, writing a new framework is a bad idea. We believe that probably some of the millions of frameworks out there should fit our problem, and if not, some hack, API, or configuration should be enough. If not, we think that contributing to some framework, suggest features or something like that should be the best solution. The 0.1% is when none of the frameworks fit to our case.

But, some of us say that it is better to have an "internal corporate framework" (for example), because it's faster to fix issues, creates a 100% fit with the app, because of the "learning" factor (when you improve your skills building a framework), etc.

I think that to go out coding frameworks like there's no tomorrow is not the right way. I've seen a lot of small teams building their own framework just to spread the word: "we built our own framework, we rule, bro". Generally, the framework is crap, without any documentation, and only works for their own applications.

Opinions are opinions, devs are devs, without the intention to start any kind of flame war, I ask:

What do you think about that? What parameters you consider when building a framework? What do you think about all this?

答:
My general rule is, if its a product, or an important part of the product, make it myself where possible.  If its not core functionality, or is acting in support of a business (something only used inhouse), go nuts with the frameworks.

Many of the applications I make are long term investments - 10+ years, possibly - and they are products being sold to customers (thus my responsibility).  So being able to 'quickly' get going using a 3rd party framework isnt as relevant for me as it would be to someone who's making a dozen apps a year. So I'm generally not opposed to diving into the nitty gritty and making my own.  Over the product's life time, a few extra weeks getting a custom framework/component going wont matter much.  But it may mean a lot fewer headaches and fewer brick walls since its designed specifically for the application.

Title: To write or not to write: Frameworks


答:
It seems to me that a framework is a collection of libraries. Once you have a bunch of them and you make sure they have consistent APIs and play nice together you bundle them and call it a framework. But you should be making sure that all your company's libraries have consistent APIs anyway whether you use the F word or not.

Frameworks tend to get written 'accidentally' when someone looks at all they have and say 'hmmm, this bunch of stuff can be useful to others'. That is unless you're a company that ships source, or you've been explicitly asked to write a framework. Doing stuff for the sake of doing stuff is always a bad idea in programming.

Whatever you do, make sure you are not re-inventing the wheel, especially as a square.

Title: To write or not to write: Frameworks

Body:
Today some friends and I started discussing frameworks..

Some of us strongly believe that in 99.9% of cases, writing a new framework is a bad idea. We believe that probably some of the millions of frameworks out there should fit our problem, and if not, some hack, API, or configuration should be enough. If not, we think that contributing to some framework, suggest features or something like that should be the best solution. The 0.1% is when none of the frameworks fit to our case.

But, some of us say that it is better to have an "internal corporate framework" (for example), because it's faster to fix issues, creates a 100% fit with the app, because of the "learning" factor (when you improve your skills building a framework), etc.

I think that to go out coding frameworks like there's no tomorrow is not the right way. I've seen a lot of small teams building their own framework just to spread the word: "we built our own framework, we rule, bro". Generally, the framework is crap, without any documentation, and only works for their own applications.

Opinions are opinions, devs are devs, without the intention to start any kind of flame war, I ask:

What do you think about that? What parameters you consider when building a framework? What do you think about all this?


问:
What is the best approach to solve a factory method problem which has to be an instance?
I have to add new funcionality in a web service legacy project and I'm thinking what is the best approach for a concrete situation.

The web service is simple: It receives a XML file, unmarshalling, generates response's objects, marshalling and finally it sends the response as a XML file. For every XML files received, the web service always responds with the same XML structure.

What I have to do is to generate a different XML file according to the XML received. So I have a controller class which has all marshalling/unmarshalling operations, but this controller class has to be an instance. Depending on XML received I need some marshalling methods or others.

Trying to make few changes on legacy source, what is the best approach? My first approach was to do a factory method pattern with the controller class, but this class has to be an instance.

I want to keep, as far as it goes, this structure:

```<code>classController.doMarshalling();
</code>```

I think this one is a bit smelly:

```<code>if(XMLReceived.isTypeOne())
    classController.doMarshallingOne();
else if(XMLReceived.isTypeTwo())
    classController.doMarshallingTwo();
else if(XMLReceived.isTypeThree())
    classController.doMarshallingThree();
else if ...
</code>```

I hope my question is well understood

答:
Is this not a classic case for generics?</p>

```<code>try
{
    ClassController<typeof(XmlReceived)>.DoMarshalling();
    // OR...
    ClassController.DoMarshalling<typeof(XmlReceived)>();

}
catch (...)
{
    ... handle if XmlReceived is not a supported type
}
</code>```

Body:
Is this not a classic case for generics?

try
{
    ClassController<typeof(XmlReceived)>.DoMarshalling();
    // OR...
    ClassController.DoMarshalling<typeof(XmlReceived)>();

}
catch (...)
{
    ... handle if XmlReceived is not a supported type
}


问:
Finding co-maintainers for open source projects
I have a number of open-source projects that have gotten some significant usage and would like to find co-maintainers so that I am not a bottleneck when it comes to maintenance and support requests and to get other perspectives on how the project should evolve.

Where should I look for co-maintainers, what should I look for in a co-maintainer, and how should I go about bringing them up to speed on the code and maintainer responsibilities?

答:
You could post notification on your projects site about wanting more contributors. If you get a lot of usage but no contributions, one reason could also be that there is difficulty in getting to know the project. Is the project easy to build? Is it easy to get to know the code? Is architecture and conventions of the codebase documented etc.

If your projects are based on Microsoft technologies you could also try posting on Project Openings on CodePlex


问:
DDD: Service or Repository
I am developing an app in DDD manner. And I have a little problem with it.

I have a Fare (airline fare) and FareRepository objects. And at some point I should load additional fare information (from a server, call server api) and setup this information to existing Fare.

I guess that I need to create an Application Service (FareAdditionalInformationService) that will deal with obtaining data from the server and than update existing Fare or put the business logic in Fare object. However, some people said me that it is necessary to use FareRepository for this problem.

I don't know wich place is better for my problem Service or Repository.

UPDATE:

After researching, I came to the conclusion, that the better place for fetching additional Fare information is a service like (AdditionalFareService).

The code would look something like this:

```<code>//create service for fetching fare information
AdditionalFareService service = new AdditionalFareService();
//get a fare by Id
Fare fare = fareRepository.GetById(myFareId);
//Obtain information from service
var fareInformation=service.getAdditionalInformation(fare)
//Add it to the fare.
fare.AddInformation(fareInformation);
//save it to the repository.
fareRepository.Save(fare);
</code>```

答:
You say you're doing this is a DDD manner, right? Then the FareRepository should be concerned with persisting your data (exposing the Fare data as if it were an in memory collection).

If all you have to do is modify some simple properties and save, then using just the repository is fine.

If there is certain business logic that must be considered when updating the Fare classes with the additional information, then that business logic should be in a service.

One of your comments indicated that there are all sorts of 'external' considerations like flight schedules, fuel costs, upgrade, and such to deal with when adding the additional information. This almost mandates that you should have a service coordinate the process.

Title: DDD: Service or Repository


答:
This is a common problem, mapping input to a class that can process it.  One  common solution is to build a map from the input type to the processing class.  To handle input, you determine the input type, use the map to look up the processing class, then instantiate the class and call the desired methods.

In Ruby:

```<code>processorByType = { 'type1' => Type1Processor,
                    'type2' => Type2Processor,
                    ...
}

def handle(input)
    processorByType[input.type].new().process(input, context);
end
</code>```

Title: What is the best approach to solve a factory method problem which has to be an instance?

Body:
I have to add new funcionality in a web service legacy project and I'm thinking what is the best approach for a concrete situation.

The web service is simple: It receives a XML file, unmarshalling, generates response's objects, marshalling and finally it sends the response as a XML file. For every XML files received, the web service always responds with the same XML structure.

What I have to do is to generate a different XML file according to the XML received. So I have a controller class which has all marshalling/unmarshalling operations, but this controller class has to be an instance. Depending on XML received I need some marshalling methods or others.

Trying to make few changes on legacy source, what is the best approach? My first approach was to do a factory method pattern with the controller class, but this class has to be an instance.

I want to keep, as far as it goes, this structure:

```<code>classController.doMarshalling();
</code>```

I think this one is a bit smelly:

```<code>if(XMLReceived.isTypeOne())
    classController.doMarshallingOne();
else if(XMLReceived.isTypeTwo())
    classController.doMarshallingTwo();
else if(XMLReceived.isTypeThree())
    classController.doMarshallingThree();
else if ...
</code>```

I hope my question is well understood

Body:
This is a common problem, mapping input to a class that can process it.  One  common solution is to build a map from the input type to the processing class.  To handle input, you determine the input type, use the map to look up the processing class, then instantiate the class and call the desired methods.

In Ruby:

processorByType = { 'type1' => Type1Processor,
                    'type2' => Type2Processor,
                    ...
}

def handle(input)
    processorByType[input.type].new().process(input, context);
end


问:
Is having 'Util' classes a cause for concern?
I sometimes create 'Util' classes which primarily serve to hold methods and values that don't really seem to belong elsewhere.  But every time I create one of these classes, I think "uh-oh, I'm gonna regret this later ...", because I read somewhere that it's bad.

But on the other hand, there seem to be two compelling (at least for me) cases for them:

implementation secrets that are used in multiple classes within a package

providing useful functionality to augment a class, without cluttering its interface

Am I on the way to destruction?  What you say !!  Should I refactor?

答:
It's perfectly acceptable to have util classes, though I prefer the term ClassNameHelper. The .NET BCL even has helper classes in it. The most important thing to remember, is to thoroughly document the classes purpose, as well as each individual helper method, and to make it high quality maintainable code.

And don't get carried away with helper classes.


答:
Util classes are not cohesive and are, generally, bad design because a class has to have a single reason to change (Single Responsability Principle).

Yet, I've seen "util" classes in the very Java API, like: Math, Collections and Arrays.

These are, in fact, utility classes but all their methods are related to a single theme, one has mathematical operations, one has methods for manipulating collections and the other for manipulating arrays.

Try not no have totally unrelated methods in an utility class. If that is the case, chances are you can as well put them elsewere where they really belong.

If must have util classes then try them to be separated by theme like Java's Math, Collections and Arrays. It, at least, shows some intention of design even when they are just namespaces.

I for one, always avoid utility classes and never have had the need to create one.

Title: Is having 'Util' classes a cause for concern?

Body:
I sometimes create 'Util' classes which primarily serve to hold methods and values that don't really seem to belong elsewhere.  But every time I create one of these classes, I think "uh-oh, I'm gonna regret this later ...", because I read somewhere that it's bad.

But on the other hand, there seem to be two compelling (at least for me) cases for them:

implementation secrets that are used in multiple classes within a package

providing useful functionality to augment a class, without cluttering its interface

Am I on the way to destruction?  What you say !!  Should I refactor?


答:
Modern OO design accepts that not everything is an object. Some things are behaviors, or formulae, and some of those don't have state. It's good to model these things as pure functions to get the benefit of that design.

Java and C# (and others) require you make a util class and jump through that hoop to do it. Annoying, but not the end of the world; and not really troublesome from a design perspective.


问:
Alternate method to dependent, nested if statements to check multiple states
Is there an easier way to process multiple true/false states than using nested if statements? I think there is, and it would be to create a sequence of states, and then use a function like when to determine if all states were true, and drop out if not. I am asking the question to make sure there is not a preferred Clojure way to do this.

Here is the background of my problem:

I have an application that depends on quite a few input files. The application depends on .csv data reports; column headers for each report (.csv files also), so each sequence in the sequence of sequences can be zipped together with its columns for the purposes of creating a smaller sequence; and column files for output data.

I use the following functions to find out if a file is present:

```<code>(defn kind [filename]
  (let [f (File. filename)]
    (cond
      (.isFile f)      "file"
      (.isDirectory f) "directory"
      (.exists f)      "other"
      :else            "(cannot be found)" )))

(defn look-for
  [filename expected-type]
    (let [find-status (kind-stat filename expected-type)]
      find-status))
</code>```

And here are the first few lines of a multiple if which looks ugly and is hard to maintain:

```<code>(defn extract-re-values
  "Plain old-fashioned sub-routine to process real-estate values / 3rd Q re bills extract."
  [opts]
  (if (= (utl/look-for (:ifm1 opts) "f") 0)             ; got re columns?
    (if (= (utl/look-for (:ifn1 opts) "f") 0)           ; got re data?
      (if (= (utl/look-for (:ifm3 opts) "f") 0)         ; got re values output columns?
        (if (= (utl/look-for (:ifm4 opts) "f") 0)       ; got re_mixed_use_ratio columns?
          (let [re-in-col-nams  (first (utl/fetch-csv-data (:ifm1 opts)))
                re-in-data      (utl/fetch-csv-data (:ifn1 opts))
                re-val-cols-out (first (utl/fetch-csv-data (:ifm3 opts)))
                mu-val-cols-out (first (utl/fetch-csv-data (:ifm4 opts)))
                chk-results     (utl/chk-seq-len re-in-col-nams (first re-in-data) re-rec-count)]
</code>```

I am not looking for a discussion of the best way, but what is in Clojure that facilitates solving a problem like this.

答:
Monads is the answer to this, the Maybe monad to be precise.

There is at least one Clojure library for monads.

Monads have a reputation for being difficult to learn, but they're definitely worth it (and not that bad).

You might check some Haskell tutorials on monads too, as they're a bigger part of Haskell than Clojure.


问:
Is it my responsibility to code for errors on a completely separate website and domain when redirecting or doing a single sign on?
If my application is responsible for redirecting/doing a single sign on to a destination managed by a third party, in general, where should I draw the line for error handling during this process? If an error happens on the other application's end, is it reasonable for my stakeholder to expect the application I am working with to share responsibility for handling these scenarios?

Notes:

I am going to keep solutions limited to those that entail only one
request--I am familiar with the "do an xmlhttprequest and see how
that fares before doing anything else" approach.

I am speaking in
terms of an enterprise-level application with fairly decent customer
traffic.

答:
In my experience, customers are only happy when the entire solution works. Not that it partially works because of some 3rd-party bug. A fair portion of my working life is working around bugs  - in other systems, in the code libraries and frameworks I employ, inconsistent data, the client's own systems.

You can stop working around bugs when the customer is happy with the solution I think. :-)


问:
How do you safely work around broken code?
Once in a while, a co-worker will check-in bad code which blocks my application from initializing properly.

To get around this problem quickly, I comment out the offending code. I then forget to uncomment the offending code at the time of my check-in, so I want to prevent this from happening again.

Do you have any suggestions on how to:

Disable bad code that stop you from working

Prevent yourself from checking in unwanted changes?

I'm currently using Visual Studio as my IDE and TFS as my source code repo.

答:
Taking all of the other advice about process and code quality into account, if you're going to comment out broken code, put a big, blinking sign on it.

```<code>// FIXME: Commented out due to broken build
</code>```

Then, before checkin, search for FIXME and undo those changes.

Body:
Taking all of the other advice about process and code quality into account, if you're going to comment out broken code, put a big, blinking sign on it.

// FIXME: Commented out due to broken build

Then, before checkin, search for FIXME and undo those changes.


问:
Model-View-Controller (MVC) Which component handles save/load operations?
In a traditional MVC application, which component (model, view, or controller) is responsible for reading/writing the model to/from disk?</p>

答: The Model is generally responisble to reading from/writing to the file system or database.</p>


答:
I'm on the opposite side of the spectrum from GrandmasterB. To me, this is a buy versus build question.

From my perspective, my time and effort can be represented by a cost. The question then becomes, when it there sufficient return on investment to build a framework? (If I'm working for a client, I think about these questions from the client's perspective.)

Here are the questions I ask myself:

Does the framework already exist?

If I build this framework, is this something I want to be known for? In other words, is this framework a differentiator for me?

Oftentimes, I find the answer to the second question is no. I'm working for a healthcare company now. They don't have a desire to be known as the developer of a best-of-breed scheduling engine. I should outsource the development and maintenance of that framework.

However, if we're talking about a pricing engine, that's the company's bread and butter, so I should definitely focus my energy on making a superb engine.

Title: To write or not to write: Frameworks


问:
Generic Handler vs Direct Reference
In a project where I'm working on the data access layer I'm trying to make a decision how to send data and objects to the next layer (and programmer). Is it better to tell him to

reference my dll, OR

should I build a generic handler and let him take the objects from there (i.e. json format)

If I understand correctly, In case of 2. he would have to handle the objects on his own, whereas in case 1. he will have the entities I've built.

Note: It is very probable that other people would need to take the same data, though, we're not up to that yet. Same question here - should I make it into a webservice, or have them access the handler?

答:
The answer is "it depends".

If you are building a tightly coupled system where your team has full control of the various layers, then you're probably better off having him reference your DLL.  This will usually offer the best performance and as you say, he will be able to reuse the entities you have created.

You mention that other people may need to use the same data.  This is where a service oriented approach could provide dividends especially if they will be making calls from servers you don't control or where it would be difficult for them to get copies of your binaries.

Finally, there are cases where you might consider doing both.  Based on the language and frameworks you are using, it might be pretty easy to provide direct DLL binding to those on your own team while also supporting an API (JSON or whatever) for external callers.

Title: Generic Handler vs Direct Reference


答:
It's hard to offer concrete advice without knowing more about your ecosystem.

An approach similar to Bryan's that I've seen work was in a WCF solution. There, we published a DLL that defined serialized data objects (POCOs) that our service code also  consumed.

Other applications could also import that DLL and use our objects. In the case of non-.NET service consumers, those teams implemented their own serialization objects based off the WSDL.

Title: Generic Handler vs Direct Reference

Body:
In a project where I'm working on the data access layer I'm trying to make a decision how to send data and objects to the next layer (and programmer). Is it better to tell him to

reference my dll, OR

should I build a generic handler and let him take the objects from there (i.e. json format)

If I understand correctly, In case of 2. he would have to handle the objects on his own, whereas in case 1. he will have the entities I've built.

Note: It is very probable that other people would need to take the same data, though, we're not up to that yet. Same question here - should I make it into a webservice, or have them access the handler?


答:
Never say "Never"

I don't think it's necessarily bad, it's only bad if you do it badly and abuse it.

We All Need Tools and Utilities

For starters, we all use some libraries that are sometimes deemed as almost ubiquitous and must-haves. For instance, in the Java world, Google Guava or some of Apache Commons (Apache Commons Lang, Apache Commons Collections, etc...).

So there clearly is a need for these.

Avoid Hard-Word, Duplication, and Introducing Bugs

If you think about these are pretty much just a very big bunch of these Util classes you describe, except someone went through great lengths to get them (relatively) right, and they've been time-tested and heavily eye-balled by others.

So I'd say the first rule of thumb when feeling the itch to write a Util class is to check that Util class actually doesn't already exist.

The only counter-argument I've seen for that is when you want to limit your dependencies because:

you want to limit the memory footprint of your dependencies,

or you want to tightly control what developers are allowed to use (happens in obsessive large teams, or when a particular framework is known for having the odd super-crappy class to absolutely avoid somewhere).

But both of these can be tackled by re-packaging the lib using ProGuard or an equivalent, or taking it apart yourself (for Maven users, the maven-shade-plugin offers some filtering patterns to integrate this as part of your build).

So, if it's in a lib and matches your use case, and no benchmarks tells you otherwise, use it. If it varies a bit from what you, extend it (if possible) or extend it, or in the last resort re-write it.

Naming Conventions

However, so far in this answer I called them Utils like you. Don't name them that.

Give them meaningful names. Take Google Guava as a (very, very) good example of what to do, and just imagine that the com.google.guava namespace is actually your util root.

Call your package util, at worst, but not the classes. If deals with String objects and manipulation of string constructs, call it Strings, not StringUtils (sorry, Apache Commons Lang - I still like and use you!). If it does something specific, choose a specific class name (like Splitter or Joiner).

Unit-Test

If you have to resort to writing these utilities, make sure to unit-test them. The good thing about utilities is that they usually are rather self-contained components, which take specific inputs and return specific outputs. That's the concept. So there's no excuse to not unit-test them.

Also, unit-testing will allow you to define and document their API's contract. If tests break, either you changed something the wrong way, or it means you are trying to change your API's contract (or that your original tests were crap - learn from it, and don't do it again).

API Design

The design decision's you'll take for these APIs will follow you a long-time, possibly. So, while not spending hours on writing a Splitter-clone, do be careful about how you approach the issue.

Ask yourself a few questions:

Does your utility method warrant a class on its own, or is a static method good enough, if it makes sense for it to be part of a group of similarly useful methods?

Do you need factory methods to create objects and make your APIs more readable?

Speaking of readability, do you need a Fluent API, builders, etc...?

You want these utils to cover a large breadth of use-cases, to be robust, stable, well-documented, following the principle of least surprise, and to be self-contained. Ideally, each sub-package of your utils, or your whole util package at least, shall be exportable to a bundle for easy re-use.

As usual, learn from giants here:

Sift through these, then analyze and compare, and go back to them often to do it again (note that I am not making any judgment about whether these are absolutely or partially good or bad, the emphasis is on the analyze and compare bit):

Java's util package (which contains the Collections library) and its .Net equivalent,

Google Guava and Apache Commons,

C++'s STL and Boost,

Scala's collection library and scalaz,

and go Back to Basics and have a look at the goo ol' lib C.

Watch Josh Bloch's How to Design a Good API and Why it Matters (slides).

Read and watch some additional Bloch material:

Effective Java (Bloch, 2008),

Java Puzzlers (Bloch, Gafter, 2005),

Creating Java Objects.

Read API Design Matters.

Yes, many of these have an emphasis on collections and data-structures, but don't tell me that's not where or what for you're usually likely to implement most of your utils, directly or indirectly.


答:
I try to get the most miles from available frameworks and tools on any new project.  After the project has evolved, maybe burned in for a year or two, then replacing the parts of the framework that cause the most pain is a reasonable choice.  Unless your business plan centers around creating a new framework, I wouldn't plan to write your own.

When a piece of technology really fails, I keep a list of specific complaints and ideas for how it should be redesigned to work better.  In the short term, this "manifesto" gives me an outlet for my frustrations while still using the existing framework.  In the medium term, it helps me identify the worst pain points so that I don't waste energy fixing minor issues.  In the long term, the manifesto can become a design for a partial or complete replacement, or a feature list for choosing a new framework.

Title: To write or not to write: Frameworks


问:
Architecture advice for converting biz app from old school to new school?
I've got a WinForms business application that evolved over the past few years.  It's forms over data with a number custom UI experiences taylored to the business, so I don't think it's a candidate to port to something like SharePoint or re-write in LightSwitch (at least not without significant investment).

When I started it in 2009 I was new to this type of development (coming from more low level programming and my RDBMS knowledge was just slightly greater than what I got from school).

Thus, when I was confronted with a business model that operates on a strict monthly accounting cycle, I made the unfortunate decision to create a separate database for each accounting period.

Also, when I started I knew DataSets, then I learned Linq2Sql, then I learned EntityFramework.  The screens are a mix and match of those.

Now, after a few years developing this thing by myself I've finally got a small team.

Ultimately, I want a web front end (for remote access to more straight up screens with grids of data) and a thick client (for the highly customized interfaces).

My question is: can you offer me some broad strokes architecture advice that will help me formulate a battle plan to convert over to a single database and lay the foundations for my future goals at the same time?

Here's a screen shot showing how an older screen uses DataSets and a newer screen uses EF (I'm thinking this might make it more real for someone reading the question - I'm willing to add any amount of detail if someone is willing to help).

答:
I think you need an abstraction layer between all the accounting period databases and the applications, so your applications see the databases as a single data source. With such a layer in place, you can consolidate the databases or enhance the applications independently.

What form that abstraction layer takes is up for debate. A couple of options came to me:

a C# library that handles database I/O which both application inherit

a single SQL database that has synonyms or symbolic links to the others


问:
How do I structure code and builds for continuous delivery of multiple applications in a small team?
Background:

3-5 developers supporting (and building new) internal applications for a non-software company.  We use TFS although I don't think that matters much for my question.

I want to be able to develop a deployment pipeline and adopt continuous integration / deployment techniques.

Here's what our source tree looks like right now.  We use a single TFS Team Project.

```<code>$/MAIN/src/
$/MAIN/src/ApplicationA/VSSOlution.sln
$/MAIN/src/ApplicationA/ApplicationAProject1.csproj
$/MAIN/src/ApplicationA/ApplicationAProject2.csproj
$/MAIN/src/ApplicationB/...
$/MAIN/src/ApplicationC
$/MAIN/src/SharedInfrastructureA
$/MAIN/src/SharedInfrastructureB
</code>```

My Goal (a pretty typical promotion pipeline)

When a code change is made to a given application I want to be able to build that application and auto-deploy that change to a DEV server.

I may also need to build dependencies on Shared Infrastructure Components.

I often also have some database scripts or changes as well

If developer testing passes I want to have an manually triggered but automated deploy of that build on a STAGING server where end-users will review new functionality.

Once it's approved by end users I want to a manually triggered auto-deploy to production

Question:

How can I best adopt continuous deployment techniques in a multi-application environment?  A lot of the advice I see is more single-application-specific, how is that best applied to multiple applications?

For step 1, do I simply setup a separate Team Build for each application?

What's the best approach to accomplishing steps 2 and 3 of promoting latest build to new environments?

I've seen this work well with web apps but what about database changes

答:
At a company I worked for a few years ago, we had TFS 2008 and handled deployments through build labels and a WF workflow. When a build label changed, a trigger would deploy the application to an environment. Database changes were handled through change scripts checked into a database project.

If I were doing this from scratch, I'd consider TeamCity or another dedicated CI solution rather than trying to enhance TFS. That having been said, maybe the story with TFS has improved to the point that it's viable to try it with TFS.


答:
I use a two tiered approach.  A "Globals" class in a "util" package (folder).  For something to go into a "Globals" class or "util" package, it must be:

Simple,

Unchanging,

Not dependent on anything else in your application

Examples that pass these tests:

System-wide date and decimal formats

Immutable global data, like EARLIEST_YEAR (that the system supports) or IS_TEST_MODE or some-such truly global and unchanging (while the system is running) value.

Very small helper methods that work around gaps in your language, framework, or toolkit

Here's an example of a very small helper method, completely independent of the rest of the application:

```<code>public static String ordinal(final int i) {
    return (i == 1) ? "1st" :
           (i == 2) ? "2nd" :
           (i == 3) ? "3rd" :
           new StringBuilder().append(i).append("th").toString();
}
</code>```

Looking at this I can see a bug that 21 should be "21st", 22 should be "22nd", etc. but that's beside the point.

If one of those helper methods grows or becomes complicated it should be moved to its own class in the util package.  If two or more helper classes in the util package are related to each other, they should be moved off into their own package.  If a constant or helper method turns out to be related to a specific part of your application, it should be moved there.

You should be able to justify why there's no better place for everything you stick in a Globals class or util package and you should clean it periodically using the above tests.  Otherwise, you are just creating a mess.

Body:
I use a two tiered approach.  A "Globals" class in a "util" package (folder).  For something to go into a "Globals" class or "util" package, it must be:

Simple,

Unchanging,

Not dependent on anything else in your application

Examples that pass these tests:

System-wide date and decimal formats

Immutable global data, like EARLIEST_YEAR (that the system supports) or IS_TEST_MODE or some-such truly global and unchanging (while the system is running) value.

Very small helper methods that work around gaps in your language, framework, or toolkit

Here's an example of a very small helper method, completely independent of the rest of the application:

public static String ordinal(final int i) {
    return (i == 1) ? "1st" :
           (i == 2) ? "2nd" :
           (i == 3) ? "3rd" :
           new StringBuilder().append(i).append("th").toString();
}

Looking at this I can see a bug that 21 should be "21st", 22 should be "22nd", etc. but that's beside the point.

If one of those helper methods grows or becomes complicated it should be moved to its own class in the util package.  If two or more helper classes in the util package are related to each other, they should be moved off into their own package.  If a constant or helper method turns out to be related to a specific part of your application, it should be moved there.

You should be able to justify why there's no better place for everything you stick in a Globals class or util package and you should clean it periodically using the above tests.  Otherwise, you are just creating a mess.


问:
What are the methods to estimate source code value?
I've been working on some project on my free time for the past few months. Recently I've been approached by friends to build a startup, and this source code would be very valuable to us.

As a co-founder, this code could count for something in the company's capital, and be exchanged for shares. But how can you estimate its value? Do you just multiply industry-standard wages by the time I spent on it, or are there other methods?

答:
Ohloh have a wiki article on how they calculate cost for the projects they track. It links to a Wikipedia article that seems thorough enough.

Ohloh wiki

I hope that this helps.


答:
Value it the same you would a "real" product:

What is the replacement cost?:

If there's no comparable product - what would be a cost to hire someone to re-do it from scratch?  What would be the cost of working around some IP/patent contained within?

If there is a comparable product - in what ways is your product better, in what ways is it worse - what is that difference worth?

The "sunk" cost - the time you've already spent and can not "un-spend" should be irrelevant to your decision.

Even future "costs" are not that relevant to the price/value - things can be worth more than what they cost to build(e.g. Mona Lisa is worth more than labor+paint+frame+canvas+30% margin)

Title: What are the methods to estimate source code value?

Body:
I've been working on some project on my free time for the past few months. Recently I've been approached by friends to build a startup, and this source code would be very valuable to us.

As a co-founder, this code could count for something in the company's capital, and be exchanged for shares. But how can you estimate its value? Do you just multiply industry-standard wages by the time I spent on it, or are there other methods?


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
As Alan Kay said almost 30 years ago, point of view is worth 80 IQ points. Books that changed my point of view:

"Philosophical Investigations" by Ludwig Wittgenstein

Sometimes we think we know, when in fact, we don't know. W. shows how to take a closer look.

"Fact, Fiction, and Forecast" by Nelson Goodman

Here I've learned what the word analytic really means. Also, what the word pragmatic really means.

"Zen and the Art of Motorcycle Maintanance" by Robert M. Pirsig

How can there be things that are better than other things? Why isn't everything the same, quality-wise? IOW, what is it that good movies, good cars, good food and good software have in common, that makes them good?

ContentLicense: CC BY-SA 2.5


问:
Why should most logic be in the monitor objects and not in the thread objects when writing concurrent software in Java?
When I took the Realtime and Concurrent programming course our lecturer told us that when writing concurrent programs in Java and using monitors, most of the logic should be in the monitor and as little as possible in the threads that access it. I never really understood why and I really would like to.

Let me clarify.

In this particular case we had several classes.

```<code>Lift extends Thread
Person extends Thread
LiftView
Monitor, all methods synchronized.
</code>```

This is nothing we came up with, our task was to implement a lift simulation with persons waiting on different floors, and theses were the class skeletons that were given.

Then our lecturer said to implement most of the logic in the monitor (he was talking about class Monitor as THE monitor) and as little as possible in the threads.

Why would he make a statement like that?

答:
He's getting you to do some really elementary multithreading.  Or perhaps you could call it single-threading.  If everything's in the Monitor class, and every method there is synchronized, nothing can get accessed by more than one thread at a time.  This gives up most of the benefits of multithreaded code and is not apt to teach you much.  On the other hand, the program is apt to work, thus building confidence in the students.  It's no doubt a good starting point.

Hard core multithreading means lots of threads accessing the same fields at the same time.  It keeps all the cores on your computer busy and so gets the work done faster.  But it's insanely tricky, generating lots of unsolvable bugs.  I think your lecturer is trying to ease you into it slowly.  (And probably trying to save himself some work helping students whose programs have extremely subtle bugs.  And also let the students finish all their assignments by the end of the semester.)


答:
The COCOMO system has within it a model for estimating the time to write software.  As time is money, you then also get the value of the software from the perspective of "how much would it cost to have someone write it".  The current formulation of this model is the COCOMO II which has a rather nice web tool.

With this web tool, one can go from an estimation of size (you don't have an estimation, you've got actual numbers of how big the code is...) and get the estimated planning, testing, and development costs.

Assuming 20k sloc (source lines of code) and a value of $10k/month for developer (and all other things being nominal) you get an estimated time of 79.3 person months to do it (remember, this is planning, construction and testing) for a value of $793k.

This value should be considered to be the minimum of the worth of the code.  The actual value would be higher because it generates revenue and is the core intellectual property of the potential company.

ContentLicense: CC BY-SA 4.0


答:
Don't confuse your time spent on it for what it's worth. You also had the idea, designed and risked your time in order to built it. This is way beyond the cost of a hired programmer.

As of now, you should own 100% of the startup. It's up to the rest of the potential partners to show what they're worth. I would make those share contingent on producing something as well (sales, marketing, industry contacts, additional coding, etc.).


答:
If you're like me, your job is to provide business value as efficiently as possible, not to debug and tweak pet projects. If there is a widely used framework that does what you need, don't waste your time reinventing the wheel, as the widely accepted framework probably does it better than you can. They've had more time, experience, and resources to develop it.

Over the last 6 months my company recently had me write 2 different applications that do a lot of similar things. Recently I've been asked to write a 3rd similar application, and there's a lot of room for more similar applications in the future. Since no one has developed a framework for the proprietary technology I'm working with, I saw no other option but to develop my own framework. If I don't develop my own framework, I will spend a lot of time repeating myself, and that will be a waste of time and money.

I think this is the key as to whether it's worth it to build your own or use someone else's. If you have to waste a ton of cash over the next few years, or build a framework, then build the framework.

It's very difficult to accurately predict what an ideal framework would look like without having first built something. Harvested solutions are generally better than foundation solutions (thanks for the links caarlos0), because your code is not built on guesses about what the client programmer wants, but actual experience. Read: Emergent Design.

That said, there's only one reason in my mind to build your own framework: if you've done the same work twice and are probably going to do it several more times, and nobody has done the work for you.

Title: To write or not to write: Frameworks


答: Unless you're using multiple else statements, you can just chain the conditions together with an "and". In Clojure, "and" is a macro which turns its arguments into a sequence of nested if statements.</p>

Title: Alternate method to dependent, nested if statements to check multiple states

Body:
Is there an easier way to process multiple true/false states than using nested if statements? I think there is, and it would be to create a sequence of states, and then use a function like when to determine if all states were true, and drop out if not. I am asking the question to make sure there is not a preferred Clojure way to do this.

Here is the background of my problem:

I have an application that depends on quite a few input files. The application depends on .csv data reports; column headers for each report (.csv files also), so each sequence in the sequence of sequences can be zipped together with its columns for the purposes of creating a smaller sequence; and column files for output data.

I use the following functions to find out if a file is present:

```<code>(defn kind [filename]
  (let [f (File. filename)]
    (cond
      (.isFile f)      "file"
      (.isDirectory f) "directory"
      (.exists f)      "other"
      :else            "(cannot be found)" )))

(defn look-for
  [filename expected-type]
    (let [find-status (kind-stat filename expected-type)]
      find-status))
</code>```

And here are the first few lines of a multiple if which looks ugly and is hard to maintain:

```<code>(defn extract-re-values
  "Plain old-fashioned sub-routine to process real-estate values / 3rd Q re bills extract."
  [opts]
  (if (= (utl/look-for (:ifm1 opts) "f") 0)             ; got re columns?
    (if (= (utl/look-for (:ifn1 opts) "f") 0)           ; got re data?
      (if (= (utl/look-for (:ifm3 opts) "f") 0)         ; got re values output columns?
        (if (= (utl/look-for (:ifm4 opts) "f") 0)       ; got re_mixed_use_ratio columns?
          (let [re-in-col-nams  (first (utl/fetch-csv-data (:ifm1 opts)))
                re-in-data      (utl/fetch-csv-data (:ifn1 opts))
                re-val-cols-out (first (utl/fetch-csv-data (:ifm3 opts)))
                mu-val-cols-out (first (utl/fetch-csv-data (:ifm4 opts)))
                chk-results     (utl/chk-seq-len re-in-col-nams (first re-in-data) re-rec-count)]
</code>```

I am not looking for a discussion of the best way, but what is in Clojure that facilitates solving a problem like this.


问:
How can I explain object-oriented programming to someone who's only coded in Fortran 77?
My mother did her college thesis in Fortran, and now (over a decade later) needs to learn c++ for fluids simulations. She is able to understand all of the procedural programming, but no matter how hard I try to explain objects to her, it doesn't stick. (I do a lot of work with Java, so I know how objects work) I think I might be explaining it in too high-level ways, so it isn't really making sense to someone who's never worked with them at all and grew up in the age of purely procedural programming.

Is there any simple way I can explain them to her that will help her understand?

答:
I would suggest downloading BlueJ, playing with it for 20 minutes then having her play with it for 20 minutes.

The way it visualizes classes, interfaces and inheritence is so obvious and intuitive that it really gives you an instant understanding as you implement something--anything.

It even shows you directly the difference between a class and an object

It won't give any deep insights into OO design patterns, but it will give a fantastic overview of the concepts.


答: If these are friends, why don't you just split the worth of the company evenly? Statistically speaking your startup will fail so it won't matter. And if you are wildly successful, well, you'll still have lots of money so it won't matter either.</p>


问:
ASP.NET MVVM Handling multiple Data Transfer Objects on a single page
I have an asp.net mvc "edit" page which allows the user to make edits to the parent entity, and then also "create" child entities on the same page. Note: I'm making these data transfer objects up.

```<code>public class CustomerViewModel
{
    public int Id { get; set; }
    public Byte[] Timestamp { get; set; }
    public string CustomerName { get; set; }
    public etc..
    public CustomerOrderCreateViewModel CustomerOrderCreateViewModel { get; set; }
}
</code>```

In my view I have two html form's. One for Customer "edit" Http Posts, and the other for CustomerOrder "create" Http Posts. In the view page, I load the CustomerOrder "create" form in using:

```<code><div id="CustomerOrderCreate">
    @Html.Partial("Vendor/_CustomerOrderCreatePartial", Model.CustomerOrderCreateViewModel)
</div>
</code>```

The CustomerOrder html form action posts to a different controller HttpPost ActionResult than the Customer "edit" Action Result.

My concern is this, on the CustomerOrder controller, in the HttpPost ActionResult

```<code>[HttpPost]
public ActionResult Create(CustomerOrderCreateViewModel vm)
{
    if (!ModelState.IsValid)
    {
        return [What Do I Return Here]
    }
    ...[Persist to database code]...
}
</code>```

I don't know what to return if the model state isn't valid. Right now it's not a problem, because jquery unobtrusive validation handles validation on the client. But what if I need more complex validation (ie: the server needs to handle the validation).

答:
Well, it is a problem now because you can't trust jQuery to do your validation for you.  You can't trust anything on the client because it's not really under your control.  You have to validate everything on the server, even if you're doing it client-side just to be slick.

What you call a ViewModel is what I like to call the EditModel.  That is, a flattened representation of the Model that can be in an invalid state.  Your server needs to be able to translate from a ViewModel DTO to the Model and back again, but it also needs to have the validation logic to check the ViewModel before it performs the conversion.

So when you submit the DTO to the server, you always get back another ViewModel.  In the case where it was a success, you get back your new ViewModel with the edits applied, or if it was unsuccessful maybe you get back a ViewModel that has validation errors.  The page has to display those  validation errors.  Those errors have to be in the ViewModel either as fields, or as a collection of validation messages that get displayed in a pop-down or something.


答:
You are not responsible for the error yourself, but most customers would hold you responsible for trying to fix/tpatch the error.

The first thing you should try to do is to notify the other party of the error at their end.

The second thing you might try to do is to to fix the error from your end (to the extent possible).

The minimum you should do when redirecting traffic to the other site is to point out the error at the other end to users. Pylons and flashing lights do this from time to time when there is, say a hole in the road.

If all else fails, you should consider "pulling" your directions, so customers aren't directed to the erroneous site through you.

Title: Is it my responsibility to code for errors on a completely separate website and domain when redirecting or doing a single sign on?

Body:
If my application is responsible for redirecting/doing a single sign on to a destination managed by a third party, in general, where should I draw the line for error handling during this process? If an error happens on the other application's end, is it reasonable for my stakeholder to expect the application I am working with to share responsibility for handling these scenarios?

Notes:

I am going to keep solutions limited to those that entail only one
request--I am familiar with the "do an xmlhttprequest and see how
that fares before doing anything else" approach.

I am speaking in
terms of an enterprise-level application with fairly decent customer
traffic.


问:
Improvements to Joshua Bloch's Builder Design Pattern?
Back in 2007, I read an article about Joshua Blochs take on the "builder pattern" and how it could be modified to improve the overuse of constructors and setters, especially when an object has a large number of properties, most of which are optional. A brief summary of this design pattern is articled here.

I liked the idea, and have been using it since. The problem with it, while it is very clean and nice to use from the client perspective, implementing it can be a pain in the bum! There are so many different places in the object where a single property is reference, and thus creating the object, and adding a new property takes a lot of time.

So...I had an idea. First, an example object in Joshua Bloch's style:

Josh Bloch Style:

```<code>public class OptionsJoshBlochStyle {

    private final String option1;
    private final int option2;
    // ...other options here  <<<<

    public String getOption1() {
        return option1;
    }

    public int getOption2() {
        return option2;
    }

    public static class Builder {

        private String option1;
        private int option2;
        // other options here <<<<<

        public Builder option1(String option1) {
            this.option1 = option1;
            return this;
        }

        public Builder option2(int option2) {
            this.option2 = option2;
            return this;
        }

        public OptionsJoshBlochStyle build() {
            return new OptionsJoshBlochStyle(this);
        }
    }

    private OptionsJoshBlochStyle(Builder builder) {
        this.option1 = builder.option1;
        this.option2 = builder.option2;
        // other options here <<<<<<
    }

    public static void main(String[] args) {
        OptionsJoshBlochStyle optionsVariation1 = new OptionsJoshBlochStyle.Builder().option1("firefox").option2(1).build();
        OptionsJoshBlochStyle optionsVariation2 = new OptionsJoshBlochStyle.Builder().option1("chrome").option2(2).build();
    }
}
</code>```

Now my "improved" version:

```<code>public class Options {

    // note that these are not final
    private String option1;
    private int option2;
    // ...other options here

    public String getOption1() {
        return option1;
    }

    public int getOption2() {
        return option2;
    }

    public static class Builder {

        private final Options options = new Options();

        public Builder option1(String option1) {
            this.options.option1 = option1;
            return this;
        }

        public Builder option2(int option2) {
            this.options.option2 = option2;
            return this;
        }

        public Options build() {
            return options;
        }
    }

    private Options() {
    }

    public static void main(String[] args) {
        Options optionsVariation1 = new Options.Builder().option1("firefox").option2(1).build();
        Options optionsVariation2 = new Options.Builder().option1("chrome").option2(2).build();

    }
}
</code>```

As you can see in my "improved version", there are 2 less places in which we need to add code about any addition properties (or options, in this case)! The only negative that I can see is that the instance variables of the outer class are not able to be final. But, the class is still immutable without this.

Is there really any downside to this improvement in maintainability? There has to be a reason which he repeated the properties within the nested class that I'm not seeing?

答: The builder in Bloch's pattern may be used many times to generate objects that are "mostly" the same.  Additionally, immutable objects (all fields are final and themselves immutable) have thread safety advantages which your changes may defeat.</p>


问:
What did Linus Torvalds mean by his quotation about portability?
In a debate with Andrew Tanenbaum over microkernel vs. monolithic operating system architecture, Linus Torvalds said,

Portability is for people who cannot write new programs.

What did he mean by that?

答:
It means that people who can write good programs don't need things to be portable, because they can work from scratch.

It is less gifted programmers who want to "import" other programs (portability) to the current one.


答:
Many CI systems like teamcity or jenkins can be set up to monitor your version control system and kick off builds when checkins are detected. The sequence of events that is kicked off by the CI system often goes like this:

If the build completes without errors, the unit tests run.

If the unit tests complete without any failures, the build is deployed to staging

If the staging server deploy is successful, integration tests run (at this stage people can connect to the staging server and also make sure the system is working)

If the integration tests all pass, the build is copied to "good build" area

A person can then deploy the "good build" at will

Regarding database changes, during the deployment process a backup of the data could be restored to the staging server and then a database migration process could be kicked off. The integration tests should catch migration problems and alert you that there were problems deploying to staging, which would disallow the copy to the "good builds" area.

Title: How do I structure code and builds for continuous delivery of multiple applications in a small team?

Body:
Background:

3-5 developers supporting (and building new) internal applications for a non-software company.  We use TFS although I don't think that matters much for my question.

I want to be able to develop a deployment pipeline and adopt continuous integration / deployment techniques.

Here's what our source tree looks like right now.  We use a single TFS Team Project.

```<code>$/MAIN/src/
$/MAIN/src/ApplicationA/VSSOlution.sln
$/MAIN/src/ApplicationA/ApplicationAProject1.csproj
$/MAIN/src/ApplicationA/ApplicationAProject2.csproj
$/MAIN/src/ApplicationB/...
$/MAIN/src/ApplicationC
$/MAIN/src/SharedInfrastructureA
$/MAIN/src/SharedInfrastructureB
</code>```

My Goal (a pretty typical promotion pipeline)

When a code change is made to a given application I want to be able to build that application and auto-deploy that change to a DEV server.

I may also need to build dependencies on Shared Infrastructure Components.

I often also have some database scripts or changes as well

If developer testing passes I want to have an manually triggered but automated deploy of that build on a STAGING server where end-users will review new functionality.

Once it's approved by end users I want to a manually triggered auto-deploy to production

Question:

How can I best adopt continuous deployment techniques in a multi-application environment?  A lot of the advice I see is more single-application-specific, how is that best applied to multiple applications?

For step 1, do I simply setup a separate Team Build for each application?

What's the best approach to accomplishing steps 2 and 3 of promoting latest build to new environments?

I've seen this work well with web apps but what about database changes


问:
What did Bill Gosper mean by saying a data structure is just a stupid programming language?
There's a quotation by Ralph William Gosper, Jr that says:

A data structure is just a stupid programming language.

What did he mean by this?  Alas, all I can find in Google about it is relentless copy/pastes of the quotation itself, without any context.

答:
A data structure is a REPRESENTATION of a programming language. But not a particularly "sharp" one.

This can be seen from a "node diagram" like the one in the wiki article below:

http://en.wikipedia.org/wiki/Root_node#Terminology

Nevertheless, a data structure is INCOMPLETE as a programming language, because it lacks syntax and complete thoughts that would be intelligible to a programmer. A data structure's "language" might be compared to a child who said something like, "Me, cold. Get coat."

The "language" is fractured, but can be understood. The child is saying that "s/he is cold, and would like more clothes as covering." The child's utterance is a "stupid" version of the English language, and likewise data structure in relation to a programming language.


问:
DDD: Service or Repository
I am developing an app in DDD manner. And I have a little problem with it.

I have a Fare (airline fare) and FareRepository objects. And at some point I should load additional fare information (from a server, call server api) and setup this information to existing Fare.

I guess that I need to create an Application Service (FareAdditionalInformationService) that will deal with obtaining data from the server and than update existing Fare or put the business logic in Fare object. However, some people said me that it is necessary to use FareRepository for this problem.

I don't know wich place is better for my problem Service or Repository.

UPDATE:

After researching, I came to the conclusion, that the better place for fetching additional Fare information is a service like (AdditionalFareService).

The code would look something like this:

```<code>//create service for fetching fare information
AdditionalFareService service = new AdditionalFareService();
//get a fare by Id
Fare fare = fareRepository.GetById(myFareId);
//Obtain information from service
var fareInformation=service.getAdditionalInformation(fare)
//Add it to the fare.
fare.AddInformation(fareInformation);
//save it to the repository.
fareRepository.Save(fare);
</code>```

答:
Let aside the patterns for a moment, and look for the responsibilities you have to divide across the system.

Get to the server and retrieve Additional Information for fares

Associate the retrieved info with existent Fare object

Update Fare objects with additional info

For sure, the first responsibility has little in common with FareRepository duties (database/orm mapping of Fare objects). Putting them together would harm your system cohesion.

The second one is clear an responsibility to put into Fare objects.

The third one is an responsibility of FareRepository, since it has to handle update/retrieval of Fare objects in any state (with ou without additional information associated). Even if the additional information deserves an specific class.

So, just looking to responsibilities and cohesion, it doesn't make much sense to use the repository to access the server. The service pattern is a good choice to encapsulate the first responsibility.

Regards.

Title: DDD: Service or Repository


答:
Starting Value, Ending Value, Selling Fairness

You may save yourself time and heartache over this negotiation if you consider the code in relation to what will be needed for your MVP (minimum viable product).  If the code is half the MVP, for fairness you need something for it.  If the code is 10%, 5%, or even as little as 1% of the effort, it will matter a lot less.

If you do demand money or greater equity (hmm, that sounds like an oxymoron), be sure you can do a good job selling it from the fairness perspective in a way that can endure through what may be many challenges along the way to selling the product.

Also, consider things symmetrically.  Will your partners also write code and can they or will they catch up to or exceed your contribution?  How much will you pay your partners for their interest in the resulting code if the business ends?  The tone and expectations you set now will in large part set the tone and expectations later.

Software Engineering Economics

I consider Dr. Barry Boehm to be the father of software engineering economics.  Among his accomplishments was to invent COCOMO, to propose the Theory-W method of managing projects, and to create a model of software development models called MBASE.  His models discuss product models that describe what is or has been built (like UML diagrams), process models (like Scrum, waterfall, etc), property models that describe attributes of the product or organization (cost, schedule, dependability) and success models.

Success Model and Potential Exit Strategy

You should certainly be thinking about whether your success is based on something formal like Theory-W or something informal like IKIWISI (I'll know it when I see it).  The success model might also help you set expectations for how much time and effort will go into your start up, what criteria you use for go/no go, needing to pivot, selling or closing the business, and the distribution of assets both in event of success or failure.  My grandfather was pitched some securities years ago that had a name like "Silver Screen Limited Partnership 7" that were essentially funding for a Hollywood movie that began before the movie, then ended after the movie had it run in theaters (this was pre-DVD days).  If I were you, I would make sure my start up was not a lifelong commitment before it started.

A Prototype Is Not a Product

One of the first Boehm papers I read included a diagram that graphically compared a prototype to a product.  It used a square for the prototype and a grid of squares three high and three wide for the product.  Depending on your sense of confidence vs. realism, you might either dismiss this notion or start recollecting past projects where the dimensions of the product were 25 or 81 or 100 times the cost and effort of the prototypes.

Valuing Your Unique Contribution

To value your code in the context of the start up, you should probably also value your role and its uniqueness to the start up.  If you are the developer and your partners are the financial backers or salesmen, you are kind of like the proverbial pig and they are the chickens going into business for a restaurant that serves breakfast.  They risk little until they write a check, and may perhaps work comparatively little until there is something to sell.  If you are each developers, potentially if they have no code to put in the pot at the start, it might turn out to be a very lopsided venture.  To the extent the movie "The Social Network" portrays things correctly, there is a hugely successful start up that had partners who did very little who put in very little effort as the product was being made.

Starting Up with Start Ups

Be really careful how you bind yourself to partners for a start up.  Work up an operating agreement that covers as much of what might happen during the life of the start up as possible.  Consider scoping very narrowly, and following a lean start up model.  Find safe ways to try out team projects.  School is a great way.  Some universities and other sponsors have created things like Rapid Start Up School.  A very widespread method of getting a taste of the what a start up might be like is to participate in a Start Up Weekend.  There are community and commercially sponsored incubators and coworking spaces.  My limited experience occurred at places like Gangplank (I enjoyed their very inexpensive program for Start Up Weekend) and Cohoots.

Use Protection

You should always protect your self legally, financially, and physically.  Criminal and civil liability can happen in connection with a start up.  If the business borrows money or hires someone who cuts their finger off, you could be stuck with some bills that are hard to pay.  You need to use sound accounting procedures and may need some insurance, and you must protect yourself and your partners from finding themselves on a slippery slope.

A Few Cautionary Stories

While it was not a start up, I knew an organization that permitted a person who was out of work and was under financial stresses to be their treasurer.  He co-mingled the funds from ticket sales for a banquet for about five hundred people with his own bank account.  He may not have thought he was stealing, but he definitely used poor judgement.  When it was clear the money was gone, there were ugly problems with the person being prosecuted for embezzlement.  The organization had insurance that permitted the banquet to be held, but if they didn't those 500 ticket buyers would have been left holding the bag.

Another case I know had a casually begun Limited Liability Corporation turn into big hassles.  There was a judgement against one of the partners and when it was hard to collect, attorneys sent a process server to the home of the partner who had forgotten they signed on for the company.  There were claims against the partner and legal responses were required.  After visits to the court and seeking legal advice, the partner took care of it, but these headaches often don't go away until real money comes out of someone's pocket.

Work Diligently, and Do Due Diligence

Team building and finding the proper partners is extremely important.  Larry Page talks about spending a long time looking for partners to found Google.


问:
Does the windows 8 store only support windows RT?
I'm in a project for creating a game engine and eventually a game, and we need ideas on how to get our game out into the internet.

I had an idea with putting it onto the windows 8 store at a low cost(or free) in order to get the word out, but does the windows 8 store only support apps programmed in windows RT?

Our game will be built in C++ / OpenGL / GLEW / Actionscript / GLM / etc.. , so we won't be using any windows RT functionality at all.

答:
No.

From White papers for Windows Store apps (emphasis mine):

This paper addresses various aspects of developing Windows Store apps for Windows RT. The bulk of Windows Store app development practices are the same for both Windows 8 and Windows RT, but in a few scenarios Windows RT and the hardware particular to these PCs may require special consideration.


问:
Finding co-maintainers for open source projects
I have a number of open-source projects that have gotten some significant usage and would like to find co-maintainers so that I am not a bottleneck when it comes to maintenance and support requests and to get other perspectives on how the project should evolve.

Where should I look for co-maintainers, what should I look for in a co-maintainer, and how should I go about bringing them up to speed on the code and maintainer responsibilities?

答:
I think that you should probably start by looking for people to contribute patches to the project(s) first.  That way you get an idea how good they are as coders and whether or not you trust them enough to want them as a co-maintainer.  </p>

<p>Something I've seen discussed on the mailing lists for Debian is the idea of making small, simple, bite-sized tasks, so that people can easily get their feet wet.  The idea is that some programmer who uses your project will stop by the website, see that something simple needs doing and think to themselves, "Hey, I can do that, that's easy."  </p>

Body:
I think that you should probably start by looking for people to contribute patches to the project(s) first.  That way you get an idea how good they are as coders and whether or not you trust them enough to want them as a co-maintainer.

Something I've seen discussed on the mailing lists for Debian is the idea of making small, simple, bite-sized tasks, so that people can easily get their feet wet.  The idea is that some programmer who uses your project will stop by the website, see that something simple needs doing and think to themselves, "Hey, I can do that, that's easy."


答:
I think Jenkins CI should help you to achieve what you want.

You can also manage dependencies between different applications using pre/post build action plugins of Jenkins.

Build Pipeline plugin should help you to manage the pipeline. The latest plugin allows "retry" which should help you to quickly revert back to the previous builds if you want to.

I've not used TFS myself, but looks like Jenkins has TFS plugin available.

About the database migrations, versioning DB should be done, in that way you can deploy a migration scripts along with the deployment.

Jenkins + Build Pipeline has been working well for me for a long time. Those were mainly small/medium complex web applications. I've tried it for small iOS and Android apps too.


问:
Pattern for a class that does only one thing
Let's say I have a procedure that does stuff:

```<code>void doStuff(initalParams) {
    ...
}
</code>```

Now I discover that "doing stuff" is quite a compex operation. The procedure becomes large, I split it up into multiple smaller procedures and soon I realize that having some kind of state would be useful while doing stuff, so that I need to pass less parameters between the small procedures. So, I factor it out into its own class:

```<code>class StuffDoer {
    private someInternalState;

    public Start(initalParams) {
        ...
    }

    // some private helper procedures here
    ...
}
</code>```

And then I call it like this:

```<code>new StuffDoer().Start(initialParams);
</code>```

or like this:

```<code>new StuffDoer(initialParams).Start();
</code>```

And this is what feels wrong. When using the .NET or Java API, I always never call new SomeApiClass().Start(...);, which makes me suspect that I'm doing it wrong. Sure, I could make StuffDoer's constructor private and add a static helper method:

```<code>public static DoStuff(initalParams) {
    new StuffDoer().Start(initialParams);
}
</code>```

But then I'd have a class whose external interface consists of only one static method, which also feels weird.

Hence my question: Is there a well-established pattern for this type of classes that

have only one entry point and

have no "externally recognizable" state, i.e., instance state is only required during execution of that one entry point?

答:
There are several patterns can be found on Martin Fowler's P of EAA catalog;

Transaction Script: Somewhat similar to the approach you mentioned.

Replace method w/ Method object: Look like a good approach too as @anon mentioned.


答:
Yes.

You can advertise in Windows Store, but you need to handle payment, deployment and installation yourself.

Title: Does the windows 8 store only support windows RT?

Body:
I'm in a project for creating a game engine and eventually a game, and we need ideas on how to get our game out into the internet.

I had an idea with putting it onto the windows 8 store at a low cost(or free) in order to get the word out, but does the windows 8 store only support apps programmed in windows RT?

Our game will be built in C++ / OpenGL / GLEW / Actionscript / GLM / etc.. , so we won't be using any windows RT functionality at all.