问:
Understanding Visitor Pattern
I have a hierarchy of classes that represents GUI controls. Something like this:

```<code>Control->ContainerControl->Form
</code>```

I have to implement a series of algoritms that work with objects doing various stuff and I'm thinking that Visitor pattern would be the cleanest solution. Let take for example an algorithm which creates a Xml representaion of a hierarchy of objects. Using 'classic' approach I would do this:

```<code>public abstract class Control
{
    public virtual XmlElement ToXML(XmlDocument document)
    {
        XmlElement xml = document.CreateElement(this.GetType().Name);
        // Create element, fill it with attributes declared with control
        return xml;
    }
}

public abstract class ContainerControl : Control
{
    public override XmlElement ToXML(XmlDocument document)
    {
        XmlElement xml = base.ToXML(document);
        // Use forech to fill XmlElement with child XmlElements
        return xml;
    }
}

public class Form : ContainerControl
{
    public override XmlElement ToXML(XmlDocument document)
    {
        XmlElement xml = base.ToXML(document);
        // Fill remaining elements declared in Form class
        return xml;
    }
}
</code>```

But I'm not sure how to do this with visitor pattern. This is the basic implementation:

```<code>public class ToXmlVisitor : IVisitor
{
    public void Visit(Form form)
    {
    }
}
</code>```

Since even the abstract classes help with implementation I'm not sure how to do that properly in ToXmlVisitor?

The reason that I'm considering Visitor pattern is that some algorithms will need references not available in project where the classes are implemented and there is a number of different algorithms so I'm avoiding large classes.

答:
The visitor pattern is a mechanism to simulate dual binding in programming languages that only support single binding. Unfortunately, that statement might not clarify things a lot, so let me explain with a simple example.

In .NET and C#, the platform you are using, objects can be converted to strings using the ToString() function. What that funtion does, i.e. the code being executed, depends on the type of object you're applying it to (it's a virtual method). What code is executed depends on one thing, the one type of the object, hence the mechanism used is called single binding.

But what if I want to have more than one way to convert an object to a string, for each different kind of object? What if I wanted to have two ways to convert objects to strings, so that the code being executed depends on two things: not only the object to be converted, but also the way in which we want it to be converted?

That could be solved nicely if we had dual binding. But most OO languages, including C#, only support single binding.

The visitor pattern solves the problem, by turning dual binding into two succesive single bindings.

In our example above, it would use a virtual method in the object to convert, that calls a second virtual method in the object implementing the conversion algorithm.

But that implies that the object upon which you want to apply the algorithm needs to collaborate with this: it needs to have support for the visitor pattern baked in.

You seem to be using .NET's Windows Forms classes, which do not have support for the visitor pattern. More specifically, they would need to have a public virtual void Accept(IVisitor) method, which obviously they don't have.

So, what's the alternative? Well, .NET does not only support single binding, it also supports dynamic binding, which is even more peowerful than dual binding.

For more information on how to apply that technique, which will allow you to solve your problem (if I understand it well), take a look at Farewell Visitor.

UPDATE:

To apply the technique to your specific problem, first define your extension method:

```<code>public static XmlDocument ToXml(this Control control)
{
    XmlDocument xml = new XmlDocument();
    XmlElement root = xml.CreateElement(control.GetType().Name);
    xml.AppendChild(root);

    Visit(control, xml, root);

    return xml;
}
</code>```

Create the dynamic dispatcher:

```<code>private static void Visit(Control control, XmlDocument xml, XmlElement root)
{
    dynamic dynamicControl = control; //notice the 'dynamic' type.
                                      //this is the key to dynamic dispatch

    VisitCore(dynamicControl, xml, root);
}
</code>```

Then fill in the specific methods:

```<code>private static void VisitCore(Control control, XmlDocument xml, XmlElement root)
{
    // TODO: specific Control handling
}

private static void VisitCore(ContainerControl control, XmlDocument xml, XmlElement root)
{
    // call the "base" method
    VisitCore(control as Control, xml, root);

    // TODO: specific ContainerControl handling
    // for example:
    foreach (Control child in control.Controls)
    {
        XmlElement element = xml.CreateElement(child.GetType().Name);
        root.AppendChild(element);

        // call the dynamic dispatcher method
        Visit(child, xml, element);
    }
}

private static void VisitCore(Form control, XmlDocument xml, XmlElement root)
{
    // call the "base" method
    VisitCore(control as ContainerControl, xml, root);

    // TODO: specific Form handling
}
</code>```

Title: Understanding Visitor Pattern

Body:
The visitor pattern is a mechanism to simulate dual binding in programming languages that only support single binding. Unfortunately, that statement might not clarify things a lot, so let me explain with a simple example.

In .NET and C#, the platform you are using, objects can be converted to strings using the ToString() function. What that funtion does, i.e. the code being executed, depends on the type of object you're applying it to (it's a virtual method). What code is executed depends on one thing, the one type of the object, hence the mechanism used is called single binding.

But what if I want to have more than one way to convert an object to a string, for each different kind of object? What if I wanted to have two ways to convert objects to strings, so that the code being executed depends on two things: not only the object to be converted, but also the way in which we want it to be converted?

That could be solved nicely if we had dual binding. But most OO languages, including C#, only support single binding.

The visitor pattern solves the problem, by turning dual binding into two succesive single bindings.

In our example above, it would use a virtual method in the object to convert, that calls a second virtual method in the object implementing the conversion algorithm.

But that implies that the object upon which you want to apply the algorithm needs to collaborate with this: it needs to have support for the visitor pattern baked in.

You seem to be using .NET's Windows Forms classes, which do not have support for the visitor pattern. More specifically, they would need to have a public virtual void Accept(IVisitor) method, which obviously they don't have.

So, what's the alternative? Well, .NET does not only support single binding, it also supports dynamic binding, which is even more peowerful than dual binding.

For more information on how to apply that technique, which will allow you to solve your problem (if I understand it well), take a look at Farewell Visitor.

UPDATE:

To apply the technique to your specific problem, first define your extension method:

public static XmlDocument ToXml(this Control control)
{
    XmlDocument xml = new XmlDocument();
    XmlElement root = xml.CreateElement(control.GetType().Name);
    xml.AppendChild(root);

    Visit(control, xml, root);

    return xml;
}

Create the dynamic dispatcher:

private static void Visit(Control control, XmlDocument xml, XmlElement root)
{
    dynamic dynamicControl = control; //notice the 'dynamic' type.
                                      //this is the key to dynamic dispatch

    VisitCore(dynamicControl, xml, root);
}

Then fill in the specific methods:

private static void VisitCore(Control control, XmlDocument xml, XmlElement root)
{
    // TODO: specific Control handling
}

private static void VisitCore(ContainerControl control, XmlDocument xml, XmlElement root)
{
    // call the "base" method
    VisitCore(control as Control, xml, root);

    // TODO: specific ContainerControl handling
    // for example:
    foreach (Control child in control.Controls)
    {
        XmlElement element = xml.CreateElement(child.GetType().Name);
        root.AppendChild(element);

        // call the dynamic dispatcher method
        Visit(child, xml, element);
    }
}

private static void VisitCore(Form control, XmlDocument xml, XmlElement root)
{
    // call the "base" method
    VisitCore(control as ContainerControl, xml, root);

    // TODO: specific Form handling
}


问:
What is the right level of site blocking for you as a developer?
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?

答:
No site blocking.

If my projects are delivered on time and my productivity is not suffering, I don't see any reason to block anything (except - if you really must block something - well known spyware/malware sites).

I don't really have anything else to add except that.

We are professionals, not children.

ContentLicense: CC BY-SA 2.5


问:
Can Setter Validation affect performance?
In a scenario where you use an ORM to map your entities to the DB and you have setter validations (nullable, date lower than today validation, etc), every time the ORM gets a result, it will pass into the setter to instance the object.

If I have a grid that usually returns 500 records, I assume that for each record it passes on all validations. If my entity has 5 setter validations, than I have passed in 2.500 validations.

Are these 2.500 validations going to affect the performance?

If it was 15.000 validation, will it be different?

In my opinion, and according to this answer, setter validation is useful than constructors validation.

Is there a way to avoid unnecessary validation, since I am safe to say that
the values I send to the DB when saving the entity won't change until I
edit it on my system?

答:
Can affect performance?

Sure, it will.

If you are validating anything at all you got an overhead there. Sometimes this overhead is significant, other times it is negligible.

Should I validate on the setter?

If validating on the property setter is hurting your performance maybe you should only perform the validation when strictly necessary, like when persisting it in a database (something like a isValid method). The downside of this approach is that you may have invalid objects lying around.

There is also a third school of thought here:

Mutable objects that are never invalid (always validating on the setter, like your scenario)

Mutable objects that can be in a invalid state (validating only when necessary, like I said above)

Immutable objects that can't be invalid (if it is invalid you don't construct the object at all)

One downside with the first, the one that you are currently using, is that you might perform the validation when it's not necessary.

They all have pros and cons, which one to pick depends a lot of your scenario and your (colleagues) programming background.

Should the validation be performed on the object itself at all?

This is one is even more debatable. Separating the data from the business logic is often referred as anemic domain model. A famous objector of anemic domain model is Martin Fowler, which in this particular subject I disagree with him, but that's ok, it's my opnion :)

I'm simplifying way too much here but the main difference between letting your domain anemic and not is that one is more compliant with pure theoretical OOP and, at first, requires less effort to design and maintain; the other does better separation of concerns and it's way better when dealing with concurrency (since the objects are stateless).

This topic is a great food for thought. I suggest you to leaving everything as it is if you are on a more problem-solving scenario; big changes on the status quo might not be healthy if the time isn't right.

P.S.

Being specific to your ORM, depending on the language or framework you are using, your ORM may find a way to serialize/deserialize without using getters or setters.

ContentLicense: CC BY-SA 3.0


问:
Data Transformation Pipeline
I have create some kind of data pipeline to transform coordinate data into more useful information.

Here is the shell of pipeline:

```<code>public class PositionPipeline
{
    protected List<IPipelineComponent> components;

    public PositionPipeline()
    {
        components = new List<IPipelineComponent>();
    }

    public PositionPipelineEntity Process(Position position)
    {
        foreach (var component in components)
        {
            position = component.Execute(position);
        }

        return position;
    }

    public PositionPipeline RegisterComponent(IPipelineComponent component)
    {
        components.Add(component);
        return this;
    }
}
</code>```

Every IPipelineComponent accepts and returns the same type - a PositionPipelineEntity. Code:

```<code>public interface IPipelineComponent
{
    PositionPipelineEntity Execute(PositionPipelineEntity position);
}
</code>```

The PositionPipelineEntity needs to have many properties, many which are unused in certain components and required in others.  Some properties will also have become redundant at the end of the pipeline.

For example, these components could be executed:

TransformCoordinatesComponent: Parse the raw coordinate data into a Coordinate type.

DetermineCountryComponent: Determine and stores country code.

DetermineOnRoadComponent: Determine and store whether coordinate is on a road.

Code:

```<code>pipeline
    .RegisterComponent(new TransformCoordinatesComponent())
    .RegisterComponent(new DetermineCountryComponent())
    .RegisterComponent(new DetermineOnRoadComponent());

pipeline.Process(positionPipelineEntity);
</code>```

The PositionPipelineEntity type:

```<code>public class PositionPipelineEntity
{
    // Only relevant to the TransformCoordinatesComponent
    public decimal RawCoordinateLatitude { get; set; }

    // Only relevant to the TransformCoordinatesComponent
    public decimal RawCoordinateLongitude { get; set; }

    // Required by all components after TransformCoordinatesComponent
    public Coordinate CoordinateLatitude { get; set; }

    // Required by all components after TransformCoordinatesComponent
    public Coordinate CoordinateLongitude { get; set; }

    // Set in DetermineCountryComponent, not required anywhere.
    // Requires CoordinateLatitude and CoordinateLongitude (TransformCoordinatesComponent)
    public string CountryCode { get; set; }

    // Set in DetermineOnRoadComponent, not required anywhere.
    // Requires CoordinateLatitude and CoordinateLongitude (TransformCoordinatesComponent)
    public bool OnRoad { get; set; }
}
</code>```

Problems:

I'm very concerned about the dependency that a component has on properties.  The way to solve this would be to create specific types for each component.  The problem then is that I cannot chain them together like this.

The other problem is the order of components in the pipeline matters.  There is some dependency.  The current structure does not provide any static or runtime checking for such a thing.

Any feedback would be appreciated.

答:
It appears to me as though your problem here might be partly that your pipeline is a little too abstract. It's important to work with abstractions, but the openness of the design you have is making it hard for you to visualise the solution.

For example, with the order of components, you probably want to split these out in the pipeline, so that

```<code>pipeline
.RegisterComponent(new TransformCoordinatesComponent())
.RegisterComponent(new DetermineCountryComponent())
.RegisterComponent(new DetermineOnRoadComponent());
</code>```

Might become something like

```<code>pipeline.TransformationCoordinates.Register(new TransformCoordinatesComponent());
pipeline.Determinations.Register(new DetermineCountryComponent());
pipeline.Determinations.Register(new DetermineOnRoadComponent());
</code>```

Then your granularity becomes that of the number of different types of ordered component you need to have, so the Pipeline can have zero or many TransformationCoordinate components, Determination components and so on and will run all the ones available in order. Of course, this might be hidden inside pipeline.RegisterComponent splitting them out by interface, but this is an easier way to illustrate what I mean.

As you become less abstract you lose flexibility, in this case you would need to have a new collection if you added a new ordered type, so if you wanted to have an InvertComponent that ran between the TransformationCoordinate and the Determination components you would have to change your Pipeline accordingly. This is probably not a terrible thing, as long as your architecture is generally solid, however - you are likely to have to make the jump from the theoretical to the pragmatic at some point anyway.

Once you know the different component types you can guarantee that you have the correct properties available for each stage in the process- you could either ensure that the properties are set at each step on a type that always has them available or you could return a new object from each stage with the properties needed for the next.

Either way, I think you will find your work is easier if you start to think in more concrete terms about the exact processes you need to follow.

Title: Data Transformation Pipeline

Body:
It appears to me as though your problem here might be partly that your pipeline is a little too abstract. It's important to work with abstractions, but the openness of the design you have is making it hard for you to visualise the solution.

For example, with the order of components, you probably want to split these out in the pipeline, so that

pipeline
.RegisterComponent(new TransformCoordinatesComponent())
.RegisterComponent(new DetermineCountryComponent())
.RegisterComponent(new DetermineOnRoadComponent());

Might become something like

pipeline.TransformationCoordinates.Register(new TransformCoordinatesComponent());
pipeline.Determinations.Register(new DetermineCountryComponent());
pipeline.Determinations.Register(new DetermineOnRoadComponent());

Then your granularity becomes that of the number of different types of ordered component you need to have, so the Pipeline can have zero or many TransformationCoordinate components, Determination components and so on and will run all the ones available in order. Of course, this might be hidden inside pipeline.RegisterComponent splitting them out by interface, but this is an easier way to illustrate what I mean.

As you become less abstract you lose flexibility, in this case you would need to have a new collection if you added a new ordered type, so if you wanted to have an InvertComponent that ran between the TransformationCoordinate and the Determination components you would have to change your Pipeline accordingly. This is probably not a terrible thing, as long as your architecture is generally solid, however - you are likely to have to make the jump from the theoretical to the pragmatic at some point anyway.

Once you know the different component types you can guarantee that you have the correct properties available for each stage in the process- you could either ensure that the properties are set at each step on a type that always has them available or you could return a new object from each stage with the properties needed for the next.

Either way, I think you will find your work is easier if you start to think in more concrete terms about the exact processes you need to follow.


问:
how to architect this to make it unit testable
I'm currently working on a project where I'm receiving an object via web service (WSDL).

The overall process is the following:

Receive object -> add/delete/update parts (or all) of it -> and return the object with the changes made.

The thing is that sometimes these changes are complicated and there is some logic involved, other databases, other web services, etc. so to facilitate this I'm creating a custom object that mimics the original one but has some enhanced functionality to make some things easier.

So I'm trying to have this process:

Receive original object -> convert/copy it to custom object -> add/delete/update -> convert/copy it back to original object -> return original object.

Example:

```<code>public class Row
{
    public List<Field> Fields { get; set; }
    public string RowId { get; set; }
    public Row()
    {
        this.Fields = new List<Field>();
    }
}

public class Field
{
    public string Number { get; set; }
    public string Value { get; set; }
}
</code>```

So for example, one of the "actions" to perform on this would be to find all Fields in a Row that match a Value equal to something, and update them with some other value.

I have a CustomRow class that represents the Row class, how can I make this class unit testable? Do I have to create an interface ICustomRow to mock it in the unit test?
If one of the actions is to sum all of the Values in the Fields that have a Number equal to 10, like this function, how can design the custom class to facilitate unit tests.

Sample function:

```<code>public int Sum(FieldNumber number)
{
    return row.Fields.Where(x => x.FieldNumber.Equals(number)).Sum(x => x.FieldValue);
}
</code>```

Am I approaching this the wrong way?

答:
Yes, I would say you're approaching it the wrong way. Why mock anything?

Let's look at your units:

receive object - testing the web service call isn't your goal, use an integration test.

convert to custom object - you need the original object and the result object to make sure this operation works. Just use them.

stuff - modifying your custom object uses just the custom object. No dependencies to mock here. Make a custom object, run the conversion, make sure you end up in the new state.

(and the reverse conversions use the same traits)

Since there's no unnecessary dependencies, there's nothing to mock.


问:
where do you track team Decisions
I have been on many development teams and as the team matures decisions about direction are made.  These decisions often come back up over and over.  Like why don't we fill in this field why didn't we use memcache over a custom solutions.  These decisions add up over time and become a significant part of style guides coding standards and unit tests.

My question is I have never run into a good way of tracking these decisions or the discovery that went into making them.  Does anyone have a best practice.

答:
Agile Software Development Methodology does address these development decisions very efficiently. At the end of each iteration, we can have retrospective session. We jot down our lessons that we have learnt over a period of time and review them before we initate the next iteration for improvement.

I would suggest that you shold look into Using Large Agile Retrospectives to Improve Projects

Title: where do you track team Decisions


答:
(in my experience)

Major decisions (especially involving product owners) belong in design documents.

Trivial technical decisions (why is is field empty?) belongs in a comment right next to the field.

In between sort of decisions are odd. I tend to think that undocumented communal knowledge is best, since documentation of a decision is useless if nobody follows it and these medium decisions are often things that everyone needs to follow. I've seen wikis used for this with little success. Especially for style guide stuff, having it in code is often "good enough" for people to go with the flow.

Title: where do you track team Decisions

Body:
I have been on many development teams and as the team matures decisions about direction are made.  These decisions often come back up over and over.  Like why don't we fill in this field why didn't we use memcache over a custom solutions.  These decisions add up over time and become a significant part of style guides coding standards and unit tests.

My question is I have never run into a good way of tracking these decisions or the discovery that went into making them.  Does anyone have a best practice.


问:
Scala as a language for Generic Programming
In the paper “An Extended Comparative Study of Language Support for Generic Programming” by Garcia et al. an interesting comparison of programming languages features for generic programming is given:

with the brief explanation of terminology:

Can anyone test Scala support for generic programming inside this framework? I.e. add a column in the first table with explanations if possible.

答:
As mentioned in one of the comments from the OP, this is the table that explains how Scala compares for generic programming support.  Link to source pdf

Later on, the following summary is provided:

Scala

  Using the CONCEPT pattern we can model multi-type concepts, multiple constraints and support retroactive modeling. Furthermore, Scala’s support for implicits means that the drawbacks of the Java and C# solutions in terms of the additional overhead, do not apply to Scala. Thus, Scala scores well in both the implicit argument deduction and the  retroactive modeling criteria. Section 6 shows that associated types are supported in Scala through type members and dependent method types, and type members can also be used as type aliases.

  As shown in Section 3, Scala supports lexically scoped models. Furthermore type-checking is fully modular. Prioritized overlapping implicits provide some support for concept-based overloading as illustrated by the zipWithN example in Section 6.5. However, overlapping models have to be structured using a subtyping hierarchy, which may not always be desirable. Thus, the score for this feature is only sufficient. Finally, Scala has full support for first-class functions and it also supports equality constraints.

  In summary Scala turns out to be a language with excellent support for generic programming features, managing to fare at the same level, or even slightly better, than G (which was specially designed as a language for generic programming in the large) or Haskell (which has been recognized has having very good support for generic programming).

And then in the summary:

Type members and dependent method types add extra power to the language and a combination of the two mechanisms allows associated types to be expressed. In combination with implicits, type members and dependent method types make Scala an language ready for generic programming in the large


问:
Browser-based GUI for a python application
I want to create a web/browser-based GUI for a command-line python application. The goal is to make use of HTML/JS technologies to create this GUI. As the application itself, it needs to run on Linux and Windows, and the interface will be accessible only from localhost (not exposed to internet). The GUI will contain 5 to 10 pages.

I don't want a traditional desktop GUI that includes HTML/JS, but just a bunch of html files and some kind of controller between those and the application.

I also want to make use of asynchronous programming (ajax like) so I can load and print data in the GUI without refreshing the whole page. I'd probably use jQuery for that and a couple other things.

How would you recommend to design this? Performance is not the key here, I'm rather looking at reliability, portability and simplicity.

I'm thinking of using a lightweight python HTTP server / framework (like CherryPy) and maybe later a Python templating system (at the begining it will just be a couple pages).

EDIT:

I'm looking for ideas/recommendations how to build this, not for alternatives to browser/web-based GUI.

答:
Your stated criteria are:

Reliability

Portability

Simplicty

If thats the case, a desktop app is the way to go.  There is no need to throw a web server into the mix.  That will just complicate matters for no actual gain.

Based on the OP's edit - that an HTML-based interface is desired - a possible route might be node-webkit.  This will allow you to create a desktop application that runs on Windows, Linux, and Mac using HTML & Javascript.  It takes an approach somewhat similar to PhoneGap (with the exception that the same embedded browser is used on all platforms).  Node is used to power the Javascript, which provides access to a large number of libraries.  And you have access to the underlying system, allowing you to run the Python-based command line program.


答:
I am currently trying to do pretty much the same thing. Looks like Python has a server (SimpleHTTPServer) so I trying to make an AngularJS web application that will be interacting with Python server.

Potentially there is a cefpython project that would allow distributing Python applications as standalone programs.

Title: Browser-based GUI for a python application

Body:
I want to create a web/browser-based GUI for a command-line python application. The goal is to make use of HTML/JS technologies to create this GUI. As the application itself, it needs to run on Linux and Windows, and the interface will be accessible only from localhost (not exposed to internet). The GUI will contain 5 to 10 pages.

I don't want a traditional desktop GUI that includes HTML/JS, but just a bunch of html files and some kind of controller between those and the application.

I also want to make use of asynchronous programming (ajax like) so I can load and print data in the GUI without refreshing the whole page. I'd probably use jQuery for that and a couple other things.

How would you recommend to design this? Performance is not the key here, I'm rather looking at reliability, portability and simplicity.

I'm thinking of using a lightweight python HTTP server / framework (like CherryPy) and maybe later a Python templating system (at the begining it will just be a couple pages).

EDIT:

I'm looking for ideas/recommendations how to build this, not for alternatives to browser/web-based GUI.


答:
I'm familiar with the problem.  One nice solution I heard about (but haven't tried myself) was an agile team that did Kanban properly (with a real physical board) and added a "principles" area where decisions like this - or at least nags about recurring pain points - could be written up ("use X if you're doing Y", "don't forget W", "our stuff now needs to work with Z").  On the physical board they'd have a good chance of being seen by someone going to move their story card to an "active" or "done" column and jogging their memory that it's something they need to bear in mind/do something about.

Of course it's diminishing returns if you have too many of them, but stuff would get from the principles area into the culture/communal knowledge/habits of the team and the board space could then be updated to be something about something else now thought to be causing more trouble.

Good example of an "information radiator" in action I think.

Title: where do you track team Decisions


问:
How to read thousands lines of code without any documentation?
Previously I was searching for a good TimeLine control for a WPF project. I found an answer in Here which direct me to this CodePlex project.

Now I want to change code to feed my culture needs. But there are some mismatches!

My question is:

How you interact with such thousands lines of code?

EDIT:

Any shortcut will be great!

答:
The best way, as with all programming not just large chunks of uncommented code, is to break it down into pieces. This is both something you should do in your head as well as visually in the code. This may mean adding big bold comments or multiple line breaks. This helps while scrolling through it to see the pieces. Try to find the logical chunks of code.

Of course, as you understand bits, comment them for what you know at that time, possibly putting in notes about about something you don't understand.

I would also recommend not trying to understand the entire piece right from the start. Instead try to understand the pieces that you need to know right now and work on the rest later.


问:
OpenGL extension vs OpenGL core
I was doubting: I'm writing a cross-platform engine OpenGL C++, I figured out Windows forces the developers to access OpenGL features above 1.1 through extensions.

Now the thing is, on Linux, I know that I can directly access functions if the version supports it through glext.h and opengl version. The problem is that if on Linux, the core doesn't support it, is it possible there is an extensions that supports the same functionality, in my case vertex buffer objects?

I'm doing something like this:

Windows:

```<code>#define glFunction functionpointer_to_the_extension
</code>```

Linux:

Since glext already defined glFunction, I can write in client code glFunction, and compile it both on Windows AND Linux without changing a single line in my client code using the engine (my goal).

Now the thing is, I saw a tutorial use only the extension on Linux, and not checking for the opengl implementation version. If the functionality is available in the core, is it also available as extension (VBO's e.g.)? Or is an extension something you never know is available?

I want to write an engine that is capable of using all the hardware functionalities, so I need to check (on Linux) for extensions as well as core version for possible functionality implementation.

答:
I was doubting: I'm writing a cross-platform engine OpenGL C++, I figured out windows forces the developers to access OpenGL features above 1.1 through extensions.

That sounds odd, because Windows have never forced me to use extensions, I always use core functions when possible, and while saying "when possible" I mean if my graphics card/driver supports the features. Because that plays the biggest part.

If the functionality is available in the core, is it also available as extension (VBO's e.g.)?

Not necessarily! But always favor the core functions when you can. Though when using extensions (EXT, ARB, etc) just always remember to check, if they are available.

If you're going to release a program using an NV Extension (Nvidia Extension), then again be sure to have something that checks whether the function is available, as if someone with a non-Nvidia graphics card uses your program it will most likely crash.

Or is an extension something you never know is available?

Yes, you never know for sure if an extension is available, it depends on various things such as.

The OpenGL version you're using

Your Graphics Card

Your Graphics Card version and model (GeForce, Cuda, Radeon, etc)

Your Graphics Card vendor (Nvidia, AMD, etc)

By using core functions the chances are that the majority of people will be able to run the program, as long as their graphics card can run the particular GL version.

EXT extensions usually only are supported by a few vendors.

ARB extensions are often supported by the majority but not necessarily all vendors.

Core functions are supported by every card which supports the particular GL version, which the program is using.

Remember

Always remember you can't mix-match and use GL_TEXTURE1 with glActiveTextureARB and you can't use GL_TEXTURE1_EXT with glActiveTexture. Even though mixing them sometimes produces the desired result, there is no guarantee for that.

ContentLicense: CC BY-SA 4.0

Title: OpenGL extension vs OpenGL core


问:
What's is the point of PImpl pattern while we can use interface for the same purpose in C++?
I see a lot of source code that uses PImpl idiom in C++. I assume Its purpose is to hide the private data/type/implementation, so it can remove dependence, and then reduce compile time and header include issue.

But interface/pure-abstract classes in C++ also have this capability, they can also be used to hide data/type/implementation. And to let the caller just see the interface when creating an object, we can declare a factory method in the interface's header.

The comparison is:

Cost:

The interface way cost is lower, because you don't even need to repeat the public wrapper function implementation void Bar::doWork() { return m_impl->doWork(); }, you just need to define the signature in the interface.

Well understood:

The interface technology is better understood by every C++ developer.

Performance:

Interface way performance is not worse than PImpl idiom, both requires an extra memory access. I assume the performance is same.

Following is the pseudocode to illustrate my question:

```<code>// Forward declaration can help you avoid include BarImpl header, and those included in BarImpl header.
class BarImpl;
class Bar
{
public:
    // public functions
    void doWork();
private:
    // You don't need to compile Bar.cpp after changing the implementation in BarImpl.cpp
    BarImpl* m_impl;
};
</code>```

The same purpose can be implemented using interface:

```<code>// Bar.h
class IBar
{
public:
    virtual ~IBar(){}
    // public functions
    virtual void doWork() = 0;
};

// to only expose the interface instead of class name to caller
IBar* createObject();
</code>```

So what's the point of PImpl?

答:
I just want to address your performance point. If you use an interface, you necessarily have created virtual functions which WILL NOT be inlined by the compiler's optimizer. The PIMPL functions can (and probably will, because they are so short) be inlined (perhaps more than once if the IMPL function is also small). A virtual function call can't be optimized over unless you use full program analysis optimizations which take a very long time to do.

If your PIMPL class is not used in a performance critical way, then this point doesn't matter much, but your assumption that the performance is the same only holds in some situations, not all.


问:
Good architecture for user information on separate databases?
I need to write an API to connect to an existing SQL database.  The API will be written in ASP.Net MVC3.

The slight problem is that with existing users of the system, they may have a username on multiple databases.

Each company using the product gets a brand new instance of the database, but over the years (the system has been running for 10 years) there are quite a few users (hundreds) who have multiple usernames across multiple "companies" (things got fragmented obviously and sometimes a single Company has 5 "projects" that each have their own database).

Long story short, I need to be able to have a single unified user login that will allow existing users to access their information across all their projects.

The only thing I can think is storing a bunch of connection strings, but that feels like a really bad idea.

I'll have a new Database that will hold the "unified user" information...can anyone suggest a solid system architecture that can handle a setup like this?

答:
See: https://stackoverflow.com/a/19460296/88409

If you're going to have users in a separate database, that's fine, but you must understand that referential integrity cannot be guaranteed.  Therefore, you must do your best to maintain it (through application logic, distributed transaction, trigger, etc.), and you must keep the remote references minimized.

In other words, if you are going to have a foreign key that refers to a remote database, then it's best to create a table in your local database that associates the remote key with a local one, so that local tables can refer to the local key rather than directly to the remote one.

For example, suppose you have a remote key called "facebook_id" (and it's a GUID).  Rather than have all your local tables reference it directly, create a table called local_facebook_id, which stores a locally unique id along with the facebook_id, then have all your local tables refer to your local id rather than directly to the facebook_id.  The benefit is that you get local referential integrity to a single point of reference.

Futhermore, you can also expand that local_facebook_id table to cache credentials and other profile information, so that if the remote database goes missing or the user's account is deleted, users of your application could still be allowed to log in against the local_facebook_id table's credentials.  Also, it would contain enough meaningful information about them that if the remote account gets permanently wiped out, your local data remains linked to a local source of meaningful personal information (rather than just a meaningless GUID), which could even be used later to re-link the local account to a new facebook_id (e.g. by email address or some other uniquely identifying information).


答:
Options for Python web apps:

django

web.py

werkzeug (w/ or w/o flask)

twisted

cherry.py

raw wsgi

raw simplehttpserver

Any one of these will work. As far as how you build an app; most of these frameworks have online tutorials. Just follow along and adapt it to fit your needs.


问:
Software attribution / design credits
We just completed developing a web app for a client. And like I usually do, I added
developed by "My Company" at the footer at a very small insignificant size.

I sent the client an End user license stating some of the following in summary

```<code>you can't resell, redistribute, etc without our notice
...
you can't remove the attribution or design credits
</code>```

the client got back to me and complained, telling me now that he was also developing for someone, and that 'I can't add my attribution' without his/her consent, but?

Although I sign a NDA within summary states that I cannot disclose the software to anyone else.

There was no agreement before the project that am not to add design credits or attribution.

I know every software I install have that, and so is every products from companies, mostly technological products.

How does this work (adding design credits)?

答: If you didn't include this "end user license" in the original contract, I'd say you're in the wrong.  In many jurisdictions, you can't retroactively remove rights or impose restrictions that would otherwise seem normal.</p>

Title: Software attribution / design credits


问:
If I send an IPA over TestFlight, can it be used to deploy to the app store?
I am currently working for a small startup. I was previously under contract, now I am working for equity (no pay). The thing is, there is not yet a signed agreement in place as the details are being worked out. I may finish development before the contract is ready.

I'm not currently under any contract or agreement, so the other party doesn't have any legal claim (that I know of) to the code I'm writing now, other than NDA (which just precludes me from cutting him out and releasing on my own). He already has the old code that I wrote under contract. I've made it clear to the other party that I won't submit the app or turn over the code until there's something signed to protect my interests. I've stopped pushing commits to the company repo (I'm now the only developer actively working on the project).

However, I would still like to send builds over TestFlight for feedback and testing purposes. The other party has access to the developer portal and iTunes Connect for code signing, etc. Things are amicable and I don't foresee getting burnt on this, but I'm not going to put myself in that position. My concern is that if I send a finished build via TestFlight, it could be extracted and submitted to the app store without my participation. They wouldn't have the source for future maintenance and updates, of course, but it could be reverse-engineered by another developer later working from the old code base.

Is this technically feasible at all? If so, is there a way I can send builds for testing while protecting my interests?

答:
If you are concerned about the binary, and other assets, within an Ad Hoc distributed app being repackaged and submitted to the App store before it is reversed engineered, then including one or more checks for an expiration date a few days out may be suitable.  Perhaps have the expiration send the user back to TestFlight to encourage them to test only your latest builds.  Another possibility is for the Ad Hoc deployed test version to include incidental use of several private or disallowed APIs (UDID, etc.) that may cause Apple to reject a submitted app.

You might also consider the appearance of an Easter-egg copyright notice (suitably obfuscated in code) to which the other party is not legally entitled to display.

But after any reverse engineering of an app's binary, all bets are off.


答:
Personally, I prefer non blocked access, and developers you can depend on in way of work. When they're not working on something they can surf as much as they like.

Unfortunatelly, that doesn't always go.

So, you might block some ... harmful sites (obviously), xxx and such, general (non programming related) news sites, facebook (I can't think of one reason where it could be useful during work) ...

but generally, do keep it open, and work on trying to establish a good working atmosphere.

Title: What is the right level of site blocking for you as a developer?

Body:
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?


问:
Data Structure for Small Number of Agents in a Relatively Big 2D World
I'm working on a project where we will implement a kind of world simulation where there is a square 2D world. Agents live on this world and make decisions like moving or replicating themselves based on their neighbor cells(world=grid) and some extra parameters(which are not based on the state of the world). I'm looking for a data structure to implement such a project.

My concerns are :
I will implement this 3 times: sequential, using OpenMP, using MPI. So if I can use the same structure that will be quite good.

The first thing comes up is keeping a 2D array for the world and storing agent references in it. And simulate the world for each time slice by checking every cell in each iteration and further processing if an agents is found in the cell. The downside is what if I have 1000x1000 world and only 5 agents in it. It will be an overkill for both sequential and parallel versions to check each cell and look for possible agents in them. I can use quadtree and store agents in it, but then how can I get the information about neighbor cells then?

Please let me know if I should elaborate more.

答:
The data structure will become obvious after you analyze the problem and constraints.

You have three implementation targets: sequential, OpenMP, and MPI. Of these, MPI is the most constrained, IMO. Work through how the sim can be built using MPI, and you will see that a key issue is the process control model (you have already alluded to this). From what you have said, IMO the Actors should be the active elements. Challenge that idea.

As you build up your conceptual model of the processes and their communication, you will encounter issues of concurrency, data locality, and message bandwidth. Work through those, and you will have your data structures.

The other two models will be simplified versions of that.


答:
You have quoted the following paramenters for your world,

You have a 2D world (NxN grid where N=1000).

There are Agents located in the world, each agent at a grid location.

Agents can move.

There can be few agents (5) to many agents (1M).

The world may be sparsely to densely populated.

You need to find the locations which have agents, and process then.

You need to cover all agents.

You would like to process as few grid elements as possible.

You want a data structure amenable to parallelization

You need to be able to find neighbors, and agents within neighbors

Exhaustive scan of the entire 2D world will find you agents, but it might be inefficient (looking at 1M grid locations for only 5 agents is wasteful).

Questions:

Is there a priority to agents? assume no.

Can you skip some agents? assume no,.

Does it matter what order you examine agents? assume any.

What is the most agents you expect in any one grid location? suppose 50.

Suggestions:

Keep a data structure (grid or tree) counting the number of agents in a given grid location.  Only 1M locations is simple enough, and you could use a single byte per grid location to count up to 2^7 (0-127), agents.  Use an overflow area for locations with more agents (assuming you seldom have more than 127 agents in a location - do you have an expected average?).  lock/parallelize based upon regions of the grid (10x10) areas.

Keep the agents ordered in some tree (quadtree, trie based upon grid location), but tree is not as parallel-izable.  My suggestion here would be a 2D list of lists (or vector of vectors) ordered by grid coordinates.

You want to pick a coordinate system where you can easily compute neighbors, and find out whether agents are in neighbors - note that the counts structure mentioned will be valuable here.

What you are looking for is a topological sort of your data, and a quadtree is one approach.  But you care about everybody 'nearby'.  The problem you discuss is similar in some respects to the finite element analysis.

You mention move and replicate, which both change state not just of self, but other grid elements and tree analysis.  These methods would affect how parallelization is done.

Title: Data Structure for Small Number of Agents in a Relatively Big 2D World

Body:
I'm working on a project where we will implement a kind of world simulation where there is a square 2D world. Agents live on this world and make decisions like moving or replicating themselves based on their neighbor cells(world=grid) and some extra parameters(which are not based on the state of the world). I'm looking for a data structure to implement such a project.

My concerns are :
I will implement this 3 times: sequential, using OpenMP, using MPI. So if I can use the same structure that will be quite good.

The first thing comes up is keeping a 2D array for the world and storing agent references in it. And simulate the world for each time slice by checking every cell in each iteration and further processing if an agents is found in the cell. The downside is what if I have 1000x1000 world and only 5 agents in it. It will be an overkill for both sequential and parallel versions to check each cell and look for possible agents in them. I can use quadtree and store agents in it, but then how can I get the information about neighbor cells then?

Please let me know if I should elaborate more.


问:
Switch vs Polymorphism when dealing with model and view
I can't figure out a better solution to my problem. I have a view controller that presents a list of elements. Those elements are models that can be an instance of B, C, D, etc and inherit from A. So in that view controller, each item should go to a different screen of the application and pass some data when the user select one of them. The two alternatives that comes to my mind are (please ignore the syntax, it is not a specific language)

1)
switch (I know that sucks)

```<code>//inside the view controller
void onClickItem(int index) {
    A a = items.get(index);

    switch(a.type) {
         case b:
             B b = (B)a;
             go to screen X;
             x.v1 = b.v1; // fill X with b data
             x.v2 = b.v2;
         case c:
             go to screen Y;
         etc...
    }
}
</code>```

2) polymorphism

```<code>//inside the view controller
void onClickItem(int index) {
    A a = items.get(index);
    Screen s = new (a.getDestinationScreen()); //ignore the syntax
    s.v1 = a.v1;   // fill s with information about A
    s.v2 = a.v2;
    show(s);
}

//inside B
Class getDestinationScreen(void) {
    return Class(X);
}

//inside C
Class getDestinationScreen(void) {
    return Class(Y);
}
</code>```

My problem with solution 2 is that since B, C, D, etc are models, they shouldn't know about view related stuff. Or should they in that case?

答:
I think that perhaps an implementation of the visitor pattern would be useful here.  The B, C, and D class would need to be "visited" to determine the view type, but would not need to know anything about views.  The ViewFactory (below) would visit the item and use polymorphism to determine the correct view to build.  No switch statements.  No asking about model internals to decide what to build.  The visitor interface uses polymorphism to select the correct setter for the view.  The setter can pass the item to the constructor of the specific view type (X or Y or Z) and that view can then populate its fields from the item.</p>

```<code>   //inside the view controller
   void onClickItem(int index) {
      ViewFactoryVisitable a = items.get(index);
      ViewFactory aViewFactory = new ViewFactory(
      s = aViewFactory.getViewFor(a);
      show(s);
   }

--------

//Element interface
public interface ViewFactoryVisitable
{
    public void accept(ViewFactory theViewFactory);
}

---------

public interface ViewFactoryVisitor
{
   // one for each concrete type, polymorphism will choose correct setter
   public set setViewFor(B b);
   public set setViewFor(C c);
   public set setViewFor(D d);
}

--------

// B, C, D must implement this visitable interface
class B implements ViewFactoryVisitable
{
   ...

   //accept the ViewFactory as a visitor
   public void accept(ViewFactoryVisitor theViewFactoryVisitor)
   {
      theViewFactoryVisitor. setViewFor(this);
   }

   ...
}

--------

class ViewFactory implements ViewFactoryVisitor
{
   ViewFactory(ViewFactoryVisitable theItem) {
      theItem.accept(this);
   }

   private View mView = null;
   ...

   public void setViewFor(B b) {
      // construct a view x and populate with data from b
      mView = new ViewX(b);
   }

   public void setViewFor(C c) {
      mView = new ViewY(c);
   }

   public void setViewFor(D d) {
      mView = new ViewZ(d);
   }

   View getView() {
      return mView;
   }

}
</code>```

Body:
I think that perhaps an implementation of the visitor pattern would be useful here.  The B, C, and D class would need to be "visited" to determine the view type, but would not need to know anything about views.  The ViewFactory (below) would visit the item and use polymorphism to determine the correct view to build.  No switch statements.  No asking about model internals to decide what to build.  The visitor interface uses polymorphism to select the correct setter for the view.  The setter can pass the item to the constructor of the specific view type (X or Y or Z) and that view can then populate its fields from the item.

   //inside the view controller
   void onClickItem(int index) {
      ViewFactoryVisitable a = items.get(index);
      ViewFactory aViewFactory = new ViewFactory(
      s = aViewFactory.getViewFor(a);
      show(s);
   }

--------

//Element interface
public interface ViewFactoryVisitable
{
    public void accept(ViewFactory theViewFactory);
}

---------

public interface ViewFactoryVisitor
{
   // one for each concrete type, polymorphism will choose correct setter
   public set setViewFor(B b);
   public set setViewFor(C c);
   public set setViewFor(D d);
}

--------

// B, C, D must implement this visitable interface
class B implements ViewFactoryVisitable
{
   ...

   //accept the ViewFactory as a visitor
   public void accept(ViewFactoryVisitor theViewFactoryVisitor)
   {
      theViewFactoryVisitor. setViewFor(this);
   }

   ...
}

--------

class ViewFactory implements ViewFactoryVisitor
{
   ViewFactory(ViewFactoryVisitable theItem) {
      theItem.accept(this);
   }

   private View mView = null;
   ...

   public void setViewFor(B b) {
      // construct a view x and populate with data from b
      mView = new ViewX(b);
   }

   public void setViewFor(C c) {
      mView = new ViewY(c);
   }

   public void setViewFor(D d) {
      mView = new ViewZ(d);
   }

   View getView() {
      return mView;
   }

}


问:
UI design and confirmation paradigm
I just saw this lecture by Spolsky, where he questions the need for choices and confirmation dialogs. At some point he has a MacOS settings window and he mentions that "now some are getting rid of the OK button". The window indeed has no OK (or cancel) button. Changing a setting makes it change, when you're done configuring, you close that window, period.

Being a long time Windows user and a recent Mac owner, the difference is noticeable at first. I looked for the OK button for a while, only to find out, quite naturally and painlessly, that there was none. I expressed satisfaction and went on my merry way.

However, I'm curious to know if this UI design pattern would succeed in the Windows-based world. Granted that if Microsoft brought it out with say Windows-8 (fat chance, I know), people would get used to it eventually. But is there some experience out there of such an approach, of changing the "confirmation paradigm" on a platform where it's so prevalent? Did it leave users (especially the non-technical ones) confused, frustrated, scared, or happy?

TL;DR: Remove OK/cancel confirmation, what happens?

EDIT:

Mac GUI for appearance settings.

答:
The role of the confirmation dialog is for the user to CONFIRM that the changes he made are the ones that he intended to and he didn't changed something unintentionally.

If a world with no OK buttons you must ensure that either:

The user makes always the right choices [yeah, right]

or

The changes are not irreversible

The undo operation is simple

Once a change is done without confirmation from the user, the user is aware of its effects - in a short after. You don't want the user to find out that the change he made unintentionally, 6 weeks ago, had unwanted effects

So, in conclusion, I don't think that confirmation dialogs prevents user from taking the wrong decision or doing something unintentionally but at least it offers another layer of protection for the end user. However, for a user with a lot of experience, this might be annoying.

Title: UI design and confirmation paradigm


问:
What the best way to wire up Entity Framework database context (model) to ViewModel in MVVM WPF?
As in the question above: What the best way to wire up Entity Framework database model (context) to viewModel in MVVM (WPF)?

I am learning MVVM pattern in WPF, alot of examples shows how to implement model to viewModel, but models in that examples are just simple classes, I want to use MVVM together with entity framework model (base first approach). Whats the best way to wire model to viewModel.

Thanks for answers.

```<code>//ctor of ViewModel
public ViewModel()
{
db = new PackageShipmentDBEntities(); // Entity Framework generated class

ListaZBazy = new ObservableCollection<Pack>(db.Packs.Where(w => w.IsSent == false));
}
</code>```

This is my usual ctor of ViewModel, think there is a better way, I was reading about repository pattern, not sure if I can adapt this to WPF MVVM

答:
I've looked into this quite a bit and haven't found a "perfect" solution. The repository pattern works wonderfully for MVC applications where the context is short lived because it exists in a short lived controller, but the problem happens when you try to apply that same structure to a wpf app where the VM can persist for long periods of time.

I have used this solution in the past which is much more simple than many of the repo patterns I have seen that attempt to abstract things out to an extreme amount, resulting in near unreadable amounts of code that are difficult to debug. Here are the steps...

Create a separate project for the EDMX to act as your Data access layer

Create a "Repositories" folder under the same project

Create a base class "BaseRepository" to act as the "Unit of Work". IDisposable will allow you to use this in a using(){} and the partial will allow you do implement other repositories

```<code>public partial class MyEntityRepository : IDisposable
{
    MyEntities context = new MyEntities();

    public void Dispose()
    {
        context.Dispose();
    }
}
</code>```

Create another file called "MyOtherRepository". create the same partial class but implement methods based on what you want that file to contain

```<code>public partial class MyEntityRepository
{
    public void MyOtherMethodSave(EntityObject obj)
    {
        //work with context
        ...

        context.SaveChanges();
    }
}
</code>```

Now in your VM you can do this...

```<code>using(MyEntityRepository repo = new MyEntityRepository())
{
     repo.MyOtherMethodSave(objectToSave);
}
</code>```

This groups all your repositories under one class so you don't have to deal with separate context. It allows you better manage different repos by grouping the methods into different files and helps prevent code duplication. On top of that, your contexts are as short lived as they were without using this pattern.

The disadvantage is that with larger systems, you may have a lot of methods that get bundled under your repo. One solution in that case would be to implement some basic common commands like "Find" or "Add", and implement specialized ones in their respective repository.

Body:
I've looked into this quite a bit and haven't found a "perfect" solution. The repository pattern works wonderfully for MVC applications where the context is short lived because it exists in a short lived controller, but the problem happens when you try to apply that same structure to a wpf app where the VM can persist for long periods of time.

I have used this solution in the past which is much more simple than many of the repo patterns I have seen that attempt to abstract things out to an extreme amount, resulting in near unreadable amounts of code that are difficult to debug. Here are the steps...

Create a separate project for the EDMX to act as your Data access layer

Create a "Repositories" folder under the same project

Create a base class "BaseRepository" to act as the "Unit of Work". IDisposable will allow you to use this in a using(){} and the partial will allow you do implement other repositories

public partial class MyEntityRepository : IDisposable
{
    MyEntities context = new MyEntities();

    public void Dispose()
    {
        context.Dispose();
    }
}

Create another file called "MyOtherRepository". create the same partial class but implement methods based on what you want that file to contain

public partial class MyEntityRepository
{
    public void MyOtherMethodSave(EntityObject obj)
    {
        //work with context
        ...

        context.SaveChanges();
    }
}

Now in your VM you can do this...

using(MyEntityRepository repo = new MyEntityRepository())
{
     repo.MyOtherMethodSave(objectToSave);
}

This groups all your repositories under one class so you don't have to deal with separate context. It allows you better manage different repos by grouping the methods into different files and helps prevent code duplication. On top of that, your contexts are as short lived as they were without using this pattern.

The disadvantage is that with larger systems, you may have a lot of methods that get bundled under your repo. One solution in that case would be to implement some basic common commands like "Find" or "Add", and implement specialized ones in their respective repository.


答:
Opposed to repositories, which I don't like. I would recommend using Command pattern, as recommended by Ayende.

Simply said, for each operation, you create a separate ThisOperationCommand class. Inside this class you will work with normal EF context. You might even use some base class EFCommand that does some plumbing for you.

From ViewModel side, you create instance of this command, fill it with parameters (you can even pass whole ViewModel instance if you don't mind tight coupling between the command and ViewModel) and then pass it to some kind of Execute method, that will start up the command, execute it, tear it down and then return whatever the command got. You can also have it return multiple values if you get it from instance of the command after execution.

The advantage is that you don't need to duplicate the whole data access layer as reposotory and you can reuse and compose commands as long as you create some simple infrastructure to support it. For example executing commands from other commands.

Title: What the best way to wire up Entity Framework database context (model) to ViewModel in MVVM WPF?

Body:
As in the question above: What the best way to wire up Entity Framework database model (context) to viewModel in MVVM (WPF)?

I am learning MVVM pattern in WPF, alot of examples shows how to implement model to viewModel, but models in that examples are just simple classes, I want to use MVVM together with entity framework model (base first approach). Whats the best way to wire model to viewModel.

Thanks for answers.

```<code>//ctor of ViewModel
public ViewModel()
{
db = new PackageShipmentDBEntities(); // Entity Framework generated class

ListaZBazy = new ObservableCollection<Pack>(db.Packs.Where(w => w.IsSent == false));
}
</code>```

This is my usual ctor of ViewModel, think there is a better way, I was reading about repository pattern, not sure if I can adapt this to WPF MVVM


问:
What is the right level of site blocking for you as a developer?
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?

答:
No blocking at all.

Good developers

Those will get the job done, they know how to find information quickly and they also know how to use that information. Of course if you don't give them enough to do, they'll waste their time over at the Stackoverflow Chatrooms :P

Bad developers

Well you can't do anything about them. If you block 90% of the interwebz just because they can't focus on their work, you'll only hinder the good developers... they will leave and you're left with the bad ones! (well in a perfect world...)


问:
How to safely run random binary codes?
Okay, so I am looking for a way to safely run a randomly generated binary code. I also need to be able to decompile the code. Any ideas and all programming languages are welcome. </p>

<p>BTW it most be binary code; byte code or source code will not work. This is a research project, so I can't go adding variables.       </p>

答:
So you are going to randomly generate code and run it?

The way I see it, your language choices are:

binary (straight machine instructions)

any higher level language

If (2) is randomly generated, it probably simply won't compile. Assuming your code isn't truly random and you get it to compile, most likely you'll just end up with exceptions because of all the bad data being passed around.

So that leaves you with just (1).  You have a much higher probability (still not 100%) that you'll be able to string together a bunch of "valid-looking" machine instructions that might run.  But then again, 99.99% of your randomly generated machine instructions won't even get past 4 or 5 of them.

If you want to prove this for yourself. I'd say forget trying to prevent damage. There won't be any. Just compile any C++ program, put a breakpoint in main function, open disassembly window and pave over memory with random data and just see how far your program gets.

The only protection you need is already provided for you by any modern OS that supports virtual memory. A normal user process (i.e. one that isn't running in kernel mode) cannot do any damage to another process or the OS itself.  The worst it can do is kill itself while executing invalid instructions.  I think for your experiment, that should be all protection you ever need.

Title: How to safely run random binary codes?


问:
Using Dynamic LINQ to get a filter for my Web API
We are considering using the Dynamic.CS linq-sample included in the "Samples" directory of visual studio 2008 for our WebAPI project to allow clients to query our data.

The interface would be something like this (In addition to the normal GET-methods):

```<code>public HttpResponseMessage List(string filter = null);
</code>```

The plan is to use the dynamic library to parse the "filter"-variable and then execute the query agains the DB. Any thoughts if this is a good idea? Is it a security problem?

答:
We implement it a bit differently right now.

We introduced Filter classes and filter Processors.

Filter processor takes intstance of the filter and converts it to expression of type Expression<Func<FilteredEntityType,bool>> which is then used as parameter of Where in Repository.

At the stage of processing the filter you can introduce some complex logic which concerns access rights for instance.

It's also viable to process OData query against exposed DTOs and convert it corresponding POCO  filtering query. But it's a bid harder to wotk with expression trees rather class.

Here is one of our filters:

```<code>[DataContract]
public class ProductFilter
{
    [DataMember]
    public int? ProductId { get; set; }

    [DataMember]
    public int? VendorId { get; set; }

    [DataMember]
    public string VendorNameEquals { get; set; }

    [DataMember]
    public int? ProductTypeId { get; set; }

    [DataMember]
    public string NameContains { get; set; }

    [DataMember]
    public string NameEquals { get; set; }
}
</code>```

Body:
We implement it a bit differently right now.

We introduced Filter classes and filter Processors.

Filter processor takes intstance of the filter and converts it to expression of type Expression<Func<FilteredEntityType,bool>> which is then used as parameter of Where in Repository.

At the stage of processing the filter you can introduce some complex logic which concerns access rights for instance.

It's also viable to process OData query against exposed DTOs and convert it corresponding POCO  filtering query. But it's a bid harder to wotk with expression trees rather class.

Here is one of our filters:

[DataContract]
public class ProductFilter
{
    [DataMember]
    public int? ProductId { get; set; }

    [DataMember]
    public int? VendorId { get; set; }

    [DataMember]
    public string VendorNameEquals { get; set; }

    [DataMember]
    public int? ProductTypeId { get; set; }

    [DataMember]
    public string NameContains { get; set; }

    [DataMember]
    public string NameEquals { get; set; }
}


问:
Best supporting argument for refactoring
Currently I am working on a code best described as C code living in C++ body. However I haven't been able to convince power that be to re-factor on ground of ease of maintenance. </p>

<p>What in your opinion is the best argument for refactoring the code. </p>

答:
The only way to get a business to agree to a refactor is to show them it will save them money. I dont mean just tell them, you need to be able to say we will save x days on bug type y saving us z pounds.Or in terms of savings when it comes to adding features.

It's all about the money.

Edit: I'm assuming this code is now live or late stage development. Refactoring during dev is a whole different question.


问:
Is it wise to store a big lump of json on a database row
I have this project which stores product details from amazon into the database.

Just to give you an idea on how big it is:

```<code>[
  {
    "title": "Genetic Engineering (Opposing Viewpoints)",
    "short_title": "Genetic Engineering ...",
    "brand": "",
    "condition": "",
    "sales_rank": "7171426",
    "binding": "Book",
    "item_detail_url": "http://localhost/wordpress/product/?asin=0737705124",
    "node_list": "Books > Science & Math > Biological Sciences > Biotechnology",
    "node_category": "Books",
    "subcat": "",
    "model_number": "",
    "item_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=128",
    "details_url": "http://localhost/wordpress/product/?asin=0737705124",
    "large_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/large-notfound.png",
    "medium_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/medium-notfound.png",
    "small_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/small-notfound.png",
    "thumbnail_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/thumbnail-notfound.png",
    "tiny_img": "http://localhost/wordpress/wp-content/plugins/ecom/img/tiny-notfound.png",
    "swatch_img": "http://localhost/wordpress/wp-content/plugins/ecom/img/swatch-notfound.png",
    "total_images": "6",
    "amount": "33.70",
    "currency": "$",
    "long_currency": "USD",
    "price": "$33.70",
    "price_type": "List Price",
    "show_price_type": "0",
    "stars_url": "",
    "product_review": "",
    "rating": "",
    "yellow_star_class": "",
    "white_star_class": "",
    "rating_text": " of 5",
    "reviews_url": "",
    "review_label": "",
    "reviews_label": "Read all ",
    "review_count": "",
    "create_review_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=132",
    "create_review_label": "Write a review",
    "buy_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=19186",
    "add_to_cart_action": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/add_to_cart.php",
    "asin": "0737705124",
    "status": "Only 7 left in stock.",
    "snippet_condition": "in_stock",
    "status_class": "ninstck",
    "customer_images": [
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/31FIM-YIUrL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg"
    ],
    "disclaimer": "",
    "item_attributes": [
      {
        "attr": "Author",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Binding",
        "value": "Hardcover"
      },
      {
        "attr": "EAN",
        "value": "9780737705126"
      },
      {
        "attr": "Edition",
        "value": "1"
      },
      {
        "attr": "ISBN",
        "value": "0737705124"
      },
      {
        "attr": "Label",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Manufacturer",
        "value": "Greenhaven Press"
      },
      {
        "attr": "NumberOfItems",
        "value": "1"
      },
      {
        "attr": "NumberOfPages",
        "value": "224"
      },
      {
        "attr": "ProductGroup",
        "value": "Book"
      },
      {
        "attr": "ProductTypeName",
        "value": "ABIS_BOOK"
      },
      {
        "attr": "PublicationDate",
        "value": "2000-06"
      },
      {
        "attr": "Publisher",
        "value": "Greenhaven Press"
      },
      {
        "attr": "SKU",
        "value": "G0737705124I2N00"
      },
      {
        "attr": "Studio",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Title",
        "value": "Genetic Engineering (Opposing Viewpoints)"
      }
    ],
    "customer_review_url": "http://localhost/wordpress/wp-content/ecom-customer-reviews/0737705124.html",
    "flickr_results": [
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/5105560852_06c7d06f14_m.jpg"
    ],
    "freebase_text": "No around the web data available yet",
    "freebase_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/freebase-notfound.jpg",
    "ebay_related_items": [
      {
        "title": "Genetic Engineering (Introducing Issues With Opposing Viewpoints), , Good Book",
        "image": "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/140.jpg",
        "url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=12165",
        "currency_id": "$",
        "current_price": "26.2"
      },
      {
        "title": "Genetic Engineering Opposing Viewpoints by DAVID BENDER - 1964 Hardcover",
        "image": "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/140.jpg",
        "url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=130",
        "currency_id": "AUD",
        "current_price": "11.99"
      }
    ],
    "no_follow": "rel=\"nofollow\"",
    "new_tab": "target=\"_blank\"",
    "related_products": [],
    "super_saver_shipping": "",
    "shipping_availability": "",
    "total_offers": "7",
    "added_to_cart": ""
  }
]
</code>```

So the structure for the table is:

asin

title

details (the product details in json)

Will the performance suffer if I have to store like 10,000 products? Is there any other way of doing this? I'm thinking of the following, but the current setup is really the most convenient one since I also have to use the data on the client side:

store the product details in a file. So something like ASIN123.json

store the product details in one big file. (I'm guessing it will be a drag to extract data from this file)

store each of the fields in the details in its own table field

Thanks in advance!

UPDATE

Thanks for the answers! I just want to add some more details to my question.
First, the records are updated for a specific interval. Only specific data such as the price or the title are updated.

Second, I'm also using the json encoded data in the client-side so I thought at first it would be easier to just have it json encoded so I can easily use it in the client side without having to convert. Does this change your opinion about simply storing the fields in a regular table field in an RDBMS setup?

答:
Size is not so much of an issue, the ability to query and maintain the data however is.

If, for example, Greenhaven Press decides they want to change their name to Greenhaven Press International, you'll have to find the record, deserialize it, change it, serialize it, pump it back into the database.

Consider this: does storing these objects as serialized data offer you a clear added value over storing it in a relational form? If the answer is no, then it might not be worth the hassle.

UPDATE

As far as your update of your question goes: I'm inclined to say no, it makes little or no difference. Whether you update one field or all of them in this json string is irrelevant because the whole process is identical.

Don't forget that your requirements might change; even though you're using json on the client side now doesn't mean you'll need json in the future. Storing your data in a relational form guarantees technology-independence while preserving relationships, data constraints and queryable metadata: this is where the true value of a relational db lies. Discarding those advantages will neither give you a performance gain nor make your application more scalable or flexible.


问:
Repository query conditions, dependencies and DRY
To keep it simple, let's suppose an application which has Accounts and Users. Each account may have any number of users. There's also 3 consumers of UserRepository:

An admin interface which may list all users

Public front-end which may list all users

An account authenticated API which should only list it's own users

Assuming UserRepository is something like this:

class UsersRepository extends DatabaseAbstraction {
    private function query() {
        return $this->database()->select('users.*');
    }
    public function getAll() {
        return $this->query()->exec();
    }
    // IMPORTANT:
    // Tons of other methods for searching, filtering,
    // joining of other tables, ordering and such...
}
```

<p>Keeping in mind the comment above, and the necessity to abstract user querying conditions, How should I handle querying of users filtering by <code>account_id</code>? I can picture three possible roads:</p>

<h3>1. Should I create an <code>AccountUsersRepository</code>?</h3>

<pre class="lang-php prettyprint-override"><code>class AccountUsersRepository extends UserRepository {
    public function __construct(Account $account) {
        $this->account = $account;
    }
    private function query() {
        return parent::query()
            ->where('account_id', '=', $this->account->id);
    }
}
</code>```

This has the advantage of reducing the duplication of UsersRepository methods, but doesn't quite fit into anything I've read about DDD so far (I'm rookie by the way)

2. Should I put it as a method on AccountsRepository?

class AccountsRepository extends DatabaseAbstraction {
    public function getAccountUsers(Account $account) {
        return $this->database()
            ->select('users.*')
            ->where('account_id', '=', $account->id)
            ->exec();
    }
}
```

<p><em>This requires the duplication of all <code>UserRepository</code> methods and may need another <code>UserQuery</code> layer, that implements those querying logic on chainable way.</em></p>

<h3>3. Should I query <code>UserRepository</code> from within my account entity?</h3>

<pre class="lang-php prettyprint-override"><code>class Account extends Entity {
    public function getUsers() {
        return UserRepository::findByAccountId($this->id);
    }
}
</code>```

This feels more like an aggregate root for me, but introduces dependency of UserRepository on Account entity, which may violate a few principles.

4. Or am I missing the point completely?

Maybe there's an even better solution?

Footnotes: Besides permissions being a Service concern, in my understanding, they shouldn't implement SQL query but leave that to repositories since those may not even be SQL driven.

答:
I would keep all User related data-access in the UserRepository. It is not a good idea to make repositories depend on each other but it's perfectly ok to have a service depend on multiple repositories. So in this case you could have an AccountService which uses both UserRepository and AccountRepository.

The third option you have considered is something I've also used and it has the benefit that now the user list is loaded lazily (although this can be accomplished by other means as well). The huge drawback is that it will be very hard to serialize that object to send it over wire for example and it also couples the data-access layer with your object model.


答: Sounds like you basically have a cellular automaton. Have a look at Hashlife: A quad tree based algorithm that can be used to simulate spatially sparse, structurally similar cellular automata very very quickly. Depending on your exact problem you can use it directly or at least draw some inspiration.</p>


问:
What is the most inspiring speech from a developer you ever watched?
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)

答:
http://www.youtube.com/watch?v=hQVTIJBZook

JavaScript: The Good Parts by Doug Crockford

JavaScript is a language with more
  than its share of bad parts. It went
  from non-existence to global adoption
  in an alarmingly short period of time.
  It never had an interval in the lab
  when it could be tried out and
  polished. JavaScript has some
  extraordinarily good parts. In
  JavaScript there is a beautiful,
  highly expressive language that is
  buried under a steaming pile of good
  intentions and blunders. The best
  nature of JavaScript was so
  effectively hidden that for many years
  the prevailing opinion of JavaScript
  was that it was an unsightly,
  incompetent abomination. This session
  will expose the goodness in
  JavaScript, an outstanding dynamic
  programming language. Within the
  language is an elegant subset that is
  vastly superior to the language as a
  whole, being more reliable, readable
  and maintainable.


问:
where do you track team Decisions
I have been on many development teams and as the team matures decisions about direction are made.  These decisions often come back up over and over.  Like why don't we fill in this field why didn't we use memcache over a custom solutions.  These decisions add up over time and become a significant part of style guides coding standards and unit tests.

My question is I have never run into a good way of tracking these decisions or the discovery that went into making them.  Does anyone have a best practice.

答:
Records of decisions made, whether in the form of design documents or meeting transcripts, should be stored in plain UTF-8 text files within the version control system, in the same repository as the organisation's source code, so that you can maintain traceability between when a decision was made, and when it was implemented.

Ideally, the decisions/minutes & other design documents should make use of machine readable conventions such as YAML or Markdown so that reports can be generated in whatever file format is required (HTML; PDF; DOC), whilst also permitting the use of version control tools like diff, merge and blame.

Title: where do you track team Decisions


问:
Requring static class setter to be called before constructor, bad design?
I have a class, say Foo, and every instance of Foo will need and contain the same List object, myList.

Since every class instance will share the same List Object, I thought it would be good to make myList static and use a static function to set myList before the constructor is called.

I was wondering if this was bad, because this requires the setter to be called before the constructor? If the person doesn't, the program will crash. Alternative way would be passing myList every time.

答:
By having global state you effectively implemented a FooFactory as a singleton (well, using static fields, but the effect is the same).

How about making the factory part explicit and getting rid of the singleton part (as singleton  is quite untestable, due to the action-at-a-distance problem):

```<code>public class FooFactory {
  private List myList;
  public FooFactory(List myList) {
    // ideally probably create an immutable copy of it
    this.myList = Collections.unmodifiableList(new ArrayList(myList));
    // ensure that myList has all the required characteristics
    if (this.myList.isEmpty()) {
      throw new IllegalArgumentException("Can't build a FooFactory with an empty myList");
    }
  }

  public Foo newFoo() {
    return new Foo(myList);
  }
}
</code>```

This, together with a package-private Foo constructor (so that noone can go the direct, dangerous route) ensures that only proper Foo objects will be created.

no action-at-a-distance, you always explicitly reference the FooFactory that contains the state

no accidentally changing someone elses FooFactory (since it's immutable)

you can't accidentally create a broken Foo object

Body:
By having global state you effectively implemented a FooFactory as a singleton (well, using static fields, but the effect is the same).

How about making the factory part explicit and getting rid of the singleton part (as singleton  is quite untestable, due to the action-at-a-distance problem):

public class FooFactory {
  private List myList;
  public FooFactory(List myList) {
    // ideally probably create an immutable copy of it
    this.myList = Collections.unmodifiableList(new ArrayList(myList));
    // ensure that myList has all the required characteristics
    if (this.myList.isEmpty()) {
      throw new IllegalArgumentException("Can't build a FooFactory with an empty myList");
    }
  }

  public Foo newFoo() {
    return new Foo(myList);
  }
}

This, together with a package-private Foo constructor (so that noone can go the direct, dangerous route) ensures that only proper Foo objects will be created.

no action-at-a-distance, you always explicitly reference the FooFactory that contains the state

no accidentally changing someone elses FooFactory (since it's immutable)

you can't accidentally create a broken Foo object


问:
Importance of uniformity of development architecture across the team
If some developers still use a 32 bit 'Windows XP' and others use a '64 bit Windows 7', would it be advisable for the entire team to work with 32 bit development tools even if their OS is 64 bit? Are there any problems that could happen if uniformity is not followed?</p>

答:
There's far less probability of issues if you all use the same toolchain.

There may not ever be a problem, but can you soak the time spent investigating why "it works on my machine" for our 64bit friends, and not with your 32bit ones if there is? It's usually the best option to go with lowest common denominator.

Behaviour does sometime differ from platform to platform, particularly for optimised release builds.

Again, very unlikely that there will be a problem, but always a good idea to standardise things.


答:
You have choices:

everyone uses the same architecture as you're providing to users. If you ship 64 bit, then develop on 64bit.

Everyone uses whatever dev architecture they like, and you ensure quality through a good integration environment, or multiple if you ship different versions.

There are problems, but these are quite temporary - in that you might have a problem with someone's code where they made assumptions that are not true on a different architecture. This is not such a bad thing, as its better to find these problems before your customer does. So all in all, standardise on a dev environment if it help you deploy new developers quicker, but otherwise concentrate on the end-product quality, no matter what the developer used to build it.

Title: Importance of uniformity of development architecture across the team

Body: If some developers still use a 32 bit 'Windows XP' and others use a '64 bit Windows 7', would it be advisable for the entire team to work with 32 bit development tools even if their OS is 64 bit? Are there any problems that could happen if uniformity is not followed?</p>


答:
Is it wise to store a big lump of json on a database row?

No, generally it is a bad idea to store multi-valued data in one cell of a relational database because it goes against the basic structure/rules of RDBMS (as mentioned in the other answer).

However, you may look into the possibility of using one of the non-relational (no-sql) databases, such as MongoDB, which will help you store JSON objects and search for data inside those objects.

Body:
I have this project which stores product details from amazon into the database.

Just to give you an idea on how big it is:

```<code>[
  {
    "title": "Genetic Engineering (Opposing Viewpoints)",
    "short_title": "Genetic Engineering ...",
    "brand": "",
    "condition": "",
    "sales_rank": "7171426",
    "binding": "Book",
    "item_detail_url": "http://localhost/wordpress/product/?asin=0737705124",
    "node_list": "Books > Science & Math > Biological Sciences > Biotechnology",
    "node_category": "Books",
    "subcat": "",
    "model_number": "",
    "item_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=128",
    "details_url": "http://localhost/wordpress/product/?asin=0737705124",
    "large_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/large-notfound.png",
    "medium_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/medium-notfound.png",
    "small_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/small-notfound.png",
    "thumbnail_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/thumbnail-notfound.png",
    "tiny_img": "http://localhost/wordpress/wp-content/plugins/ecom/img/tiny-notfound.png",
    "swatch_img": "http://localhost/wordpress/wp-content/plugins/ecom/img/swatch-notfound.png",
    "total_images": "6",
    "amount": "33.70",
    "currency": "$",
    "long_currency": "USD",
    "price": "$33.70",
    "price_type": "List Price",
    "show_price_type": "0",
    "stars_url": "",
    "product_review": "",
    "rating": "",
    "yellow_star_class": "",
    "white_star_class": "",
    "rating_text": " of 5",
    "reviews_url": "",
    "review_label": "",
    "reviews_label": "Read all ",
    "review_count": "",
    "create_review_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=132",
    "create_review_label": "Write a review",
    "buy_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=19186",
    "add_to_cart_action": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/add_to_cart.php",
    "asin": "0737705124",
    "status": "Only 7 left in stock.",
    "snippet_condition": "in_stock",
    "status_class": "ninstck",
    "customer_images": [
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/31FIM-YIUrL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg"
    ],
    "disclaimer": "",
    "item_attributes": [
      {
        "attr": "Author",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Binding",
        "value": "Hardcover"
      },
      {
        "attr": "EAN",
        "value": "9780737705126"
      },
      {
        "attr": "Edition",
        "value": "1"
      },
      {
        "attr": "ISBN",
        "value": "0737705124"
      },
      {
        "attr": "Label",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Manufacturer",
        "value": "Greenhaven Press"
      },
      {
        "attr": "NumberOfItems",
        "value": "1"
      },
      {
        "attr": "NumberOfPages",
        "value": "224"
      },
      {
        "attr": "ProductGroup",
        "value": "Book"
      },
      {
        "attr": "ProductTypeName",
        "value": "ABIS_BOOK"
      },
      {
        "attr": "PublicationDate",
        "value": "2000-06"
      },
      {
        "attr": "Publisher",
        "value": "Greenhaven Press"
      },
      {
        "attr": "SKU",
        "value": "G0737705124I2N00"
      },
      {
        "attr": "Studio",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Title",
        "value": "Genetic Engineering (Opposing Viewpoints)"
      }
    ],
    "customer_review_url": "http://localhost/wordpress/wp-content/ecom-customer-reviews/0737705124.html",
    "flickr_results": [
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/5105560852_06c7d06f14_m.jpg"
    ],
    "freebase_text": "No around the web data available yet",
    "freebase_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/freebase-notfound.jpg",
    "ebay_related_items": [
      {
        "title": "Genetic Engineering (Introducing Issues With Opposing Viewpoints), , Good Book",
        "image": "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/140.jpg",
        "url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=12165",
        "currency_id": "$",
        "current_price": "26.2"
      },
      {
        "title": "Genetic Engineering Opposing Viewpoints by DAVID BENDER - 1964 Hardcover",
        "image": "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/140.jpg",
        "url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=130",
        "currency_id": "AUD",
        "current_price": "11.99"
      }
    ],
    "no_follow": "rel=\"nofollow\"",
    "new_tab": "target=\"_blank\"",
    "related_products": [],
    "super_saver_shipping": "",
    "shipping_availability": "",
    "total_offers": "7",
    "added_to_cart": ""
  }
]
</code>```

So the structure for the table is:

asin

title

details (the product details in json)

Will the performance suffer if I have to store like 10,000 products? Is there any other way of doing this? I'm thinking of the following, but the current setup is really the most convenient one since I also have to use the data on the client side:

store the product details in a file. So something like ASIN123.json

store the product details in one big file. (I'm guessing it will be a drag to extract data from this file)

store each of the fields in the details in its own table field

Thanks in advance!

UPDATE

Thanks for the answers! I just want to add some more details to my question.
First, the records are updated for a specific interval. Only specific data such as the price or the title are updated.

Second, I'm also using the json encoded data in the client-side so I thought at first it would be easier to just have it json encoded so I can easily use it in the client side without having to convert. Does this change your opinion about simply storing the fields in a regular table field in an RDBMS setup?