答:
Since you wrote in your comment that you mainly need the list for a foreach loop, let me suggest an alternative approach. Why not just return an (immutable) IEnumerable instead of a (mutable) List?

```<code>public IEnumerable<IElement> CreateElements()
{
    yield return new Type1();
    foreach (var e in GetType2Elements())
        yield return e;
    foreach (var e in GetType3Elements())
        yield return e;
}
</code>```

Since the IEnumerable created by yield is immutable, the order can never change. However, it would still be possible to do

```<code>foreach (var e in CreateElements())
    e.consume();
</code>```

Note, though, that the behavior changes slightly due to deferred execution:

```<code>var elements = CreateElements();  // Elements have not been created yet!
foreach (var e in elements)       // New Type1 is executed as soon as the first
    e.consume();                  // element is accessed.
</code>```

If you go for stu's wrapper, you could add a custom enumerator as follows:

```<code>public class Wrapper : IEnumerable<IElement>
{
    ....

    public IEnumerator<IElement> GetEnumerator()
    {
        yield return MainObject;
        foreach (Type2 e in SubElements)
            yield return e;
        foreach (Type3 e in OtherElements)
            yield return e;

    }

    // required since IEnumerable<T> inherits non-generic IEnumerable
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
</code>```

This would allow you to do

```<code>foreach (var e in myWrapper)
    e.consume();
</code>```

Since myWrapper never exposes its enumeration as a list, it can never be reordered.

Body:
Since you wrote in your comment that you mainly need the list for a foreach loop, let me suggest an alternative approach. Why not just return an (immutable) IEnumerable instead of a (mutable) List?

public IEnumerable<IElement> CreateElements()
{
    yield return new Type1();
    foreach (var e in GetType2Elements())
        yield return e;
    foreach (var e in GetType3Elements())
        yield return e;
}

Since the IEnumerable created by yield is immutable, the order can never change. However, it would still be possible to do

foreach (var e in CreateElements())
    e.consume();

Note, though, that the behavior changes slightly due to deferred execution:

var elements = CreateElements();  // Elements have not been created yet!
foreach (var e in elements)       // New Type1 is executed as soon as the first
    e.consume();                  // element is accessed.

If you go for stu's wrapper, you could add a custom enumerator as follows:

public class Wrapper : IEnumerable<IElement>
{
    ....

    public IEnumerator<IElement> GetEnumerator()
    {
        yield return MainObject;
        foreach (Type2 e in SubElements)
            yield return e;
        foreach (Type3 e in OtherElements)
            yield return e;

    }

    // required since IEnumerable<T> inherits non-generic IEnumerable
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

This would allow you to do

foreach (var e in myWrapper)
    e.consume();

Since myWrapper never exposes its enumeration as a list, it can never be reordered.


问:
Clang warning flags for Objective-C development
As a C & Objective-C programmer, I'm a bit paranoid with the compiler warning flags.

I usually try to find a complete list of warning flags for the compiler I use, and turn most of them on, unless I have a really good reason not to turn it on.

I personally think this may actually improve coding skills, as well as potential code portability, prevent some issues, as it forces you to be aware of every little detail, potential implementation and architecture issues, and so on...

It's also in my opinion a good every day learning tool, even if you're an experienced programmer.

For the subjective part of this question, I'm interested in hearing other developers (mainly C, Objective-C and C++) about this topic.

Do you actually care about stuff like pedantic warnings, etc? And if yes or no, why?

Now about Objective-C, I recently completely switched to the LLVM toolchain (with Clang), instead of GCC.

On my production code, I usually set this warning flags (explicitly, even if some of them may be covered by -Wall):

-Wall

-Wbad-function-cast

-Wcast-align

-Wconversion

-Wdeclaration-after-statement

-Wdeprecated-implementations

-Wextra

-Wfloat-equal

-Wformat=2

-Wformat-nonliteral

-Wfour-char-constants

-Wimplicit-atomic-properties

-Wmissing-braces

-Wmissing-declarations

-Wmissing-field-initializers

-Wmissing-format-attribute

-Wmissing-noreturn

-Wmissing-prototypes

-Wnested-externs

-Wnewline-eof

-Wold-style-definition

-Woverlength-strings

-Wparentheses

-Wpointer-arith

-Wredundant-decls

-Wreturn-type

-Wsequence-point

-Wshadow

-Wshorten-64-to-32

-Wsign-compare

-Wsign-conversion

-Wstrict-prototypes

-Wstrict-selector-match

-Wswitch

-Wswitch-default

-Wswitch-enum

-Wundeclared-selector

-Wuninitialized

-Wunknown-pragmas

-Wunreachable-code

-Wunused-function

-Wunused-label

-Wunused-parameter

-Wunused-value

-Wunused-variable

-Wwrite-strings

I'm interested in hearing what other developers have to say about this.

For instance, do you think I missed a particular flag for Clang (Objective-C), and why?

Or do you think a particular flag is not useful (or not wanted at all), and why?

EDIT

To clarify the question, note that -Wall only provides a few basic warnings.

They are actually a lot more warning flags, not covered by -Wall, hence the question, and the list I provide.

答: I don't use Clang, but I hope you won't mind having my opinion, too. I also go with the maximum warning level (I assume that's what -Wall means) and with treating warnings as errors (I assume that's what -Werror means) and I only disable those few warnings that don't make much sense. Actually, I am quite annoyed by the fact that certain very useful warnings are not issued by the C# compiler, and one has to run special code analysis tools to see them. I like warnings, because they help me catch little mistakes and bugs in my code. I like them so much, that when a warning is issued for a piece of code that I know is correct, I refactor that piece of code anyway, so that the warning will not be issued, rather than disable the warning, or --even worse-- allow it to appear and ignore it. I think warnings are awesome, and I wish there were more of them.</p>

OwnerDisplayName: Macmade

ContentLicense: CC BY-SA 3.0


问:
Should I use an aggregate root when designing my repository?
I have an entity that is called Master which is composed of a number of Slave entities.

There can only be one Master in my database and I want to query repositories to get the Slave for a given id.

I initially created a SlaveRepository and queried that by id. That seems fine and works and other developers could use my repository.

Then I thought about aggregate roots and created a MasterRepository and returned the Master and then did a loop on that to get the required Slave entity. The problem I felt here is once I expose this to other developers they would have to do the same, so I through about having a method on the MasterRepository called GetSlaveByID(string id) and then I could get the Slave directly (hides the loop functionality).

Now, should my repository return a Slave even though it is called a MasterRepository?
And more importantly which is the right way to go?

I am in the early stages of trying to apply DDD and TDD so there are probably lots of things I need to think about before deciding which is the correct way I guess.

答:
According to Eric Evans way of Domain Driven Design, you should avoid repositories for non aggregate roots.

He clearly states:

Only Aggregate Roots can be obtained directly with database queries.
  Everything else must be done through traversal.

But it also means, that the repository for the root has to fullfill all requirements. If you need direct access to parts of the aggregate, then an aggregate root object or its repository is responsible for doing so.

So it's perfectly fine to have methods like the following in an aggregate root repository:

```<code>Slave GetSlave(string id)
</code>```

But this signature is a bit dangerous, as identities of children in DDD only make sense in the context of an actual root object and are shallow without the root.

This leads us to a better and more DDD like approach for an implementation in a repository:

```<code>Slave GetSlaveOfMaster(Master master, string slaveId)
// or
Slave GetSlaveOfMaster(Identity masterId, Identity slaveId)
</code>```

But I probably wouldn't even have this method on the repository but on the master entity itself to quickly access the slaves. Possibly even exposed as a hashtable. That's the cleanest approach I can think of.

```<code>//within the Master entity
Slave GetSlave(Identity slaveId);
</code>```

Hold on, this is not the end of the story. If you need to fetch slaves without knowledge of the master, then you should think about your aggregates and your object model. Perhaps you need a second aggregate where the slave is a root and then you should have a custom repository for them. The slave is then not only a child of the master, but a separate hierarchy that probably holds a reference to a master as well. It's important to know whether a slave object can exist without a master at all. If it can, then a separate aggregate is probably the way to go.

Body:
According to Eric Evans way of Domain Driven Design, you should avoid repositories for non aggregate roots.

He clearly states:

Only Aggregate Roots can be obtained directly with database queries.
  Everything else must be done through traversal.

But it also means, that the repository for the root has to fullfill all requirements. If you need direct access to parts of the aggregate, then an aggregate root object or its repository is responsible for doing so.

So it's perfectly fine to have methods like the following in an aggregate root repository:

Slave GetSlave(string id)

But this signature is a bit dangerous, as identities of children in DDD only make sense in the context of an actual root object and are shallow without the root.

This leads us to a better and more DDD like approach for an implementation in a repository:

Slave GetSlaveOfMaster(Master master, string slaveId)
// or
Slave GetSlaveOfMaster(Identity masterId, Identity slaveId)

But I probably wouldn't even have this method on the repository but on the master entity itself to quickly access the slaves. Possibly even exposed as a hashtable. That's the cleanest approach I can think of.

//within the Master entity
Slave GetSlave(Identity slaveId);

Hold on, this is not the end of the story. If you need to fetch slaves without knowledge of the master, then you should think about your aggregates and your object model. Perhaps you need a second aggregate where the slave is a root and then you should have a custom repository for them. The slave is then not only a child of the master, but a separate hierarchy that probably holds a reference to a master as well. It's important to know whether a slave object can exist without a master at all. If it can, then a separate aggregate is probably the way to go.


问:
What are frameworks, stacks, and middleware?
I often see several terms (such as software stack, framework, and middleware)  thrown around a lot, and it would be very helpful for someone to explain the differences between them

I was prompted by my research that I did when reading this question.

I've read their corresponding Wikipedia articles, but I am still uncertain about their differences.

Furthermore, is there a difference between software framework and application framework? What exactly are they?

答:
I tend to think about it like this, but this is just my opinion (not science):

Stack: Is a set of tools serving the purpose of providing a software solution. The tools are meant to be compatible and complementary to one another.

Framework: Is a set of methods, patterns, possibly tools or components that serve the development of only part of the software solution.

Example:

Microsoft ASP.NET Stack: IIS, ASP.NET (Framework), HTML, CSS + MVC Framework (GUI) + Entity Framework (for data persistance)


问:
Understanding the bridge design pattern
I do not understand the "bridge" design pattern at all. I have gone through various web sites, but they haven't helped.

Can anybody help me in understanding this?

答:
In OOP we use polymorphism so an abstraction can have multiple implementations.  Let's look at the following example:

```<code>//trains abstraction
public interface Train
{
    move();
}
public class MonoRail:Train
{
    public override move()
    {
        //use one track;
    }
}
public class Rail:Train
{
    public override move()
    {
        //use two tracks;
    }
}
</code>```

A new requirement introduced and needs to bring in the acceleration perspective of the trains, so change the code as below.

```<code>    public interface Train
    {
        void move();
    }
    public class MonoRail:Train
    {
        public override void move()
        {
            //use one track;
        }
    }
    public class ElectricMonoRail:MonoRail
    {
        public override void move()
        {
            //use electric engine on one track.
        }
    }
    public class DieselMonoRail: MonoRail
    {
        public override void move()
        {
            //use diesel engine on one track.
        }
    }
    public class Rail:Train
    {
        public override void move()
        {
            //use two tracks;
        }
    }
    public class ElectricRail:Rail
    {
        public override void move()
        {
            //use electric engine on two tracks.
        }
    }
    public class DieselRail: Rail
    {
        public override void move()
        {
            //use diesel engine on two tracks.
        }
    }
</code>```

The above code is not maintainable and lacks reusability (assuming we could reuse the acceleration mechanism for the same track platform). The following code applies the bridge pattern and separates the two different abstractions, train transport and acceleration.

```<code>public interface Train
{
    void move(Accelerable engine);
}
public interface Accelerable
{
    public void accelerate();
}
public class MonoRail:Train
{
    public override void move(Accelerable engine)
    {
        //use one track;
        engine.accelerate(); //engine is pluggable (runtime dynamic)
    }
}
public class Rail:Train
{
    public override void move(Accelerable engine)
    {
        //use two tracks;
        engine.accelerate(); //engine is pluggable (runtime dynamic)
    }
}
public class ElectricEngine:Accelerable{/*implementation code for accelerable*/}
public class DieselEngine:Accelerable{/*implementation code for accelerable*/}
</code>```

Title: Understanding the bridge design pattern

Body:
In OOP we use polymorphism so an abstraction can have multiple implementations.  Let's look at the following example:

//trains abstraction
public interface Train
{
    move();
}
public class MonoRail:Train
{
    public override move()
    {
        //use one track;
    }
}
public class Rail:Train
{
    public override move()
    {
        //use two tracks;
    }
}

A new requirement introduced and needs to bring in the acceleration perspective of the trains, so change the code as below.

    public interface Train
    {
        void move();
    }
    public class MonoRail:Train
    {
        public override void move()
        {
            //use one track;
        }
    }
    public class ElectricMonoRail:MonoRail
    {
        public override void move()
        {
            //use electric engine on one track.
        }
    }
    public class DieselMonoRail: MonoRail
    {
        public override void move()
        {
            //use diesel engine on one track.
        }
    }
    public class Rail:Train
    {
        public override void move()
        {
            //use two tracks;
        }
    }
    public class ElectricRail:Rail
    {
        public override void move()
        {
            //use electric engine on two tracks.
        }
    }
    public class DieselRail: Rail
    {
        public override void move()
        {
            //use diesel engine on two tracks.
        }
    }

The above code is not maintainable and lacks reusability (assuming we could reuse the acceleration mechanism for the same track platform). The following code applies the bridge pattern and separates the two different abstractions, train transport and acceleration.

public interface Train
{
    void move(Accelerable engine);
}
public interface Accelerable
{
    public void accelerate();
}
public class MonoRail:Train
{
    public override void move(Accelerable engine)
    {
        //use one track;
        engine.accelerate(); //engine is pluggable (runtime dynamic)
    }
}
public class Rail:Train
{
    public override void move(Accelerable engine)
    {
        //use two tracks;
        engine.accelerate(); //engine is pluggable (runtime dynamic)
    }
}
public class ElectricEngine:Accelerable{/*implementation code for accelerable*/}
public class DieselEngine:Accelerable{/*implementation code for accelerable*/}

ContentLicense: CC BY-SA 4.0


问:
What syntax element do you hate most in a programming language you use frequently?
No matter how much you love a programming language, there are always a few details in it that aren’t quite as nice as they could be.

In this question, I would like to specifically focus on syntax elements. In a programming language that you use frequently (perhaps your favourite programming language, or perhaps the one you are forced to use at work), which syntax element do you find most unreadable, unclear, inconvenient or unpleasant?

答:
& && | || in C

C++ has rectified it to some extend with explicit "and" "or" keywords. Many a bugs and torn hair could have been avoided in C if logical operations and bitwise operations weren't so hard to differentiate.

ContentLicense: CC BY-SA 2.5


问:
How can Continuous Delivery work in practice?
Continuous Delivery sounds good, but my years of software development experience suggest that in practice it can't work.

(Edit: To make it clear, I always have lots of tests running automatically. My question  is about how to get the confidence to deliver on each checkin, which  I understand is the full form of CD. The alternative is not year-long cycles. It is iterations every week (which some might consider still CD if done correctly), two weeks, or month; including an old-fashioned QA at the end of each one, supplementing the automated tests.)

Full test coverage is impossible. You have to put in lots of time -- and time is money -- for every little thing. This is valuable, but the time could be spent  contributing to quality in other ways.

Some things are hard to test automatically. E.g. GUI. Even Selenium won't tell you  if your GUI is wonky. Database access is hard to test without bulky fixtures, and even that won't cover weird corner cases in your data storage. Likewise security and many other things. Only business-layer code is effectively unit-testable.

Even in the business layer, most code out there is not simple functions whose arguments and return values can be easily isolated for test purposes. You can spend lots of time building mock objects, which might not correspond to the real implementations.

Integration/functional tests supplement unit tests, but these take a lot of time to run because they usually involve reinitializing the entire system on each test. (If you don't reinitialize, the test environment is inconsistent.)

Refactoring or any other changes break lots of  tests. You spend lots of time fixing them. If it's a matter of validating meaningful spec changes, that's fine, but often tests break because of meaningless low-level implementation details, not stuff that really provides important information. Often the tweaking is focused on reworking the internals of the test, not on truly checking the functionality that is being tested.

Field reports on bugs cannot easily be matched with the precise micro-version of the code.

答:
To be honest, ALL software is in continuous delivery! The most important thing is to get it out the door! Get your users using it and prioritize the feature requests and bug squashing after that.

"Real artists ship"

-- Steve Jobs.


问:
If your algorithm is correct, does it matter how long it took you to write it?
I recently found out that Facebook had a programming challenge that if completed correctly you automatically get a phone interview.

There is a sample challenge that asks you to write an algorithm that can solve a Tower of Hanoi type problem. Given a number of pegs and discs, an initial and final configuration; Your algorithm must determine the fewest steps possible to get to the final configuration and output the steps.

This sample challenge gives you a 45 minute time limit but allows you to still test your code to see if it passes once your time limit expires.

I did not know of any cute math solution that could solve it, and I didn't want to look for one since I think that would be cheating. So I tried to solve the challenge the best I could on my own.

I was able to make an algorithm that worked and passed. However, it took me over 4 hours to make, much longer than the 45 minute requirement. Since it took me so much longer than the allotted time, I have not attempted the actual challenge.

This got me wondering though, in reality does it really matter that it took me that long? I mean is this a sign that I will not be able to get a job at a place like this (not just Facebook, but Google, Fog Creek, etc.) and need to lower my aspirations, or does the fact that I actually passed on my first attempt even though it took too long be taken as good?

答:
Time maters but don't get the idea that you're stupid if it takes you longer. A lot of people have things "memorized".  They practice applying techniques like recursion so much that it becomes 2cd nature. It's not that their smarter, they just have practiced to the point of 2cd nature and you can too!

Consider the following math problem: 2+2=?

If you immediately knew the answer was 4 it's not because you're smart, but because it's 2cd nature. A child learning to add may be forced to go through the most basic operations of counting to get the answer. But that child may have the potential to surpass the adult.


答:
A software stack generally refers to a set of technologies that work together to support the development, maintenance and operation of software. Stack in this context is a bit of a colloquialism and doesn't have an official definition, but often includes all software that is required for your solution (including the webserver, the OS, any special extensions like memcache etc, as well as developer tools like a tightly coupled platform/language/IDE). Sometimes, the definition might even extend to a hardware stack like Amazon's cloud computing services.

A framework has a more technical definition, and although the term is sometimes used interchangeably with library, a framework is usually distinguished by a property called Inversion of Control. Contrasted with a library, where methods are called by the programmer where needed, using a framework usually means that much of the application functionality is deferred to the framework, allowing the programmer to avoid writing boilerplate code and merely "fill in the blanks", leaving the framework to decide when its appropriate to execute core business logic.

Middleware is a bit more esoteric, but often refers to software or an application interface built to facilitate standard communication between complex systems. You can expect middleware to perform tasks like  parsing, authentication or just provide a standard way to communicate data between systems. Contrasted with a library or framework, middleware is generally not considered a "developer tool" per-say and tends to be pretty tightly integrated into the systems it facilitates.

Title: What are frameworks, stacks, and middleware?

Body:
I often see several terms (such as software stack, framework, and middleware)  thrown around a lot, and it would be very helpful for someone to explain the differences between them

I was prompted by my research that I did when reading this question.

I've read their corresponding Wikipedia articles, but I am still uncertain about their differences.

Furthermore, is there a difference between software framework and application framework? What exactly are they?


问:
Use Case level confusion
I'm working on the use case model of a web design application something like Dreamwaver, I'm little confusing about to which level should I write the use case model.
ex: when the user insert a text should I provide a use cases of:

select font

select size

color

Italic

bold

..

..

..

or it's enough just providing a use case called "modify text properties"?

答:
If it is okay by your customer to provide a use-case called "modify text properties" and list in it all the text properties that should be modifiable, then it should be okay.

The question sparks in the end the question on what the appropriate level of granularity is. But it all depends on what level that you want your use-cases to be in (as a developer or designer) or what level of control that your client has or wants. It is a balance act and there are some things to consider between fine and course use-cases:

Fine (small and plenty)

Easier to time estimate (because they're small in scope)

Related use-cases are harder to keep track of if they're put in different project scopes. Design that you did in previous project/sprint will mandate a redesign when a conflicting change is needed

Pushes the control over implementational design over to BA or who ever writes the use-case

Course (large and few)

Simpler to write

Easier to keep in your head and design

Difficult to time estimate, though the developer can always break it down for himself and time estimate each piece of functionality needed for the use-case to be implemented

The developer can be more flexible with design and implementational details

I found the best is a balanced mix of them, and also let the customer specify (or specify it for them) the features they wants and form use-cases from them. It is okay for use-cases to be course, the customer shouldn't care about in the finer details of how the software works. The only thing they care about is if the feature is working or not.

Now time estimation is important, both for you and your customer/client/project manager, and if the use-case is too large for you to time estimate then you have an option as a developer to break it down for yourself so you can plan, make a top-down design and be able to estimate it better. Think about it; it is easier to estimate several 1 hour changes than one big 8 hour change.

Title: Use Case level confusion


答: It is best to define use case at user goal level (some thing user would achieve after having done the use case), since use cases are meant to capture functional requirements and detailed steps can be elaborate in use case descriptions or use case realizations.  For your case "modify text properties" would enough and different usage scenarios can describes as different use case instances and paths.</p>

Title: Use Case level confusion

Body:
I'm working on the use case model of a web design application something like Dreamwaver, I'm little confusing about to which level should I write the use case model.
ex: when the user insert a text should I provide a use cases of:

select font

select size

color

Italic

bold

..

..

..

or it's enough just providing a use case called "modify text properties"?


问:
How should I design a correct OO design in case of a Business-logic wide operation
EDIT:

Maybe I should ask the question in a different way.
in light of ammoQ's comment, I realize that I've done something like suggested which is kind of a fix and it is fine by me.

But I still want to learn for the future, so that if I develop new code for operations similar to this, I can design it correctly from the start.

So, if I got the following characteristics:

The relevant input is composed from data which is connected to

several different business objects

All the input data is validated and cross-checked

Attempts are made in order to insert the data to the DB

All this is just a single operation from Business side prospective, meaning all of the cross checking and validations are just side effects.

I can't think of any other way but some sort of Operator/Coordinator kind of Object which activates the entire procedure, but then I fall into a Functional-Decomposition kind of code. so is there a better way in doing this?

Original Question

In our system we have many complex operations which involve many validations and DB activities.

One of the main Business functionality could have been designed better.
In short, there were no separation of layers, and the code would only work from the scenario in which it was first designed at, and now there were more scenarios (like requests from an API or from other devices)

So I had to redesign.

I found myself moving all the DB code to objects which acts like Business to DB objects, and I've put all the business logic in an Operator kind of a class, which I've implemented like this:

First, I created an object which will hold all the information needed for the operation let's call it InformationObject.

Then I created an OperatorObject which will take the InformationObject as a parameter and act on it.

The OperatorObject should activate different objects and validate or check for existence or any scenario in which the business logic is compromised and then make the operation according to the information on the InformationObject.

So my question is - Is this kind of implementation correct?

PS, this Operator only works on a single Business-wise Operation.

答:
If you want to restructure you code and expect further enhancements, you would apply domain driven design with N-layered approach.

microsoft architectue

The approach you applied is not object oriented, but procedual style, you use info classes to maintain the data and all the business logics are in another class.  It is fine if you are not stricly following the OOP design, but it is advisible to have both data and behaviour in a single class so that you can elaborate with other OOP features like encapsulation, polymophism etc.


问:
Recommended content for layers
As an expansion from my previous question about using separate projects for seperate layers - Good practice on Visual Studio Solutions

I now wish to know if I am putting the right functionality in the correct layers.

Background

I'm building a WPF application from scratch, that contains business logic and business objects. The database itself sits on another server on the web with access to it, restricted to web API calls using OAuth authentication.

I think the following content should be in these layers. The idea being, you go from layer 1 to layer 4, you are only depending on the layers below you. To prevent circular dependencies.

1. Presentation

WPF View (what the user will see)

WPF ViewModel (how the program responds to user interaction)

No WPF Model, as it will just be the business object

2. Application/Services

Repository (class used by ViewModel to load/save business objects)

Utility classes to assist in saving objects, by selecting the correct API calls.

3. Business layer

Business objects/Entities/DTO (whichever name is preferred)

Factories (Used by the repositories in the creation of business objects)

Other misc business class (i.e. storage of currently logged in user)

4. Infrastructure/Data Access

OAuth client (makes authenticated calls against the web server, used by repository classes)

答:
Nlayer design .net 4.0

Repository interfaces should be in the business layer (or) domain layer so that you can have different persistence implementations against your domain model.  Note that interface belongs to the client not the implementer.

Data Access Logic could be in infrastructure since it deals with technologies such as EF or NHibernate.  Everything related to the technology such as UI framework, DB framework, logging framework implementations could be in the infrastructure layer and you could have Infrastructure.Crosscutting and Infrastructure.Data name spaces.

Title: Recommended content for layers


问:
How is the "Pizza picking problem" solved using dynamic programming techniques?
Winkler's pizza picking problem:

A circular pizza pie of n slices, where slice i has area S_i i.e, the area is different for each pie piece.

Eaters Alice and Bob take turns picking slices, but it is rude to create multiple gaps in the pie (consider it not allowed).

Thus each eater is restricted to taking one of the two slices adjacent to the open region. Alice goes first, and both eaters seek as much pie as possible.

How would a dynamic programming algorithm determine how much pie Alice eats, if both Alice and Bob play perfectly to maximize their pizza consumption?

My understanding:

In a general DP problem, we go forward with finding sub-problems which can be visualized using recursion tree or, more tightly, using a DAG. Here, I'm not finding any lead to find the sub-problems here.

Here, for a given set of S_i s, we need to maximize the area of slices eaten by Alice. This will depend on choosing a permutation of Pizza slices out of (n-1) permutations. Choosing a max area slice out of two options available in every n\2 turns Alice gets, will give us the total area of slice for a permutation. We need to find area of slice for all such permutations. And then the maximum out of these.

Can somebody help me out on how to go forward?

答:
For part of pizza define F(i,j) as maximum how much person that first picks slice can eat.
Slices of part of pizza (i,j) are:

```<code>if i <= j than slices i, i+1, ..., j-1, j
if i > j than slices i, i+1, ..., n-1, n, 1, 2, ..., j-1, j
and we don't define it for whole pizza, abs(i-j) < n-1
</code>```

Define R(i,j) (how much left for second person) as sum(S_x, x in slices(i,j)) - F(i,j).

With:

```<code>F(i,i) = S_i,
F(i,j) = max( S_i + R(i+1,j), S_j + R(i,j-1) ),
</code>```

maximum that Alice can eat is calculated by:

```<code>max( S_i + F(i+1, (i-1) if i > 1 else n) ).
</code>```

OwnerDisplayName: ami

Body:
For part of pizza define F(i,j) as maximum how much person that first picks slice can eat.
Slices of part of pizza (i,j) are:

if i <= j than slices i, i+1, ..., j-1, j
if i > j than slices i, i+1, ..., n-1, n, 1, 2, ..., j-1, j
and we don't define it for whole pizza, abs(i-j) < n-1

Define R(i,j) (how much left for second person) as sum(S_x, x in slices(i,j)) - F(i,j).

With:

F(i,i) = S_i,
F(i,j) = max( S_i + R(i+1,j), S_j + R(i,j-1) ),

maximum that Alice can eat is calculated by:

max( S_i + F(i+1, (i-1) if i > 1 else n) ).

OwnerDisplayName: Ante


答:
Start by considering the slices just placed on a row and you can pick from one of the two ends. In this case supposing it's your turn to chose it's clear that pizzaAmount(slices) is

If there's no pizza left result is 0

If there's only one slice result is that slice

If there are at least two slices then the result is:

(using Python syntax)

```<code>max(slices[0] + sum(slices[1:]) - pizzaAmount(slices[1:]),
    slices[-1] + sum(slices[:-1]) - pizzaAmount(slices[:-1]))
</code>```

in other words you should consider both alternatives and that after taking your slice you will get all the remaining pizza except the result of the recursive call (because your friend will use the same strategy).

You can implement this with DP (or memoizing) because the array is indeed fixed and you can just consider as parameters the first and last slice index.

To solve the original full problem you just need to try all slices as starting slice and chose the one that maximizes the result.

Title: How is the "Pizza picking problem" solved using dynamic programming techniques?

Body:
Winkler's pizza picking problem:

A circular pizza pie of n slices, where slice i has area S_i i.e, the area is different for each pie piece.

Eaters Alice and Bob take turns picking slices, but it is rude to create multiple gaps in the pie (consider it not allowed).

Thus each eater is restricted to taking one of the two slices adjacent to the open region. Alice goes first, and both eaters seek as much pie as possible.

How would a dynamic programming algorithm determine how much pie Alice eats, if both Alice and Bob play perfectly to maximize their pizza consumption?

My understanding:

In a general DP problem, we go forward with finding sub-problems which can be visualized using recursion tree or, more tightly, using a DAG. Here, I'm not finding any lead to find the sub-problems here.

Here, for a given set of S_i s, we need to maximize the area of slices eaten by Alice. This will depend on choosing a permutation of Pizza slices out of (n-1) permutations. Choosing a max area slice out of two options available in every n\2 turns Alice gets, will give us the total area of slice for a permutation. We need to find area of slice for all such permutations. And then the maximum out of these.

Can somebody help me out on how to go forward?

Body:
Start by considering the slices just placed on a row and you can pick from one of the two ends. In this case supposing it's your turn to chose it's clear that pizzaAmount(slices) is

If there's no pizza left result is 0

If there's only one slice result is that slice

If there are at least two slices then the result is:

(using Python syntax)

max(slices[0] + sum(slices[1:]) - pizzaAmount(slices[1:]),
    slices[-1] + sum(slices[:-1]) - pizzaAmount(slices[:-1]))

in other words you should consider both alternatives and that after taking your slice you will get all the remaining pizza except the result of the recursive call (because your friend will use the same strategy).

You can implement this with DP (or memoizing) because the array is indeed fixed and you can just consider as parameters the first and last slice index.

To solve the original full problem you just need to try all slices as starting slice and chose the one that maximizes the result.


问:
Code Smell: Inheritance Abuse
It's been generally accepted in the OO community that one should "favor composition over inheritance". On the other hand, inheritance does provide both polymorphism and a straightforward, terse way of delegating everything to a base class unless explicitly overridden and is therefore extremely convenient and useful.  Delegation can often (though not always) be verbose and brittle.

The most obvious and IMHO surest sign of inheritance abuse is violation of the Liskov Substitution Principle.  What are some other signs that inheritance is The Wrong Tool for the Job even if it seems convenient?

答:
Perhaps most obvious is when the inheriting class ends up with a pile of methods/properties that are never used in the exposed interface. In the worst cases, where the base class has abstract members, you'll find empty (or meaningless) implementations of the abstract members just to 'fill in the blanks' as it were.

More subtly, sometimes you see where in an effort to increase code reuse two things which have similar implementations have been squeezed into one implementation - despite those two things not being related. This tends to increase code coupling and disentangling them when it turns out that the similarity was just a coincidence can be quite painful unless it's spotted early.

Updated with a couple of examples: Although not directly to do with programming as such, I think the best example for this sort of thing is with localisation/internationalisation. In English there's one word for "yes". In other languages can be many, many more in order to agree grammatically with the question. Someone could say, ah let's have a string for "yes" and that's fine for lots of languages. Then they realise that the string "yes" doesn't really correspond to "yes" but actually the concept of "the affirmative answer to this question" - the fact that it's "yes" all the time is a coincidence and the time saved only having one "yes" is completely lost in disentangling the resulting mess.

I've seen one particularly nasty example of this in our code base where what was actually a parent -> child relationship where the parent and child had properties with similar names was modelled with inheritance. No-one noticed this as everything seemed to be working, then the behaviour of the child (actually base) and parent (subclass) needed to go in different directions. As luck would have it, this happened at exactly the wrong time when a deadline was looming - in attempting to tweak the model here and there the complexity (both in terms of logic and code duplication) went through the roof immediately. It was also really difficult to reason about/work with as the code simply didn't relate to how the business thought or talked about the concepts these classes represented. In the end we had to bite the bullet and do some major refactoring which could have been completely avoided if the original guy hadn't decided that a couple of similar sounding properties with values that happened to be the same represented the same concept.

Title: Code Smell: Inheritance Abuse


问:
How come the design process is so different for Web Design and GUI Design?
I had the opportunity to develop applications in several niches:

server back-end,  desktop clients, and recently a small scale website.

Once indulged in the website design I am asking myself and you

how come the UI design process is so different?
Can you point out the differences, and why they originated?

Once, HTML was for marking up text and desktop GUI was the front-end for doing the real job,
but today, why the GUI development process is still so different?

Here are some for a start:

Desktop: Use of explicit layout. (ex: StackPanel in WPF, BorderLayout in Swing)

Web: Layout is a set of CSS properties (ex: height/width, margin/padding, float, display..) that are given to each container  like element.

Desktop: Isolation of GUI components to OO classes, easy reuse.

Web: Components are not reused in html level, they may be reused in dynamic server-side html generation. Only CSS styles may be reused.

Can you name a few more? and why?
Why can't they be similar?

Side note: I have some experience with GWT, it creates a client application that runs in the browser, but why can't I make a webpage (like a blog page) with desktop UI design methods and tools?

答:
Different historical background that now are unifying

I must say the reason is the historical background. Web pages was simple text documents at the beginning, with forms. Then more and more functionallity was added with scripting (JavaScript) and separation of semantics (HTML) and design (CSS).

GUI applications has always been applications with "functionality" as highest priority in contrast to pages with information. Then GUI programs got colors and more design elements to improve the usability and now web applications.

Web design and GUI applications had different strengths that now are unifying into web applications.

Web Design:

Pages with information (lack of programmatic functionality)

Scripting added and separation of semantic elements (HTML) and design (CSS)

Web applications (HTML5 with more form elements, canvas element and web sockets) (side by side with pages with information)

GUI Design:

Black and White applications

Colors and more design elements added

Web applications (HTML5) with easier deployment (no installation) in a networked world.

Todays user interface frameworks

Today with WPF, Android, JavaFX the layout is done similar to as in HTML-files with an XML-document. CSS or similar theme-files may be used for styling. Click-Once and Java Webstart may be used for deployment.

At the same time, web applications use Unobtrusive JavaScript to keep the HTML-document clean from programming code. And more features that only was available in the GUI-world is introduced on the web with HTML5.

So the design process once was very different, but now is getting more and more similar. Microsoft tried with ASP.NET to make web sites in the same way as GUI applications have been done historically. And with WPF and Silverlight they tried again, to do web applications and GUI applications the same way and used the same program (Expression Blend) for both in the design proces.

Adobe Air, Adobe Flex tried also to have the same design process. And now a few frameworks for Smartphones tries to do Smartphone-apps the same way as web applications are done, see Titanium and PhoneGap.

In the end, the reason to why I think web applications will win, is that almost all interesting applications are network applications (client-server) and Mobile code is the easiest way to do and deploy network applications and at the same time be Cross-platform.


答:
HTML started out as a way to present documents. The early web was nothing but a great big filing cabinet with a ton of references (hyperlinks). Gradually structured data and interactivity was added, but the core philosophy remains that of the document. You GET a document or a list of documents in a folder, you POST changes to it, you DELETE it if you don't need it, and you PUT a new document in a folder. That's what RESTful API's are about: the document IS the app. The model is one of encapsulation of data into documents.

Desktop platforms by contrast have an application-centric philosophy. At the heart is not the document, but the behavior. The app pulls in documents, processes them, and pushes them back out. The app is not the document. The focus is on the behavior that operates on the document. The OS vendors delivered API's that encourage you to build apps out of standardized widgets. Since the model is about apps and widgets, the philosophy became one of encapsulation of behavior.

The difference of philosophy at this point is an artifact of history, entrenched by inertia. Neither philosophy is more right in general, the truth is somewhere in the middle. I think the web still has a lot to learn from desktop apps, and vice versa. Web apps still have lousy interactivity, while desktop apps still won't let you think of documents first.

Title: How come the design process is so different for Web Design and GUI Design?

Body:
I had the opportunity to develop applications in several niches:

server back-end,  desktop clients, and recently a small scale website.

Once indulged in the website design I am asking myself and you

how come the UI design process is so different?
Can you point out the differences, and why they originated?

Once, HTML was for marking up text and desktop GUI was the front-end for doing the real job,
but today, why the GUI development process is still so different?

Here are some for a start:

Desktop: Use of explicit layout. (ex: StackPanel in WPF, BorderLayout in Swing)

Web: Layout is a set of CSS properties (ex: height/width, margin/padding, float, display..) that are given to each container  like element.

Desktop: Isolation of GUI components to OO classes, easy reuse.

Web: Components are not reused in html level, they may be reused in dynamic server-side html generation. Only CSS styles may be reused.

Can you name a few more? and why?
Why can't they be similar?

Side note: I have some experience with GWT, it creates a client application that runs in the browser, but why can't I make a webpage (like a blog page) with desktop UI design methods and tools?


答:
Is it really "generally accepted"? It's an idea I've heard a few times, but it's hardly a universally-recognized principle.  As you just pointed out, inheritance and polymorphism are the hallmarks of OOP.  Without them, you've just got procedural programming with goofy syntax.

Composition is a tool for building objects a certain way.  Inheritance is a tool for building objects a different way.  There's nothing wrong with either of them; you just have to know how they both work and when it's appropriate to use each style.

Title: Code Smell: Inheritance Abuse

Body:
It's been generally accepted in the OO community that one should "favor composition over inheritance". On the other hand, inheritance does provide both polymorphism and a straightforward, terse way of delegating everything to a base class unless explicitly overridden and is therefore extremely convenient and useful.  Delegation can often (though not always) be verbose and brittle.

The most obvious and IMHO surest sign of inheritance abuse is violation of the Liskov Substitution Principle.  What are some other signs that inheritance is The Wrong Tool for the Job even if it seems convenient?


问:
An example of a beginner-level Algorithm, intermediate level Algorithm and a complex/expert level Algorithm?
I'd like to get a sense for the range of complexity that algorithms fall into. I think it would be interesting and helpful for those, like me, trying to better understand how algorithms are formulated and how to deconstruct them.

Can you offer a basic algorithm with explanation, an intermediate algorithm with explanation, and maybe an expert level one (with or without) an explanation?

答:
Some more examples

Beginner: Linked list reversal, Mergesort, Sieve of Eratosthenes, Red-black tree algorithms (insertion and removal)

Intermediate: Simplex, Miller-Rabin primality test, Huffman coding, Kruskal's algorithm

Advanced: Viterbi Algorithm, Cooley–Tukey FFT, Simulated Annealing, Hindley–Milner type inference

I tried to find links that had at least some pseudocode and/or good explanation. But the thing about advanced algorithms is that they have many variations. So, you can explain the basic outline of a "genetic algorithm", but there are actually many algorithms that goes by that name. (The same for the FFT; I linked a named variant of it)

This text about numerical integration, for a gaming audience, describes two algorithms for numerical integration: a simpler, straightforward algorithm (the Euler integrator), and a more advanced one (the Runge-Kutta order 4 integrator). It may be a good for seeing "basic vs. advanced". You can use integrators for simulating physics, and the Euler integrator leads to enormous errors, so he recommends RK4 instead. But they are arguably variations of the "same" algorithm: Euler is first-order RK.


问:
What is ethical/unethical while seeking help on the web with programming assignments?
I have used the web and Stack Overflow extensively during the past month or so in creating my final project for my C# class. I have used so much code that I didn't write myself that I feel I am being unethical by not giving proper credit to the people who helped me; or the websites that have provided excellent examples.

Is it unethical to publish work which was created by me, even though its hardest problems were solved by other people? Should I credit these people for helping me with my assignment? Or the web sites which provided examples?

答:
I think you should cite your sources, and bother most about learning more.

Homework is not useful per se, it is a mean for you to learn things. If you didn't learn enough, you are the loser (not your teacher).


答:
Think about it like this: It's a class. The purpose is for you to learn things. It does not really matter whether you learn them from the teacher or from some website, as long as you do learn. And the purpose of the assignment is twofold: having you learn actively (by using your knowledge, which tends to make it stick better) and having you prove that you've learned. The result will not really be "published" in a meaningful way.

Considering all this, there are only ways in which your behaviour would be unethical is if you used all that code without learning from it, and either

The class is graded on a curve and your getting a better grade than you should might cause others to get worse grades than they would otherwise have gotten.

You use the diploma or certificate gained through that class to misrepresent your actual skill level to prospective employers.

Title: What is ethical/unethical while seeking help on the web with programming assignments?

Body:
I have used the web and Stack Overflow extensively during the past month or so in creating my final project for my C# class. I have used so much code that I didn't write myself that I feel I am being unethical by not giving proper credit to the people who helped me; or the websites that have provided excellent examples.

Is it unethical to publish work which was created by me, even though its hardest problems were solved by other people? Should I credit these people for helping me with my assignment? Or the web sites which provided examples?


问:
Does any programming language use variables as they're in maths?
In maths, a variable means you can put any number there, and an equation will still be true:

```<code>root(square(x)) = abs(x)
</code>```

In programming languages, this is not so: a var can change. In Python:

```<code>y = (x**2)**.5
x *= 2
assert y == abs(x)
</code>```

will raise an exception, since x in the last line is not the same.

Are there programming languages that use immutable variables?

答: Purely functional programming languages, such as Haskell, enforce immutable variables. I like to call them identifiers though, instead of variables.</p>


问:
Are there any Web Frameworks for beginners?
I was wandering if there are any frameworks like Google Web Toolkit to create Web Apps? (Apps like Evernote, Spring Pad, Google Docs, etc.).

I am fluent in Java but could learn a new language without much problem. So is there any kind of framework that would allow me to write Web Apps without worrying much about UI element design and client-server communication?

I have heard of one-- Vaadin. Is it something like what I am looking for? If yes, are there any alternatives?

I'm hoping to make a Web App similar to this: Gantter. Mostly the UI and smooth usability.

答:
I do suggest Django framework it is based on Python (learning Python is very easy). This framework is great in separating your webapp code from UI but it does NOT do the UI for you. you may also take a look on Django Book

---- illustrative Example from Django Book----

The MVC Design Pattern

Let’s dive in with a quick example that demonstrates the difference between the previous approach and a Web framework’s approach. Here’s how you might write the previous CGI code using Django. The first thing to note is that that we split it over four Python files (models.py, views.py, urls.py) and an HTML template (latest_books.html):

```<code>    # models.py (the database tables)

    from django.db import models

    class Book(models.Model):
        name = models.CharField(max_length=50)
        pub_date = models.DateField()

    # views.py (the business logic)

    from django.shortcuts import render_to_response
    from models import Book

    def latest_books(request):
        book_list = Book.objects.order_by('-pub_date')[:10]
        return render_to_response('latest_books.html', {'book_list': book_list})

    # urls.py (the URL configuration)

    from django.conf.urls.defaults import *
    import views

    urlpatterns = patterns('',
        (r'^latest/$', views.latest_books),
    )

    # latest_books.html (the template)

    <html><head><title>Books</title></head>
    <body>
    <h1>Books</h1>
    <ul>
    {% for book in book_list %}
    <li>{{ book.name }}</li>
    {% endfor %}
    </ul>
    </body></html>
</code>```

Body:
I do suggest Django framework it is based on Python (learning Python is very easy). This framework is great in separating your webapp code from UI but it does NOT do the UI for you. you may also take a look on Django Book

---- illustrative Example from Django Book----

The MVC Design Pattern

Let’s dive in with a quick example that demonstrates the difference between the previous approach and a Web framework’s approach. Here’s how you might write the previous CGI code using Django. The first thing to note is that that we split it over four Python files (models.py, views.py, urls.py) and an HTML template (latest_books.html):

    # models.py (the database tables)

    from django.db import models

    class Book(models.Model):
        name = models.CharField(max_length=50)
        pub_date = models.DateField()

    # views.py (the business logic)

    from django.shortcuts import render_to_response
    from models import Book

    def latest_books(request):
        book_list = Book.objects.order_by('-pub_date')[:10]
        return render_to_response('latest_books.html', {'book_list': book_list})

    # urls.py (the URL configuration)

    from django.conf.urls.defaults import *
    import views

    urlpatterns = patterns('',
        (r'^latest/$', views.latest_books),
    )

    # latest_books.html (the template)

    <html><head><title>Books</title></head>
    <body>
    <h1>Books</h1>
    <ul>
    {% for book in book_list %}
    <li>{{ book.name }}</li>
    {% endfor %}
    </ul>
    </body></html>


问:
DDD with ORM where should the business logic go?
I have used an MDA (model driven architecture) tool in the past where we modeled via UML and this generated the business entities (our domain model) and the ORM (mapping etc) amongst other things.

A lot of the business code and services working on the domain were part of the model and our repositories were returning the business entities (so it would have been impossible to switch out to another ORM (not that we wanted to)).

However, now I am starting a project and I want to think in terms of DDD.

So far it feels as though I put my business logic in my domain model and via repositories I would work with the ORM (which ever I chose). However, if I wanted to continue to use the MDA tool for the ORM part of the application, the model created here would be very anemic (i.e not contain any business logic). Similarly if I used Entity framework (.net) or NHibernate for my ORM it too would be an anemic model.? I am not sure where you would put the business logic if I just used NHibernate.

Am I correct in thinking this way, in other words with DDD all the business logic in the domain and just use the ORM for persistence via repositories?

答:
so it would have been impossible to switch out to another ORM (not
  that we wanted to)).

That seems wrong. A major advantage of the repository pattern is that you hide the data access logic and that it is easily exchangeable.

So far it feels as though I put my business logic in my domain model
  and via repositories I would work with the ORM (which ever I chose).
  However, if I wanted to continue to use the MDA tool for the ORM part
  of the application, the model created here would be very anemic (i.e
  not contain any business logic). Similarly if I used Entity framework
  (.net) or NHibernate for my ORM it too would be an anemic model.? I am
  not sure where you would put the business logic if I just used
  NHibernate.

An anemic domain model is considered a bad practice by many, for example by Martin Fowler. You should avoid such a design because such a model leads to procedural design techniques rather than a good object oriented design. You then have data classes and manager/processing classes which means you separated state and behaviour. But an object really should be "state and behaviour".

NHibernate does a great job at persistence ignorance. You can hide away the mapping details in XML or with FluentNHibernate and just write plain POCOs. It's very easy to create a rich domain model with NHibernate. I think you can do that with entity framework and the MDA tool, too. As long as this tool produces partial classes you can extend the generated code pretty easily without having to worry that a new generation might destroy your user-written code.

To cut this long story short. When you use NHibernate, nothing, I repeat nothing, stops you from embracing a rich domain model. I recommend using it with FluentNHibernate and mapping by hand. The mapping code takes only 5 to 10 minutes to write. I suppose that the very same is true for entity framework and that its tools at least create partial classes that are easily extensible.

Am I correct in thinking this way, in other words with DDD all the
  business logic in the domain and just use the ORM for persistence via
  repositories?

For the most part you are correct. You should have a rich domain model. Especially when things become more and more complex, it's easier to maintain and extend when you've designed it properly. But do keep in mind that DDD also knows (Domain Layer and Application Layer) Services to implement business logic and Factories to encapsulate creational logic.

I also tend to differentiate business logic into domain logic and actual application business logic. The domain logic is how the domain interacts and behaves while the application logic, which is a completely different layer, encapsulates how the domain is used for the specific use-case/application. Often times I have to update the domain model to support specific use cases and to make it more powerful.


答:
Python is a great language but in my opinion PHP is easier to learn - especially coming from a Java background; which is exactly how it was for me.  They're pretty similar syntactically (in certain areas of course) and it's really easy to setup your environment.

Windows: Just download XAMPP

Mac: Just download MAMP

Linux: you can just yum install httpd/php/mysql-server mysql

That said, there are many great frameworks for PHP. CodeIgniter is supposed to be easy to learn.. It's light and well-documented. I personally use the Zend Framework. CakePHP is also pretty easy to learn.  I would recommend those two for beginners over Zend for the sake of simplicity alone.

A simple example (filename: example.php):

```<code><html>
<head>
    <title>Very Simple Example</title>
</head>
<body>
    <?php
        $headline = 'This is a page headline';
        echo "<h1>{$headline}</h1>";

        $links = array(
            'http://framework.zend.com' => 'Zend',
            'http://codeigniter.com' => 'CodeIgniter',
            'http://cakephp.org' => 'CakePHP'
        );
    ?>

    <ul class="menu">
        <?php foreach ($links as $link => $label): ?>
            <li>
                <a href="<?= $link; ?>"><?= $label; ?></a>
            </li>
        <?php endforeach; ?>
    </ul>
</body>
</html>
</code>```

Title: Are there any Web Frameworks for beginners?

Body:
I was wandering if there are any frameworks like Google Web Toolkit to create Web Apps? (Apps like Evernote, Spring Pad, Google Docs, etc.).

I am fluent in Java but could learn a new language without much problem. So is there any kind of framework that would allow me to write Web Apps without worrying much about UI element design and client-server communication?

I have heard of one-- Vaadin. Is it something like what I am looking for? If yes, are there any alternatives?

I'm hoping to make a Web App similar to this: Gantter. Mostly the UI and smooth usability.

Body:
Python is a great language but in my opinion PHP is easier to learn - especially coming from a Java background; which is exactly how it was for me.  They're pretty similar syntactically (in certain areas of course) and it's really easy to setup your environment.

Windows: Just download XAMPP

Mac: Just download MAMP

Linux: you can just yum install httpd/php/mysql-server mysql

That said, there are many great frameworks for PHP. CodeIgniter is supposed to be easy to learn.. It's light and well-documented. I personally use the Zend Framework. CakePHP is also pretty easy to learn.  I would recommend those two for beginners over Zend for the sake of simplicity alone.

A simple example (filename: example.php):

<html>
<head>
    <title>Very Simple Example</title>
</head>
<body>
    <?php
        $headline = 'This is a page headline';
        echo "<h1>{$headline}</h1>";

        $links = array(
            'http://framework.zend.com' => 'Zend',
            'http://codeigniter.com' => 'CodeIgniter',
            'http://cakephp.org' => 'CakePHP'
        );
    ?>

    <ul class="menu">
        <?php foreach ($links as $link => $label): ?>
            <li>
                <a href="<?= $link; ?>"><?= $label; ?></a>
            </li>
        <?php endforeach; ?>
    </ul>
</body>
</html>


答:
If you're looking for an easy, pre-packaged UI, I would take a look at JQueryMobile.  True, it's designed for mobile devices, but boy is it easy to use and your apps look very slick.

Just have your Java/Django/PHP/whatever app spit out markup that utilizes the special JQuery Mobile html elements and incorporate the framework's wide array of list views, forms, etc. and you're good to go.


问:
What kind of interface should a double container offer?
I want to write a class which offers two sequences of elements to its users. The first one (lets call it "primary") is the main of the class and will be use 80% of the time. The second one (lets call it "secondary") is less important, but still need to be in the same class. The question is: what interface should the class offer to its users?

By looking at STL style, a class with a single sequence of elements should offer begin() and end() functions for traversal and function like insert() and erase() for modifications.

But how should my class offer the second sequence?

For now, I have two ideas:

Expose the two containers to the user (what about the Law of Demeter ?)

Provide the main container with STL interface and expose only the second one.

Here is an example.

```<code>#include <vector>

class A {
    public:
        std::vector<int>&  primary();
        std::vector<char>& secondary();

    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
};

class B {
    public:
        std::vector<int>::iterator begin();
        std::vector<int>::iterator end();
        std::vector<char>& secondary();

    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
};

// Classes implementation
// ...

int main() {

    // --------------------------------------------------
    // Case 1
    // --------------------------------------------------

    A a;

    for(auto it = a.primary().begin(); it != a.primary().end(); ++it) {
        // ...
    }
    for(auto it = a.secondary().begin(); it != a.secondary().end(); ++it) {
        // ...
    }

    // --------------------------------------------------
    // Case 2
    // --------------------------------------------------

    B b;

    for(auto it = b.begin(); it != b.end(); ++it) {
        // ...
    }
    for(auto it = b.secondary().begin(); it != b.secondary().end(); ++it) {
        // ...
    }
}
</code>```

What is the more C++ish way to do that? Is one best than the other or is there an other solution?

Context

This problem came in the context of an exercise in which I am writing a simple database access framework. Here are the classes involved in the question:

table

column

row

field

The table class consists of a sequence of columns and an other sequence of rows. The main use of the table is manipulating (access, add and remove) the rows.

Deeper in the hierarchy, a row is made of column and field so a user can ask the value (field) corresponding to a given column or column name. Each time a column is add/modify/remove from the table, every rows will need to be modify to reflect the modification.

I want the interface to be simple, extensible and combining well with existing code (like STL or Boost).

答:
A proper way would be to implement like this :

```<code>    #include <vector>
    struct A {
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
    };

int main()
{
  A a;
  for ( auto & it : a.m_primary )
  {
  }
  for ( auto & it : a.m_secondary )
  {
  }
}
</code>```

As you can see, you do not need an interface for such classes.

Body:
A proper way would be to implement like this :

    #include <vector>
    struct A {
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
    };

int main()
{
  A a;
  for ( auto & it : a.m_primary )
  {
  }
  for ( auto & it : a.m_secondary )
  {
  }
}

As you can see, you do not need an interface for such classes.


答:
Don't expose your guts, guide visitors :

```<code>class A {
    public:

        // we assume you want read-only versions, if not you can add non-const versions
        template< class Func >
        void for_each_primary( Func f ) const { for_each_value( f, m_primary ); }

        template< class Func >
        void for_each_secodary( Func f ) const { for_each_value( f, m_secondary ); }

    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;

        template< class Func, class Container >
        void for_each_value( Func f, const Container& c )
        {
             for( auto i : c )
                 f( i );
        }
};

int main()
{
    A a;
    a.for_each_primary( [&]( int value )
         { std::cout << "Primary Value : " << value ; } );
    a.for_each_secondary( [&]( int value )
         { std::cout << "Secondary Value : " << value ; } )
}
</code>```

Note that you could use std::function instead of template parameter if you want to put the implementation in a cpp file, making implementation changes less expensive on compilation times in big projects.

Also, I didn't try to compile it now, but I used a lot this pattern in my open-source projects.

This solution is a C++11 enhancement of B I guess.

HOWEVER

This solution have several issues :

It requires C++11 to be effective, because it's efficient for the user of you class ONLY if he can use lambda.

It relies on the fact that the class implementer really know what algorithms precisely are to be available to users. If the user need to do complex manipulations to the numbers, jumping from index to index in an unpredictable way for example, then exposing iterators, a copy of the values OR the values would be better.

In fact, this kind of choice totally depends on what you intend the user to do with this class.

By default I prefer the solution I gave you because it's the most "isolated" one, making sure the class know how it's values can be manipulated by external code. It's a bit like "extensions points".
If it's a map, providing a find function to your class is easy. So I think that's the more sane way to expose data and it's also made available by lambdas.

As said, if you need to make sure the user can manipulate the data as he wish, then providing a copy of the container is the next "isolated" option (maybe with a way to reset the container with the copy after that). If a copy would be expensive, then iterators would be better. If not enough then a reference is acceptable but it's certainly a bad idea.

Now assuming you're using C++11 and don't want to provide algorithms, the most idiomatic way is using iterators this way (only the user code changes) :

```<code>class B {
    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
    public:

        // your code is read-write enabled... make sure it's not const_iterator you want
        // also I'm using decltypt to allow changing container type without having to manually change functions signatures
        decltype(m_primary)::iterator primary_begin() const;
        decltype(m_primary)::iterator primary_end() const;

        decltype(m_secondary)::iterator secondary_begin() const;
        decltype(m_secondary)::iterator secondary_end() const;

};

int main()
{
    B b;

    std::for_each( b.primary_begin(), b.primary_end(), []( int& value ) {
        // ...
    });
    std::for_each( b.secondary_begin(), b.secondary_end(), []( double& value ) {
        // ...
    });

}
</code>```

Title: What kind of interface should a double container offer?

Body:
I want to write a class which offers two sequences of elements to its users. The first one (lets call it "primary") is the main of the class and will be use 80% of the time. The second one (lets call it "secondary") is less important, but still need to be in the same class. The question is: what interface should the class offer to its users?

By looking at STL style, a class with a single sequence of elements should offer begin() and end() functions for traversal and function like insert() and erase() for modifications.

But how should my class offer the second sequence?

For now, I have two ideas:

Expose the two containers to the user (what about the Law of Demeter ?)

Provide the main container with STL interface and expose only the second one.

Here is an example.

```<code>#include <vector>

class A {
    public:
        std::vector<int>&  primary();
        std::vector<char>& secondary();

    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
};

class B {
    public:
        std::vector<int>::iterator begin();
        std::vector<int>::iterator end();
        std::vector<char>& secondary();

    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
};

// Classes implementation
// ...

int main() {

    // --------------------------------------------------
    // Case 1
    // --------------------------------------------------

    A a;

    for(auto it = a.primary().begin(); it != a.primary().end(); ++it) {
        // ...
    }
    for(auto it = a.secondary().begin(); it != a.secondary().end(); ++it) {
        // ...
    }

    // --------------------------------------------------
    // Case 2
    // --------------------------------------------------

    B b;

    for(auto it = b.begin(); it != b.end(); ++it) {
        // ...
    }
    for(auto it = b.secondary().begin(); it != b.secondary().end(); ++it) {
        // ...
    }
}
</code>```

What is the more C++ish way to do that? Is one best than the other or is there an other solution?

Context

This problem came in the context of an exercise in which I am writing a simple database access framework. Here are the classes involved in the question:

table

column

row

field

The table class consists of a sequence of columns and an other sequence of rows. The main use of the table is manipulating (access, add and remove) the rows.

Deeper in the hierarchy, a row is made of column and field so a user can ask the value (field) corresponding to a given column or column name. Each time a column is add/modify/remove from the table, every rows will need to be modify to reflect the modification.

I want the interface to be simple, extensible and combining well with existing code (like STL or Boost).

Body:
Don't expose your guts, guide visitors :

class A {
    public:

        // we assume you want read-only versions, if not you can add non-const versions
        template< class Func >
        void for_each_primary( Func f ) const { for_each_value( f, m_primary ); }

        template< class Func >
        void for_each_secodary( Func f ) const { for_each_value( f, m_secondary ); }

    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;

        template< class Func, class Container >
        void for_each_value( Func f, const Container& c )
        {
             for( auto i : c )
                 f( i );
        }
};

int main()
{
    A a;
    a.for_each_primary( [&]( int value )
         { std::cout << "Primary Value : " << value ; } );
    a.for_each_secondary( [&]( int value )
         { std::cout << "Secondary Value : " << value ; } )
}

Note that you could use std::function instead of template parameter if you want to put the implementation in a cpp file, making implementation changes less expensive on compilation times in big projects.

Also, I didn't try to compile it now, but I used a lot this pattern in my open-source projects.

This solution is a C++11 enhancement of B I guess.

HOWEVER

This solution have several issues :

It requires C++11 to be effective, because it's efficient for the user of you class ONLY if he can use lambda.

It relies on the fact that the class implementer really know what algorithms precisely are to be available to users. If the user need to do complex manipulations to the numbers, jumping from index to index in an unpredictable way for example, then exposing iterators, a copy of the values OR the values would be better.

In fact, this kind of choice totally depends on what you intend the user to do with this class.

By default I prefer the solution I gave you because it's the most "isolated" one, making sure the class know how it's values can be manipulated by external code. It's a bit like "extensions points".
If it's a map, providing a find function to your class is easy. So I think that's the more sane way to expose data and it's also made available by lambdas.

As said, if you need to make sure the user can manipulate the data as he wish, then providing a copy of the container is the next "isolated" option (maybe with a way to reset the container with the copy after that). If a copy would be expensive, then iterators would be better. If not enough then a reference is acceptable but it's certainly a bad idea.

Now assuming you're using C++11 and don't want to provide algorithms, the most idiomatic way is using iterators this way (only the user code changes) :

class B {
    private:
        std::vector<int>  m_primary;
        std::vector<char> m_secondary;
    public:

        // your code is read-write enabled... make sure it's not const_iterator you want
        // also I'm using decltypt to allow changing container type without having to manually change functions signatures
        decltype(m_primary)::iterator primary_begin() const;
        decltype(m_primary)::iterator primary_end() const;

        decltype(m_secondary)::iterator secondary_begin() const;
        decltype(m_secondary)::iterator secondary_end() const;

};

int main()
{
    B b;

    std::for_each( b.primary_begin(), b.primary_end(), []( int& value ) {
        // ...
    });
    std::for_each( b.secondary_begin(), b.secondary_end(), []( double& value ) {
        // ...
    });

}


答:
When inheriting just to get functionality, you're probably abusing inheritance. This leads to the creation of a God Object.

Inheritance itself is not a problem as long as you see a real relation between the classes (like the classic examples, such as Dog extends Animal) and you're not putting methods on the parent class that doesn't make sense on some of it's children (for example, adding a Bark() method in the Animal class wouldn't make any sense in a Fish class that extends Animal).

If a class needs functionality, use composition (perhaps injecting the functionality provider into the constructor?). If a class needs TO BE like other, then use inheritance.

Title: Code Smell: Inheritance Abuse


答:
What I do in my team is to model my object, domain and add my business logic at the same time. I don't use Model Driven Development which would generate a code from a model but prefer the annotation approach.
I mean that at object level inside the class diagram I add ORM stereotypes. This will add persistence annotations directly in the code which are compatible with EJB3/hibernate. THe database creation is done by Hibernate and certainly not by the UML templates.
This is a lot better because if the code change and the added annotations is not exactly what the hibernate specialist then he/she can change it but the model is still good. I can also change my requirements and my domain model is still ok.

Developers can add business logic inside each method and add a comment, I can also model and add constraints. For example the sales should be over 50k if not etc.... I don't need to code it but just write in the model and this information woould be visible to the developer team.
Really cool and flexible UML.

Title: DDD with ORM where should the business logic go?

Body:
I have used an MDA (model driven architecture) tool in the past where we modeled via UML and this generated the business entities (our domain model) and the ORM (mapping etc) amongst other things.

A lot of the business code and services working on the domain were part of the model and our repositories were returning the business entities (so it would have been impossible to switch out to another ORM (not that we wanted to)).

However, now I am starting a project and I want to think in terms of DDD.

So far it feels as though I put my business logic in my domain model and via repositories I would work with the ORM (which ever I chose). However, if I wanted to continue to use the MDA tool for the ORM part of the application, the model created here would be very anemic (i.e not contain any business logic). Similarly if I used Entity framework (.net) or NHibernate for my ORM it too would be an anemic model.? I am not sure where you would put the business logic if I just used NHibernate.

Am I correct in thinking this way, in other words with DDD all the business logic in the domain and just use the ORM for persistence via repositories?


答:
However, if I wanted to continue to use the MDA tool for the ORM part
  of the application, the model created here would be very anemic (i.e
  not contain any business logic).

I don't know which MDA tool you're using, but the ones I've worked with always create partial classes so you're free to complete them with as much business logic as you want.

However, I do feel MDA tools are a little bit less appropriate in a DDD context than ORMs, because code generation often tends to produce classes that are muddled with tool-specific noise instead of the streamlined, clearly expressed domain entities we expect. Actually, what you often get is a mix of domain data, persistence logic, constraint validation logic... and I don't know if there's a way to separate these concerns with most MDA tools.

And of course, you can't touch the generated code except via partial classes, which means you can't eliminate potential anti-DDD behaviour that would be integrated. This is problematic in an approach where you want to enforce strict barriers between Aggregates and tailor the relationships between your entities perfectly. Build time in a continuous integration environment can suffer from the additional code generation step as well.

Apart from that, I think Falcon pretty much said it all -absolutely nothing in ORM or MDA tools prevents you from having rich domain entities.


问:
Should I use an aggregate root when designing my repository?
I have an entity that is called Master which is composed of a number of Slave entities.

There can only be one Master in my database and I want to query repositories to get the Slave for a given id.

I initially created a SlaveRepository and queried that by id. That seems fine and works and other developers could use my repository.

Then I thought about aggregate roots and created a MasterRepository and returned the Master and then did a loop on that to get the required Slave entity. The problem I felt here is once I expose this to other developers they would have to do the same, so I through about having a method on the MasterRepository called GetSlaveByID(string id) and then I could get the Slave directly (hides the loop functionality).

Now, should my repository return a Slave even though it is called a MasterRepository?
And more importantly which is the right way to go?

I am in the early stages of trying to apply DDD and TDD so there are probably lots of things I need to think about before deciding which is the correct way I guess.

答:
In general, within the aggregate boundary there should be only one repository. And - as Falcon said - you might end up with two separate aggregates, master and slave.

However looks like the primary focus in your question is data retrieval, while in DDD it should be behavior. Aggregate boundaries are a consequence of constraints imposed by behavior (things that change together and invariants to be enforced), the internal structure of the aggregate is a consequence of that choice.

For example, if you group things correctly according to the need of change together, there's not so much of a need to call an external Repository. Most of the cases, the needed data for a business operation in the Aggregate should already be within the aggregate boundaries, the need to access different aggregates it's probably a smell of an inconsistent boundary.


答:
Python is a great language to start with, Flask is also a great web framework for people who want to learn the fundamentals of web development, it's called a micro-framework, it only does a few things, unlike other frameworks.

You can use 3rd party libraries, or even your own to provide new functionality.

This is better suited for a beginner since you won't learn too much at once.

Here's a "hello, world!" app in Flask:

```<code>from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()
</code>```

However, if you want to stick to Java, there's Play!, it's easy to learn, and has a decent feature set.

Body:
Python is a great language to start with, Flask is also a great web framework for people who want to learn the fundamentals of web development, it's called a micro-framework, it only does a few things, unlike other frameworks.

You can use 3rd party libraries, or even your own to provide new functionality.

This is better suited for a beginner since you won't learn too much at once.

Here's a "hello, world!" app in Flask:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

However, if you want to stick to Java, there's Play!, it's easy to learn, and has a decent feature set.


答:
The strength of inheritance is reusability. Of interface, data, behavior, collaborations. It's a useful pattern from which to convey attributes to new classes.

The drawback to using inheritance is reusability. The interface, data and behavior are encapsulated and transmitted en masse, making it an all-or-nothing proposition. The problems become especially evident as hierarchies become deeper, as properties which might be useful in the abstract become less so and begin to obscure properties at the local level.

Every class that uses the composition object will have to more-or-less re-implement the same code to interact with it. While this duplication requires some violation of DRY, it affords greater freedom for designers to pick-and-choose those properties of a class most meaningful to their domain. This is particularly advantageous when classes become more specialized.

In general, it should be preferred to create classes via composition, and then converting to inheritance those classes with the bulk of their properties in common, leaving the differences as compositions.

IOW, YAGNI (You Aren't Gonna Need Inheritance).

Title: Code Smell: Inheritance Abuse


答:
Lot of documents about UML and how to write use cases, focuses only the how part. Here is one document that seems to be best answer your question.
Read this : Writing Effective Use Cases. (Write to me if you want a copy) The same author have the book which is an extended form. See the book here.

In essence, as the books puts up, you first need to define the scope of the overall system at different levels. For example, it starts with An Organization X serving its client organization. The use case is defined of the organization at that scale. Further down, now individual functions are then done at (one or more Products) say a client application (that the client application as well as administrators use) will talk to server and so on.

The level of details increases as you go down, but the scope becomes narrow. Understand that the purpose is not to repeat things but to organize things in the form of different levels hierarchy.

This way, you keep refining the scope and go deeper. So when do you stop? Probably the simple answer is: when it is trivial not to write the question. Essentially, (as per the book) you write use cases of each entity separately. - The organization, various systems (or products) being consumed, At some point writing use cases of an entire UI application could be enough; But if you do have a major component which does seems of far more important than use case at that level of is more important; at that level you probably have to write use case at the level of forms/inputs at that level.

EDIT:

Now coming to your question - as i said, it depends on the scope. From the UI (also when you are treating word processor or rich text editor within a very larger system), you expect that UI provides many messages back to core (each formatting command as a simple message). However, from the point of view of the actual model object which implements this - each command is a unique item. Hence, for the back-end object, each command is unique functionality and hence they are unique different use cases.

Title: Use Case level confusion


答:
Take a look at ASP.NET MVC3. If you know Java then picking up C# should not be a problem.

MVC3 in my experience has been the easiest to understand compared to Django and Ruby on Rails. It helps you understand web development without trying to do anything too fancy or over complicate request handling. You have a controller, a model, and a view. That's it. And you are ready to develop. There is tons of documentation and videos that will make learning not only easy but satisfying.

Go get started.


问:
What programming languages and skills are required in addition when building freelance platform with python?
I have a question about compatibility and co-integration of programming languages, databases, frameworks, libraries, different API and more (together referred as “items”).  I have added a list of items that are planned to be used when building freelance platform/marketplaced, but I would like to know if I am missing anything, or if given combination could result in some compatibility issues.

I’ve done a research on mentioned items, but there is still a list of things that are not clear, so I would be grateful to get more information on the topic. Sorry, if I am bad with terminology, codenames, or missing any valuable points to get accurate answer – I will add any additional information, if asked for clarification in any part. Here is basic information to help answer the question:

We are looking to build a freelance platform with a need of:

-   high level of modularity and scalability;

-   autonomous development, which is to be processed by semi/fully-independent task groups;

-   ability to integrate/import a lot of third-party APIs (ie. Facebook connect).

Let’s take oDesk for benchmarking (thus at least such functionality possibilities are needed), where some of them are:

-   Business processes / work-flow (client – freelancer connection, client – consultant connection, etc.);

-   User listing and detailed profiling (portfolios, completed projects, etc.);

-   Semantic search;

-   … (ie. at least full currently existing freelance platforms functionality).

I’ve developed a list of items that will be used in process of building the freelance platform, which is as follows:

Programming language (and framework): PHP (Zend) vs. Python (Django)

Decision criteria: modularity (ease of updating individual modules | existing library of modules | ease of creating new modules) | availability of highly skilled work-force | development time | standardization (ease of autonomous development).

Result was choosing Python v2.X/v3.X over PHP5.X. Decision was based on part of decision criteria (arguments for Python):

Possibility to update/edit certain module in most cases without a need to change other modules;

No huge hassle to create new modules from scratch (or at least does not take more time or resources as compared to the same result in php);

Approach of python developers seems to create more opportunities for autonomous development (person is developing in a way that others can develop their modules (or fragments of modules) separately, or take over the task quite easily from the point where this person ended – ie. updating).

Overall Python seems as a more long-run oriented solution, which does not create any big drawbacks in a short-run.

Database:  MySQL vs. …:

Decision criteria: functionality | popularity | initial costs | overheads

MySQL was chosen over MsSQL, as it seems to have fully sufficient functionality (in free version) and can be upgraded to enterprise version when it will make financial sense in terms of bandwidth overheads over licensing fees.

Business processes: Apache ODE vs. Oracle BPEL vs. …:

Decision rules: python compatibility | modularity | customization | availability of highly skilled work-force

No clear decision here yet. Current front-runner seems to be Apache ODE, but adopting modules from one of python libraries, customizing them and creating new ones seems to be attractive option at the moment as well.

Front-end: HTML4/HTML5 + CSS2/CSS3 + AJAX;

In the beginning there will be web-based UI only, afterwards we will also include desktop and mobile UI.

I’ve listed items that are currently considered in order to develop the platform, please refer to any of the points in decision making if You think that they are flawed, and if I should consider more, or different decision criteria, which could influence which item to pick, etc.

Other things under consideration

1)  Have I picked proper combination of items considering they will be used for developing freelance platform; (1.1) Am I missing any items that will be necessary (ie. programming language / framework / platform);
2)  Is it reasonable to use django framework to save time on development and could it result in some major scalability issues;

(2.1) What libraries should be considered using to acquire as many prebuilt modules for freelance platform as possible;

3)  BPEL (ie. using Apache ODE) can be adopted for a variety of business processes (including client-freelancer connection), but wouldn’t it result in great restrictions of what solutions can we offer; (3.1) Would it be better to consider developing our own modules in python to achieve needed result; (3.2) Or is there any python library that supports BPEL;

4)  Is it possible to connect python with php in terms of using php libraries (example: http://code.google.com/p/php-excel/) when ones are not available in python;(4.1) If yes,  what modules/platforms/solutions are needed for it;
I will update any parts if needed as soon as I get feedback on it. Looking for Your answers. Thanks!

答:
You're putting a lot of thought into this, but at the same time, you are only allowing yourself a narrow corridor.

If you are considering PHP (and I really am not saying you should), then you must consider Symfony, Flow3, CakePHP and Codeigniter.

If you are really interested in "long-run oriented solutions", then you should go for a statically typed language. I suggest Scala with Lift.

If you don't like static typing, then you should add Ruby (Rails, Sinatra), node.js (Express) and CommonLisp (weblocks)

You really should consider alternatives to SQL. There's a number of very scalable document stores, key value stores, graph databases and whatnots, most of which offer great performance and flexibility in the usecases they were designed for. It might turn out that SQL (i.e. MySQL in particular) is the best way to go here, but if you really want to choose between actual alternatives, then you need to look a little further.

Business processes? Really? You may or may not be needing this kind of stuff, but right now this is way too early. Right now, you should focus on the real problems, such as feature design, UX design and the little detail of implementing all that stuff into a reliable, fast solution. The whole point of ESBs is that you can quite easily plug your services in there. You will not gain any advantage over you competitors just by using architecture that is easily available to them.

Put your energy into iterating your features and into having a clean, robust, tested, flexible code base. Don't waste it reading pages of dry technical documentation and wading knee-deep in configuration XMLs. This is something for another time and probably best delegated to someone you hire just for that once you see that your project is headed in the right direction.


问:
Does freelancing require supreme ability on programming?
I can write independent java, python, c, c++ code but I do not know every aspect of them. For example, I don't how to code with database in python/c/c++. I have few experience with GUI programming.

I was aware that most of the jobs isn't just need us to write an simple code. They may need some GUI and you need to upload the programming result to a FTP server via some ftp code with some I-don't-know-the-name plugin/library. I have seen a job of web scrapping by python, and the client wants the program to insert the data into a database immediately after the web scrapping, and delete old data older than 6 month.

A client won't accept a contractor to say "I will need to figure this xyz-technology for sometime before I can tell you whether I can do it". What is worse, is that you find you are incapable of doing his job for whatever the reason, you are screwed.

I am wondering, do you apply for a freelance job if you don't feel like an expert to all the fields/technology listed in the job requirement?

答:
Does freelancing require supreme ability on programming?

Not in my experience. I've met more than one freelancer that couldn't code his way through fizzbuzz.

I am wondering, do you apply for a freelance job if you don't feel like an expert to all the fields/technology listed in the job requirement?

Think of it as a wishlist of the customer - some things are more important than others. If you are competent in most of these you should apply. Worst that will happen is that you will not get the job. Best that will happen is that you will and in the process learn something new.