答:
I'm of the belief that a class should not implement an interface unless that class can be used when an implementation of the interface is required.

BaseWorker fulfills that requirement.  Just because you can't directly instantiate a BaseWorker object doesn't mean you can't have a BaseWorker pointer that fulfills the contract.  Indeed, that's pretty much the whole point of abstract classes.

Also, it's difficult to tell from the simplified example you posted, but part of the problem may be that the interface and the abstract class are redundant.  Unless you have other classes implementing IFooWorker that do not derive from BaseWorker, you don't need the interface at all.  Interfaces are just abstract classes with some additional limitations that make multiple inheritance easier.

Again being difficult to tell from a simplified example, the use of a protected method, explicitly referring to the base from a derived class, and the lack of an unambiguous place to declare the interface implementation are warning signs that you are inappropriately using inheritance instead of composition.  Without that inheritance, your whole question becomes moot.

Title: Interfaces on an abstract class

Body:
My coworker and I have different opinions on the relationship between base classes and interfaces.  I'm of the belief that a class should not implement an interface unless that class can be used when an implementation of the interface is required.  In other words, I like to see code like this:

```<code>interface IFooWorker { void Work(); }

abstract class BaseWorker {
    ... base class behaviors ...
    public abstract void Work() { }
    protected string CleanData(string data) { ... }
}

class DbWorker : BaseWorker, IFooWorker {
    public void Work() {
        Repository.AddCleanData(base.CleanData(UI.GetDirtyData()));
    }
}
</code>```

The DbWorker is what gets the IFooWorker interface, because it is an instantiatable implementation of the interface.  It completely fulfills the contract.  My coworker prefers the nearly identical:

```<code>interface IFooWorker { void Work(); }

abstract class BaseWorker : IFooWorker {
    ... base class behaviors ...
    public abstract void Work() { }
    protected string CleanData(string data) { ... }
}

class DbWorker : BaseWorker {
    public void Work() {
        Repository.AddCleanData(base.CleanData(UI.GetDirtyData()));
    }
}
</code>```

Where the base class gets the interface, and by virtue of this all inheritors of the base class are of that interface as well.  This bugs me but I can't come up with concrete reasons why, outside of "the base class cannot stand on its own as an implementation of the interface".

What are the pros & cons of his method vs. mine, and why should one be used over another?


问:
Understanding the static keyword
I have some experience in developing with Java, Javascript and PHP.

I am reading Microsoft Visual C# 2010 Step by Step which I feel it is a very good book on introducing you to the C# language.

I seem to be having problems in understanding the static keyword. From what I understand this far if a class is declared static all methods and variable have to be static. The main method always is a static method so in the class that the main method exists all variables and methods are declared static if you have to call them in the main method. Also I have noticed that in order to call a static method from another class you do not need to create an object of that you can use the class name.

But what is the actual purpose of the static keyword? When should I declare static variable and methods?

答:
The 'static' keyword in C# is refering to something in the class, or the class itself, that is shared amongst all instances of the class.  For example, a field that is marked as static can be accessed from all instances of that class through the class name.

```<code>public class SomeObject
{
    //Static Field
    static int Foo = 3;

    //instance field
    private int _Foo2 = 4;

    //instance property
    public int Foo2{get{return _Foo2;}set{_Foo2 = value;}}

    //static factory method
    public static SomeObject CreateSomeObject(int fooValue)
    {
        SomeObject retVal = new SomeObject();
        retVal.Foo2 = fooValue;
        return retVal;
    }

    //Parameterless instance constructor
    public SomeObject()
    {
    }

    public static int Add(int x)
    {
        //Static methods can only deal with local variables, or fields that
        //  are also static in the class.  This one adds x to the static member foo
        return x + Foo;

        //Foo2 is not accessable here!
    }

      //Instance method
    public int AddSomething(int x)
    {
        //Add x to the property value of Foo2
        return x + this.Foo2;

        //Note that Foo *is* accessable here as 'SomeObject.Foo'
    }

}
</code>```

I can honestly say that I have never used a class marked as static with the exception of creating extention methods (Quick tutorial on extension methods).

Anyways, there are specific design patterns for utilizing static methods, such as factory pattern and singleton pattern, but the important thing to remember is that static methods and constructors do not deal with any specific instance of a class (unless you pass one in), typically to do calculations or to do a comparison between objects.  The "Main" method you are refering to is always static, but to see it from a different point of view, see this article.

To follow up with this, here is how the difference between static and instantiated methods, fields and properties are called.

```<code>public static void Main(string[] args)
{
    //This is a static method that starts a thread in an application
    // space.  At this point not everything actually has to be static...

    //Here is an instantiation with a parameterless contruction
    SomeObject obj = new SomeObject();

    //Here is an instantiation using a static factory method
    SomeObject obj2 = SomeObject.CreateSomeObject(3);

    //Getting field value from static field
    // Notice that this references the class name, not an instance
    int fooValue1 = SomeObject.Foo;

    //Getting property value from instance
    //  Note that this references an object instance
    int fooValue2 = obj2.Foo2;

    //Instance method must be called through an object
    obj2.AddSomething(4);  //if default constructor, would return 8

    //Static methods must be called through class name
    SomeObject.Add(4); //Returns 7
}
</code>```

Also, check this post out for a deeper look into static classes.

ContentLicense: CC BY-SA 3.0

Title: Understanding the static keyword

Body:
The 'static' keyword in C# is refering to something in the class, or the class itself, that is shared amongst all instances of the class.  For example, a field that is marked as static can be accessed from all instances of that class through the class name.

public class SomeObject
{
    //Static Field
    static int Foo = 3;

    //instance field
    private int _Foo2 = 4;

    //instance property
    public int Foo2{get{return _Foo2;}set{_Foo2 = value;}}

    //static factory method
    public static SomeObject CreateSomeObject(int fooValue)
    {
        SomeObject retVal = new SomeObject();
        retVal.Foo2 = fooValue;
        return retVal;
    }

    //Parameterless instance constructor
    public SomeObject()
    {
    }

    public static int Add(int x)
    {
        //Static methods can only deal with local variables, or fields that
        //  are also static in the class.  This one adds x to the static member foo
        return x + Foo;

        //Foo2 is not accessable here!
    }

      //Instance method
    public int AddSomething(int x)
    {
        //Add x to the property value of Foo2
        return x + this.Foo2;

        //Note that Foo *is* accessable here as 'SomeObject.Foo'
    }

}

I can honestly say that I have never used a class marked as static with the exception of creating extention methods (Quick tutorial on extension methods).

Anyways, there are specific design patterns for utilizing static methods, such as factory pattern and singleton pattern, but the important thing to remember is that static methods and constructors do not deal with any specific instance of a class (unless you pass one in), typically to do calculations or to do a comparison between objects.  The "Main" method you are refering to is always static, but to see it from a different point of view, see this article.

To follow up with this, here is how the difference between static and instantiated methods, fields and properties are called.

public static void Main(string[] args)
{
    //This is a static method that starts a thread in an application
    // space.  At this point not everything actually has to be static...

    //Here is an instantiation with a parameterless contruction
    SomeObject obj = new SomeObject();

    //Here is an instantiation using a static factory method
    SomeObject obj2 = SomeObject.CreateSomeObject(3);

    //Getting field value from static field
    // Notice that this references the class name, not an instance
    int fooValue1 = SomeObject.Foo;

    //Getting property value from instance
    //  Note that this references an object instance
    int fooValue2 = obj2.Foo2;

    //Instance method must be called through an object
    obj2.AddSomething(4);  //if default constructor, would return 8

    //Static methods must be called through class name
    SomeObject.Add(4); //Returns 7
}

Also, check this post out for a deeper look into static classes.


问:
What software do you use to help plan your team work, and why?
Planning is very difficult. We are not naturally good at estimating our own future, and many cognitive biases exacerbate the problem. Group planning is even harder. Incomplete information, inconsistent views of a situation, and communication problems compound the difficulty.

Agile methods provide one framework for organizing group planning--making planning visible to everyone (user stories), breaking it into smaller chunks (sprints), and providing retrospective analysis so you get better at planning. But finding good tools to support these practices is proving tricky.

What software tools do you use to achieve these goals? Why are you using that tool? What successes have you had with a particular tool?

答:
We use Redmine -> http://www.redmine.org/

We log all our dev in there along with support calls so we can see how much time we have free to allocate to a sprint on our latest bit of development.  It is useful because it ties in nicely with our email system and our Version Control System (Git in our case, but it works with others).

Easy to get going out of the box (written in Ruby, will run on most small servers) and with some fairly powerful addons which are easy to install and use.

ContentLicense: CC BY-SA 2.5


问:
Situations that require protecting files against tampering when stored on a users computer
I'm making a 'Pokémon Storage System' with a Client/Server model and as part of that I was thinking of storing an inventory file on the users computer which I do not wish to be edited except by my program. An alternative to this would be to instead to store the inventory file on the server and control it's editing by sending commands to the server but I was wondering if there are any situations which require files to be stored on a users computer where editing would be undesirable and if so how do you protect the files? I was thinking AES with some sort of checksum?</p>

答:
Logically it's impossible - if the clients computer has all the information to edit the inventory then it has all the information necessary to edit the inventory.

You can make it harder by encrypting the data and hiding the key inside your program, storing parts of the key in different places and calculating parts based on some maths is popular. But ultimatly it depends on how much time/effort they are going to put into it.  If this is just a kids game then simple encryption will do - if you are doing online gambling for big $$$ then it won't!


问:
Configuration data: single-row table vs. name-value-pair table
Let's say you write an application that can be configured by the user. For storing this "configuration data" into a database, two patterns are commonly used.

The single-row table

```<code>  CompanyName  |  StartFullScreen  |  RefreshSeconds  |  ...
---------------+-------------------+------------------+--------
  ACME Inc.    |        true       |       20         |  ...
</code>```

The name-value-pair table

```<code>  ConfigOption   |   Value
-----------------+-------------
 CompanyName     | ACME Inc.
 StartFullScreen | true (or 1, or Y, ...)
 RefreshSeconds  | 20
 ...             | ...
</code>```

I've seen both options in the wild, and both have obvious advantages and disadvantages, for example:

The single-row tables limits the number of configuration options you can have (since the number of columns in a row is usually limited). Every additional configuration option requires a DB schema change.

In a name-value-pair table everything is "stringly typed" (you have to encode/decode your Boolean/Date/etc. parameters).

(many more)

Is there some consensus within the development community about which option is preferable?

答:
Single row
Pros : Well defined.
Cons : Changing the configuration can be a pain. DB migrations etc..

Entity-Value
Pros : Super flexible, supports evolving your config.
Cons : Referential integrity ? More checks in your code to see if the property exists before you can do anything on it.

I would take approach 2 backed by a non-relational db like Mongo. If there is something you can be sure of, its change.


问:
What Does It Usually Mean for a Feature to be "Supported"?
I'm currently working some testing for a particular area of an application. I had to write some automated tests for a particular feature but due to the circumstances, this was not easy to do. When I asked one of the other testers about it, he mentioned that the same features exist in a sister application our company produces but isn't documented anywhere (end-user documentation or otherwise). He also said that the feature doesn't typically get tested at all in the sister application and isn't usually tested in the application I work on. Apparently this feature isn't heavily used but removing it would require a fair bit of work so the benefit-cost ratio doesn't work out.

All of this has left me with some questions. Other than "The documentation says so" or "We told the client it is", what usually makes a feature "supported" versus an unsupported feature?

答:
A feature is "supported" if the party responsible for the software's overall functionality asserts and takes responsibility for the correct behavior of the software when used in that particular way.

Think of it kind of like a prescription or OTC drug. The maker of that drug designed and intended it to have certain primary effects, targeting a certain "problem" (disease, syndrome, disorder, etc). However, doctors and patients may find that it has certain "side effects" which may actually be desirable. Diphenhydramine (Benadryl) was originally developed and marketed as an antihistamine. Minoxodil (Rogaine) was originally intended as a topical vasodilator to improve skin circulation. Viagra was intended as a blood pressure medication. In all these cases, the side effects (drowsiness, hair growth, erections) were seen as beneficial and the drug came to be marketed for that primary effect.

In contrast, there are side effects that doctors have seen as beneficial, or diseases that show improvement with the medication, that weren't the drug maker's intent. Until the drug maker goes through the approval process with the FDA for this new use, the drug maker is not allowed to market the drug to doctors as being useful for this condition, and does not have any liability for damages as a result of this "off-script" use. Doctors can still prescribe it - they can prescribe pretty much anything for anything - but they carry full liability for any ill effects or other failure.

Software is similar, but without FDA oversight (or drowsiness, dry mouth, heart attack, stroke, coma, death or halitosis). The product owner may have designed a piece of software to fill a certain specific need. Users of the software may then find that if you set it up a certain way, it does this other useful thing. The project owner may never have expected that, and in fact may consider it a bug. As such, they may not "support" the software being used in that way; if it fails to perform correctly in that configuration, the user is not entitled to the benefits of any warranty, nor will the developers try to fix the "problem". On the other hand, if that alternate usage is considered beneficial, the programmers may include that functionality, planning for it, testing its correctness and asserting that it will indeed perform correctly when used that way; they now "support" that usage.


答:
I was thinking AES with some sort of checksum?

No. If someone de-complies your Software they will get the Key and be able to modify the Check Sum. The ONLY way to secure this data from being modified is store it on your server.

If you install on a Computer you don’t have control of, assume the Computers owner has access to ALL the installed source code (and can modify it).

Title: Situations that require protecting files against tampering when stored on a users computer

Body: I'm making a 'Pokémon Storage System' with a Client/Server model and as part of that I was thinking of storing an inventory file on the users computer which I do not wish to be edited except by my program. An alternative to this would be to instead to store the inventory file on the server and control it's editing by sending commands to the server but I was wondering if there are any situations which require files to be stored on a users computer where editing would be undesirable and if so how do you protect the files? I was thinking AES with some sort of checksum?</p>


问:
What's the next level of abstraction?
Since programming languages initially only used lines of code executed sequentially, and it evolved into including functions which were one of the first levels of abstraction, and then classes and objects were created to abstract it even further; what is the next level of abstraction?

What's even more abstract than classes or is there any yet?

答:
The next abstraction after classes are meta classes. It's that simple ;)

a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances. Not all object-oriented programming languages support metaclasses. Among those that do, the extent to which metaclasses can override any given aspect of class behavior varies. Each language has its own metaobject protocol, a set of rules that govern how objects, classes, and metaclasses interact...

Title: What's the next level of abstraction?


答:
It's a hacking race you can't win, but you can make the contest interesting by signing and/or encrypting the data.  If there's a remote server involved, the remote can do the signing and verifying.

Also, consider that you need to prevent other things than fabrication or alteration - "good" inventory files might be shared (or sold), stored and reused, or many other creative kinds of abuse.

Remember that the weakest link is the one that will be attacked.  If your signing and verifying methods are good enough, the hackers will just target the decrypted/unsigned form of the data that has to exist in order for it to be used.


问:
How to use DI and DI containers
I am building a small PHP mvc framework (yes, yet another one), mostly for learning purposes, and I am trying to do it the right way, so I'd like to use a DI container, but I am not asking which one to use but rather how to use one.

Without going into too much detail, the mvc is divided into modules which have controllers which render views for actions. This is how a request is processed:

a Main object instantiates a Request object, and a Router, and injects the Request into the Router to figure out which module was called.

then it instantiates the Module object and sends the Request to that

the Module creates a ModuleRouter and sends the Request to figure out the controller and action

it then creates the Controller and the ViewRenderer, and injects the ViewRenderer into the Controller (so that the controller can send data to the view)

the ViewRenderer needs to know which module, controller and action were called to figure out the path to the view scripts, so the Module has to figure out this and inject it to the ViewRenderer

the Module then calls the action method on the controller and calls the render method on the ViewRenderer

For now, I do not have any DI container set up, but what I do have are a bunch of initX() methods that create the required component if it is not already there.
For instance, the Module has the initViewRenderer() method.
These init methods get called right before that component is needed, not before, and if the component was already set it will not initialize it. This allows for the components to be switched, but it does not require manually setting them if they are not there.

Now, I'd like to do this by implementing a DI container, but still keep the manual configuration to a bare minimum, so if the directory structure and naming convention is followed, everything should work, without even touching the config.

If I use the DI container, do I then inject it into everything (the container would inject itself when creating a component), so that other components can use it?
When do I register components with the DI?
Can a component register other components with the DI during run-time?
Do I create a 'common' config and use that?
How do I then figure out on the fly which components I need and how they need to be set up?

If Main uses Router which uses Request,
Main then needs to use the container to get Module (or does the module need to be found and set beforehand? How?)
Module uses Router but needs to figure out the settings for the ViewRenderer and the Controller on the fly, not in advance, so my DI container can't be setting those on the Module before the module figures out the controller and action...

What if the controller needs some other service? Do I inject the container into every controller? If I start doing that, I might just inject it into everything...

Basically I am looking for the best practices when dealing with stuff like this. I know what DI is and what DI containers do, but I am looking for guidance to using them in real life, and not some isolated examples on the net.

Sorry for the lengthy post and many thanks in advance.

EDIT: after reading a bit more, it seems that injection the container itself into objects and making them use the container to find stuff is actually service location, not dependency injection. So my latest idea is to use factories for the stuff that should be dynamically acquired based on something (like getting controllers based on what the router says), and the container would be injected into the factories where it would be used more like a service locator. The non dynamic components would be registered beforehand, and those components would be built by the container and returned fully operational, with all their dependencies filled.

So the flow would look like this:

get Main from the container, Main is injected with Request, Router and ModuleFactory which uses the container to find modules. This is all pre-configured

Main uses ModuleFactory to create the Module, injected with ModuleRouter, Request, ControllerFactory and ViewRenderer.

Module uses ControllerFactory to create a Controller, injected with any service that it depends on, and then the Module calls the action on the controller, and sends the result to the ViewRenderer to render the view.

Am I getting anywhere with this?

答:
I know its kind of a counter argument but I think it would be beneficial for you to look beyond DI.

Think about the properties of DI and what you are trying to do with applying it.

Here is a video, different aspects of programming styles are discussed(arround 25 min the case for DI is made)
http://www.infoq.com/presentations/Value-Values

Title: How to use DI and DI containers


问:
Has "Not everyone can be a programmer" been studied?
An old adage that many programmers stick to is "It takes a certain type of mind to learn programming, and not everyone can do it."

Now I'm sure that we all have our own trove of anecdotal evidence, but has this been studied scientifically?

答:
One can make studies about abstraction capacities, or other useful knowledge, but the definition of programming is unclear, and I think the quote is irrelevant, because there are opposite ways to look at programming:

The first kind: Programming languages are (or should be) some kind of human language made to describe a task for the computer to execute, so everyone who talks should be able to program. It's called scripting, BASIC, the typesetting system TeX, etc... The language or the system doesn't matter, it's the way their creators and people looked at it: "Dear program/computer, please print my name", rather than "Get me space the size of eleven chars, then give me the adress of this space, then let me store it, then enter eleven characters into this memory which you can take out of my keyboard buffer (but don't forget to clean it, etc."

In this case it's clear that the study would rather be "Not every language can be assimilated quickly?".

On the other hand, programming languages are just a way to describe how a computer works or how it should work, how it should be 'connected' if you think of 1950s computers. Therefore the programmer can't do anything, even if he 'speaks' the programming language perfectly, if his/her intelligence can't reach this abstraction level where you see bytes beeing stored in memory, strings as pointers, etc., and then go back to earth to link it to the problem. Therefore not every human can program (in assembly language...).

Apart from this, you will need all qualities required to work and produce something: know very well what you want, make it easy for others to understand/complete/review, focus on your objectives, etc... But just like an architect, a writer, a musician, a prostit..aehh prothesist, etc.

But most humans have good abstractions capacities, especially children. Some German schools are teaching Haskell to pre-teens (programming languages like Pascal or Delphi are beeing taught in every German school).

So I would say the question is very hard to answer, and any answer (or study) is likely to be irrelevant.

You will find a very brief analysis of how people learn programming in the article Teach Yourself Programming in Ten Years by Peter Norvig. He seems to think there is no born programmer.


答:
I would argue that meta-structures, modules, frameworks, platforms, and services are all higher-level feature groupings than classes. My hierarchy of programming system abstractions:

services

platforms, solution stacks

frameworks

modules, packages

meta structures: metaclasses, higher order functions, generics, templates, traits, aspects, decorators

objects, classes, data types

functions, procedures, subroutines

control structures

lines of code

Meta-structures like metaclasses,
higher order functions, and
generics
clearly add abstraction to basic classes, functions, data types, and data instances. Traits, aspects, and decorators are newer mechanisms for combining code features, and similarly 'accelerate' other classes and functions.

Even pre-object languages had modules and packages, so putting them above classes might be debatable. Bu they contain those classes and meta-structures, so I rank them higher.

Frameworks are the meatiest answer--they orchestrate multiple classes, meta-structures, modules, functions, and such in order to provide sophisticated high-level abstractions. And yet frameworks still operate almost entirely in the realm of programming.

Solution stacks or platforms generally combine multiple frameworks, subsystems, or components into an environment for solving multiple problems.

Finally, there are services--often deployed as Web or network services. These are architectures, frameworks, solution stacks, or application capabilities delivered as complete bundles. Their internals are often opaque, primarily exposing administrator, programming, and user interfaces. PaaS and SaaS are common examples.

Now, this progression may not be entirely satisfying, for a few reasons. First, it makes a neat linear progression or hierarchy of things that aren't perfectly linear or hierarchical. It covers some abstractions like "stacks" and service that are not entirely under developer control. And it doesn't posit any new magic pixie dust. (Spoiler: There is no magic pixie dust.)

I think it's a mistake to look just for new abstraction levels. All the ones I listed above have existed for years, even if they haven't all been as prominent or popular as they now are. And over those years, the abstractions possible at every level of coding have improved. We now have general-purpose, generic collections, not just arrays. We loop over collections, not just index ranges. We have list comprehensions and list filter and map operations. Many language's functions can have a variable number of arguments, and/or default arguments. And so on. We are increasing abstraction at every level, so adding more levels isn't a requirement for increasing the overall level of abstraction.

Title: What's the next level of abstraction?

Body:
Since programming languages initially only used lines of code executed sequentially, and it evolved into including functions which were one of the first levels of abstraction, and then classes and objects were created to abstract it even further; what is the next level of abstraction?

What's even more abstract than classes or is there any yet?


问:
Suggestions needed on an architecture for a multiple clients and customisable web application
Our product is a web based course managemant system. We have 10+ clients and in future we may get more clients. (Asp.net,SQL Server)

Currently if one of our customers need extra functionality or customised business logic, we will change the db schema and code to meet the needs.

(we only have one branch code base and one database schema)

To make the change wont affect each others route, we use a client flag, which defined in a web config file, thus those extra fields and biz logic only applied to a particular customer's system.

```<code>if(ClientId = 'ABC')
{
   //DO ABC Stuff
}
else
{
   //Normal Route
}
</code>```

One of our senior colleagues said, in this way, small company like us can save resources on supporting multiple resources.

But what I feel is, this strategy makes our code and database even harder to maintain.

Anyone there crossed similar situation? How do you handle that?

答:
Parameterize as much as you can first, of course.

Avoid writing:

```<code>if(customer == 'foo') {
  doBarCalculation();
}
</code>```

, but rather write:

```<code>if(customer.usesBarCalculation) {
  doBarCalculation();
}
</code>```

Use the Strategy pattern:

```<code>customer.getCalculation().doCalculation();

Customer {
  CalculationStrategy getCalculation();
}

CalculationStrategy {
  doCalculation();
}
</code>```

; you can use Strategy at different scales; either offer many small, simple interfaces or a few large interfaces- it is worth thinking up the scale well; large interfaces tend to provoke code duplication between implementations (and code duplication is bad), while smaller interfaces are often harder to design in advance or increase complexity.

Body:
Parameterize as much as you can first, of course.

Avoid writing:

if(customer == 'foo') {
  doBarCalculation();
}

, but rather write:

if(customer.usesBarCalculation) {
  doBarCalculation();
}

Use the Strategy pattern:

customer.getCalculation().doCalculation();

Customer {
  CalculationStrategy getCalculation();
}

CalculationStrategy {
  doCalculation();
}

; you can use Strategy at different scales; either offer many small, simple interfaces or a few large interfaces- it is worth thinking up the scale well; large interfaces tend to provoke code duplication between implementations (and code duplication is bad), while smaller interfaces are often harder to design in advance or increase complexity.


答:
For me, whether you go single-row or EAV (Entity-Attribute-Value) depends on how you want to consume them.

EAV's power is that new data can be added with no change to structure. This means that if you want a new configuration value, you just add it to the table and pull it out where you want it in code, and you don't need to add a new field to the domain, schema, mapping, DAL queries, etc.

Its flaw is that it has only the barest structure, requiring you to deal with the data pessimistically. Every usage of any configuration value must expect the value to not be present, or not in the proper format, and behave accordingly when it isn't. A config value may not be parsable to a double, or an int, or a char. It may be null. there may be no row for the value at all. The ways around this usually require a single valid "default" value to exist for all config values of a particular in-code type (extremely rare; more often the default value is just as problematic for consuming code as none at all), or to keep a hardcoded dictionary of default values (which must change every time a new column is added, making the primary advantage of EAV storage pretty moot).

A single wide row is pretty much the opposite. You map it to a single instance of a Configuration object with a field/property for every configuration value in existence. You know exactly what type those values should be at compile time, and you "fail fast" in the DAL if a config column doesn't exist or doesn't have a value of the proper type, giving you one place to catch exceptions based on configuration retrieval/hydration problems.

The main disadvantage is that a structural change is required for each new value; new DB column, new column in the DAL (either the mapping or the SQL queries/SPs), new domain column, all necessary to properly test usage.

The proper situation in which to use either of these is the situation in which the disadvantages are mitigated. For me, most situations for config coding have called for a single-row implementation. This is mainly because if you're introducing an entirely new configuration value that governs behavior of some part of your program, you already have to change the code to use the new configuration value; why not pop over to the config object and add the value to be used?

In short, an EAV schema to store configuration really doesn't solve the problem it purports to solve, and most of the workarounds to the problems it presents violate DRY.

Title: Configuration data: single-row table vs. name-value-pair table

Body:
Let's say you write an application that can be configured by the user. For storing this "configuration data" into a database, two patterns are commonly used.

The single-row table

```<code>  CompanyName  |  StartFullScreen  |  RefreshSeconds  |  ...
---------------+-------------------+------------------+--------
  ACME Inc.    |        true       |       20         |  ...
</code>```

The name-value-pair table

```<code>  ConfigOption   |   Value
-----------------+-------------
 CompanyName     | ACME Inc.
 StartFullScreen | true (or 1, or Y, ...)
 RefreshSeconds  | 20
 ...             | ...
</code>```

I've seen both options in the wild, and both have obvious advantages and disadvantages, for example:

The single-row tables limits the number of configuration options you can have (since the number of columns in a row is usually limited). Every additional configuration option requires a DB schema change.

In a name-value-pair table everything is "stringly typed" (you have to encode/decode your Boolean/Date/etc. parameters).

(many more)

Is there some consensus within the development community about which option is preferable?

ContentLicense: CC BY-SA 4.0


答:
Maybe this is anecdotal, but when I taught intro programming to a few hundred liberal arts students, I found no such "double hump".
It seemed to me they were all quite capable, though some worked harder than others,
and a very few tried to bluff their way through.

A lot has to do with how it is taught.

A lot also has to do with desire - some don't find programming the least bit interesting.
But even so, they can learn it if they give it an honest effort.

Title: Has "Not everyone can be a programmer" been studied?

Body:
An old adage that many programmers stick to is "It takes a certain type of mind to learn programming, and not everyone can do it."

Now I'm sure that we all have our own trove of anecdotal evidence, but has this been studied scientifically?


问:
Interfaces on an abstract class
My coworker and I have different opinions on the relationship between base classes and interfaces.  I'm of the belief that a class should not implement an interface unless that class can be used when an implementation of the interface is required.  In other words, I like to see code like this:

```<code>interface IFooWorker { void Work(); }

abstract class BaseWorker {
    ... base class behaviors ...
    public abstract void Work() { }
    protected string CleanData(string data) { ... }
}

class DbWorker : BaseWorker, IFooWorker {
    public void Work() {
        Repository.AddCleanData(base.CleanData(UI.GetDirtyData()));
    }
}
</code>```

The DbWorker is what gets the IFooWorker interface, because it is an instantiatable implementation of the interface.  It completely fulfills the contract.  My coworker prefers the nearly identical:

```<code>interface IFooWorker { void Work(); }

abstract class BaseWorker : IFooWorker {
    ... base class behaviors ...
    public abstract void Work() { }
    protected string CleanData(string data) { ... }
}

class DbWorker : BaseWorker {
    public void Work() {
        Repository.AddCleanData(base.CleanData(UI.GetDirtyData()));
    }
}
</code>```

Where the base class gets the interface, and by virtue of this all inheritors of the base class are of that interface as well.  This bugs me but I can't come up with concrete reasons why, outside of "the base class cannot stand on its own as an implementation of the interface".

What are the pros & cons of his method vs. mine, and why should one be used over another?

答:
I generally agree with your coworker.

Let's take your model: the interface is implemented only by the child classes, even though the base class also enforces the exposure of IFooWorker methods. First off, it's redundant; whether the child class implements the interface or not, they are required to override the exposed methods of BaseWorker, and likewise any IFooWorker implementation must expose the functionality whether they get any help from BaseWorker or not.

This additionally makes your hierarchy ambiguous; "All IFooWorkers are BaseWorkers" is not necessarily a true statement, and neither is "All BaseWorkers are IFooWorkers". So, if you want to define an instance variable, parameter, or return type that could be any implementation of either IFooWorker or BaseWorker (taking advantage of the common exposed functionality which is one of the reasons to inherit in the first place), neither of these is guaranteed to be all-encompassing; some BaseWorkers won't be assignable to a variable of type IFooWorker, and vice versa.

Your coworker's model is much easier to use and to replace. "All BaseWorkers are IFooWorkers" is now a true statement; you can give any BaseWorker instance to any IFooWorker dependency, no problems. The opposite statement "All IFooWorkers are BaseWorkers" is not true; that allows you to replace BaseWorker with BetterBaseWorker and your consuming code (which depends on IFooWorker) won't have to tell the difference.

Title: Interfaces on an abstract class


问:
What is an appropriate language for expressing initial stages of algorithm refinement?
First, this is not a homework assignment, but you can treat it as such ;).   I found the following question in the published paper The Camel Has Two Humps.  I was not a CS major going to college (I majored in MIS/Management), but I have a job where I find myself coding quite often.

For a non-trivial programming problem, which one of the following is
  an appropriate language for expressing the initial stages of algorithm
  refinement?

(a) A high-level programming language.

(b) English.

(c) Byte code.

(d) The native machine code for the processor on which the program
  will run.

(e) Structured English (pseudocode).

What I do know is that you usually want to start your design implementation by writing down pseuducode and then moving/writing in the desired technology (because we all do that, right?)  But I never thought about it in terms of refinement.  I mean, if you were the original designer, then you might have access to the original pseudocode.  But realisticly, when I have to maintain/refactor/refine somebody elses code, I just keep trucking with the language it currently resides in.  Anybody have a definitive answer to this?

As a side note, I did a quick scan of the paper as I havn't read every single detail. It presents various score statistics, can't find where the answers are with the paper.

答:
First of all, I hardly believe that anyone have a definitive answer.

Personally me always get annoyed by any kind of pseudocode even in good books, even in excellent ones, be it Knuth's "Bible" or Corman's "Gospel".

I'm ready to apprehend and to learn any real language, there's no problem to read the algorithm implementation written on any high level language. Moreover, I found such code snippets more useful in any sense.

As for refinement, well, my first thought was to note that actually yes, there are some options, which can be conjugated with that term. For, dealing with memory, manual allocating and deallocating, can divert us from the very essence of algorithm. For the similar reasons, dynamically typed languages are more preferable compared to static ones. Roughly, Java is better for so-called algorithm refinement than С++, and Ruby or Python are better then Java.

To say this, I repeat, was my first intention. But than I've remembered that I actually have no problems with reading code snippets in Haskell (which I know a little bit), ML (which I don't know at all) or C++, which I've never used.

So, I believe it is only matter of practice. Anyone who is reading a lot of algorithm explanations have to learn to spot quickly different peculiarities of different languages. As for me, it is way better when those languages are "real".

ps
 you forgot to mention flowcharts )))


答:
Specifically for configuration values, I'd say - go with the single row.  Unless you're currently going through development, how often are those columns going to change anyway?

It's probably best to secure the datatype of the values, rather than code for extensibility you're not likely to have in the downtime between large(r) releases.  Besides, adding or removing a single column is just about the easiest migration there is.  I don't forsee a headache when creating a new configuration option.

Additionally, you said "users" can configure these options, without giving a cap.  Are they per-user configurations?  If so, I'll argue even more strongly that the configuration options should be in the columns - a single row per user.  It'll save a lot of maintenance headaches later on.


答:
There is no definitive answer, except that very few people would choose C or D.  My preference is A, but others may prefer B or E.

Modern high-level languages are expressive enough that I don't bother with pseudo-code.  Instead of writing pseudo-code that says "get data; do something complicated; output something", I can just write code

```<code>def main
    def myData = getSomeDataSomehow()
    def result = myData.doSomethingComplicated()
    result.outputSomewhere()
end
</code>```

More likely, I'll start with a test:

```<code>def testThatNoDataProducesNoOutput
    createNullData()
    runCode()
    checkForEmptyOutput()
end
</code>```

Then I successively add tests and elaborate the code until I can't think of any more tests.

Title: What is an appropriate language for expressing initial stages of algorithm refinement?

Body:
First, this is not a homework assignment, but you can treat it as such ;).   I found the following question in the published paper The Camel Has Two Humps.  I was not a CS major going to college (I majored in MIS/Management), but I have a job where I find myself coding quite often.

For a non-trivial programming problem, which one of the following is
  an appropriate language for expressing the initial stages of algorithm
  refinement?

(a) A high-level programming language.

(b) English.

(c) Byte code.

(d) The native machine code for the processor on which the program
  will run.

(e) Structured English (pseudocode).

What I do know is that you usually want to start your design implementation by writing down pseuducode and then moving/writing in the desired technology (because we all do that, right?)  But I never thought about it in terms of refinement.  I mean, if you were the original designer, then you might have access to the original pseudocode.  But realisticly, when I have to maintain/refactor/refine somebody elses code, I just keep trucking with the language it currently resides in.  Anybody have a definitive answer to this?

As a side note, I did a quick scan of the paper as I havn't read every single detail. It presents various score statistics, can't find where the answers are with the paper.

Body:
There is no definitive answer, except that very few people would choose C or D.  My preference is A, but others may prefer B or E.

Modern high-level languages are expressive enough that I don't bother with pseudo-code.  Instead of writing pseudo-code that says "get data; do something complicated; output something", I can just write code

def main
    def myData = getSomeDataSomehow()
    def result = myData.doSomethingComplicated()
    result.outputSomewhere()
end

More likely, I'll start with a test:

def testThatNoDataProducesNoOutput
    createNullData()
    runCode()
    checkForEmptyOutput()
end

Then I successively add tests and elaborate the code until I can't think of any more tests.


问:
Questions to ask before someone leaves
Apart from the obvious questions relating to specific project work someone is working on are there any questions I should be asking a fellow dev who is leaving the company?

So far I am thinking about;

Locations of things on the server he uses that not maybe everyone does.

Credentials he has set up that we wouldn't have needed.

Client details he has not yet saved into our CRM system.

答:
A phone number and/or e-mail address.

No matter what you ask him before he leaves, you will remember 10 more things to ask him as you see his car pulling out of the parking lot.

Note: you are much more likely to get good information if he is leaving on good terms - try to make the transition as pleasant as possible (no matter why he is leaving).

Title: Questions to ask before someone leaves


问:
Should interfaces extend (and in doing so inherit methods of) other interfaces
Although this is a general question it is also specific to a problem I am currently experiencing.  I currently have an interface specified in my solution called

```<code>public interface IContextProvider
{
   IDataContext { get; set; }
   IAreaContext { get; set; }
}
</code>```

This interface is often used throughout the program and hence I have easy access to the objects I need.  However at a fairly low level of a part of my program I need access to another class that will use IAreaContext and perform some operations off it.  So I have created another factory interface to do this creation called:

```<code>public interface IEventContextFactory
{
   IEventContext CreateEventContext(int eventId);
}
</code>```

I have a class that implements the IContextProvider and is injected using NinJect.  The problem I have is that the area where I need to use this IEventContextFactory has access to the IContextProvider only and itself uses another class which will need this new interface.  I don't want to have to instantiate this implementation of IEventContextFactory at the low level and would rather work with the IEventContextFactory interface throughout.  However I also don't want to have to inject another parameter through the constructors just to have it passed through to the class that needs it i.e.

```<code>// example of problem
public class MyClass
{
    public MyClass(IContextProvider context, IEventContextFactory event)
    {
       _context = context;
       _event = event;
    }

    public void DoSomething()
    {
       // the only place _event is used in the class is to pass it through
       var myClass = new MyChildClass(_event);
       myClass.PerformCalculation();
    }
}
</code>```

So my main question is, would this be acceptable or is it even common or good practice to do something like this (interface extend another an interface):

```<code>public interface IContextProvider : IEventContextFactory
</code>```

or should I consider better alternatives to achieving what I need.  If I have not provided enough information to give suggestions let me know and I can provide more.

答:
If the one interface always wants to require/provide the other, then go ahead. I've seen this in a few cases with IDisposible that have made sense. In general though, you should make sure that at least one of the interfaces behaves more like a trait than a responsibility.

For your example, it is not clear. If they are both always together, just make one interface. If one always needs the other, I would be concerned about "X and 1" sort of inheritance that very often leads to multiple responsibilities, and/or other leaky abstraction issues.


答:
The answer they're looking for is English. More accurately, the language used should be the one that is understood by the lowest common denominator (usually the end-users of the system and/or the person paying the bills).

The inference that the end users and other non-technical "stakeholders" are involved here makes the answer obvious; "the initial stages of algorithm refinement" is synonymous with "the gathering of requirements for the algorithm". Those requirements are not gathered in bytecode, machine code, C# or even pseudocode; they are gathered in English, and the users will evaluate the correctness of the algorithm in terms of what they said it should do, in English.

Once requirements are gathered in plain English, they are typically structured in a "Given... When... Then..." format. "Given that the user has left the User ID field blank, When the user clicks the 'Login' button, Then the program displays an error message and highlights the User ID field". These are still very understandable by end users and are not pseudocode. These can be taken, one at a time, and used to produce a pseudocode algorithm that can be reviewed before being developed in the native language. Depending on the environment, pseudocode may not be necessary (or even encouraged; TDD would typically have you start coding a test based on each Given/When/Then requirement, and then coding to pass each test in turn while keeping all previously-passing tests "green"), but pseudocode is a good way to structure the layout of a complex algorithm and have it reviewed by yourself or any other team member, regardless of the level of expertise that you or any of them may have with the programming language to be used.


问:
Does software testing methodology rely on flawed data?
It’s a well-known fact in software engineering that the cost of fixing a bug increases exponentially the later in development that bug is discovered. This is supported by data published in Code Complete and adapted in numerous other publications.

However, it turns out that this data never existed. The data cited by Code Complete apparently does not show such a cost / development time correlation, and similar published tables only showed the correlation in some special cases and a flat curve in others (i.e. no increase in cost).

Is there any independent data to corroborate or refute this?

And if true (i.e. if there simply is no data to support this exponentially higher cost for late discovered bugs), how does this impact software development methodology?

答:
I cannot answer your first part of the question, as I simply have not checked. But I can formulate an answer to your second question, and perhaps hint at a possible answer to the first.

It should go without saying that some most important factors in the cost of fixing a bug, barring intrinsically hard to use development tools, are the intrinsic complexity of the product, and how well the user can understand that product.

Focusing for a second on code, under the assumption that code is typically written and maintained by developers capable of dealing with the intrinsic complexities of their code (which may not be entirely true and may deserve its own debate), I would dare suggest that of cricital importance in maintenance, and thus in fixing bugs, is the maintainers' ability to understand said code.

The ability to understand code is greatly enhanced by the use of proven software engineering tools that are, unfortunately, mostly under- or improperly used. Using the right level of abstraction, modularity, enhancing module cohesion and reducing module coupling are critical tools in coping with complexity that need proper use. Coding to interfaces, or, in OOP, avoiding the over-use of inheritance over composition, packaging by feature, are some of the techniques that are often given insufficient attention in coding.

I believe that the realities of competition in the industry put a negative force on the employment of quality enhancing methods to developing software, keeping low the intrinsic quality of software as a measure of ongoing success.

Consequently, I believe that, in the industry, software tends to suffer more from bug fixing costs the bigger it grows. In such products, bugs become harder to fix over time because the system becomes harder to understand as it grows. The concerns introduced by each feature are overly coupled with other concerns, making understandability hard. Or, the right level of abstraction was not employed, making it hard for the maintainer to formulate a proper model of the system and reason about it. Lack of documentation certainly doesn't help.

There are exceptions. I'm sure Google isn't functioning at its pace without some solid practices upheld by stellar developers. And others are likely in the same situation. But for a majority of the software, I wouldn't be surprised if the data did in fact confirm the claim in Code Complete.


答:
While interfaces describe only behavior without any implementation, they can still participate in inheritance hierarchies. As an example, imagine you have, say, the common idea of a Collection. This interface would provide a few things that are common to all collections, such as a method to iterate over the members. Then you can think about some more specific collections of objects such as a List or a Set. Each of these inherits all the behavior requirements of a Collection, but adds additional requirements specific to that particular type of collection.

Any time it makes sense to create an inheritance hierarchy for interfaces, then you should. If two interfaces will always be found together, then they should probably be merged.

Title: Should interfaces extend (and in doing so inherit methods of) other interfaces

Body:
Although this is a general question it is also specific to a problem I am currently experiencing.  I currently have an interface specified in my solution called

```<code>public interface IContextProvider
{
   IDataContext { get; set; }
   IAreaContext { get; set; }
}
</code>```

This interface is often used throughout the program and hence I have easy access to the objects I need.  However at a fairly low level of a part of my program I need access to another class that will use IAreaContext and perform some operations off it.  So I have created another factory interface to do this creation called:

```<code>public interface IEventContextFactory
{
   IEventContext CreateEventContext(int eventId);
}
</code>```

I have a class that implements the IContextProvider and is injected using NinJect.  The problem I have is that the area where I need to use this IEventContextFactory has access to the IContextProvider only and itself uses another class which will need this new interface.  I don't want to have to instantiate this implementation of IEventContextFactory at the low level and would rather work with the IEventContextFactory interface throughout.  However I also don't want to have to inject another parameter through the constructors just to have it passed through to the class that needs it i.e.

```<code>// example of problem
public class MyClass
{
    public MyClass(IContextProvider context, IEventContextFactory event)
    {
       _context = context;
       _event = event;
    }

    public void DoSomething()
    {
       // the only place _event is used in the class is to pass it through
       var myClass = new MyChildClass(_event);
       myClass.PerformCalculation();
    }
}
</code>```

So my main question is, would this be acceptable or is it even common or good practice to do something like this (interface extend another an interface):

```<code>public interface IContextProvider : IEventContextFactory
</code>```

or should I consider better alternatives to achieving what I need.  If I have not provided enough information to give suggestions let me know and I can provide more.


答:
For my part, the answer to "how does this impact software development methodology" is "not much".

Whether caught by the developer or the end user, whether it takes more money to fix it after it's been caught by the user or not, the fact remains that a bug has been found in the system. If caught by the developer, hopefully it's a quick fix. The same hope holds for bugs caught by the user.

Regardless of actual developer-hour cost to fix a bug caught by an end user, there is the intangible cost of maintaining the stereotype that coders suck at what they do. When a user finds a bug, it's the developer's fault. Therefore, each bug the end user finds reduces the user's confidence in the system. It's like touring a home you want to buy, and seeing a water stain showing through the ceiling in one corner of the house. That, in itself, is an easy fix, but you wonder what caused it, and what else that root cause may have affected. What's your peace of mind worth? You may have to tear the walls down back to the studs and visually inspect everything to ensure the stain was from an isolated incident that has been fixed. Knowing that might be a possibility doesn't make you very confident in the home. Similarly, if the developer who wrote your software missed this very obvious (to you) cosmetic flaw, what's wrong deeper down?

These intangible costs are avoided the sooner the bug is caught, which is the stated purpose of TDD-style methodologies. A bug caught during typing by the developer or partner in a pair, one caught at compile time, or one caught by unit/integration testing (the layer added by TDD), is a bug that the user never has to know about, that your project manager never has to apologize for, and that you don't have to be pulled off of whatever you're doing right this second to switch gears into defect-fixing mode on a part of the system you thought you'd left behind weeks ago.

Title: Does software testing methodology rely on flawed data?

Body:
It’s a well-known fact in software engineering that the cost of fixing a bug increases exponentially the later in development that bug is discovered. This is supported by data published in Code Complete and adapted in numerous other publications.

However, it turns out that this data never existed. The data cited by Code Complete apparently does not show such a cost / development time correlation, and similar published tables only showed the correlation in some special cases and a flat curve in others (i.e. no increase in cost).

Is there any independent data to corroborate or refute this?

And if true (i.e. if there simply is no data to support this exponentially higher cost for late discovered bugs), how does this impact software development methodology?


答:
Yes, but only if it makes sense. Ask yourself the following questions and if one or more apply then it is acceptable to inherit an interface from another.

Does interface A logically extend interface B, for example IList adding functionality to ICollection.

Does interface A need to define behaviour already specified by another interface, for example implementing IDisposable if it has resources which need to be tidied up or IEnumerable if it can be iterated over.

Does every implementation of interface A require the behaviour specified by interface B?

In your example, I don't think it answers yes to any of those. You may be better off adding it as another property:

```<code>public interface IContextProvider
{
   IDataContext DataContext { get; set; }
   IAreaContext AreaContext { get; set; }
   IEventContextFactory EventContextFactory { get; set; }
}
</code>```

Body:
Yes, but only if it makes sense. Ask yourself the following questions and if one or more apply then it is acceptable to inherit an interface from another.

Does interface A logically extend interface B, for example IList adding functionality to ICollection.

Does interface A need to define behaviour already specified by another interface, for example implementing IDisposable if it has resources which need to be tidied up or IEnumerable if it can be iterated over.

Does every implementation of interface A require the behaviour specified by interface B?

In your example, I don't think it answers yes to any of those. You may be better off adding it as another property:

public interface IContextProvider
{
   IDataContext DataContext { get; set; }
   IAreaContext AreaContext { get; set; }
   IEventContextFactory EventContextFactory { get; set; }
}


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
I use;

```<code>if ($test) {
    //something
} else {
    //something else
}
</code>```

Because this is the way the phpcs (PHP Codesniffer) likes you to do things when running under it's default setting (which is the Zend standard).

The only other thing to note is the space between 'if' and '('

Body:
I use;

if ($test) {
    //something
} else {
    //something else
}

Because this is the way the phpcs (PHP Codesniffer) likes you to do things when running under it's default setting (which is the Zend standard).

The only other thing to note is the space between 'if' and '('


答:
Yes, it's fine to extend one interface from another.

The question of whether it's the right thing to do in a specific case depends on whether there's a true "is-a" relationship between the two.

What's required for a valid "is-a" relationship?

First, there must be a real difference between the two interfaces, i.e., there must be instances that implement the parent interface but not the child interface. If there are not and never will be instances that don't implement both interfaces, then the two interfaces should instead be merged.

Second, it must be the case that every instance of the child interface must necessarily be an instance of the parent: there's no (reasonable) logic under which you would create an instance of the child interface that wouldn't make sense as an instance of the parent interface.

If both of those are true, then inheritance is the right relationship for the two interfaces.


问:
Advantages and disadvantages to using XAML/C# or HTML5/JavaScipt for Metro apps?
I was just wondering if there are any major advantages or disadvantages to using either XAML/C# or HTML5/JavaScript for Metro Apps.</p>

答:
Not a MS programmer - From a programmers standpoint, it would be worth investing your time and effort in a platform agnostic, open standard like JS + HTML 5. The knowledge you gain can be re-used elsewhere.

Win 8 supports JS natively, so there wouldn't be much you cannot accomplish using it.


答:
I need to add something of a warning to these answers. Coupling the base class to the interface creates a force in the structure of that class. In your basic example, it's a no brainer that the two should be coupled, but that may not hold true in all cases.

Take Java's collection framework classes:

```<code>abstract class AbstractList
class LinkedList extends AbstractList implements Queue
</code>```

The fact that the Queue contract is implemented by LinkedList did not push the concern into AbstractList.

What's the distinction between the two cases? The purpose of BaseWorker was always (as communicated by its name and interface) to implement operations in IWorker. The purpose of AbstractList and that of Queue are divergent, but a descenant of the former can still implement the latter contract.

Title: Interfaces on an abstract class

Body:
I need to add something of a warning to these answers. Coupling the base class to the interface creates a force in the structure of that class. In your basic example, it's a no brainer that the two should be coupled, but that may not hold true in all cases.

Take Java's collection framework classes:

abstract class AbstractList
class LinkedList extends AbstractList implements Queue

The fact that the Queue contract is implemented by LinkedList did not push the concern into AbstractList.

What's the distinction between the two cases? The purpose of BaseWorker was always (as communicated by its name and interface) to implement operations in IWorker. The purpose of AbstractList and that of Queue are divergent, but a descenant of the former can still implement the latter contract.


问:
Ambiguous program requirements
it seems that most of the programming exercises that I am currently doing, are a little bit ambiguous when it comes to specifying what should I do.

When programmers work with clients, are the clients ambiguous as well about what they want and I should learn to guess?

答:
If you guess what a client wants, you will ... fail.

Clients do not typically know what they want.  They just know how an existing process works.  Many times it is your job to help them bridge the gap from the "old way" to the "new and improved" way that is possible using computer software (or new computer software).

Respect what they know, and help them learn what you know.  Then you will not fail.

Title: Ambiguous program requirements


答:
First think of what an abstract base class is, and what an interface is. Consider when you would use one or the other and when you would not.

It's common for people to think of both being very similar concepts, in fact it's a common interview question (difference between the two is??)

So an abstract base class gives you something interfaces can't which is default implementations of methods. (There's other stuff, in C# you can have static methods on an abstract class, not on an interface for example).

As an example, one common use of this is with IDisposable. The abstract class implements IDisposable's Dispose method, which means any derived version of the base class will automatically be disposable. You can then play with several options. Make Dispose abstract, forcing derived classes to implement it. Provide a virtual default implementation, so they don't, or make it neither virtual or abstract and have it call virtual methods called things like BeforeDispose, AfterDispose, OnDispose or Disposing for example.

So any time all derived classes need to support the interface, it goes on the base class. If only one or some need that interface it would go on the derived class.

That's all actually a gross over simplification. Another alternative is to have derived classes not even implement the interfaces, but provide them via an adapter pattern. An example of this I saw recently was in IObjectContextAdapter.

Title: Interfaces on an abstract class


问:
Deploying a very simple application
I have a very simple working console application written in C++ linked with a light static library. It is just for testing purposes. Now that the coding part is done, I would like to know the process of actually deploying the program. I wrote a very basic CMakeLists.txt that create makefiles or VS projects to build the sources. I also have a program that calls the static library in order to make some google tests.

To me, the deployment of this application goes like this:

to developers : the src directory with the CMakeLists.txt file (multi-platform distribution) with a README.txt and an INSTALL.txt

to users : the executable and a README.txt

git repo : everything mentioned above plus the sources for testing and the gtest external lib

A this point : considering the complexity of my application, am I doing it right?

Is there any reference that would formalize this deployment process so I can get better and go further ? Say I would like to add dynamic libraries that can be updated, external libraries like boost : how should I package this to deploy it in a professional way?

答:
It sounds like the question is not about distribution. Distribution is about getting the application to others and includes things like which sites do you host it on, how do they download it and get updates. See How to sell/distribute my software? for more information. Similarly, if you want to market your app (let people know about it), look at https://softwareengineering.stackexchange.com/questions/27078/what-is-the-best-way-to-introduce-software-created-by-you for some starting points. It sounds like you are asking more about the form the application should take when giving to customers and other developers.

Starting with customers, things to consider include how technical your customers are and what operating system they are running on. If the customers are technical people running on *nix, a readme and an executable are probably adequate. If you are writing an iPhone app, clearly not. The question infers you are targeting a *nix or Windows environment so I would at least consider an installer.

As for separating parts into dynamic libraries, this helps if you want to reference an existing library, release the library on a different schedule or reuse it in other applications. It is also useful for automated unit tests. Unfortunately, customers really do not care about any of these, except for potential version conflicts known as "DLL hell" on Windows.

As for developers, follow the conventions of our target operating system and language. If you are targeting *nix, a makefile is great. If you are targeting Windows, a Visual Studio project is useful. If you are doing cross platform development, a lowest common denominator approach may be the most maintainable.

However, the single biggest thing you can do is document your code. Most developers can work their way through even a complicated build process as long as they know how. A README or equivalent is a must with detailed instructions for building it, known issues and your contact details (such as an E-mail address or website).

As for should you split the code to external libraries or not, developers really do not care much, either, so long as the libraries work, are well maintained and you are not infringing any license agreements. The developer time and effort saved is worth it.

Title: Deploying a very simple application


问:
what's the name of this pattern?
I see this a lot in frameworks.

You have a master class which other classes register with.

The master class then decides which of the registered classes to delegate the request to. An example based passed in class may be something this.

```<code>public interface Processor {
  public boolean canHandle(Object objectToHandle);
  public void handle(Object objectToHandle);
}

public class EvenNumberProcessor extends Processor {
  public boolean canHandle(Object objectToHandle) {
     if (!isNumeric(objectToHandle)){
      return false
     }
     return isEven(objectToHandle);
   }

   public void handle(objectToHandle) {
     //Optionally call canHandleAgain to ensure the calling class is fufilling its contract
     doSomething();
   }
 }

public class OddNumberProcessor extends Processor {
  public boolean canHandle(Object objectToHandle) {
     if (!isNumeric(objectToHandle)){
      return false
     }

    return isOdd(objectToHandle);
  }

   public void handle(objectToHandle) {
     //Optionally call canHandleAgain to ensure the calling class is fufilling its contract
     doSomething();
   }
 }

//Can optionally implement processor interface
public class processorDelegator {

  private List processors;
  public void addProcessor(Processor processor) {
    processors.add(processor);
  }

  public void process(Object objectToProcess) {
     //Lookup relevant processor either by keeping a list of what they can process
     //Or query each one to see if it can process the object.

     chosenProcessor=chooseProcessor(objectToProcess);
     chosenProcessor.handle(objectToProcess);
  }

}
</code>```

Note there are a few variations I see on this. In one variation the sub classes provide a list of things they can process which the ProcessorDelegator understands.  The other variation which is listed above in fake code is where each is queried in turn.

This is similar to chain of command but I don't think its the same as chain of command means that the processor needs to pass to other processors.

The other variation is where the ProcessorDelegator itself implements the interface which means you can get trees of ProcessorDelegator which specialise further.  In the above example you could have a numeric processor delegator which delegates to an even/odd processor and a string processordelegator which delegates to different strings.

My question is does this pattern have a name?

答: To me it looks like the strategy pattern, only that the selection of the specific algorithm is not hard-coded.</p>

Title: what's the name of this pattern?


答: It probably best fits into the Chain of Responsibility, but seems specific enough that it should be considered different. I don't think there's a name though for this specific pattern.</p>

Title: what's the name of this pattern?

Body:
I see this a lot in frameworks.

You have a master class which other classes register with.

The master class then decides which of the registered classes to delegate the request to. An example based passed in class may be something this.

```<code>public interface Processor {
  public boolean canHandle(Object objectToHandle);
  public void handle(Object objectToHandle);
}

public class EvenNumberProcessor extends Processor {
  public boolean canHandle(Object objectToHandle) {
     if (!isNumeric(objectToHandle)){
      return false
     }
     return isEven(objectToHandle);
   }

   public void handle(objectToHandle) {
     //Optionally call canHandleAgain to ensure the calling class is fufilling its contract
     doSomething();
   }
 }

public class OddNumberProcessor extends Processor {
  public boolean canHandle(Object objectToHandle) {
     if (!isNumeric(objectToHandle)){
      return false
     }

    return isOdd(objectToHandle);
  }

   public void handle(objectToHandle) {
     //Optionally call canHandleAgain to ensure the calling class is fufilling its contract
     doSomething();
   }
 }

//Can optionally implement processor interface
public class processorDelegator {

  private List processors;
  public void addProcessor(Processor processor) {
    processors.add(processor);
  }

  public void process(Object objectToProcess) {
     //Lookup relevant processor either by keeping a list of what they can process
     //Or query each one to see if it can process the object.

     chosenProcessor=chooseProcessor(objectToProcess);
     chosenProcessor.handle(objectToProcess);
  }

}
</code>```

Note there are a few variations I see on this. In one variation the sub classes provide a list of things they can process which the ProcessorDelegator understands.  The other variation which is listed above in fake code is where each is queried in turn.

This is similar to chain of command but I don't think its the same as chain of command means that the processor needs to pass to other processors.

The other variation is where the ProcessorDelegator itself implements the interface which means you can get trees of ProcessorDelegator which specialise further.  In the above example you could have a numeric processor delegator which delegates to an even/odd processor and a string processordelegator which delegates to different strings.

My question is does this pattern have a name?


答:
University/school exercises are sometimes intentionally vague as they are testing your knowledge of the subject matter as well as the programming language. For example, a exercise that requires connecting to a remote host may not specify the application should support both a hostname and IP address.

That said, requirements in practice are not a monolithic, one-time thing. Even (hypothetical) customers that provide detailed, unambiguous requirements up front may change their mind during the development as they learn more about the possible solutions and requirements change over time. Key points to consider:

Keep open communication between the developer and the customer. Scrum does this through the sprint process and the product owner concept, for example.

Make incomplete versions of the product available, such as through a beta program. Getting a working application into customer hands gets the best feedback you can.

Make time in the schedule for handling changes to requirements. Planning and expectation setting is half the battle.

Title: Ambiguous program requirements

Body:
it seems that most of the programming exercises that I am currently doing, are a little bit ambiguous when it comes to specifying what should I do.

When programmers work with clients, are the clients ambiguous as well about what they want and I should learn to guess?


答:
To start off, I like to define interfaces and abstract classes differently:

```<code>Interface: a contract that each class must fulfill if they are to implement that interface
Abstract class: a general class (i.e vehicle is an abstract class, while porche911 is not)
</code>```

In your case, all workers implement work() because that is what the contract requires them to. Therefore your base class Baseworker should implement that method either explicitly or as a virtual function. I would suggest you to put this method in your base class because of the simple fact that all workers need to work(). Therefore it is logical that your baseclass (even though you cannot create a pointer of that type) includes it as a function.

Now, DbWorker does satisfy the IFooWorker interface, but if there is a specific way that this class does work(), then it really needs to overload the definition inherited from BaseWorker. The reason it should not implement the interface IFooWorker directly is that this is not something special to DbWorker. If you did that everytime you implemented classes similar to DbWorker then you would be violating DRY.

If two classes implement the same function in different ways, you could start looking for the greatest common superclass. Most of the time you will find one. If not, either keep looking or give up and accept that they don't have sufficient things in common to make a base class.

Title: Interfaces on an abstract class

Body:
To start off, I like to define interfaces and abstract classes differently:

Interface: a contract that each class must fulfill if they are to implement that interface
Abstract class: a general class (i.e vehicle is an abstract class, while porche911 is not)

In your case, all workers implement work() because that is what the contract requires them to. Therefore your base class Baseworker should implement that method either explicitly or as a virtual function. I would suggest you to put this method in your base class because of the simple fact that all workers need to work(). Therefore it is logical that your baseclass (even though you cannot create a pointer of that type) includes it as a function.

Now, DbWorker does satisfy the IFooWorker interface, but if there is a specific way that this class does work(), then it really needs to overload the definition inherited from BaseWorker. The reason it should not implement the interface IFooWorker directly is that this is not something special to DbWorker. If you did that everytime you implemented classes similar to DbWorker then you would be violating DRY.

If two classes implement the same function in different ways, you could start looking for the greatest common superclass. Most of the time you will find one. If not, either keep looking or give up and accept that they don't have sufficient things in common to make a base class.


答: I would disagree with everyone else here and go with a tierable implementation of the observer pattern. The word 'handle' gives it away: something occurs or is to occur and a list of handlers are given a piece of data based on the occurrence, and often times in observers you're first act is to test the data to see if you can handle it, and if not ignore it. The dictation back upwards that you can handle it is no different than in javascript when you call e.Cancel(); or some other such to stop the rest of the event chain.</p>

Title: what's the name of this pattern?


问:
What 's the essential difference between agile developing and plan based developing?
In agile process, the product owner put the unformal ideas/user story/backlog items to the sprint/iteration. Sprint/iteration is like a plan for a short term and it is drived by daily meeting. Planning is made in both processes. So what's the difference between agile and the old plan based developing?</p>

答: Plan based developing focuses on creating a detailed upfront plan whereas agile, or more accurately scrum, defers detailed plans until the work is about to begin and allows the order or priority of work to change. This minimizes change impact and means decisions (i.e. plans) can be made when the most knowledge is available. Whereas plan based development requires the plan to be revisted when changes occur and requires most decisions to be made upfront when the team knows the least about the problem and solutions. </p>


答:
By "Old planning" I presume that you mean waterfall, There is no customer feedback until the product is developed and delivered, and usually thats when stuff hits the fan in the waterfall process. Waterfall heavily relies on "requirement docs" - which the customer will swear that he/she never said anything of that sort in a months time.

In agile, theoretically you produce small working increments and get the customer's feedback and incorporate it in the next release. So chances of stuff hitting the fan is lowered.Overall the customer feels that he's getting something out of what he's paying you for.

Title: What 's the essential difference between agile developing and plan based developing?

Body: In agile process, the product owner put the unformal ideas/user story/backlog items to the sprint/iteration. Sprint/iteration is like a plan for a short term and it is drived by daily meeting. Planning is made in both processes. So what's the difference between agile and the old plan based developing?</p>


问:
Shared FIFO file descriptor
is ok to open fifo with one FD and share it with multiple threads?
or is it better to have multiple fds opened for the same fifo and share these fds with the threads?
BTW, I'll be doing write and read.

The environment is linux, C, pthreads

答:
Edit:

Some additional updates, spurred in part by Jan Hudec's comments (props Jan!)

From the OpenGroup Posix docs

```
 3.289 Process

An address space with one or more threads executing within that address space,
and the required system resources for those threads.

Note:
    Many of the system resources defined by POSIX.1-2008 are shared among all of the
threads within a process. These include the process ID, the parent process ID, process
group ID, session membership, real, effective, and saved set-user-ID, real, effective,
and saved set-group-ID, supplementary group IDs, current working directory, root
directory, file mode creation mask, and file descriptors.
```

So, if all of your threads are in the same process, they'll end up using the same file descriptor anyway.  But this is something I would let the OS manage for you as it will be one less headache to worry about.

(Same reference as above, under File Offset) Since you're dealing with FIFOs, you don't have to worry about the file offset being stored along with the file descriptor.  If you were dealing with regular files, then this could be an issue to be aware of.

Revised Answer

There are two cases to consider:

1. One process with multiple threads

2. two (or more) processes with one or more threads.

In the first case, all of the threads will have the same file descriptor for the FIFO because that's how the OS manages that for you.

In the second case, if you share the file descriptor between the various threads processes then you will likely have to manage the concurrency of access.

I'm pretty certain you're in the first case, not the second.

As Jan pointed out the read calls are not guaranteed to be atomic.  But the intent is for them to be that way.  See paragraphs 2 and 4 under Input and Output from the Rationale section of the manual.  Sharing file descriptors across processes can only make those concurrency issues more convoluted.

All else being equal, since the OS manages a lot of this for you I'd go with the multiple descriptors approach, even though it will likely result in the same file descriptor value being used.  My primary reasoning is that it is less code you have to write and maintain.  You can have a single routine that's called by each thread to get the descriptor.  An additional benefit is that it sets you up well in case you need to fork to new processes instead of spawning child threads.

Title: Shared FIFO file descriptor

Body:
Edit:

Some additional updates, spurred in part by Jan Hudec's comments (props Jan!)

From the OpenGroup Posix docs

 3.289 Process

An address space with one or more threads executing within that address space,
and the required system resources for those threads.

Note:
    Many of the system resources defined by POSIX.1-2008 are shared among all of the
threads within a process. These include the process ID, the parent process ID, process
group ID, session membership, real, effective, and saved set-user-ID, real, effective,
and saved set-group-ID, supplementary group IDs, current working directory, root
directory, file mode creation mask, and file descriptors.

So, if all of your threads are in the same process, they'll end up using the same file descriptor anyway.  But this is something I would let the OS manage for you as it will be one less headache to worry about.

(Same reference as above, under File Offset) Since you're dealing with FIFOs, you don't have to worry about the file offset being stored along with the file descriptor.  If you were dealing with regular files, then this could be an issue to be aware of.

Revised Answer

There are two cases to consider:

1. One process with multiple threads

2. two (or more) processes with one or more threads.

In the first case, all of the threads will have the same file descriptor for the FIFO because that's how the OS manages that for you.

In the second case, if you share the file descriptor between the various threads processes then you will likely have to manage the concurrency of access.

I'm pretty certain you're in the first case, not the second.

As Jan pointed out the read calls are not guaranteed to be atomic.  But the intent is for them to be that way.  See paragraphs 2 and 4 under Input and Output from the Rationale section of the manual.  Sharing file descriptors across processes can only make those concurrency issues more convoluted.

All else being equal, since the OS manages a lot of this for you I'd go with the multiple descriptors approach, even though it will likely result in the same file descriptor value being used.  My primary reasoning is that it is less code you have to write and maintain.  You can have a single routine that's called by each thread to get the descriptor.  An additional benefit is that it sets you up well in case you need to fork to new processes instead of spawning child threads.


答:
I believe this is, and has always been, about risk management and economics.  What is the cost of reducing the number of defects vs. the present value of the impact of future defects.  The trajectory of the yellow bird being slightly off in Angry Birds does not equate the trajectory of a Tomahawk cruise missile being off.  Software developers in either project can't make decisions based on that table.  In this regard, nothing changes.

The way I think this tends to work is via feedback, expensive bugs in the field cause companies to tighten their quality processes while no complaints from the field cause companies to relax it.  So over time software development companies will tend to converge or oscillate around something that works for them (+/-).  Code Complete may influence some initial values or may pull companies slightly one way or another.  A company that spends too much effort removing defects that no one would notice is probably going to lose business to a competitor that has a more optimized approach.  On the other hand, a company releasing buggy products will also go out of business.

Some relevant papers from a quick search (read the complete papers, do more research, and form your own opinion):

A Systematic Literature Review of Software Quality Cost Research (2011)

"While the community has thus developed a sound understanding of the
  research domain’s structure, empirical validation is often lacking.
  Only about a third of the analyzed articles presents a case study or
  more extensive empirical results. This appears to be insufficient for
  software quality cost research, which strongly relies on quantitative
  data to generate new findings. There is thus a need for novel
  approaches to gather quality cost data, as well as stronger
  cooperation between industry and research to make such data
  available."

Evaluating the Cost of Software Quality (1998)

"Finally, we have seen that it is important to monitor software
  conformance and nonconformance costs so that conformance policies can
  be adjusted to reduce the total costs of software quality."

The cost behavior of software defects (2004)

Abstract ... "The current research attempts to update our knowledge of the way in which defects and the expense of correcting them (or alternatively, leaving them uncorrected) influences the final cost of software" ... "uncorrected defects become exponentially more costly with each phase in which they are unresolved"

Test Coverage and Post-Verification Defects: A Multiple Case Study (2009)

"We also find that the test effort increases exponentially with test
  coverage, but the reduction in field problems increases linearly with
  test coverage. This suggests that for most projects the optimal levels
  of coverage are likely to be well short of 100%."

Bridge the Gap between Software Test Process and
Business Value: A Case Study (2009)


答:
Planned vs. agile processes for software can be quickly characterized by some pairs.

Waterfall vs. iterative/incremental

Watts Humphrey vs. Kent Beck.

Management driven vs. team driven.

SEI CMM vs. Agile manifesto.

Microsoft project vs. burn down lists.

Interim xyz review vs. scrum stand up meeting.

Annual release vs. daily build.

Code inspection vs. pair programming.

Planning schedules vs. planning game.

Committees vs. visionaries.

In someways, this question is already answered by the Agile Manifesto, but instead of reading left to right, read right to left.

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

Some of the comparisons above may be a little harsh, because certainly there is a lot of feature driven development that is practices with planned, and releases may be quarterly (but probably not monthly).

The best thinkers behind planned process were influenced by problems with ad-hoc or poorly suited approaches to software such as were described in Mythical Man-Month.  As early as 1968, NATO had a conference on Software Engineering to try to solve the crisis and at that point.  I think they had some great innovations.  Page 12 of their conference report has a remarkable drawing describing waterfall but with curves instead of boxes.  It also includes material about the challenges of estimating software projects.  Later, planned software process experts borrowed and stole from QA pioneers like Demming and the many Japanese experts who proved its worth in manufacturing cars and electronics.

I think the best agile thinkers were extremely familiar with planned process, and reacted against its limitations, while retaining some of its strong points.  Planned process has not lost all of its relevance, and some would argue it is essential for large projects.  Planned is still widely used, particularly in large organizations, but many try to hybrid with agile techniques.  Perhaps System of Systems design approaches are planned, but they have a good characteristic of creating small teams which is a more practical place for agile.  Planned was sensitive to the need for local tailoring, but expected it would be facilitated by meetings and committees.

Great references on this topic include Watts Humphries books, articles, and technical reports on organizational, team, and personal software process.  Contrast those with Kent Beck's introductory sections from eXtreme Programming Explained.

One of my professors described the history of software development something like this:

1970s : Tools - a Cambrian explosion of operating systems, programming languages, and tool
evolution.

1980s : Process - don't blame the people, blame (and fix) the process.

1990s : People - empower decision making and communications and interactions among people.


答:
Its just simple logic.

Error detected in spec.

```<code>Case : Error found while reviewing UseCase/Function spec.
Actions:
        Rewrite paragraph in error.

Case : Error found during unit test.
Actions:
        Fix code.
        (Possibly) rewrite paragraph in spec.
        rerun unit test.

Case : Error found in integration test.
        Fix code.
        (possibly) rewrite paragraph in spec.
        rerun unit test.
        build new release.
        rerun integration test for whole system.

Case : Error found in UAT
        Fix code.
        (possibly) rewrite paragraph in spec.
        rerun unit test.
        build new release.
        rerun integration test for whole system.
        deploy release to UAT.
        rerun UAT tests.

Case : Error found in production
        Fix code.
        (possibly) rewrite paragraph in spec.
        rerun unit test.
        Build release.
        rerun integration test for whole system.
        deploy release to UAT.
        rerun UAT tests.
        deploy release to production.
</code>```

As you can see the later the error is detected the more people are involved the more work has to be re-done and in any "normal" environment the paper work and bureaucracy increases exponentially  once you hit UAT.

This is all without including the costs a business could incur due to an error in production software (lost sales, over ordering, hacked of customers etc. etc.)

I don't think anyone has ever managed to write a non-trivial system which never had bugs in production, but, anything you can do to catch bugs early will save you time and effort in the long run.
Specification reviews, code reviews, extensive unit testing, using different coders to write the tests etc. etc. are all proven methods of catching bugs early.

Body:
Its just simple logic.

Error detected in spec.

Case : Error found while reviewing UseCase/Function spec.
Actions:
        Rewrite paragraph in error.

Case : Error found during unit test.
Actions:
        Fix code.
        (Possibly) rewrite paragraph in spec.
        rerun unit test.

Case : Error found in integration test.
        Fix code.
        (possibly) rewrite paragraph in spec.
        rerun unit test.
        build new release.
        rerun integration test for whole system.

Case : Error found in UAT
        Fix code.
        (possibly) rewrite paragraph in spec.
        rerun unit test.
        build new release.
        rerun integration test for whole system.
        deploy release to UAT.
        rerun UAT tests.

Case : Error found in production
        Fix code.
        (possibly) rewrite paragraph in spec.
        rerun unit test.
        Build release.
        rerun integration test for whole system.
        deploy release to UAT.
        rerun UAT tests.
        deploy release to production.

As you can see the later the error is detected the more people are involved the more work has to be re-done and in any "normal" environment the paper work and bureaucracy increases exponentially  once you hit UAT.

This is all without including the costs a business could incur due to an error in production software (lost sales, over ordering, hacked of customers etc. etc.)

I don't think anyone has ever managed to write a non-trivial system which never had bugs in production, but, anything you can do to catch bugs early will save you time and effort in the long run.
Specification reviews, code reviews, extensive unit testing, using different coders to write the tests etc. etc. are all proven methods of catching bugs early.