答:
Its actually a pretty good design. Using views confers the following advantages:-

It insulates your application from any changes in the underlying physical tables.

A view can be regarded as the formal interface specification between client and server.

The view allows fine grained access control to the underlying data. I.E. it is possible give different access levels to mobile, lan based and web based clients. Clients need only have access the specific data they need rather than the entire database.

Views are logical constructs. There is no performance penalty in using a view.

In many databases views will boost performance, as query cache hit rates are usually better with views than hand coded queries.

Title: At least one database view per database table-Is this good or bad design and why?

Body:
We are building a Windows Mobile based application to interface with a customer's existing web application. We are reading and writing data to the customer's SQL server 2008 database.

The customer wants all reads to happen through SQL views, and all writes to happen through stored procedures.

But taking a look at their database schema, they have a view of each and every table. And they have a view of each and every query that would be used to read data, instead of using the existing views on their tables. They have 348 tables and 655 views so far.

They want us to model our mobile application in a similar fashion i.e. create additional views for all queries that we use to retrieve data.

I know this is poor design, but I am unable to list out to the customer why their view based strategy is a poor design.

What is the consensus in the community on when to use views? How does having so many views affect performance of the SQL server?


问:
Is monkeypatching considered good programming practice?
I've been under impression, that monkeypatching is more in quick and dirty hack category, rather than standard, good programming practice. While I'd used from time to time to fix minor issues with 3rd party libs, I considered it temporary fix and I'd submit proper patch to the 3rd party project.

However, I've seen this technique used as "the normal way" in mainstream projects, for example in Gevent's gevent.monkey module.

Has monkeypatching became mainstream, normal, acceptable programming practice?

See also: "Monkeypatching For Humans" by Jeff Atwood

答:
No. It is not a standard technique for software development. It remains a workaround to solve an acute problem and has clear drawbacks. Violation of the Liskov Substitution Principle comes to mind. Monkey patching makes it seriously harder to reason about programs. For your own programs you should place the code where it belongs. For third party libs you will always live in the danger, that your patch won't work with the next version of the lib.

Of course monkey patching is useful if you know what you are doing and do not have the time to implement a SOLID solution. But you should never consider this a standard technique and build monkey patch upon monkey patch.

BTW, did you ever write a unit test for a monkey patch?

ContentLicense: CC BY-SA 3.0


问:
Should a new programmer focus on a single technology until he's proficient at it?
Ok, I've been teaching a buddy how to program for a while now. He's a very fast learner, and he's quite good at programming so far. However, he has one "issue" I keep trying to correct.

He jumps in and starts doing highlevel programming without learning some of the basics (He's created a full blown web application but still doesn't know pagination or session management).

This isn't the problem though. He keeps jumping around to new technology (Node.js, MongoDB, EC2, etc). I tried telling him that he should learn some of the basics about his RDMS of choice (MySQL) as he uses it everyday before investing a bunch of time into learning the basics of MongoDB (And probably moving to something new).

Am I the one in the wrong here, or should he try to focus on one thing at a time and get really good at it?

答:
Why is it bad?

On the opposite I think it's very good! It shows curiosity and eager to learn. Moreover, he wants to find the right tool for the right job! Better than to stick with an inadequate first choice technology. ;)

Actually, I do it likewise, as a seasoned programmer. And I recommend it.
Whenever I have a new project, my behavior is as follows:

explore (the potential technologies that may be useful)

experiment (with the ones that looks promising)

choose your techs (or experiment a little further until you know)

stick to it (develop your app and pull it through)

I think it makes perfect sense.


问:
At least one database view per database table-Is this good or bad design and why?
We are building a Windows Mobile based application to interface with a customer's existing web application. We are reading and writing data to the customer's SQL server 2008 database.

The customer wants all reads to happen through SQL views, and all writes to happen through stored procedures.

But taking a look at their database schema, they have a view of each and every table. And they have a view of each and every query that would be used to read data, instead of using the existing views on their tables. They have 348 tables and 655 views so far.

They want us to model our mobile application in a similar fashion i.e. create additional views for all queries that we use to retrieve data.

I know this is poor design, but I am unable to list out to the customer why their view based strategy is a poor design.

What is the consensus in the community on when to use views? How does having so many views affect performance of the SQL server?

答: While accessing the data through a view layer is a good idea, a separate view for every query is inevitably going to mean that you are going to repeat yourself quite a bit.  Inevitably, there are going to be business rules that are going to be common across many views (i.e. whatever filters you need for an entity to appear on one screen will almost certainly need to be repeated on all subsequent screens).  When those business rules change, you're going to have to go through and change every view that implements those business rules.  If, instead, you can embed those business rules in a single view, it is much more likely that you'll only have to change the code in one place when your logic changes.</p>


答:
Many of the answers have lots of good reasons to use views, and point out that there is no extra cost to having more views.

What may be the driver for this mandate is simply that they do not want to give you any chance to break any views/sps that exist already and potentially affect other applications, and also, their existing views/sps cannot be under suspiscion for some bug  your app has that might rear it's head later.

It is another form of layering and modularisation. Everything for your app goes through "your" view/sp layer. Install or uninstall your app, and your set of views/sps is installed/uninstalled etc.


问:
Where has Cloud Computing gone?
I have been hearing about this term for close to 5 years now. I have read about services from Microsoft (Azure), but I have never saw it adopted in the mainstream usage. The thing I am trying to understand is this:

What happened to cloud computing? Is the infrastructure at present insufficient to implement this?

Is it still in its infancy?

Is it being used in other forms, like all the services Google seems to provide (plus Plus Google OS, etc)?

If it has failed, then why?

答: Cloud Computing, like most new technologies, was painfully over-hyped by the industry media. As it matures and is adopted -- or not -- as a working strategy, it is finding its valid place in the ecosystem. It is neither a panacea for all infrastructure problems nor a failure. </p>

Title: Where has Cloud Computing gone?

ContentLicense: CC BY-SA 2.5


答:
I find his attitude as an asset rather than a liability.  His ability to do research is above average.  His learning curve is also shallow.  Why not exploit this traits if you want him to learn something.

His inquisitive mind is always on the go, why not provide him direction.  Start by telling him why pagination is an important and essential.  Let him take a look at websites with pagination and websites without those.

How about giving a constructive criticism to what he is doing.  "Wow you've done something great,  but wouldn't it be better if you do it this way with emphasis on optimization and best practices.

I think doing a comparison between a good practice and a bad practice can really stimulate his mind.

Do not restrict him, he will eventually find something he would like and settle with it for some time.  If I were you, I provide him with lots of learning material about things he is so passionate about.

I think he is doing the top down approach while you on the other hand want him to do a bottom up approach

Title: Should a new programmer focus on a single technology until he's proficient at it?

Body:
Ok, I've been teaching a buddy how to program for a while now. He's a very fast learner, and he's quite good at programming so far. However, he has one "issue" I keep trying to correct.

He jumps in and starts doing highlevel programming without learning some of the basics (He's created a full blown web application but still doesn't know pagination or session management).

This isn't the problem though. He keeps jumping around to new technology (Node.js, MongoDB, EC2, etc). I tried telling him that he should learn some of the basics about his RDMS of choice (MySQL) as he uses it everyday before investing a bunch of time into learning the basics of MongoDB (And probably moving to something new).

Am I the one in the wrong here, or should he try to focus on one thing at a time and get really good at it?


问:
When to stop inheritance?
Once upon time ago I asked a question on Stack Overflow about inheritance.

I have said I design chess engine in OOP fashion. So I inherit all my pieces from Piece abstract class but inheritance still goes. Let me show by code

```<code>public abstract class Piece
{
    public void MakeMove();
    public void TakeBackMove();
}

public abstract class Pawn: Piece {}

public class WhitePawn :Pawn {}

public class BlackPawn:Pawn {}
</code>```

Programmers has been found my design a little bit over engineering and suggested to remove colored piece classes and hold piece color as a property member like below.

```<code>public abstract class Piece
{
    public Color Color { get; set; }
    public abstract void MakeMove();
    public abstract void TakeBackMove();
}
</code>```

In this way Piece can know his color. After implementation i have seen my implementation goes like below.

```<code>public abstract class Pawn: Piece
{
    public override void MakeMove()
    {
        if (this.Color == Color.White)
        {

        }
        else
        {

        }
    }

    public override void TakeBackMove()
    {
        if (this.Color == Color.White)
        {

        }
        else
        {

        }
    }
}
</code>```

Now I see that keep color property causing if statements in implementations. It makes me feel we need specific color pieces in inheritance hierarchy.

In such a case would you have classes like WhitePawn, BlackPawn or would you go to design by keeping Color property?

Without seen such a problem how would you want to start design? Keep Color property or having inheritance solution ?

Edit: I want to specify that my example may not completely match real life example. So before try to guess implementation details just concentrate the question.

I actually simply asking if using Color property will cause if statements better to use inheritance ?

答:
Imagine you design an application which contains vehicles. Do you create something like this?

```<code>class BlackVehicle : Vehicle { }
class DarkBlueVehicle : Vehicle { }
class DarkGreenVehicle : Vehicle { }
// hundreds of other classes...
</code>```

In real life, color is a property of an object (either a car or a chess piece), and must be represented by a property.

Are MakeMove and TakeBackMove different for blacks and whites? Not at all: the rules are the same for both players, which means that those two methods will be exactly the same for blacks and whites, which means that you are adding a condition where you don't need it.

On the other hand, if you have WhitePawn and BlackPawn, I will not be surprised if soon or later you'll write:

```<code>var piece = (Pawn)this.CurrentPiece;
if (piece is WhitePawn)
{
}
else // The pice is of type BlackPawn
{
}
</code>```

or even something like:

```<code>public abstract class Pawn
{
    public Color Player
    {
        get
        {
            return this is WhitePawn ? Color.White : Color.Black;
        }
    }
}

// Now imagine doing the same thing for every other piece.
</code>```

Title: When to stop inheritance?

Body:
Imagine you design an application which contains vehicles. Do you create something like this?

class BlackVehicle : Vehicle { }
class DarkBlueVehicle : Vehicle { }
class DarkGreenVehicle : Vehicle { }
// hundreds of other classes...

In real life, color is a property of an object (either a car or a chess piece), and must be represented by a property.

Are MakeMove and TakeBackMove different for blacks and whites? Not at all: the rules are the same for both players, which means that those two methods will be exactly the same for blacks and whites, which means that you are adding a condition where you don't need it.

On the other hand, if you have WhitePawn and BlackPawn, I will not be surprised if soon or later you'll write:

var piece = (Pawn)this.CurrentPiece;
if (piece is WhitePawn)
{
}
else // The pice is of type BlackPawn
{
}

or even something like:

public abstract class Pawn
{
    public Color Player
    {
        get
        {
            return this is WhitePawn ? Color.White : Color.Black;
        }
    }
}

// Now imagine doing the same thing for every other piece.


问:
Patterns for Handling Changing Property Sets in C++
I have a bunch "Property Sets" (which are simple structs containing POD members). I'd like to modify these property sets (eg: add a new member) at run time so that the definition of the property sets can be externalized and the code itself can be re-used with multiple versions/types of property sets with minimal/no changes.

For example, a property set could look like this:

```<code>struct PropSetA
{
    bool activeFlag;
    int processingCount;
    /* snip few other such fields*/
};
</code>```

But instead of setting its definition in stone at compile time, I'd like to create it dynamically at run time. Something like:

```<code>class PropSet propSetA;
propSetA("activeFlag",true);  //overloading the function call operator
propSetA("processingCount",0);
</code>```

And the code dependent on the property sets (possibly in some other library) will use the data like so:

```<code> bool actvFlag = propSet["activeFlag"];
 if(actvFlag  == true)
 {
   //Do Stuff
 }
</code>```

The current implementation behind all of this is as follows:

```<code>class PropValue
{
 public:
    // Variant like class for holding multiple data-types
    // overloaded Conversion operator. Eg:
    operator bool()
    {
      return (baseType == BOOLEAN) ? this->ToBoolean() : false;
    }
    // And a method to create PropValues various base datatypes
    static FromBool(bool baseValue);
};

class PropSet
{

 public:
  // overloaded[] operator for adding properties
  void operator()(std::string propName, bool propVal)
  {
    propMap.insert(std::make_pair(propName, PropVal::FromBool(propVal)));
  }

 protected:
   // the property map
   std::map<std::string, PropValue> propMap;
};
</code>```

This problem at hand is similar to this question on SO and the current approach (described above) is based on this answer. But as noted over at SO this is more of a hack than a proper solution. The fundamental issues that I have with this approach are as follows:

Extending this for supporting new types will require significant code change. At the bare minimum overloaded operators need to be extended to support the new type.

Supporting complex properties (eg: struct containing struct) is tricky.

Supporting a reference mechanism (needed for an optimization of not duplicating identical property sets) is tricky. This also applies to supporting pointers and multi-dimensional arrays in general.

Are there any known patterns for dealing with this scenario? Essentially, I'm looking for the equivalent of the visitor pattern, but for extending class properties rather than methods.

Edit: Modified problem statement for clarity and added some more code from current implementation.

答:
Well, AFAIU you want some kind of reflection, but to retain static type checking the reflection data must be available for template metaprograms.  There are (or at least were) several efforts to implement such a library: Mirror C++ reflection utilities, Boost libraries for reflective programming (seem to be outdated).  Take a look at them at least as source of inspiration.  Also take a look at Boost.Fusion, it is a library for working with heterogeneous collections of data (tuples), which in turn can represent structs.

The simplest static reflection can achieved using a separate code generator which produces code like:

```<code>struct Foo {
  int a;
  double b;
};

// Types to identify struct members
namespace name_tags { struct a; struct b; }

// Reflection metadata for struct Foo
template<>
struct DataMembers<Foo> {
  typedef boost::fusion::result_of::make_map<
    name_tags::a,
    name_tags::b,
    Member<Foo, int>,
    Member<Foo, double>
  >::type type;

  type value;
};

DataMembers<Foo>::type
DataMembers<Foo>::value =
  boost::fusion::result_of::make_map<
    name_tags::a,
    name_tags::b>(Member<Foo, int>(&Foo::a, "a"),
                  Member<Foo, double>(&Foo::b, "b"));
</code>```

Where Member class template is like:

```<code>template<typename S, typename M>
struct Member
{
  M S::* ptr;
  std::string name;

  Member(M S::* ptr, const std::string& name) : ptr(ptr), name(name) { }
};
</code>```

Then you can use Boost.Fusion to apply a functor to all members of the class.  You can use additional metafunctions to mark some members, e.g. as properties to process.

Iterating over members of Foo can be done as

```<code>boost::fusion::for_each(DataMembers<Foo>::value, ProcessMember());

struct ProcessMember
{
  void operator() (const boost::fusion::pair<name_tags::a, Member<Foo, int>>& mem) const
   {
     // ...
   }

  void operator() (const boost::fusion::pair<name_tags::b, Member<Foo, double>>& mem) const
   {
     // ...
   }

   // You can also provide a default case
   template<typename T>
   void operator() (const T&) const { }
};
</code>```

Tag types name_tags::a and name_tags::b appear in the signatures of the operator() and allow to provide separate processing function for each member of Foo.  If you add a member to Foo and update the reflection data (this should be automated) and forget to update processing functors application of those functions will fail to compile.

Body:
Well, AFAIU you want some kind of reflection, but to retain static type checking the reflection data must be available for template metaprograms.  There are (or at least were) several efforts to implement such a library: Mirror C++ reflection utilities, Boost libraries for reflective programming (seem to be outdated).  Take a look at them at least as source of inspiration.  Also take a look at Boost.Fusion, it is a library for working with heterogeneous collections of data (tuples), which in turn can represent structs.

The simplest static reflection can achieved using a separate code generator which produces code like:

struct Foo {
  int a;
  double b;
};

// Types to identify struct members
namespace name_tags { struct a; struct b; }

// Reflection metadata for struct Foo
template<>
struct DataMembers<Foo> {
  typedef boost::fusion::result_of::make_map<
    name_tags::a,
    name_tags::b,
    Member<Foo, int>,
    Member<Foo, double>
  >::type type;

  type value;
};

DataMembers<Foo>::type
DataMembers<Foo>::value =
  boost::fusion::result_of::make_map<
    name_tags::a,
    name_tags::b>(Member<Foo, int>(&Foo::a, "a"),
                  Member<Foo, double>(&Foo::b, "b"));

Where Member class template is like:

template<typename S, typename M>
struct Member
{
  M S::* ptr;
  std::string name;

  Member(M S::* ptr, const std::string& name) : ptr(ptr), name(name) { }
};

Then you can use Boost.Fusion to apply a functor to all members of the class.  You can use additional metafunctions to mark some members, e.g. as properties to process.

Iterating over members of Foo can be done as

boost::fusion::for_each(DataMembers<Foo>::value, ProcessMember());

struct ProcessMember
{
  void operator() (const boost::fusion::pair<name_tags::a, Member<Foo, int>>& mem) const
   {
     // ...
   }

  void operator() (const boost::fusion::pair<name_tags::b, Member<Foo, double>>& mem) const
   {
     // ...
   }

   // You can also provide a default case
   template<typename T>
   void operator() (const T&) const { }
};

Tag types name_tags::a and name_tags::b appear in the signatures of the operator() and allow to provide separate processing function for each member of Foo.  If you add a member to Foo and update the reflection data (this should be automated) and forget to update processing functors application of those functions will fail to compile.


问:
What to include in a report on software implementation and how?
I am currently writing an extended report on a software library I have written. The reviewer will be a professor at my univeristy. He knows basically what I had to do, but the report will be evaluated. I have produced some samples results with the library which I already plan to include in the work. What I want to know know is :

What should I write about the library itself?

How should I structure it?

Which points need to be emphasized?

Also, the professor is as allergic to mundane implementation details as a business manager.

答:
In my view there are two things important in software documentation/report:

Technical documentation, for each function/class you describe the input and output, and what it does. This could also include the class hierarchy if you are using object orientation.

User documentation: This includes stuff like:

What is the goal of the library, what are the requirements

How and why have you designed the library in a particular way. Which design patterns have you used (in case of OOP), or why have you ordered your procedures in a certain way. For your professor this is also important if he wants to see if you can think on a high abstraction level, and not only in the nitty gritty details.

Example uses (tutorials) which show a few good examples of how the library can be used. You can link back to design decisions and point out that this example shows why it was a good idea to design in a particular way.


答:
Reading your last sentence, probably you have to describe what the library does, instead of how it does it. Including the samples is a good idea; lots of students forget doing it, so you'll probably will have additional points for that. Moreover, you may want to:

Write documentation. Samples are great to discover the library, but too hard to use to find a very specific thing. Also, samples tend to never show features which exists, but are rarely used.

Some indications about how the library is implemented may still be relevant. It is sometimes unavoidable in order for your library to be used efficiently.

Example: your library has a following method:

```<code>// Adds words from a single source to a dictionary.
void AddToDictionary(Source dataSource);

// Adds words in parallel from multiple sources to a dictionary, while opening
// and saving the dictionary only once.
void AddToDictionary(IEnumerable<Source> dataSource);
</code>```

Without proper documentation, I would be unable to know that I must use the second overload for four or more dictionaries, and stick with the basic first implementation for one to three dictionaries, because your library is implemented in such a way that the parallel task will be effective only with a large number of libraries: with less, the time to load and save the dictionary several times will be too small.

Last but not least, what are the requirements for your library? If it's written in .NET Framework, do I require .NET Framework 3.5? 4? 4.5? How to deploy it? Just by downloading the file? By downloading the setup and running it? By getting the package and doing one hundred steps in order to make it work?

Title: What to include in a report on software implementation and how?

Body:
I am currently writing an extended report on a software library I have written. The reviewer will be a professor at my univeristy. He knows basically what I had to do, but the report will be evaluated. I have produced some samples results with the library which I already plan to include in the work. What I want to know know is :

What should I write about the library itself?

How should I structure it?

Which points need to be emphasized?

Also, the professor is as allergic to mundane implementation details as a business manager.

Body:
Reading your last sentence, probably you have to describe what the library does, instead of how it does it. Including the samples is a good idea; lots of students forget doing it, so you'll probably will have additional points for that. Moreover, you may want to:

Write documentation. Samples are great to discover the library, but too hard to use to find a very specific thing. Also, samples tend to never show features which exists, but are rarely used.

Some indications about how the library is implemented may still be relevant. It is sometimes unavoidable in order for your library to be used efficiently.

Example: your library has a following method:

// Adds words from a single source to a dictionary.
void AddToDictionary(Source dataSource);

// Adds words in parallel from multiple sources to a dictionary, while opening
// and saving the dictionary only once.
void AddToDictionary(IEnumerable<Source> dataSource);

Without proper documentation, I would be unable to know that I must use the second overload for four or more dictionaries, and stick with the basic first implementation for one to three dictionaries, because your library is implemented in such a way that the parallel task will be effective only with a large number of libraries: with less, the time to load and save the dictionary several times will be too small.

Last but not least, what are the requirements for your library? If it's written in .NET Framework, do I require .NET Framework 3.5? 4? 4.5? How to deploy it? Just by downloading the file? By downloading the setup and running it? By getting the package and doing one hundred steps in order to make it work?


答:
In this answer, I'm assuming that by "chess engine", the author of the question means "chess AI", not merely a move validation engine.

I think using OOP for pieces and their valid movements is a bad idea for two reasons:

The strength of a chess engine is highly dependent on how fast it can manipulate boards, see e.g. Chess program board representations. Considering the level of optimization this article describes, I don't think a regular function call is affordable. A call to a virtual method would add a level of indirection and incur an even higher performance penalty. The cost of OOP isn't affordable there.

The benefits of OOP such as extensibility are of no use for pieces, as chess isn't likely to get new pieces any time soon. A viable alternative to inheritance-based type hierarchy includes using enums and switch. Very low-tech and C-like, but hard to beat performance-wise.

Moving away from performance considerations, including the color of the piece in the type hierarchy is in my opinion a bad idea. You will find yourself in situations where you need to check if two pieces have different colors, for instance for capturing. Checking this condition is easily done using a property. Doing it using is WhitePiece-tests would be uglier in comparison.

There is also another practical reason for avoiding moving move generation to piece-specific methods, namely that different pieces share common moves, e.g. rooks and queens. In order to avoid duplicate code, you would have to factorize common code into a base method, and have yet another costly call.

That being said, if it's the first chess engine you are writing, I would definitely advise to go with clean programming principles and avoid the optimization tricks described by Crafty's author. Dealing with the specifics of chess rules (castling, promotion, en-passant) and complex AI techniques (hashing boards, alpha-beta cut) is challenging enough.

Title: When to stop inheritance?

Body:
Once upon time ago I asked a question on Stack Overflow about inheritance.

I have said I design chess engine in OOP fashion. So I inherit all my pieces from Piece abstract class but inheritance still goes. Let me show by code

```<code>public abstract class Piece
{
    public void MakeMove();
    public void TakeBackMove();
}

public abstract class Pawn: Piece {}

public class WhitePawn :Pawn {}

public class BlackPawn:Pawn {}
</code>```

Programmers has been found my design a little bit over engineering and suggested to remove colored piece classes and hold piece color as a property member like below.

```<code>public abstract class Piece
{
    public Color Color { get; set; }
    public abstract void MakeMove();
    public abstract void TakeBackMove();
}
</code>```

In this way Piece can know his color. After implementation i have seen my implementation goes like below.

```<code>public abstract class Pawn: Piece
{
    public override void MakeMove()
    {
        if (this.Color == Color.White)
        {

        }
        else
        {

        }
    }

    public override void TakeBackMove()
    {
        if (this.Color == Color.White)
        {

        }
        else
        {

        }
    }
}
</code>```

Now I see that keep color property causing if statements in implementations. It makes me feel we need specific color pieces in inheritance hierarchy.

In such a case would you have classes like WhitePawn, BlackPawn or would you go to design by keeping Color property?

Without seen such a problem how would you want to start design? Keep Color property or having inheritance solution ?

Edit: I want to specify that my example may not completely match real life example. So before try to guess implementation details just concentrate the question.

I actually simply asking if using Color property will cause if statements better to use inheritance ?


问:
Is there a lightweight method to describe web services, similar to robots.txt or sitemap.xml?
I'd like to provide a very lightweight method to describe my web services. No WSDL, WADL or similar complex stuff. Just a mapping from the web service's base URL to a simple description which can be detected and parsed automatically. Basically

The name of the service

A link to some human readable documentation (optional)

Possibly a contact address

Usage conditions, URL patterns etc. are less needed to keep it simple.

The best I could find is OpenSearch Description Documents, but first it could be simpler with plain text config files, and second there is no standard how to connect these service description documents to arbitrary web services (only autodiscovery in ATOM/RSS and HTML).

I thought about creating my own format and provide it similar to robots.txt:

```<code>$ curl http://example.org/services.txt

service: http://example.org/foobar
name: Foobar API
about: http://example.org/foobar-doc.html

service: http://example.org/some/unapi
name: Example ORG's unAPI

# additional fields, to be discussed
standard: http://unapi.info
pattern: ?id={id}&format={format}
</code>```

So if you know the base URL of a service, such as http://example.org/some/unapi, you can look up at least the name in the service description file.

Instead of defining my own standard, however, I'd like to know whether there is already something similar to reuse.

答:
There is a standard, but its called WSDL.

While the WS* standard are dauntingly complex and all encompassing in the breadth of their coverage in practice its pretty easy.

There is a very comprehensive and mature set of tooling and implementation built up around SOAP. In most cases all you need to write is the WSDL itself and the actual business logic service in Java, php, python C++ or whatever. The tooling and SOAP engine does the rest -- including responding to requests for a description of the web service.

There really is not much point in defining your own standard in isolation as its unlikely anyone but yourself would use it.

Although its not yet a standard the JSON SMD proposal may be more to your liking. Its much simpler than WSDL although it still very much describes the interface itself rather than the higher level description (contact details, ownership etc ) you desire.


答:
Personally I wouldn't inherit anything from Piece at all, because I don't think you gain anything from doing that.   Presumably a piece doesn't actually care how it moves, only which squares are a valid destination for its next move.

Perhaps you could create a Valid Move Calculator which knows the available movement patterns for a type of piece, and is able to retrieve a list of valid destination squares, for example

```<code>interface IMoveCalculator
{
    List<Square> GetValidDestinations();
}

class KnightMoveCalculator : IMoveCalculator;
class QueenMoveCalculator : IMoveCalculator;
class PawnMoveCalculator : IMoveCalculator;
// etc.

class Piece
{
    IMoveCalculator move_calculator;
public:
    Piece(IMoveCalculator mc) : move_calculator(mc) {}
}
</code>```

Title: When to stop inheritance?

Body:
Personally I wouldn't inherit anything from Piece at all, because I don't think you gain anything from doing that.   Presumably a piece doesn't actually care how it moves, only which squares are a valid destination for its next move.

Perhaps you could create a Valid Move Calculator which knows the available movement patterns for a type of piece, and is able to retrieve a list of valid destination squares, for example

interface IMoveCalculator
{
    List<Square> GetValidDestinations();
}

class KnightMoveCalculator : IMoveCalculator;
class QueenMoveCalculator : IMoveCalculator;
class PawnMoveCalculator : IMoveCalculator;
// etc.

class Piece
{
    IMoveCalculator move_calculator;
public:
    Piece(IMoveCalculator mc) : move_calculator(mc) {}
}


问:
Are code reviews necessary for junior developers?
I've worked at two companies, who each had a different methodology when it came to code reviews:

In the first company, a code review was conducted by the team leaders and was required after the completion of every module.

However, in the second company, team leaders weren't required to conduct any code reviews, and just checked for functionality and design issues.

So I am confused. Is the code review process really needed? If it is, why? And if it isn't, why not?

答:
We make online football game in Turkey. A lot of users and game masters helps us on functionality. Also they give comments on needed features. So I think, if you have a lot of users, functionality tests can be done for helping or getting badges. Collobration of developers, game masters and users with forums, support teams and private test environments create a social project.   </p>

<p>Sure code reviews and sharing experiences between development team is needed but if it's not critical you don't have to force yourself. </p>

Body:
We make online football game in Turkey. A lot of users and game masters helps us on functionality. Also they give comments on needed features. So I think, if you have a lot of users, functionality tests can be done for helping or getting badges. Collobration of developers, game masters and users with forums, support teams and private test environments create a social project.

Sure code reviews and sharing experiences between development team is needed but if it's not critical you don't have to force yourself.


问:
How would you know if you've written readable and easily maintainable code?
How would one know if the code one has created is easily readable, understandable, and maintainable? Of course from the author's point of view, the code is readable and maintainable, because the author wrote it and edited it, to begin with. However, there must be an objective and quantifiable standard by which our profession can measure code.

These goals are met when one may do the following with the code without the expert advice of the original author:

It is possible to read the code and understand at a basic level the flow of logic.

It is possible to understand at a deeper level what the code is doing to include inputs, outputs, and algorithms.

Other developers can make meaningful changes to the original code such as bug fixes or refactoring.

One can write new code such as a class or module that leverages the original code.

How do we quantify or measure code quality so that we know it readable, understandable, and maintainable?

答:
Reading How To Write Unmaintainable Code - Ensure a job for life by Roedy Green, laughing, and learning.

...how to write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code...

The essay gives you numerous examples of how to write bad code, using plenty of funny examples. It continues to explain how to utilize Creative Miss-spelling, Reuse of Names, the highly appreciated technique of Reuse of Global Names as Private.

In a humorous way the essay teaches you how to avoid all of the examples of unreadable and unmaintainable code.

Actually, I found it hard to believe that anyone would write code with similarities to the examples in the text. That was when I was fresh from school. But, after working for a few years I see code from the text every day…


问:
What does Bucket mean?
I found in legacy code a class which name is BucketService.

Because english is not my native language I was trying to translate that, but it doesn't make sense.

I found few termins like bucket sorting and so on, but I still don't get it. Actually this word is used quite frequently in programming

I would be helpfull for some simple explanation of that word

答:
A bucket in English is a device for holding water.

When used in software, it normally means a data type that groups objects together.

The term is used often when discussing hashing algorithms, where different items that have the same hash code (hash collision) go into the same "bucket". Meaning, the objects are grouped by the hash.

In general, a hashing function may map several different keys to the same index. Therefore, each slot of a hash table is associated with (implicitly or explicitly) a set of records, rather than a single record. For this reason, each slot of a hash table is often called a bucket, and hash values are also called bucket indices.

Informally, I have seen the term used with dictionaries whose value (not key) is a collection of items.

Wikipedia has a page dedicated to the term as used in computing - Bucket (Computing):

In computing, the term bucket can have several meanings. It is used both as a live metaphor, and as a generally accepted technical term in some specialised areas. A bucket is most commonly a type of data buffer or a type of document in which data is divided into regions.

Title: What does Bucket mean?


问:
How important are UML diagrams for a successful project?
I'm in the middle of a project and I was asked to write UML diagrams (use cases,class diagram,etc). The project isn't very complex.

I was wondering if this be a waste of my time? Should I just be doing other fun stuff like writing code? And when is it not ok to build something without going through all of the conceptual phase? Is it all about complexity? And if so, how to measure it?

答:
I love diagrams, but if I was asked to make one (especially UML!), I'd ask two questions:

Who is it for?

Do they need it now?

Diagrams go out of date straight away. So unless you're using it to communicate with someone now, it will just rot. And if the person you're communicating with would do better with a text description, or a phone call, or an informal digram on a whiteboard - suggest that instead.


答:
It's still out there and being used quite a bit. The conundrum is that it was never defined very succinctly and became an umbrella term for just about anything related to the Internet.

Depending on how you define it, you could say it is very widely used (SalesForce, GMail, StackOverflow, etc.). Given the ambiguity, I think people are using more specific terms now instead of the over-hyped moniker "Cloud computing". For example Platform as a Service (MS Azure), Infrastructure As a Service (Amazon EC3), or Application as a Service (GMail).

More and more, however, I think the term "Cloud computing" where it is still used is mostly applied to PaaS or IaaS. In that aspect it is very much used. A big example is FaceBook apps, many of which run on cloud providers.

Title: Where has Cloud Computing gone?

Body:
I have been hearing about this term for close to 5 years now. I have read about services from Microsoft (Azure), but I have never saw it adopted in the mainstream usage. The thing I am trying to understand is this:

What happened to cloud computing? Is the infrastructure at present insufficient to implement this?

Is it still in its infancy?

Is it being used in other forms, like all the services Google seems to provide (plus Plus Google OS, etc)?

If it has failed, then why?


问:
Which collection structure I should use for parametrical grouping ordering in c#?
I have various windows forms applications that contain various controls that build up custom "group by" and "where" clauses for my class methods.

I am thinking to pass a collection structure of some kind in order for the methods to be able to build the group by's and the where clauses.

Let's say a list containing the field and the value for the group by or where.

Am I going to the right direction?

Update:

I dont have code yet but let me try to explain better:

We have a form with 10 dropdownlists and a checkmark beside them.

Also we have adatagrid on the form.

Every dropdownlist corresponds to a field in a table.

If a dropdownlist has its checkbox checked means that it must be part of the group by clause in the select statement.

The value of the dropdownlist must be part of the where clause.

*note: *  Another application could have different numbers of dropdownboxes and different corresponding fields.

I want to create a common method that will retrieve data with user selectable group by and where clauses.

So what i think is to pass to the method 2 lists.

One with (fieldname, value) for the where clauses

And one with (fieldname) for the group by

depending on the logic above...

I hope this is more clear.

答:
The logic for Group By is very complex. First, you should ask yourself, is this something you need/has the resources to program on your own, or is it better to use a tool for that? For example, if you group by a timestamp, you may decide to group only by date, hours and minutes and ignore the rest. You also have to use the real data values and not the formatted strings, etc.

There are 3rd party tools that help you do this nicely, easily and provide great GUI effects like drag and drop of your grid columns into grouping area (much like Outlook).

Now, if you decided to do it on your own, I suggest you perform the grouping in the database not on the client. There are many reasons for that such as:

This will let you not worry about memory management for large lists

Coding and testing will be simplified

You don't have to worry about data types in comparison or in filtering

You will get up-to-date data

Going forward with this approach, you can ask the user to select the group by fields and every selected field can be used to build a string. When the user selects all desired fields, you end up with a string like:

"Country, Gender, Age"

Do the same for the grouping condition (MS Access for example has an expression builder which I think is not necessary, but it helps end user build an expression) and eventually end up with a string such as:

"Age > 12"

Now you could plug these strings into your original select query to get:

SELECT ...
GROUP BY Country, Gender, Age
HAVING Age > 12

The other tricky part is to figure out what your user wants to do with the group by. Usually you want to run an aggregate function like SUM or COUNT on the grouped set. So you need to take this in consideration also.


答:
Here is a technique I like to use:

Show the code to one of your peer programmers and have them explain to you what it does. Watch for these things.

1) If they can't easily explain the purpose of a block of code refactor it.

2) If they have to jump to another section of code to understand the current section,   refactor it.

4) Anytime you feel an urge to speak during the process, that section of code needs refactoring. (The code isn't speaking for itself).

Title: How would you know if you've written readable and easily maintainable code?

Body:
How would one know if the code one has created is easily readable, understandable, and maintainable? Of course from the author's point of view, the code is readable and maintainable, because the author wrote it and edited it, to begin with. However, there must be an objective and quantifiable standard by which our profession can measure code.

These goals are met when one may do the following with the code without the expert advice of the original author:

It is possible to read the code and understand at a basic level the flow of logic.

It is possible to understand at a deeper level what the code is doing to include inputs, outputs, and algorithms.

Other developers can make meaningful changes to the original code such as bug fixes or refactoring.

One can write new code such as a class or module that leverages the original code.

How do we quantify or measure code quality so that we know it readable, understandable, and maintainable?


答:
What you should ask yourself is why you really need those statements in your Pawn class:

```<code>    if (this.Color == Color.White)
    {

    }
    else
    {
    }
</code>```

I am pretty sure it will be sufficient to have a small set of functions like

```<code>public abstract class Piece
{
    bool DoesPieceHaveSameColor(Piece otherPiece) { /*...*/   }

    Color OtherColor{get{/*...*/}}
    // ...
}
</code>```

in your Piece class and implement all of the functions in Pawn (and the other derivations of Piece) using those functions, without ever having any of those if statements above. Only exception may be the function to determine the move direction for a Pawn by its color, since this is specific to pawns, but in almost all other cases you won't need any color-specific code.

The other interesting question is if you should really have different subclasses for different kinds of pieces at all. That seems reasonable and natural to me, since the rules for the moves for each piece are different and you can surely implement this by using different overloaded functions for each kind of piece.

Of course, one could try to model this in a more generic way, by separating the properties of the pieces from their moving rules, but this may end in an abstract class MovingRule and a subclass hierarchy MovingRulePawn, MovingRuleQueen, ... I would not start it that way, since it could easily lead to another form of over-engineering.

Title: When to stop inheritance?

Body:
What you should ask yourself is why you really need those statements in your Pawn class:

    if (this.Color == Color.White)
    {

    }
    else
    {
    }

I am pretty sure it will be sufficient to have a small set of functions like

public abstract class Piece
{
    bool DoesPieceHaveSameColor(Piece otherPiece) { /*...*/   }

    Color OtherColor{get{/*...*/}}
    // ...
}

in your Piece class and implement all of the functions in Pawn (and the other derivations of Piece) using those functions, without ever having any of those if statements above. Only exception may be the function to determine the move direction for a Pawn by its color, since this is specific to pawns, but in almost all other cases you won't need any color-specific code.

The other interesting question is if you should really have different subclasses for different kinds of pieces at all. That seems reasonable and natural to me, since the rules for the moves for each piece are different and you can surely implement this by using different overloaded functions for each kind of piece.

Of course, one could try to model this in a more generic way, by separating the properties of the pieces from their moving rules, but this may end in an abstract class MovingRule and a subclass hierarchy MovingRulePawn, MovingRuleQueen, ... I would not start it that way, since it could easily lead to another form of over-engineering.


问:
Real-time Dataflow Programming

Background

Recently, I have been fascinated about the possibilities of dataflow-based programming approaches - in particular, signal/event-based concepts as realized by functional reactive programming, Boost::Dataflow::Signals, and the like.

Sample scenario:

Consider a car that has four speed sensors, one at each of its tires. Let's simplify things and say that these sensors are analog sensors providing the measured speed at that tire. The car further has individual brakes on the four tires (the actuators) that one can program to break more or less strongly.

There is no concrete task, but imagine having to realize things like detecting tires not turning due to aqua-planing, or ABS-support, or or or... In short: you have to evaluate the speed sensor data and control the actuators according to some logic.

From a programming point of view, one could think of realizing this via a signal-network of the following sort:

```<code>timer ------------\
sensor1/2/3/4 -> logic -> brakes1/2/3/4
</code>```

(That is, the timer triggers the logic, which takes the latest analog values of the sensors)

Like this, the timer can be programmed to trigger in fixed intervals (especially important to ensure the real-time constraints).

The advantage of the dataflow-approach here is that the above diagram is directly realized in the code, i.e. you have a logical wiring of signals and just need to provide an implementation that turns your actual hardward sensor's data into a signal (of the corresponding library you are using).

When it comes to real-time requirements, the maximal signal path length can also be computed (or at least more easily derived from the source).

The question

Of course, all of this is just an application idea and I am sure several brilliant people have come up with this before. What I am looking for is the follow-up. Are there any hard problems with this scenario which make it unrealizable in practice? Are there experiences from real-world projects on following such a line of thought? Is there even existing literature on this?

To make things clearer and more objective, I am looking for an answer that either shows an inherent fault in my line of thinking or provides reference to existing work/literature along with evaluations. Bonus points if real-time constraints are taken into account.

答:
Are there any hard problems with this scenario which make it unrealizable in practice?

Inattention and sensor failure.  The Metro subway system in Washington DC, USA, was computer controlled in the past.  While this made for an efficient system from the point of view of the riders, two major problems developed.

1)  The train operators had almost nothing to do.  Since the computer controlled everything, the train operators became inattentive.  In an emergency, the operators could not respond.  This problem was mitigated (not solved) by requiring the operators to assume manual control for an hour of their shift, to keep their skills up.

2)  There were two catastrophic accidents in the last 7 years due to sensor failure.  Imagine the poor train operator moving towards a stopped train at 55 miles per hour, unable to stop the train in time because the computer did not sense the stopped train.

At Least 6 Killed in Red Line Crash

I don't know that these problems make data flow based programming unrealizable.  I do know that these and other problems make data flow based programming hard.

Title: Real-time Dataflow Programming


问:
Hourly or per project billing?
How do you bill your programming projects? Do you do it per hour? Per job?

Please include what kind of project you are doing in the answer. (Mobile, Web, Desktop, etc... You can be more specific if you want.)

BONUS:

If you'd like to give specific amounts in your answer, you may. ;-)

答:
I work at a web dev shop (~25 people) and we do it mostly by the project, since that's what customers prefer.  They don't want open-ended commitments to keep giving us money.

Some exceptions have occurred, though.  When we do hourly, it's usually a deal where we'll give them N hours of work between M developers per month to work on whatever they want.

Title: Hourly or per project billing?


答:
Distributed resources is what defines a grid.

Although good answers thus far I believe most of you have missed some of the big key points.

To my knowledge there was a committee which has defined protocols to standardize cloud computing.  Google, amazon, microsoft, the big name players have all implemented their own cloud solutions to provide SAAS provisions for internal and in some cases external use.

In terms of cloud computing for the end user it is just not there yet.  People think of the cloud as in: "My computer is strictly virtual with as client accessing it wherever I am physically located."  This idea is not yet ready and will take much effort to form protocols and specifications for interoperability.

There are great examples of cloud computing though.  One example in the educational sector is "ChindaGrid".  Google it if you wish.  It was a project from CERNET in China to provide computational resources to institutions such as universities.  IBM has extensive interest/effort put forth towards grid computing.

Also it should be noted that p2p is a form of grid computing.  Distributed resources is what defines a grid.

Remember the internet came about in the 60's for physicists to communicate across distances and then expanded to DARPA/ARPNET project for government use to have a decentralized network with no single point of failure.  We are talking how many years before the internet as we know it became alive.  The grid is still in its infancy and will take time to mature but the idea of scalable on demand provisioning is where computers will go without a doubt.

Great question, looking forward to other answers/comments!

Title: Where has Cloud Computing gone?


问:
Development Patterns for dealing with Data Import / Export
I have a ASP.NET web based application that allows the end user to export data to a flat file format. (essentially taking a point-in-time backup of their work)

At a later date they can re-upload (import) that data back into the web application.

The actual format of the backup is pretty trivial. An object graph is serialized using the WCF DataContractSerializer to xml, and then the resultant xml document is compressed. Importing, unzips it and deserializes the data.

There's one small problem I see with this approach. versioning... as time moves on and the data structures change (properties / child-collections are added/removed or renamed) then previously exported versions of a users data will no longer map to the object graph in the application.

Are there any specifici patterns or practices that address this issue? or any other reading material you could recommend.

答:
We have been using .NET Xml Serialization of pretty big graph of .NET objects for several years.  We opted to take a very simple approach: keep the objects backward compatible at the code level.  We generally only add new properties, and in the one case where we modified the datatype of a property, we created a new property with the modified datatype, and initialized it from the old data when user upgraded.

I think the one best practice we instituted, was that any new properties were always added as a full fledged property, and not just a class member variable.  This enabled us to ensure that the code always initialized the new property to a helpful default value (instead of the blank/null value which it initializes to during deserialization.)

This has covered us for upgrades to the application over 5 years, with no bugs caused by deserializing old versions of the objects into newer version of the application. (once we adopted the approach above).


问:
How to code on a very tight schedule?
I'm working on a project that has very tight schedule. I don't have much time to code and test (even though I work more than 12 hours everyday, it's still delayed), and the result is very fragile. Its code is also very dilemma.

This program is used by all offices in our customer's company, which is located in many countries. I regularly get phone calls at midnight about errors from our user/tester or about them not knowing how to use some features.

After three years on this project, I feel very stressed and I can't sleep well because I'm very worried about errors and phone calls.

I have a few questions:

For three years, all the code I've written is just the perfect usage scenario code (so it break easily). It's poorly designed and doesn't have any unit tests. I have lots of problems because of this fact. Therefore, I want to know whether is it's feasible to write code that works when the project has a very tight schedule?

How can I write better code in the same amount of time?

How can I clear my mind and don't get worried about work when I go to sleep?

答:
Ban phone calls and implement a strict "bugs go to the bug tracker ONLY" rule. Then your first move of the day is to triage newly entered bugs, clean up dupes, prioritize, and get to work on bug fixes FIRST. And make sure your bug fixes actually fix the bug and don't introduce new bugs.

How do you do that last part? By retrofitting test cases onto your existing code. If you've got functions, test that they input and output what you expect, and that they fail nicely if you give them junk. Use some sort of automated UI testing to test the integration and performance front-to-back.

You're not actually getting out of bed at 3am to solve code problems, are you? If so, you deserve everything you get.

Title: How to code on a very tight schedule?


问:
Learning MVC - Why does home and about share the same controller?
Let me start this out by saying I've been a asp.net web forms developer for a while now and that I understand mvc is a new way of doing things. As I'm learning mvc and going through tutorials and training videos, I have questions that these tutorials don't address. This is my attempt to address them here...

I started a new project with the new internet application template in Visual Studio. I'm looking around the project trying to wrap my head around the mvc paradigm and I notice there is a Home and an About page. In the views, there is a file for each of these two pages. That makes sense. But why do they share the same controller? I think it would make sense if I had several screens that edit/view/delete the same data table, but the home and the about page don't necessarily have anything to do with each other. Does this mean if I create other pages that don't need a full blown controller (like a sitemap or something), I should just stick their views in the "Home" views folder? It just doesn't seem right.

I know this basic stuff isn't that big of a deal, but this is the type of stuff that bugs the hell out of me. Thanks in advance for the clarification!

答:
Because it makes a little bit of sense when considering the default routes in the same template. It allows things that 'look nicer' at http://www.foo.com/about rather than having the longer url with a controller in there: http://www.foo.com/controller/about

Not particularly necessary, but that routing is an important concept to understand with ASP.NET MVC.


问:
How can one best avoid writing bloated GUI code?
I find whenever I work with GUI code, the code tends to bloat faster then other kinds of code. It also seems harder to refactor. Whereas in other kinds of code I can refactor pretty easily -- I find I can decompose a larger class into smaller pieces of functionality -- with most GUI frameworks I'm often bound to a framework that requires my widget/control/whatever class to implement a lot more things more directly in the widget/control/whatever. Sometimes this is due to needing to either (a) inherit off of some base widget/control/thing or (b) need access to protected methods.

I typically also have to, for example, respond to a large variety of inputs via signals/events/whatever from the framework to implement all the modes of interacting with the user. I might need in one GUI widget/control to handle a large variety of input/output that might include:

a right click/context menu

reacting to selections from the context menu -- which may be many

a special way to paint the GUI

react to keyboard input

buttons, checkboxes,

etc etc

... all the while manage the classes under the GUI representing business logic.

A simple straight-forward GUI can have its code grow pretty quickly, even when seperating out buisiness logic and using MVC, I find GUI code is a big magnet for change.

Is there any way to manage GUI code in a sane way and avoid letting it become a broken window? Or is a mass of random event handlers/overridden methods really the best we can do for GUI code?

答:
There's lots of great answers here.

One thing that has helped me simplify the GUI code is to make sure that the GUI has its own data model.

To take a simple example, if I have a GUI with 4 text entry fields, then I have a separate data class that keeps the contents of those 4 text entry fields.  More complicated GUIs require more data classes.

I design a GUI as a model - view.  The GUI model is controlled by the application controller of the application model - view - controller.  The application view is the GUI model, rather than the GUI code itself.


答:
In a single word, Experience.

To start, you need to have put in the ground work, so I can't recommend more highly that programmers should take the time to read books such as Refactoring, which will provide some of the more essential tools in a programmers arsenal that will improve your ability to maintain code, and Clean Code which has been written by some of the most highly recognizable talents in our field, and which describes nearly everything you need to understand in order to ensure your code is clean and readable.

No amount of reading however is a substitute for hard-earned experience. You really need to have worked with code for a while in order to fully appreciate the difference that attention to code quality can make.  Through experiencing the pleasure of working with clean, well factored code, as well as the pain of working with code spaghetti, you learn to better understand what the authors of these books were really trying to teach you, but you do so in the wider context of real live production code, where the quality of what you do really matters, and impacts your ability to work easily with your code on a daily basis.

It also helps to have either a good mentor, or a peer with the experience to confirm that you are putting the effort into writing code to a high standard. This is just one reason why code reviews can be so useful. Using code checking and formatting tools can also be a very useful aid to ensure that you are keeping things clean. Nothing however compares to experience earned through years of writing software, such that you automatically find yourself writing code that is clean, readable, and structured simply for ease of maintenance, and all because you've made it a habit to apply best practices for so long.


问:
How to keep Free/Paid version of the app separate in subversion
I have a paid application on the android marketplace, however, I want to release a free ad-supported version.

The easiest way I thought to do this was to set up a branch on my subversion repository that has the additional code to add the ads. However, when I went to submit this to the android marketplace, they require unique package names. This solution no longer works for me because I'd have to change the package of every class file, which would make merging the trunk and branch very painful.

What is the best way I can keep these two projects together, sharing patches, but with a different package?

答:
If you really want to do separate, the best way is to set it up as two parts of the same repository. That way you can at least merge changes across the different branches. If you want to keep things completely separate then you will be doing alot of schlepping patch files.

I've done this and frankly it isn't a great strategy in practice. Much better, especially in compiled environments, is to have a separate build process for free versus paid so there is one codebase rather than two. If there are two codebases things will diverge.


答:
Have you considered compiler directives?

Example:

```<code>#define FREE
// ...
#if FREE
Console.WriteLine("Free version");
#else
Console.WriteLine("Paid version");
#endif
</code>```

You can keep the exact same code base and target the two builds using two separate build scripts or a parametrable one.

```<code>msbuild /p:DefineConstants=FREE
</code>```

To do it with Java, read this and this. And maybe this.

Title: How to keep Free/Paid version of the app separate in subversion

Body:
I have a paid application on the android marketplace, however, I want to release a free ad-supported version.

The easiest way I thought to do this was to set up a branch on my subversion repository that has the additional code to add the ads. However, when I went to submit this to the android marketplace, they require unique package names. This solution no longer works for me because I'd have to change the package of every class file, which would make merging the trunk and branch very painful.

What is the best way I can keep these two projects together, sharing patches, but with a different package?

Body:
Have you considered compiler directives?

Example:

#define FREE
// ...
#if FREE
Console.WriteLine("Free version");
#else
Console.WriteLine("Paid version");
#endif

You can keep the exact same code base and target the two builds using two separate build scripts or a parametrable one.

msbuild /p:DefineConstants=FREE

To do it with Java, read this and this. And maybe this.


问:
What benefits for the developer does the Ruby language offer that C# does not have?
What benefits for the developer does the Ruby language have that are not available in C# (preferably with code examples)?</p>

答: Ruby's extremely dynamic nature makes it very easy to create Domain Specific Languages. Ruby on Rails is the ne plus ultra of this aspect of Ruby as far as I know. RoR's ActiveMigrations is a DSL that takes a very difficult problem set and addresses it in a way that is easy to understand and to use. ActiveRecord, too.</p>


问:
How meaningful is the concept of "software craftsmanship"?
There seems to be a lot of buzz around software craftsmanship lately.

Is it a well-defined concept? What does imply? To what extent is programming effectively a craft activity?

答:
To demonstrate how much variation there is in the definition, I'll add my view to S.Robins excellent answer.

Software craftsmanship is harkening back to the idea of the craftsman, such as a carpenter. He is a man versed in his field, capable of turning the client's request into a physical object. He can do this because he he has a specific set of skills:

A construction methodology (agile, waterfall, mixed)

Problem solving skillset (scientific method, mental "toolbox" of ways to fix issues)

Knowledge of the field (when and where to use DB/language/optimization/concurrency)

Practiced at specific tools (Vim, valgrind, c, python, sql, git/hg, current "hot" tech)

A professional mien

Thus, when the craftsman is faced with a problem for a client, he has not only all the prerequisites to build to object in question, he has the skills necessary to solve any problems along the way, learn new skills if necessary, and all the while conduct himself in a professional manner.

As a professional, he knows that this is business. He is out to do the best for everyone involved (including himself), producing the best solution possible within the constraints given. He understands that emotion has no place here (it's business, not personal), and that when errors and mistakes occur they can be dealt with and solved by his existing skills.


问:
What steps can I take to avoid character encoding issues in a web application?
In previous web applications I've built, I've had issues with users entering exotic characters into forms which get stored strangely in the database, and sometimes appear different or double-encoded when retrieved from the database and displayed back in the browser.  I'm starting a new project now, and I want to prevent these issues right from the start.

What I'm looking for is a checklist of things I can do to prevent character encoding issues such as these, no matter what users enter into forms.  If I set my database tables to UTF-8, and set all of my web pages to assume content is UTF-8, is this enough?  Will some characters still appear differently than the user entered them?  Should I do some validation on the client side that doesn't let users enter in certain characters?

答:
If I set my database tables to UTF-8, and set all of my web pages to assume content is UTF-8, is this enough?

You need to ensure that the connection between the web application and the database doesn't mangle the encoding (I believe you need to explicitly set this on the connection string for MySQL, for instance).

Basically you need to ensure that every step in the chain is using the same encoding.


问:
Where does my database schema live in MVC?
I'm starting to check in the SQL files for creating/maintaining our database. Previously SQL files were kept totally separate from our codebase's version control.

I'd like to pragmatically store my database construction/manipulation files with my other code. Do they make the most sense in a subdirectory of my Models or as a separate directory somewhere?

For the most part the SQL statements are the data my Models access, but some other stuff is maintenance scripts ect; stuff that doesn't pragmatically fit into my MVC folder structure.

答: Have you looked at the SSMS plug-in SQL Source Control? It connects SQL Server to SVN, TFS, Vault, Mercurial, etc. Details at http://www.red-gate.com/products/sql-development/sql-source-control/</p>


答:
Version control is a poor way of managing things like this. You'll end up with a maintenance nightmare - two separate applications that need to be almost identical.

Have you considered a multiple project solution? (caveot: I haven't actually done this, but it seems feasible, and I think Android will allow it. I'll try it later and see for sure.) Compile all your app code into a main project jar. Then create two separate Android apps, one for your paid version, and one for the free version. This will solve your package naming problem. These apps will just delegate to the main jar for pretty much everything, except that your ad version will include the code to support the ads.

You may also find this discussion on a similar topic interesting.


答: You need to make sure you are specifying the correct data type for columns as well, nchar/nvarchar/ntext are required to hold unicode values, char/varchar/text will only hold ASCII values. Also depending on how you transfer data you may need to escape certain characters to avoid unexpected results, lists of these characters can be found through Google searches easily enough.</p>

Title: What steps can I take to avoid character encoding issues in a web application?

Body:
In previous web applications I've built, I've had issues with users entering exotic characters into forms which get stored strangely in the database, and sometimes appear different or double-encoded when retrieved from the database and displayed back in the browser.  I'm starting a new project now, and I want to prevent these issues right from the start.

What I'm looking for is a checklist of things I can do to prevent character encoding issues such as these, no matter what users enter into forms.  If I set my database tables to UTF-8, and set all of my web pages to assume content is UTF-8, is this enough?  Will some characters still appear differently than the user entered them?  Should I do some validation on the client side that doesn't let users enter in certain characters?


问:
How to perform code review of visual code?
Lately, I've been writing code in SAS Enterprise Guide, which produces "code" that looks like this (screenshot from the linked page):

My question is twofold:

Do you think it's necessary to perform code review on this type of code? My gut feeling is yes, given that (1) it's still code, just visually laid out, and (2) errors = big problems.

If "yes" to above, how to perform the review? Are there standards for visual code?

I'm really open to any ideas, comments, and suggestions here. Thanks!

答:
Well, you gave the answer to the first question already by yourself, so I will only focus on the second.

A review is typically just a form of quality assurance where you have a document written by person A, and person B reads it "line by line", tries to understand it and makes suggestions for improvement. Sometimes person A helps B reading it by explaining it "line by line".

As you will have noticed, I did not use the word "code" in the former description, since it applies to arbitrary documents, not only computer programs. And so it does apply to your visual documents, there is no real difference.

Of course, what you cannot check in your case is formal "coding style", "indentation", "length of methods" etc. But you can obviously check "layout style", "use of clear and understandable names", logical errors etc. And probably you cannot easily check the differences between different versions using your diff tool from your VCS to see what parts / changes should be reviewed if your system evolves. But that's a general problem with "visual programming" you will always have to face, not only for the review process.


答: Only your application package must be unique.  See here.  That's the package declared in your manifest file.  You can have most of your code in com.mydomain.myapp, and just have a different main activity in com.mydomain.myapp.free.


问:
Tips for going from personal projects to enterprise scale projects
I wanted to know if anyone had any tips for transitioning from small personal projects and coursework, to a large enterprise scale project?

Im in my second year at university and have attained a placement with a large tech company, to work on a pretty large project, I'm just a little apprehensive about 'finding my way around' such a large project.

答:
Take your time, learning a new code base takes lots of time. Get familiar with the language the code is written in,  and the style used to write that code, if you aren't already familiar with it. Learn about the code before learning the code, with large code bases its nearly impossible to remember exactly what every piece of code does, and its pointless because the code is always there to show you what it does, if you can find it, so learn how to find the code you want.

You have to start small, and your employer will probably help with this by only assigning small tasks at first that only require localized changes and gradually work towards bigger changes. Also never be afraid to ask your team members questions, especially early on you need to build relationships with them just as much as you need to learn the code.


答:
The most important thing I see lacking in my company for new hires that came right from university is the habit of documenting the code comprehensively. Unfortunately, most courses teach you how to express what you want to do to the machine (the progam) but not to the poor soul that has to mantain the code later.

I'm not talking that much about things like UML. That usually is covered. I mean Javadoc, Doxygen and the like; code review; specs and contracts; clarity when writing the description for a commit to the VCS; clarity when creating new issues in the issue tracker. The more experienced you get, the bigger the projects you handle, these things tend to become even more important than the code itself.

Title: Tips for going from personal projects to enterprise scale projects

Body:
I wanted to know if anyone had any tips for transitioning from small personal projects and coursework, to a large enterprise scale project?

Im in my second year at university and have attained a placement with a large tech company, to work on a pretty large project, I'm just a little apprehensive about 'finding my way around' such a large project.


答:
Have you considered using LINQ/ an expression-tree?  It seems exactly to match your problem, unless I've missed something.

Whatever the detail of the particular collection-type, as long as it's enumerable, you can use all the benefits of LINQ.  You have the datasource of your gridview (or whatever the datasource is); you can then attach events to the check-boxes/ drop-downs that add/remove the where/group-by based on the binding that they have to the fields in the database.

Personally, I'd also design the system without much regard to the persistence mechanism, you want an easily-understood abstraction model at each level, it is rare that the same model is appropriate in different layers.

I'm assuming you're using at least C# 3.

Title: Which collection structure I should use for parametrical grouping ordering in c#?

Body:
I have various windows forms applications that contain various controls that build up custom "group by" and "where" clauses for my class methods.

I am thinking to pass a collection structure of some kind in order for the methods to be able to build the group by's and the where clauses.

Let's say a list containing the field and the value for the group by or where.

Am I going to the right direction?

Update:

I dont have code yet but let me try to explain better:

We have a form with 10 dropdownlists and a checkmark beside them.

Also we have adatagrid on the form.

Every dropdownlist corresponds to a field in a table.

If a dropdownlist has its checkbox checked means that it must be part of the group by clause in the select statement.

The value of the dropdownlist must be part of the where clause.

*note: *  Another application could have different numbers of dropdownboxes and different corresponding fields.

I want to create a common method that will retrieve data with user selectable group by and where clauses.

So what i think is to pass to the method 2 lists.

One with (fieldname, value) for the where clauses

And one with (fieldname) for the group by

depending on the logic above...

I hope this is more clear.


问:
Should cases be reopened for bugs, or should bugs be opened as a new case?
Currently at my work place we use FogBugz for managing all our features and bugs for our different web applications.

When a new feature is to be added to one of our web applications, a new Case is created. For example "Create CSV Upload Form".

I then work on the case recording the amount of time I've spent on it. Once this case is completed, I then resolve it, and it gets assigned back to the case opener (usually the project manager), who then closes the case.

If there are any bugs with the feature, my Project Manager then re-opens the case, and assigns it back to me with a bullet point list of bugs.

In my opinion I believe these bullet pointed bugs should be opened as individual bug cases, so that they can be tracked easier, and not get cluttered with the original feature case notes.

My managers disagree with me stating that it is easier to work out the total time spent on the feature if its all in one case.

Furthermore they believe it is less confusing for our clients as they only have 1 case number reference for the feature. However I would stress that the bugs should be dealt with as seperate cases as this is post-completion of the original case.

Am I right in stating that bugs should be reopened as a new case? And what are the pros/cons of each way of managing this?

答: I think you can make an argument both ways. I would try to sit down with the PM and explain why you think having discrete issues will help you out. I personally want each todo item should be its own ticket but I can see why he wants it that way.</p>


答:
I agree with you completely, and so does FogBugz - that is why it defines different categories for Bugs and Features. FogBugz was not designed to be a tool to track time use; this is an accidental byproduct of the introduction of evidence-based scheduling.

Bugs for a completed feature can be linked to the main case for the feature (in FogBugz, by use of a tag name, or a cross-reference, or by making them sub-cases). I can see that this is a bit more work for your PM to consolidate information across several cases, but it often also makes sense to be able to separate time spent on original development and time spent on maintenance, especially for fixed-price contracts, and you lose the ability to do this if you put everything into one case.

Title: Should cases be reopened for bugs, or should bugs be opened as a new case?

Body:
Currently at my work place we use FogBugz for managing all our features and bugs for our different web applications.

When a new feature is to be added to one of our web applications, a new Case is created. For example "Create CSV Upload Form".

I then work on the case recording the amount of time I've spent on it. Once this case is completed, I then resolve it, and it gets assigned back to the case opener (usually the project manager), who then closes the case.

If there are any bugs with the feature, my Project Manager then re-opens the case, and assigns it back to me with a bullet point list of bugs.

In my opinion I believe these bullet pointed bugs should be opened as individual bug cases, so that they can be tracked easier, and not get cluttered with the original feature case notes.

My managers disagree with me stating that it is easier to work out the total time spent on the feature if its all in one case.

Furthermore they believe it is less confusing for our clients as they only have 1 case number reference for the feature. However I would stress that the bugs should be dealt with as seperate cases as this is post-completion of the original case.

Am I right in stating that bugs should be reopened as a new case? And what are the pros/cons of each way of managing this?


问:
What does Bucket mean?
I found in legacy code a class which name is BucketService.

Because english is not my native language I was trying to translate that, but it doesn't make sense.

I found few termins like bucket sorting and so on, but I still don't get it. Actually this word is used quite frequently in programming

I would be helpfull for some simple explanation of that word

答: Perhaps it's a reference to 'bit bucket'.  That's where the bits that get shifted off a byte go on left and right bit shifts.</p>

Title: What does Bucket mean?


答:
Are the bugs found before or after the product has been 'shipped/released' to customers?

If it is before a release, the bugs should tracked against the original ticket.

If it is after a release, each bug should be its own ticket.


答:
If this is all happening before the feature is released to the customer then just have one case. The argument here is that the case isn't truly complete until it's passed QA and ready to be released. The other benefits - a single case number for the billing and end users to reference are valid and important.

Once the feature has been released and bugs are found these should be raised as new issues in your issue tracking software.


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答:
I made a site templating language, in an early version of which all HTTP parameters were implicitly expanded as variables. This meant that you could write a URL like:

```page.vis?body=<body><p>Oh dear</p></body>```

And it would do exactly what it looks like it does.

Luckily I have no users (sigh), so I guess it wasn't too much of a security risk.

Title: Biggest mistake you've ever made

Body:
I made a site templating language, in an early version of which all HTTP parameters were implicitly expanded as variables. This meant that you could write a URL like:

page.vis?body=<body><p>Oh dear</p></body>

And it would do exactly what it looks like it does.

Luckily I have no users (sigh), so I guess it wasn't too much of a security risk.


答:
Its my opinion that once a ticket is closed it should stay closed, your bug tracker should be capable of linking to other cases anyway. I would try to point out that creating new bugs and linking them to the original case provides better benefits than the method you describe.

clients can still have one reference number that contains links to each bug.

each bug's status can be individually tracked, allowing for better prioritization and status reporting.

having separate bugs will allow you manager to break down time spent on bugs vs time spent developing new features, and should only be a minimal additional effort to get a total number for all bugs related to a change and the development of that change.

separating bugs makes it much easier for your manager to gather other metrics like total bugs, average time per bug fix, ratios of closed/in progress/fixed bugs.

separate cases per bug allows tasks to be better divided between all developers and hold each accountable for their own work, or allows this possibility should more developers be hired at a later date.

The only advantage to your current setup is that its extremely simple for the people who aren't the main users of the system. The purpose of a bug tracker is for the developer to have a place to report everything about a bug in a single place that also happens to be friendly enough for others to see the progress, your current system seems to undermine almost every part of that.


答:
I was in the same boat last year.
I'd suggest brushing up on your SQL skills, you'll be using those quite a bit. In my experience in University, SQL wasn't taught too thorough if at all, and with any large project in a large tech company, expect to have exposure to it.

Another thing that really helped transition to the workforce was networking. Meet as many of your coworkers as you can, most of them came to me and offered help and/or advice, and I'd be behind where I am now without it.


答:
Both you and your manager have good reason for dealing the way each of you prefer, and there is no real need to compromise. There is a solution that works for me and addresses both concerns.

For cases like yours I use high level task / low level sub-tasks approach (concept I picked from JIRA, can't tell if FogBugz support it explicitly looks like it does). This way, "client-facing" bulleted lists go to high level tasks while "developer iterations" that are important for me are reflected in sub-tasks.

When high level task is "reopened", I create a new sub-task to track the added effort for self.

That way allows developer to clearly reflect all the permutations, perversions and twists passed through by feature specification, still letting manager to present it to clients as-if-perfect. By the way as-if-perfect presentation has its value to me as developer - because having it easier to read for clients helps in getting more accurate adjustments.

This also naturally allows to have a clear justification in cases when feature implementation takes much more time than anticipated originally.

As for time tracking per task or sub-task - since JIRA allows to include sub-tasks tracking into higher level summary, it is acceptable for manager that I track time in sub-tasks. However, even if this would be not the case, I could live with formally tracking time in "parent" task - in this case I would just use sub-tasks comments to state how much time has been spent on particular iteration.


答:
Building your app using a feature toggle would allow you to reach your objective but you might have to rework a lot of code.

By defining 2 (I would recommand 3) feature container environment in a .ini file like :

```<code>[paid]
features.ads = false
features.featureOne = true
features.featureTwo = true
features.premiumFeature = true
features.underDevFeature = false
features.debug = false;

[free:paid]
features.ads = true
features.premiumFeature = false

; And the optionnal third
[development:paid]
features.debug = true
features.underDevFeature = true
</code>```

This way, you have a version that that is uniform and require only one branch in your version control source

In your specific scripts you then have to check if the feature is authorized, if not, you dont display it

Body:
Building your app using a feature toggle would allow you to reach your objective but you might have to rework a lot of code.

By defining 2 (I would recommand 3) feature container environment in a .ini file like :

[paid]
features.ads = false
features.featureOne = true
features.featureTwo = true
features.premiumFeature = true
features.underDevFeature = false
features.debug = false;

[free:paid]
features.ads = true
features.premiumFeature = false

; And the optionnal third
[development:paid]
features.debug = true
features.underDevFeature = true

This way, you have a version that that is uniform and require only one branch in your version control source

In your specific scripts you then have to check if the feature is authorized, if not, you dont display it


问:
Desktop GUI loading slow
I am developing desktop based GUI (single form) using wxPython and loads it using remote citrix access from client private network.

Suppose, the GUI has certain group of select and text boxes which are loaded together when application starts. The value of select boxes come from database and on the basis of selection of select box value, corresponding text boxes (which are initially blank) are populated from database.

Now the problem is, due to slow remote access, we have to wait for long time (approximately 5-7 minutes ) before all controls are loaded. Is there any suggestion, if we can reduce this time ?

One way coming in first thought is to divide the GUI in multiple tabs and divide the controls among tabs. This way I need to load less controls when application starts for showing first tab. Other controls load, only after user click corresponding tab.

Any other way or this one is the best approach?

答: With any form design, it's best to only load the data the user will need to see upon initial load. So instead of throwing every control the user will interact with on the first form, either spread it out as you suggested with tabs, or have them open on separate windows/menus/etc. </p>

Title: Desktop GUI loading slow


答:
Where I work, only the QA people can close a case. We have checkboxes for Code Reviewed, Engineer Tested, and Demo to Stakeholder (in your case Project Manager). If the QA team sees a case marked as "Done" which doesn't have all of these fields marked, they will mark it undone and send it back to us.

Once a case has passed all these phases and QA closes the case, any new issues they find are logged as bugs.

This system seems to work well for us.


问:
Should large or old codebases be expected to be easy to navigate?
I'm an Undergraduate Computer Science Student currently on a placement year at a company that produces and supports a large enterprise web application. I'm loving the experience of seeing how software is produced in the real world, and feel very lucky to find a company that offers a chance to not only maintain and extend existing functionality but also develop entirely new features for the product.

All that said, though, I'm very conscious that this is very, very unlikely to be a perfect example of how to develop correctly. Far from it, in fact. I feel I'm learning a massive amount from my experience here, and I don't want to learn the wrong things or pick up bad habits from colleagues that could be hard to shake off further down the road. Mostly it's easy to tell what's good and what's not - for example the Unit Test coverage here is practically non-existent for various reasons (mostly poor excuses mixed in with one or two valid points). Lately, though, I've been noticing a regular occurrence that I'm just not sure about.

Whenever we start a new project, naturally we need to find any relevant code that needs to be extended, altered, or removed. It seems to me that, the vast majority of the time, anything not within the most commonly used sections of the application takes people an age to find within the codebase. There are one or two tech leads who know their section of the code well, but even they get stumped sometimes and have to spend a long time searching for what they require, or turn to someone who has been editing that part of the code recently (if anyone) for help. When I say a long time, I don't mean hours (usually) but it seems to me that a good codebase would be navigable to any point within a few minutes at worst, to anyone even vaguely familiar with the system.

So, my question. Is the above problem due to poorly structured code? Alternatively, is it down to developers not having enough knowledge of the codebase? Or is it simply unavoidable in large applications, regardless of how much work goes into keeping the file structure clear?

Or, indeed...am I just wasting my time on a topic that really doesn't matter?

答:
When tackling a brownfield application, the ideal first step is to write unit tests for it.

This accomplishes several things:

It forces you to work through the code and understand it

The unit tests serve as documentation and sample code for the existing functionality, and

The unit tests provide a safety net for refactoring.

Whether or not the organization has the inclination to allow you to do this is another matter.  They've lived without unit tests for this long; getting them to agree to reduce the technical debt in this way will be difficult.