答:
If you're using .Net and managed C++ code, you could think about using Automapper.

I haven't found a generic C++ approach, though.

Title: Is there an efficient way to adapt data from a structure to another in c++?

Body:
I'm writing an interface between two configuration models that use different structures. While I know that there is no "magic" way to do the translation from a structure type to another, I wandered if there might be some best practices or an efficient/effective way to setup such a system. I think it's similar to how programs may manage different configuration structures accross versions.

Here's a simple example: let's say we have a structure of type A which contains 3 parameters:

```<code>struct A {
  int alpha;
  bool beta;
  bool charlie;
};
</code>```

The second configuration structure share the same parameters, but in a different order, let's see structure B:

```<code>struct B {
  union {
    struct {
      char beta : 1;
      char charlie : 1;
    } bit;
    char field;
  }
  int alpha;
};
</code>```

A simple program to convert an A to a B would be:

```<code>void convert(A const *aelem, B *belem) {
      belem->alpha = aelem->alpha;
      belem->bit.beta = aelem->beta;
      belem->bit.charlie = aelem->charlie;
    }
</code>```

So, while this may seem fairly simple with such basic structures, I'm dealing with dozens of structures, each of one contains around 50 parameters. So do anybody knows of a good pattern to follow for such a problem ?


问:
Is coupling with strings "looser" than with class methods?
I'm starting a school group project in Java, using Swing.  It's a straightforward GUI on Database desktop app.

The professor gave us the code from last year's project so we could see how he does things.  My initial impression is that the code is far more complicated than it ought to be, but I imagine programmers often think this when looking at code they didn't just write.

I'm hoping to find reasons why his system is good or bad.  (I asked the professor and he said I'd see later on why it's better, which doesn't satisfy me.)

Basically, to avoid any coupling between his persistable objects, models (business logic), and views, everything is done with strings.  The persistable objects that get stored in the database are hashtables of strings, and the models and views "subscribe" to each other, providing string keys for the "events" they subscribe to.

When an event is triggered, the view or model sends a string to all of its subscribers who decide what to do for that event.  For instance, in one of the views action listener methods (I believe this just sets the bicycleMakeField on the persistable object):

```<code>    else if(evt.getSource() == bicycleMakeField)
    {
        myRegistry.updateSubscribers("BicycleMake", bicycleMakeField.getText());
    }
</code>```

That call eventually gets to this method in the Vehicle model:

```<code>public void stateChangeRequest(String key, Object value) {

            ... bunch of else ifs ...

    else
    if (key.equals("BicycleMake") == true)
    {
                ... do stuff ...
</code>```

The professor says that this way of doing stuff is more extensible and maintainable than having the view simply call a method on a business logic object.  He says there is no coupling between the views and models because they don't know of each others' existence.

I think this is a worse kind of coupling, because the view and model have to use the same strings in order to work.  If you remove a view or model, or make a typo in a string, you get no compile errors.  It also makes the code a whole lot longer than I think it needs to be.

I want to discuss this with him, but he uses his industry experience to counter any argument that I, the inexperienced student, might make.  Is there some advantage to his approach that I'm missing?

To clarify, I want to compare the above approach, with having the view be obviously coupled to the model.  For instance, you could pass the vehicle model object to the view, and then to change the "make" of the vehicle, do this:

```<code>vehicle.make = bicycleMakeField.getText();
</code>```

This would reduce 15 lines of code that are currently ONLY used to set the make of the vehicle in one place, to a single readable line of code.  (And since this kind of operation is done hundreds of times throughout the app, I think it would be a big win for readability as well as safety.)

Update

My team leader and I restructured the framework the way we wanted to do it using static typing, informed the professor, and ended up giving him a demo.  He's generous enough to let us use our framework as long as we don't ask him for help, and if we can keep the rest of our team up to speed -- which seems fair to us.

答:
What your professor is proposing is the use of "magic strings". While it does "loosely couple" classes between each other, allowing for easier changes, it is an anti-pattern; strings should very, VERY rarely be used to contain or control code instructions, and when it absolutely has to happen, the value of the strings you are using to control logic should be centrally and constantly defined so there is ONE authority on the expected value of any particular string.

The reason why is very simple; strings are not compiler-checked for syntax or consistency with other values (at best, they're checked for proper form regarding escape characters and other language-specific formatting within the string). You can put anything you want in a string. As such, you can get a hopelessly broken algorithm/program to compile, and it's not until it runs that an error occurs. Consider the following code (C#):

```<code>private Dictionary<string, Func<string>> methods;

private void InitDictionary() //called elsewhere
{
   methods = new Dictionary<string, Func<string>>
      {{"Method1", ()=>doSomething()},
       {"MEthod2", ()=>doSomethingElse()}} //oops, fat-fingered it
}

public string RunMethod(string methodName)
{
   //very naive, but even a check for the key would generate a runtime error,
   //not a compile-time one.
   return methods[methodName]();
}

...

//this is what we thought we entered back in InitDictionary for this method...
var result = RunMethod("Method2"); //error; no such key
</code>```

... all of this code compiles, first try, but the error is obvious with a second look. There are numerous examples of this kind of programming, and they are all subject to this kind of error, EVEN IF you define strings as constants (because constants in .NET are written to the manifest of each library in which they are used, which must then all be recompiled when the defined value is changed in order for the value to change "globally"). As the error is not caught at compile-time, it must be caught during run-time testing, and that's only guaranteed with 100% code coverage in unit tests with adequate code exercise, which is usually only found in the most absolute fail-safe, real-time systems.

ContentLicense: CC BY-SA 3.0

Body:
What your professor is proposing is the use of "magic strings". While it does "loosely couple" classes between each other, allowing for easier changes, it is an anti-pattern; strings should very, VERY rarely be used to contain or control code instructions, and when it absolutely has to happen, the value of the strings you are using to control logic should be centrally and constantly defined so there is ONE authority on the expected value of any particular string.

The reason why is very simple; strings are not compiler-checked for syntax or consistency with other values (at best, they're checked for proper form regarding escape characters and other language-specific formatting within the string). You can put anything you want in a string. As such, you can get a hopelessly broken algorithm/program to compile, and it's not until it runs that an error occurs. Consider the following code (C#):

private Dictionary<string, Func<string>> methods;

private void InitDictionary() //called elsewhere
{
   methods = new Dictionary<string, Func<string>>
      {{"Method1", ()=>doSomething()},
       {"MEthod2", ()=>doSomethingElse()}} //oops, fat-fingered it
}

public string RunMethod(string methodName)
{
   //very naive, but even a check for the key would generate a runtime error,
   //not a compile-time one.
   return methods[methodName]();
}

...

//this is what we thought we entered back in InitDictionary for this method...
var result = RunMethod("Method2"); //error; no such key

... all of this code compiles, first try, but the error is obvious with a second look. There are numerous examples of this kind of programming, and they are all subject to this kind of error, EVEN IF you define strings as constants (because constants in .NET are written to the manifest of each library in which they are used, which must then all be recompiled when the defined value is changed in order for the value to change "globally"). As the error is not caught at compile-time, it must be caught during run-time testing, and that's only guaranteed with 100% code coverage in unit tests with adequate code exercise, which is usually only found in the most absolute fail-safe, real-time systems.


问:
Is there an alternative to bits?
Is there an alternative to bits as the smallest unit of data? Something that won't be only 0 or 1, but actually hold many possible states in between? Wouldn't it be more natural to store floats like that?</p>

答:
Storage can be thought as transmission to the future, all of the transmission problems with continuous(analogue) media will apply.

Storing those states could be trivial (a three way switch or some sort of grid) and physically storing these states is one issue that many answers cover, much better than I could.

My primary concern is how this stored state is encoded and it seem that there's a high posibility that this task is a fools errand, since bits are sufficient for representation of practical continuous data, depending the accuracy you need, keep adding more bits.

Truly continuous data is impossible to store in this way, but equations to calculate them e.g.

1/3

can be stored.

Title: Is there an alternative to bits?


答:
A clue and an inkling are smaller pieces of information than a bit. Several clues are usually required to establish the definite value of a bit. Inklings are worse: no matter how many you add up, you still can't know the value of the resulting bit for certain.

More seriously, there are multi-valued logics where the fundamental unit can have one of n states, where n > 2. You could consider these units to carry less information than a bit in the sense of the preceding paragraph, but from an information theory point of view you'd have to say they carry more. For example, you'd need two bits to represent the same amount of information that a single value in a four-valued logic could carry.

Title: Is there an alternative to bits?

Body: Is there an alternative to bits as the smallest unit of data? Something that won't be only 0 or 1, but actually hold many possible states in between? Wouldn't it be more natural to store floats like that?</p>


问:
Is a programmer supposed to be self-sufficient?
At my current workplace, we don't have any testers, the rationale for that from the management being: "if we had testers, you wouldn't test your own code at all". This kind of thinking seems to be detrimental to product quality, as while I do test my own code, there are a lot of things that I will miss just for the fact that I know the system inside out and don't know how to use it "wrong". Black box testing doesn't really work as I subconsciously avoid the pitfalls that a dedicated tester would fall into. A lot of my time goes into fixing bugs that have slid into production code and found by the end user.

The system in question is large but is developed solely by me. This has also caused some managemental duties to fall on my lap, such as defining schedules and working on specifications.

Should these kind of tasks be my responsibility? I see myself strictly as a programmer and nothing else. And if these are my responsibility, to what extent? When is a project so large that it requires testers? Should a programmer have to refine the specification, worry about management of the project or even provide customer support?

Note

Some might have got the impression that I am against widening my responsibilities – that is not the case, I'm eager to get a role that involves more management duties, but currently it is not in my job description. Until I'm officially employed as such or the additional duties start showing in my paycheck, I'm going to think of myself as 'just' a programmer. Unfortunately, as a junior developer, shifting to managerial duties is not going to happen very soon.

Excellent answers so far, keep them coming if you have something to add or personal experiences to share!

答:
What they are saying and reality are probably two different things. Most likely the rationale is:

"Why do I have to pay a tester's salary when I can just make the programmer do double duty?"

Of course, they aren't going to say that and will make up all sorts of excuses they think are reasonable. I can think of several rebuttals to their point, but honestly they aren't going to help. I've seen this battle over and over and they will just shift their approach whenever you debunk their current reasoning. Eventually they will give up and just direct you to do it anyway and you will be labeled a complainer.

The best approach I can think of is to address it not from a quality point of view, which management never seems to value until there are problems, but from a cost point of view. Testers are, or at least are perceived as, less expensive than programmers. Remind them that by having you do double duty they are paying a higher paid resource (programmer) to do the work that could be accomplished by a less expensive resource (tester). Thus they are not maximizing the value they are extracting from your programming skill.

This approach does have the downside of falling apart if you are salaried and they have no compunctions about just making you work more unpaid overtime, but it is worth a shot.

ContentLicense: CC BY-SA 2.5


问:
Is it possible to integrate UDP file transfer into a .NET web application?

Background

I have recently been tasked with designing a rebuild of an existing .NET web application that currently uses a third-party company to handle large file transfers (as big as 50Gb).

Currently, the .NET app depends on a .JAR (Java Applet) provided by this third-party which is called up inside of an iFrame and exposes the appropriate file-system interaction for selecting entire directories for upload and so forth.

I realize that so far all of this is possible using some combination of .NET networking classes (ftp) and Flash or Silverlight for client access.

I have been told that the reason that the third-party plugin is so special is that it uses UDP protocol so that if an upload or download is interrupted, it can be resumed later right where it left off. I have also been told that the third-party tool suite allows the IT folks to throttle bandwith (I don't even know what that means) and do a couple of other cool things.

Question

Assuming that we will use the latest version of C# and and the .NET framework (4.0), is it reasonably possible to replicate this UDP-based behavior? By reasonable, I mean could it be accomplished in less than, say, 240 dev hours.

Please note that the rebuilt app will ideally use all Microsoft technologies (including Silverlight for client access) and will run on Azure.

答:
Disclaimer: I work for a company which produces UDP file transfer software, probably a competitor of the maker of the UDP plug-in you talk about.

Yes it is possible to build a UDP file transfer application using C#, but no it is not possible to do it well within 240 developer hours.

UDP/IP involves placing nearly raw datagrams onto the network wire.  Things you take for granted with TCP/IP, like making sure the datagram gets there, avoiding duplicates, keeping messages in order, making sure you don't send data too fast or too slow, all have to be done by you.

UDP based file transfer solutions are becoming very popular because of the opportunity to develop all of the transport functionality from scratch, thereby avoiding a lot of the problems inherent in TCP.  UDP is simply a blank slate upon which one can create a better (or worse) solution.

Throttling simply means making sure that the data rate does not exceed some set value.  That's actually pretty easy by itself.  All UDP transport solutions that I know of will do that.

Making sure that the network can actually handle going that fast is much harder and is a key differentiator amongst the various UDP solutions out there.  Cramming too much data into a network path, even for a moment, can create huge disruptions.  Setting a throttle limit is the simplest way to avoid that, but it only works if you know in advance what the network capacity happens to be.


问:
Is there an efficient way to adapt data from a structure to another in c++?
I'm writing an interface between two configuration models that use different structures. While I know that there is no "magic" way to do the translation from a structure type to another, I wandered if there might be some best practices or an efficient/effective way to setup such a system. I think it's similar to how programs may manage different configuration structures accross versions.

Here's a simple example: let's say we have a structure of type A which contains 3 parameters:

```<code>struct A {
  int alpha;
  bool beta;
  bool charlie;
};
</code>```

The second configuration structure share the same parameters, but in a different order, let's see structure B:

```<code>struct B {
  union {
    struct {
      char beta : 1;
      char charlie : 1;
    } bit;
    char field;
  }
  int alpha;
};
</code>```

A simple program to convert an A to a B would be:

```<code>void convert(A const *aelem, B *belem) {
      belem->alpha = aelem->alpha;
      belem->bit.beta = aelem->beta;
      belem->bit.charlie = aelem->charlie;
    }
</code>```

So, while this may seem fairly simple with such basic structures, I'm dealing with dozens of structures, each of one contains around 50 parameters. So do anybody knows of a good pattern to follow for such a problem ?

答:
There is not a way to manage this in C/C++ during runtime execution since these languages do not support reflection.  However, there are methods that can help during design time such as a code generation tool. There are many code generation tools (a simple google will help you identify them).

If you use Excel, you could try the following: Place each of your structures in different columns.  Then, using a custom formula (such as name/type matching), populate a column with the intended mapping results.  Then simply copy/paste the mapping results into a text file and complete it where necessary.  This approach won't get you 100% there but could be a good starting point to help ease the process.


问:
At what point should I have my Windows developers upgrade to the latest release of Windows?
At what point should I begin upgrading our developer's machines to a later Windows release?

From experience, Microsoft typically has an epic fail about every other O.S. (I am really not trying to start a debate about this, it is my perception let it be) i.e. 2000 was a stable and useful O.S, yet m.e. didn't do well, xp was a great O.S. that many businesses still use, Vista didn't do well (I know that the reason this one didn't do well wasn't really Microsoft's fault and that Vista and 7 are the same major revision), while 7 seems to be an excellent O.S. that will be around for a while--sort of like xp is now.

Anyways, this makes me reluctant to upgrade our development machines to Windows 8.

a. I don't want to cost our business a ton of money for an O.S. that
will only be used for a year or two.

b. They also have to have linux dual boots, and I have read that Windows 8 and grub will not play well together.

I do want our developers to develop in the latest environment and to have a leading edge in any technology they are developing with. I do want to stay ahead of--or at least with--the technology curve, yet I want it to make business sense.

So in particular, should I upgrade their machines at this point?
In general, what calculus should I use for deciding this sort of thing?

edit

They do write desktop UI applications as well as ASP.NET applications. Also, I do make sure that they always have the latest release of Visual Studio.

答:
Before asking your developers anything, ask yourself first this:

What I need to do with Windows 8, that I can't do with current windows versions?

Does Windows 8 offers any true enhancements to the work I do?

Do I want to use Windows 8, just to be updated (ie. to follow with the hype)?

If the answer to one or two is yes and stronger, than the yes you might give to three, than go ahead. If not, forget it... You need an true motive to update, that isn't just because others are doing it.


问:
Advantages of Scrum for the developers themselves?
Scrum being a project management methodology, how would you 'sell' it to the developers in a team that is reasonably happy with its current situation?

It seems easy to me to explain to our Product Manager how Scrum will allow him to get regular releases, to amend requirements, and get the team to focus on the high-priority stories first.  I found it easy to explain what TDD or Continuous Integration bring in a developer's day-to-day life.

But how can developers be convinced to embrace Scrum?  How would Scrum make their life easier?

答: The fact that requirements will change is taken into account right from start.  Developers don't need to create detailed specs with precise estimates and then spend weeks developing a feature only to realize that the customer changes his mind as soon as he sees the result...</p>


答: The optimal numerical base is e, but since the simplest way to represent a number in digital electronic is with two states (high voltage=1, low voltage=0), the binary number representation was chosen.</p>

Title: Is there an alternative to bits?


问:
Java - using single class or multiple class for each type?
I currently have a Java class called "node" which has a number of fields. Which fields in the class are used depends on a field called "type". There are close to 10 (this can grow) different types of "nodes". I was wondering if it is good to have a single class to handle all types or have different class for each type. What is the best programming practice in these cases? I would like to know (or a link to similar question/tutorials) how the performance will be affected (like memory etc.) if I use a single class?</p>

答: This is a standard case for inheritance. You do not incur performance problems due to sub-classing. If you are performing any casting between sub types and super types several if statements will be executed at run time and are used to check for cast exceptions. In your single class model you would need to check your "type" field whenever a method or field is accessed to see if that particular "type" of node has those fields available. Memory should also not be a concern because you will be creating the same number of objects in either the single class model or the inheritance model.</p>


答:
The giveaway is in the name of your variable: type. You are trying to represent a type using a variable when that is exactly what classes are for. In your case I would consider refactoring to Replace Type Code with Subclasses.

Each subclass should contain the fields relevant only to it. By doing this refactoring, your code will be easier to maintain and extend.

Good design generally trumps (and usually helps) performance. In this case - don't worry about it.

Title: Java - using single class or multiple class for each type?

Body: I currently have a Java class called "node" which has a number of fields. Which fields in the class are used depends on a field called "type". There are close to 10 (this can grow) different types of "nodes". I was wondering if it is good to have a single class to handle all types or have different class for each type. What is the best programming practice in these cases? I would like to know (or a link to similar question/tutorials) how the performance will be affected (like memory etc.) if I use a single class?</p>


问:
What's wrong in returning hashtable from public method and when does it make sense to do so?
What are the design problems in returning a hashtable from a public method when you want to return multiple items instead of creating a class and returning object of that?

If it does have problems then under what circumstances it makes sense to do so?

How does the answer to this question change depending upon whether the language is dynamic or not?

Edit: This is to clarify that the keys would be constant and are part of code, not data. Something that we typically create a class for. The question is why would it be wrong to use hashtable instead if creating a class indeed does seem to be the right choice.

答:
Use a better defined class as a return type than a hashtable which holds arbitrary number of values as name/value pairs.

The first and fore most important point is - Maintainability.  By looking at the code, a new programmer can never say what are the values the method is returning. If a new person does not understand this by looking at the code, the code is not going to be useful and prone to errors whenever someone is going to add more key/values to that data or enhance the application.

Methods are contracts between the caller and the service. The most important thing in a method is their input and output. This input and output should be easily readable and understandable and self documenting. If you use a Person class as a return value which has first name, last name, age -- It is self documenting. If you generate a Javadoc for this , user can navigate between the classes to understand this better. If you use a hashtable, you have to either explain it in the comments which no one will read or update when things change.

You can't use generics like HashMap<String,String> in case if you want to add a number (say age) to the return statement. If you don't use generics , then you will have to cast back and forth between the object to actual type. You may save this if you use dynamic typing.

Also there are more chances of runtime failure than catching issues in compile time. e.g if someone deletes an entry from the hashmap and one of the old callers is expecting the entry, client fails during runtime. It is always better to catch this issue in compile time.

It will be difficult to return a immutable type if you want to use hashmap as return type and so on. But if you use a user defined your own type, you can control this.

It will be tempting to use a hashmap as return type because you can avoid creating couple of classes at the beginning but it will be a nightmare to maintain the code in the future. Go object oriented !!!!


答:
It might be a decorator or state design pattern or a composition

since we are talking about nodes here, composite pattern is a good candidate and since every node might possibly behave differently depending on the type, we may consider each node instance as states with different handling of a more generic behavior or we could have a base abstract class for a node and several concrete classes that are just decorators to provide additional functionality or customized behaviors.

http://www.go4expert.com/forums/showthread.php?t=5127


问:
Maintaining referential integrity between a mobile client and a server
So I have a relatively simple system. A mobile client creates records in a sqlite database that I would like to have synced to a remote SQL server (that is shared with other mobile clients). So when I create a new record in the phone's sqlite table, I then push that change to my remote service through a RESTful API. The problem I'm having, is how do I order the primary keys so that there isn't collisions in the data (i.e. a record in the phone has the same primary key as a completely different record on the server). What is the usual "best practice for referencing the record on the client, and for referencing the same record on the server?

答:
I bet that you absolutely, without question cannot have referential integrity between the two.  Specifically, do your users expect the mobile application to work when it is disconnected?

There are two practices for this:

One is to create "provisional" records on the client, and then when you sync them to the server have the central system assign the ID.  The client can update the local record to reflect that.

The other is that you distribute ID creation in a way that (normally probabilistically) allows clients to create the ID without collisions.

For that, go to UUIDs - v4 are fairly unlikely to collide.

Otherwise, consider something that puts the unique mobile device ID in the record ID.  So, your record ID might be ${imei}-${local sequence number} or something, where the IMEI ensures uniqueness, and the local sequence number is just a normal sequential database ID.


答: In addition to Daniel Pittman's answer, one possibility would be for the server to assign each client a unique client ID, and make the Client ID a part of the primary key.</p>

Title: Maintaining referential integrity between a mobile client and a server

Body: So I have a relatively simple system. A mobile client creates records in a sqlite database that I would like to have synced to a remote SQL server (that is shared with other mobile clients). So when I create a new record in the phone's sqlite table, I then push that change to my remote service through a RESTful API. The problem I'm having, is how do I order the primary keys so that there isn't collisions in the data (i.e. a record in the phone has the same primary key as a completely different record on the server). What is the usual "best practice for referencing the record on the client, and for referencing the same record on the server?


答: For me, you get to self assign tasks from the backlog is the biggest selling point from a developer point of view. Also, the intimacy with the customer / product owner helps understand the larger scheme of things.</p>

Title: Advantages of Scrum for the developers themselves?

Body:
Scrum being a project management methodology, how would you 'sell' it to the developers in a team that is reasonably happy with its current situation?

It seems easy to me to explain to our Product Manager how Scrum will allow him to get regular releases, to amend requirements, and get the team to focus on the high-priority stories first.  I found it easy to explain what TDD or Continuous Integration bring in a developer's day-to-day life.

But how can developers be convinced to embrace Scrum?  How would Scrum make their life easier?


问:
Is it possible to release a library based on the ASIO SDK under the LGPLv3?
I'm wondering if it's possible to write and release a library based on the ASIO SDK under the LGPLv3.

More specifically, the ASIO license says something I'm not sure how to interpret (2.2) :

The Licensee has no permission to [...]. This includes re-working this specification, or reverse-engineering any products based upon this specification.

Which sounds like it could conflict with LGPL's:

You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications

Also, 5.a) is kind of bugging me :

Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities

The way I see it, my Library will have no use, point or effect on its own, when uncombined with the ASIO SDK. Will I still have to release an uncombined dummy piece of software to respect 5.a) if I choose LGPL?

答:
It looks like you can't provide copies of the ASIO SDK.

You could develop code which uses it but have your customers get the SDK from ASIO directly and then link with your code.

You may also be able to distribute parts of the SDK (typically binary libs/dlls) with your product without supplying the entire SDK - this would be typical for commercial apps.

The reverse engineering clause is standard boilerplate - interestingly since the company says GMBH they are presumably German and should know that this clause is illegal in the Eu.


答:
The normal practice is to structure your database with uniqueidentifier keys (sometimes called UUIDs or GUIDs).  You can create them in two places without realistic fear of collision.

Next, your Mobile app needs to sync "fact" tables from the server before you can create new rows.  When you create new rows, you do it locally, and when you sync again, new rows are added to the server.  You can do the same thing with updates and deletes too.

To track inserts you need a Created timestamp on your rows.  To track updates you need to track a LastUpdate timestamp on your rows.  To track deletes you need a tombstone table.

Note that when you do a sync, you need to check the time offset between the server and the mobile device, and you need to have a method for resolving conflicts.  Inserts are no big deal (they shouldn't conflict), but updates could conflict, and a delete could conflict with an update.

There are frameworks to handle this kind of thing, such as Microsoft Sync Framework.


问:
What is the best design decision approach?
I have two classes (named MyFoo1 and MyFoo2) that share some common functionality. So far, it does not seem like I need any polymorphic inheritance but, at this point, I am considering the following options:

Have the common functionality in a utility class. Both of these classes call these methods from that utility class.

Have an abstract class and implement common methods in that abstract class. Then, the MyFoo1 and MyFoo2 classes will derive from that abstract class.

Any suggestion on what would be the best design decision?

答:
As you said --

... that share some common functionality. So far it does not seem like I
  need any polymorphic inheritance ...

Which means that, you can encapsulate the common functionality. From my experience, most of the time, encapsulation is better than inheritance.

```<code>class Myclass{
   private Common common;

}
</code>```

I am not saying Inheritance is bad. It has its own place.

OwnerDisplayName: palm snow

Body:
As you said --

... that share some common functionality. So far it does not seem like I
  need any polymorphic inheritance ...

Which means that, you can encapsulate the common functionality. From my experience, most of the time, encapsulation is better than inheritance.

class Myclass{
   private Common common;

}

I am not saying Inheritance is bad. It has its own place.


问:
Source Control: Roles and Responsibilities - Best Practices
I'm looking for "Best Practices" concerning roles and responsibilities, specifically who is responsible for merges from development branches to trunk (or main). Basically I'm looking for ammunition to help my cause.

Let me describe what I'm facing. I am the lead developer (owner) of a particular application. Our company recently moved from VSS (where I was the administrator of the VSS database in which my application was stored) to TFS (where I only have permissions on development branches created by our "operations" team). In previous jobs, I was a TFS Admin, so I know my way around TFS and MSBuild.

I don't have an issue with the branching and merging strategy being used (main branch, with bug/project development branches created as needed, merged back to main then promoted to a release branch). The issues I have are:

I cannot create my own branches. I must create a TFS task to have an "operations" team member create the branch for me.

I cannot merge from Main to my development branch. I must create a TFS task to have an "operations" team member perform the merge, and then hope he doesn't "step on" any of my teams changes since the "ops guy" may or may not be a developer and certainly has little to no knowledge of the code he is merging.

I cannot merge from development to Main. Again I must create a TFS task to have the "ops guy" perform the merge, hoping that he does it correctly. Then I have to create another TFS task to merge back to my branch so that I can resolve any issues which have occured by having a non-developer merge to Main.

I cannot create or edit MSBuild scripts. Again I have to work with the "ops" team which is new to MSBuild so only the most basic build tasks can be performed. (Forget about anything complex, or heaven-forbid a custom task).

I cannot execute an MSBuild script. Again only the "ops" team can do this.

To top all of this off, typically it is an "off-shore" resource which performs the requested tasks, so even if I create the task to (branch/merge/build) in the early morning, it probably won't be completed until that evening.

Now I have no issue with the "operations" team maintaining the release branches. As all they are doing is (basically) taking the latest version from Main and promoting it to the release branch; so as long as "Main" is stable and ready, the release branch will be good.

My opinion is that technical leads (such as I) should be responsible for maintaining the trunk ("Main") and any merging to/from the development branches. The team lead should also have the ability to generate MS Build scripts to build and deploy to the Integration test environment.

Can anyone direct me to a Best Practices document that'll help me prove my case? All my searching has turned up only Best Practices concerning the techniques of branching and merging, and no mention of WHO should be performing said branching/merging.

答:
My general take on the best practices is that any member of the development team should be able to perform any action on the tree presuming those actions don't do things like kick off a production deployment. In cases where a specific branch / tag / repository does act as a source for automated deployments putting in some reasonable change control or barriers to entry make sense, more from a keeping mistakes merely mistakes perspective than some control-freak angle. I would encourage developers to create branches and improve the build scripts. I would find ways to get developers access to production if needed. Part of the point of source control is it is an effective magic eraser of mistakes -- the worst you'll need to do is roll back a rev or two and branch off that.

Unfortunately this doesn't sound like the approach they have taken here. In order to defeat this I think you need to cover a few angles:

a) Prove that these policies are detrimental to developing things. Log all the time you spend waiting on ops to get working on something. This alone should sell reasonable management on why this is a bad policy.

b) Make some friends in Ops -- perhaps there is a reason for this policy. Perhaps that reasoning could be addressed in a more effective manner.

Hope this helps.


问:
Is having public constants "bad"?
Is this:

```<code>public MyClass
{
    public const string SomeString = "SomeValue";
}
</code>```

worse than this:

```<code>public MyClass
{
    public static string SomeString { get{ return "SomeValue";}}
}
</code>```

Both can be referenced the same way:

```<code>if (someString == MyClass.SomeString)
     ...
</code>```

The second however, has the protection of being a property.  But really how much better is this than a const?

I have learned over and over the perils of having public fields.  So when I saw some code using these constants on public fields, I immediately set about refactoring them to properties.  But halfway through, I got to wondering what benefit it was to have the static properties over the constants.

Any ideas?

答:
The perils of public fields is in the fact that they are mutable and that the implementation underlying them is subject to change.

When it comes to a const this is not normally an issue (similarly to public enumerations) - unless you think that the const will end up as mutable and that you will require encapsulation around the accessor at some time (say to log how many times it was looked up), you might as well keep it as a public const.

Title: Is having public constants "bad"?


答:
The system in question is large but is developed solely by me. This has also caused some managerial duties to fall on my lap, such as defining schedules and working on specifications.

Fair enough.

Should these kind of tasks be my responsibility?

That is ultimately up to your management to decide.

I see myself strictly as a programmer and nothing else.

Perhaps you are in the wrong job then.  A lot of people like being given the extra responsibility.

And if these are my responsibility, to what extent?

If management say so, yes.

When is a project so large that it requires testers?

When there is too much other work that the developers have to do.  At that point, management need to decide whether they want to employ a dedicated tester, or take the risk of skimping on testing.  (Ultimately, developers can only do so much.)

There are definite advantages in having dedicated testers, but there are downsides as well ... in addition to the cost of employing extra staff.

Should a programmer have to refine the specification,

If necessary, yes.  In fact, if the specification needs refining and there's nobody else working on it, then the failure to do this is likely to cause the project to fail.

worry about management of the project

If necessary, yes.

or even provide customer support?

If necessary, yes.

It sound to me like you are overworked, and reacting to the pressure.  This is a problem.  But taking the position that it is "not your job to do X, Y, Z" is not going to help.  A better plan is to make it clear that there is only so much that you can do, and point out that this is likely to cause deadlines to be missed, quality to slip, poor customer support and so on.   But do your best anyway ... without damaging your health, relationships, etc in the process.

Title: Is a programmer supposed to be self-sufficient?

Body:
At my current workplace, we don't have any testers, the rationale for that from the management being: "if we had testers, you wouldn't test your own code at all". This kind of thinking seems to be detrimental to product quality, as while I do test my own code, there are a lot of things that I will miss just for the fact that I know the system inside out and don't know how to use it "wrong". Black box testing doesn't really work as I subconsciously avoid the pitfalls that a dedicated tester would fall into. A lot of my time goes into fixing bugs that have slid into production code and found by the end user.

The system in question is large but is developed solely by me. This has also caused some managemental duties to fall on my lap, such as defining schedules and working on specifications.

Should these kind of tasks be my responsibility? I see myself strictly as a programmer and nothing else. And if these are my responsibility, to what extent? When is a project so large that it requires testers? Should a programmer have to refine the specification, worry about management of the project or even provide customer support?

Note

Some might have got the impression that I am against widening my responsibilities – that is not the case, I'm eager to get a role that involves more management duties, but currently it is not in my job description. Until I'm officially employed as such or the additional duties start showing in my paycheck, I'm going to think of myself as 'just' a programmer. Unfortunately, as a junior developer, shifting to managerial duties is not going to happen very soon.

Excellent answers so far, keep them coming if you have something to add or personal experiences to share!


问:
Literate programming, good/bad design methodology
I have recently found the concept of literate programming. And I found it rather intriguing. Yet I have not been encountered with claims that it is a bad way to structure a program. It seems not covered many places. Not even here could I find any questions regarding this.

My question is not about its flaws or ways of handling documentation. I consider the documentation a side-effect of what it would mean for the flow of literate programming. I know that the design was originally intended for easy documentation as well as the concept of forward programming flow.

The concept of dividing the problem into small sentence based problems seems to be really a brilliant idea. It will thus ease the understanding of the program's flow.

A consequence of the literate design method is also that the number of functions required will be limited to the imagination of the programmer. Instead of defining a function for a certain task, it could be created as a scrap in the literate method. This would yield automatic insertion of the code, instead of a separate function compilation and subsequent requirement of an inter-procedural compilation optimization step to obtain the equivalent speed. In fact Donald E. Knuth first attempt showed an inferior execution time, due to this very fact. I know that compilers can be made to a lot of this, however this is not my concern.

So I would like to get feedback of why one should consider this a bad/good design methodology?

答:
This would yield automatic insertion of the code, instead of a
  separate function compilation and subsequent requirement of an
  inter-procedural compilation optimization step to obtain the
  equivalent speed

This is irrelevant.  Has been for decades.  You can remove it from the question, since it makes no sense with modern compilers to subvert their optimizers.

So I would like to get feedback of why one should consider this a
  bad/good design methodology?

There is no downside to literate programming.  (I expect dozens of -1 votes for that sentiment.) As a practitioner, I've never seen any problems.

There are some arguments against which all amount to "programming in a higher-level language is be subverted by tweaking the resulting code."  Right.  In the same way that programming in C++ is subverted by tweaking the .o file that gets produced.  It's true, but irrelevant.

Writing literate programs merely means combining high-level and detailed (code-level) design into one document, written with a suitable toolset that produces compiler-friendly files and people-friendly files.

When Knuth invented literate programming, mainstream OO languages didn't exist.  Therefore a great deal of the original web and weave tools allowed him to create class-like definitions for abstract data types.

Much of that is irrelevant nowadays.  Literate Programming tools can be quite simple if they're focused on modern, high-level object-oriented (or functional) programming languages.  There is less need for elaborate workarounds because of the limitations of C (or Pascal or Assembler).

The approach to writing literate programs is no different from the approach to writing illiterate programs.  It still requires careful design, unit testing, and neat coding.  The only extra work is writing explanations in addition to writing code.

For this reason only -- the need to write coherent explanations -- literate programming is difficult for some programmers.  There are a fair number of programmers who are successful (their code passes all the unit tests, is neat and easy to understand) but can't seem to write a coherent sentence in their native language.  Don't know why this is true.

There are a very large number of programmers who appear to be only marginally successful and then only by accident.  (There are enough bad questions in Stack Overflow that indicate that many programmers struggle to even grasp the fundamentals.)  For programmers who ask largely incoherent stack overflow questions, we know they can't really do a good job of literate programming, because they can't do a good job of programming.


答:
Changing a field into a property is a breaking change.  You lose binary, source, and reflection compatibility.

In addition:

There's more fine-grained access control with properties. Need it to be publicly gettable but really only want it set with protected
  access? No problem (from C# 2 onwards, at least).

Want to break into the debugger whenever the value changes? Just add a breakpoint in the setter.

Want to log all access? Just add logging to the getter.

Properties are used for data binding; fields aren't.

http://csharpindepth.com/articles/chapter8/propertiesmatter.aspx

All that said, I don't see how constants are really affected by this (especially if you don't need any of the above features), unless your API changes in such a way that they are no longer constants.

Title: Is having public constants "bad"?

Body:
Is this:

```<code>public MyClass
{
    public const string SomeString = "SomeValue";
}
</code>```

worse than this:

```<code>public MyClass
{
    public static string SomeString { get{ return "SomeValue";}}
}
</code>```

Both can be referenced the same way:

```<code>if (someString == MyClass.SomeString)
     ...
</code>```

The second however, has the protection of being a property.  But really how much better is this than a const?

I have learned over and over the perils of having public fields.  So when I saw some code using these constants on public fields, I immediately set about refactoring them to properties.  But halfway through, I got to wondering what benefit it was to have the static properties over the constants.

Any ideas?


答:
In C# it's very bad for none of the reasons mentioned in this thread.

Public constants in C# get baked into referencing assemblies.  Meaning, if you have a SomeOtherClass in a separate assembly referencing SomeString in MyClass, the CIL generated for  SomeOtherClass will contain a hardcoded "SomeValue" string.

If you go to redeploy the dll that contains MyClass but not SomeOtherClass and change the const, SomeOtherClass won't contain what you think it will--it will contain the original value.

If you're 100% positive it's a universal constant like Pi, go crazy; otherwise tread carefully.

Here's a better explanation : https://stackoverflow.com/questions/55984/what-is-the-difference-between-const-and-readonly

Title: Is having public constants "bad"?


答:
While rather new to the concept of litterate programming myself (and it's therefore likely that I'm missing the boat entirely), it seems very much to line up with the concept of a DSL.

The idea behind a DSL is to distill down a domain of problems into a simple, natural-language-oriented grammar that can be used to built algorithms for solving those problems.

To me, that same idea, or at least the core foundation of it, is the same or at least closely related to literate programming.

In the groovy world, for example, there is a strong push to use DSLs more regularly and to create new DSLs to solve common problems. This push comes from both tools within the language (easy builders), as well as core libraries supporting a DSL-based API.

Given that the trend, at least in that corner of the world, is towards literate programming, I would say that it is a good methodology to strive for.

Unfortunately, the level of thinking needed to create a good dsl is often beyond most programmers, from what I've seen. I know I personally struggle with some of the concepts needed from time to time. It may be this difficulty that has prevented such techniques from gaining more wide-spread adoption.

It's your classic case of when using the tool is one thing, but creating it is on a whole different level.

To expand on my point of view a bit, it isn't s much that DSLs are the same thing as literate programming, but rather that they make literate programming much more possible. Particularly when they are natural language DSLs.

In version 1.8 of groovy, the natural language DSL capability was substantially improved with the addition of more powerful command chains.

For example, the following lines of code are programming, not just pseudo-sentences:

```<code>drink tea with sugar and milk
move left by 30.centimeters
sendFrom "Guillaume" to "Jochen"
send from: "Jochen" to "Lidia"
Email.from "Lidia" to "Guillaume" withBody "how are you?"
contact.name "Guillaume" age 33
move left by 30.centimeters
sell 100.shares of MSFT
take 2.pills of chloroquinine in 6.hours
blend red, green of acrylic
artist.paint "wall" with "Red", "Green", and: "Blue" at 3.pm
wait 2.seconds and execute { assert true }
concat arr[0] with arr[1] and arr[2]
developped with: "Groovy" version "1.8-beta-2"
</code>```

Note: Code sample comes from Guillaume Laforge's blog

The core idea behind literate programming is that natural language is more understandable for humans and that is what matters. Groovy's natural language DSL capabilities make that a much closer reality, in my opinion. Especially when those DSLs are used to create business rules for an application.

Being able to "encode" the critical components of a system using natural language is the very essence of literate programming. Having to intersperse natural language with chunks of code is a bastardized form of literate programming. While useful, I believe that natural language DSLs that allow you to use natural language as the code itself are a huge leap forward.

Expanding the capability to programming in general is the next step in the process, but to a large extent the tools to do so are already in place. Yes, there is not a "general" DSL yet, but for smaller domains, the capability is there.

For more examples of this in action (in no particular order):

http://www.slideshare.net/glaforge/groovy-dsls-s2gforum-london-2011-guillaume-laforge

http://docs.codehaus.org/display/GroovyJSR/GEP+3+-+Command+Expression+based+DSL

https://stackoverflow.com/questions/6646811/groovy-1-8-a-b-c-style

http://svn.codehaus.org/groovy/trunk/groovy/groovy-core/src/test/gls/syntax/Gep3Test.groovy

http://groovyconsole.appspot.com/script/355001

http://docs.codehaus.org/display/GROOVY/Groovy+1.8+release+notes#Groovy18releasenotes-CommandchainsfornicerDomain-SpecificLanguages

http://mrhaki.blogspot.com/2011/05/groovy-goodness-command-chain.html

http://ice09.wordpress.com/2011/10/07/dsls-made-easy-with-groovys-chain-method-calls-gep-3/

http://eric-berry.blogspot.com/2011/05/some-dsl-fun-with-groovy-18.html

Title: Literate programming, good/bad design methodology

Body:
I have recently found the concept of literate programming. And I found it rather intriguing. Yet I have not been encountered with claims that it is a bad way to structure a program. It seems not covered many places. Not even here could I find any questions regarding this.

My question is not about its flaws or ways of handling documentation. I consider the documentation a side-effect of what it would mean for the flow of literate programming. I know that the design was originally intended for easy documentation as well as the concept of forward programming flow.

The concept of dividing the problem into small sentence based problems seems to be really a brilliant idea. It will thus ease the understanding of the program's flow.

A consequence of the literate design method is also that the number of functions required will be limited to the imagination of the programmer. Instead of defining a function for a certain task, it could be created as a scrap in the literate method. This would yield automatic insertion of the code, instead of a separate function compilation and subsequent requirement of an inter-procedural compilation optimization step to obtain the equivalent speed. In fact Donald E. Knuth first attempt showed an inferior execution time, due to this very fact. I know that compilers can be made to a lot of this, however this is not my concern.

So I would like to get feedback of why one should consider this a bad/good design methodology?

Body:
While rather new to the concept of litterate programming myself (and it's therefore likely that I'm missing the boat entirely), it seems very much to line up with the concept of a DSL.

The idea behind a DSL is to distill down a domain of problems into a simple, natural-language-oriented grammar that can be used to built algorithms for solving those problems.

To me, that same idea, or at least the core foundation of it, is the same or at least closely related to literate programming.

In the groovy world, for example, there is a strong push to use DSLs more regularly and to create new DSLs to solve common problems. This push comes from both tools within the language (easy builders), as well as core libraries supporting a DSL-based API.

Given that the trend, at least in that corner of the world, is towards literate programming, I would say that it is a good methodology to strive for.

Unfortunately, the level of thinking needed to create a good dsl is often beyond most programmers, from what I've seen. I know I personally struggle with some of the concepts needed from time to time. It may be this difficulty that has prevented such techniques from gaining more wide-spread adoption.

It's your classic case of when using the tool is one thing, but creating it is on a whole different level.

To expand on my point of view a bit, it isn't s much that DSLs are the same thing as literate programming, but rather that they make literate programming much more possible. Particularly when they are natural language DSLs.

In version 1.8 of groovy, the natural language DSL capability was substantially improved with the addition of more powerful command chains.

For example, the following lines of code are programming, not just pseudo-sentences:

drink tea with sugar and milk
move left by 30.centimeters
sendFrom "Guillaume" to "Jochen"
send from: "Jochen" to "Lidia"
Email.from "Lidia" to "Guillaume" withBody "how are you?"
contact.name "Guillaume" age 33
move left by 30.centimeters
sell 100.shares of MSFT
take 2.pills of chloroquinine in 6.hours
blend red, green of acrylic
artist.paint "wall" with "Red", "Green", and: "Blue" at 3.pm
wait 2.seconds and execute { assert true }
concat arr[0] with arr[1] and arr[2]
developped with: "Groovy" version "1.8-beta-2"

Note: Code sample comes from Guillaume Laforge's blog

The core idea behind literate programming is that natural language is more understandable for humans and that is what matters. Groovy's natural language DSL capabilities make that a much closer reality, in my opinion. Especially when those DSLs are used to create business rules for an application.

Being able to "encode" the critical components of a system using natural language is the very essence of literate programming. Having to intersperse natural language with chunks of code is a bastardized form of literate programming. While useful, I believe that natural language DSLs that allow you to use natural language as the code itself are a huge leap forward.

Expanding the capability to programming in general is the next step in the process, but to a large extent the tools to do so are already in place. Yes, there is not a "general" DSL yet, but for smaller domains, the capability is there.

For more examples of this in action (in no particular order):

http://www.slideshare.net/glaforge/groovy-dsls-s2gforum-london-2011-guillaume-laforge

http://docs.codehaus.org/display/GroovyJSR/GEP+3+-+Command+Expression+based+DSL

https://stackoverflow.com/questions/6646811/groovy-1-8-a-b-c-style

http://svn.codehaus.org/groovy/trunk/groovy/groovy-core/src/test/gls/syntax/Gep3Test.groovy

http://groovyconsole.appspot.com/script/355001

http://docs.codehaus.org/display/GROOVY/Groovy+1.8+release+notes#Groovy18releasenotes-CommandchainsfornicerDomain-SpecificLanguages

http://mrhaki.blogspot.com/2011/05/groovy-goodness-command-chain.html

http://ice09.wordpress.com/2011/10/07/dsls-made-easy-with-groovys-chain-method-calls-gep-3/

http://eric-berry.blogspot.com/2011/05/some-dsl-fun-with-groovy-18.html


答:
The most important aspect of literate programming (or even just good commenting) for me is not so much that it provides documentation, but rather it states the intent of the programmer. In knowing the stated intent, you can immediately judge whether or not the code following it really does what it should. Without intent, you have to begin with the assumption that the code is correct and then prove it right or wrong by induction -- which is more exhausting and time consuming as it often requires becoming familiar with all the surrounding code as well.

So stated intent often enables others unfamiliar with the code to quickly jump in and find errors it without having to know the larger context surrounding it.

And of course, it helps you to learn the basic flow and design of the code faster as well, as plain English is often more intuitive than pointer arithmetic for most people.


问:
Current best practice/methods to code a VB.NET DAL in SQL Server
What are the current best practice/methods to code a VB.NET DAL in SQL Server?

I have been trying to search but can't seem to find the right words to look for.

答:
LINQ-To-SQL or Entity Framework.

Entity Framework is the most current and tends to enforce better design practices but can be overkill for some projects and may not be the best option for some types of underlying data.

LINQ-To-SQL is easy to use and will fit into most projects rather easily. On the downside, it can be misused more easily than EF.


答:
You do have testers.  Only, you call them "end users."  This is detrimental for all the reasons you describe; no matter how conscientious a coder you are, you're simply never going to be able to do a good enough job overcoming your own preconceptions about how the code is "supposed" to be used for you to find all the ways it can screw up.

You need to re-open this issue with management.  By this point, it sounds like you have some hard data to back your case; the current hands-off approach to Quality Assurance both wastes your time and compromises your users' experience.  You need to be careful in how you present this so that it's clear this is a structural problem and not a case of "You just suck at testing," but it sounds like a discussion that needs to happen.

It sounds like you're coming to a crossroads with this employer.  If you're intent on remaining a programmer and nothing else, you may need to start pushing back and requesting that they start getting you the help you need to take some of the managerial tasks off your plate, either by bringing in somebody new or by expanding an existing co-worker's responsibilities.  ("This isn't what you hired me for, and these tasks aren't going away.  Time I spend doing this stuff badly is time I'm not spending on what I'm good at.")  But that may or may not be realistic.  Do you think you could handle moving into to a more managerial role if they gave you the resources and authority you'd need to get the job done right?

As to how big does a project need to be before it needs testers, I'm not sure how to precisely define that line, but I definitely think you've crossed it.  You're spending more time than you'd like fixing bug reports coming in from actual users; to me that says it's time to spend more effort stopping the bugs from getting to the users in the first place.


答:
I think the term you're looking for is ORM (Object Relational Mapping).

Entity Framework is an ORM framework. I would just add that LINQ is a standalone framework that can be used to query data, SQL, Entity Framework or even an XML file, so they are not exactly interchangeable.

Title: Current best practice/methods to code a VB.NET DAL in SQL Server

Body:
What are the current best practice/methods to code a VB.NET DAL in SQL Server?

I have been trying to search but can't seem to find the right words to look for.


问:
Solving Scrabble board?
I recently saw a question on SO about solving the scramble/boggle game, where the letters are in a 4x4 grid and you have to find as many words as possible. I looked at some of the solutions, tried it myself, and would now like to move onto solving a scrabble game.

The boggle solving code is rather simple; store the board state in a matrix and iterate over every move from every position and checking if words exist with the current letter chain.

With scrabble, the idea is similar, but I'm still having trouble figuring it out. My currently thinking of:

Storing the board in 2 dimensional array.

Iterating over each position and skipping if the position is empty.

Creating some sort of regex pattern for the letters on the rack and the letter at the position...

I'm still really iffy on what to do at step 3 because I know the tile at the position could be the beginning end, or some point in the middle of a word. And then there's the matter of making sure that if a word does fit that it also makes words with other tiles it touches..

I'm not asking for code samples, just the thought process from more experienced programmers.

To clarify, my goal is:

Given the current state of a board and a person's tiles, calculate the legal moves and the points for that move.

For anyone following this and waiting for an answer, I found this: http://www.chaddington.com/portfolio/project.html#scrabble

I might look through what he wrote, but I do want to try to figure it out myself first.

答:
I believe you've forgotten the question itself. What is your intent?

Given a Scrabble board with already filled tiles, find all the words available?

Or let the users play Scrabble by adding tiles and check the score with every newly added tile?

If it's the first point, then you may want to:

Transform your board into a set of 30 uni-dimensional arrays: one containing rows, another - the columns.

For every row, walk through the tiles in the row, surrounding the row by whitespace (empty tiles) and then, replacing consecutive whitespace (empty tiles). For example,       "····stack··meta" would become "·stack·meta".

Split those into words. "·stack·meta" would be ("stack", "meta").

Check each word against a dictionary.

If it's the second point, then you don't have to "iterate over each position" (point 2 in your list). You simply search for the words from a given position Ca, b :

Horizontally, starting from Ca, 1 and walking to the right until Ca, 15,

Vertically, starting from C1, b and walking to the bottom until C15, b.

To simplify, you can create two uni-dimensional arrays as:

A₁(a) → Ca, n, 1 ≤ n ≤ 15

A₂(b) → Cn, b, 1 ≤ n ≤ 15

Then you'll have to create a single method which will determine existent words given:

An uni-dimensional array (A₁ or A₂),

A one-dimension position of the current tile in the array.

How? I would start by isolating the word itself, i.e. find the previous and the next whitespace (i.e. empty tile), if any. Then a formed word must be checked against a dictionary. Then you count the score, taking in account the colors of tiles and the tile characters.

Example (using a syntax of an imaginary language):

var A₁ = " stack overflow".ToArray(); // Given the one-dimension array...
var b = 4; // ... and the position of the current tile...
var leftEdge = A₁.Take(b).FindLast(' '); // Find the left empty tile,
var rightEdge = A₁.Skip(b).FindFirst(' '); // Then the right empty tile,
var word = A₁.Subset(leftEdge + 1, b + rightEdge - 1); // Then extract the word itself.
Assert.AreEquals("stack", word); // Found a good one?
bool isValidWord = word.IsInDictionary("en-US"); // Search the word in the dictionary.
Assert.IsTrue(isValidWord); // "stack" is a valid word.
```

Title: Solving Scrabble board?


问:
Is it possible to work with distrusting clients
One of our junior developers has been assigned a new client (we don't have the client yet, we're still working with him to see if we can meet his needs) and the junior developer said the client will hire us if we can do the work on his project without getting access to his server.

I've had a direct conversation with the client who turned out to have had his code stolen before by some offshore company that he outsourced. This made me more sympathetic but I still have mixed feelings about this.

On one hand I want to prove to the client that we're not all bad apples. Also if we do a good job with him, we get a loyal client who'll hire us for all his projects. I haven't heard of this happen before but I guess it happens more often than we'd all like to admit.

On the other hand I'm hesitant to accept working with him because deployment time is going to be a nightmare and no where in my career or education has anyone taught me how to work with clients like him. I (or the junior developer) would have to write a detailed description of exactly what to do with the source to deploy it and that is an annoying burden when I could deploy and test the whole thing in an hour myself.

As I said, I've never had to deal with this before (we're signing a non-disclosure but apparently so did the offshore company before us). We're not fully fully booked so it's not like I have an immediate replacement, but we're not begging for work either and I wonder if working under such restricted environment is worth the trouble.

Another side is that the experience itself could be rewarding for us, but is it experience worth having, as in what's even the likelihood of getting a similar client anytime soon. Are we even expected to comply with such clients?

So since I don't have any first hand experience with this and it definitely wasn't covered in school, how would those with longer experience working with clients deal with a distrusting client like this? Would you even accept the job?

答:
Actually, a detailed description of how to deploy is valuable in itself.  Your client may want to be able to control deployment rather than going through you each time.  Just include it in your estimates and make sure you get paid for it.  Not having access to the client's server is going to make things take longer in general, but that shouldn't itself be a problem.  Remember that there also can be perfectly legitimate legal or liability reasons why you don't get access, so you probably want to have some idea how to work without access.

In any relationship where there's a trust issue, I'd pay attention to the payment schedule, and make sure I was never owed more money than I was willing to write off if things went bad.  Distrust in one area can spread.


问:
Authentication for 'participants' vs 'users'
I'm building a site that lets users schedule interviews/conferences with third parties and I'm wondering what's the best way to provide security around the participant experience while providing the smallest usability barrier possible.

Currently, I send an email with a link and a 5 digit auth-code. The link opens a page, the participant types in the auth-code and is temporarily logged in for the duration of the interview/conference.

From a security standpoint, I think the auth-code is redundant and introduces friction for the participant, who may never have cause to visit my site again and may not be technically proficient. The link I send as part of the invitation contains a random string, so I could just increase its length by 5 characters and have the same size search space for potential attackers.

The downside is that I would potentially have to rate-limit the responses for the invitation URLs, so I'm not sure there's any benefit from a complexity/lines-of-code perspective.

The non-auth-code feels less secure, but I know that's irrational. Any thoughts on what the best approach would be?

答:
Almost anything a human can do, a machine can also do.  This includes entering a bit of text in a form on a web page.  For example, curl(1) can be directed to submit POST requests, including form fields:

```<code>curl -F 'code=foo' 'http://example.com?session=bar'
</code>```

And so adding some steps for a human to perform rarely improve security.

Another issue is one of what you are really trying to prevent.  Do you really care if it's a script issuing ten requests per second or a couple of bored humans (who type fast) doing the same?  What you really want is to limit abuse.

You can go a long way in that by using a network filter that does do rate limiting for everyone (or for certain urls) which can usually be configured in most http servers.  You can also arrange for each link you provide to be usable only once (or once per day).

Body:
Almost anything a human can do, a machine can also do.  This includes entering a bit of text in a form on a web page.  For example, curl(1) can be directed to submit POST requests, including form fields:

curl -F 'code=foo' 'http://example.com?session=bar'

And so adding some steps for a human to perform rarely improve security.

Another issue is one of what you are really trying to prevent.  Do you really care if it's a script issuing ten requests per second or a couple of bored humans (who type fast) doing the same?  What you really want is to limit abuse.

You can go a long way in that by using a network filter that does do rate limiting for everyone (or for certain urls) which can usually be configured in most http servers.  You can also arrange for each link you provide to be usable only once (or once per day).


问:
Where can I get a diverse set of sample text?
I am trying to gather statistics on character or word sequences used in the English language for use in a software project.

Where can I can get a large amount (several GB would be nice) of English plain-text covering a diverse set of topics?

答:
You can use Wikipedia's data dumps. The XML data dump for English Wikipedia that includes current revisions only is about 31 GB, so I'd say it would be a good start for your research. The data dump is pretty big, so you should consider extracting the texts from XML with a SAX parser. WikiXMLJ is a handy Java API tuned for Wikipedia.

And then, of course, there is always the Stack Exchange data dumps. The latest one includes all public non-beta Stack Exchange sites & corresponding Meta sites up until September 2011. But, naturally Stack Exchange posts are concentrated on the scope of each site, so probably not as generalized as you'd wish. Meta posts are a bit more general though, so you could consider those in addition to Wikipedia.

I don't think you'll find anything better, especially in plain text. Several open data sets are available through the Data Hub, but I think the English Wikipedia data dump is very close to what you are looking for.


答:
A constant is data. Properties imply the possibility of behavior when you so much as "look" at the value.

Bundling behavior (or the future possibility thereof) with constant data is flat out wrong. For most systems it won't really matter, but it can.

Lets say the value is "PI" and used extensively in the system's calculations. Putting it behind properties will force client programmers to program defensively. They must assign the value into a duplicate constant. If they don't dupe-up, the next version the library could have some unwanted "behavior" introduced behind the property. The behavior of the property (if it's in a compiled library) is unknown. Maybe it performs well in test, but there could be hidden code that executes if a special condition is met. This is not a pre-mature optimization. Especially for a real time system people's lives depend on.

The client programmers may even lose the safety of a constant since the language may not allow them assign a property value into their duplicate constant.

Also, when programmers are forced to assign your property value into their own constant, they effectively nullify whatever behavior you were hoping to accomplish with your property.

True constant data does not need or want encapsulation.

Title: Is having public constants "bad"?


答:
For the statistics, you are probably looking at "Bigram Frequency in the English language". Take a look at: Wiki-Bigram Stats

as for finding a large text, note that the frequency would be biased to the type of text. For example, if you analyze addresses you will get different results from analyzing newspaper stories. If you just want to test, you could use any book's PDF file (better not be a math. or programming or medical book) and convert it to text then run your tests. You could also convert newspaper web pages to text and work on those.

Title: Where can I get a diverse set of sample text?

Body:
I am trying to gather statistics on character or word sequences used in the English language for use in a software project.

Where can I can get a large amount (several GB would be nice) of English plain-text covering a diverse set of topics?


答: Google has a collection of data sets that they use to determine n-gram probabilities.  Examining their bigram (2-gram) datasets should give you a good picture.  There are many other corpi out there for which these analyses have already been done.</p>


答:
Project Gutenberg has a large corpus of texts in English, already in text form.

Project Gutenberg offers over 42,000 free ebooks: choose among free epub books, free kindle books, download them or read them online.

We carry high quality ebooks: All our ebooks were previously published by bona fide publishers. We digitized and diligently proofread them with the help of thousands of volunteers...


问:
Queries in Agile process
How to determine the story point value in Agile methodology and determine the team velocity? In web search able to get the definition but not the actually process explanation.</p>

答:
There's no "formula" for story points (and no "right" answer either).  Think of story points as measuring the height of a building while standing far away.  You may not be able to precisely determine the height, but you can estimate how tall it is relative to other buildings or structures.  The same applies with story points.  Come up with some baseline for "one point" and measure everything else relative to that.

There are various methods for determining story points, but the one I prefer is "planning poker."  Buy (or make) notecards that have the numbers 1, 2, 3, 5, 8, 13, 20, and 40 on them (read here to see why).  Each team member votes on the "size" of a feature be showing the card that is closest to the size they think the feature is.  The high and low estimates explain their positions to the team (for expediency you can have one automatic re-vote without discussion) and the team votes again, repeating until there is consensus.  Other cards that can optionally be included are 0, 1/2, 100, "infinity", and "?" (meaning unsure).  There are pros and cons to using those sizes that are discussed in more detail elsewhere.

Velocity, on the other hand, is more scientific.  It is simply the average number of points that a team _completes**_ in a given iteration.  There is some variety in how you measure it (average all iterations?  Just the mast N?  Give more weight to recent iterations?) but if you keep the story point scale and the team members consistent it should give you a rough indication of how much the team can commit to completing in an iteration.

In the end, however, I encourage teams to do a "gut check" after defining an iteration.  The team needs to commit to a body of work in an iteration, which may require cutting features if it feels like too much, or adding some if there is a high confidence that there is room to take on more.

** I define Done as a feature is fully coded, tested, and validated.  I do not give partial credit for coding "most" of a feature (more specifically for completing most of the tasks necessary to complete a feature).  I will count a feature if it has been coded but some bugs are found in testing, but will, of course, put those bugs in the following iteration and count the story points there

Title: Queries in Agile process


答:
Story points represent a relative size. The actual figure doesn't matter. Comparing two stories you can estimate whether the two are the same 'size' or whether they are different in 'size'. Size here means a mix of effort, duration, complexity, risk, novelty and many more. It doesn't really matter.

To determine the relative size it pays off to do this as a team using "planning poker". Some teams use cards but basically it means that everybody puts their estimate on the table at the same time. If all agree, that's the estimated 'size'. If there is a large variation have the team discuss why they think it is larger or smaller. Then estimate again. Repeat until you have an agreement for each story. There are stories that need further exploration. Turn them into spikes with up to 3 days each. Then get together and see what you have learned from the spike.

For your first iteration look at the pile of prioritized stories and start from the top. Pick as many as you believe can complete as a team in that iteration. If you run out of stories before the end of the iteration pull in further stories. If at the end of the iteration stories are incomplete don't worry. Before you start your next iteration look at the total of story points that you completed. Don't pick more story points for your next iteration. Velocity is the average amount of story points you can complete. Some teams just use the average of the last four iterations. Be aware that this average can change. This is not a bad thing.

There are a few dangers that you'd like to avoid. Stay away from sizing stories too small, e.g. giving them smaller numbers than they are. Stay away from signing up for more story points than you can handle. It's better to pull in additional stories than to have incomplete stories at the end of the iteration. Stay away from imposing a story point number on a particular team. All they will do is put higher point values on stories. This is not an indication of increased productivity. Story points don't help with measuring productivity. They are planning tool for future iterations. Nothing more. Also try to stay away from splitting stories along traditional function, e.g. implement feature, test feature, integrate feature, each with their separate story. One story includes all work required to complete the story, coding, testing, integration, etc.

That should cover the basics. You'll find out that there are a lot of additional aspects and scenarios that are worth considering. Experience comes with practice. Just give it a try and learn from what works and what doesn't. Good luck!

Title: Queries in Agile process

Body: How to determine the story point value in Agile methodology and determine the team velocity? In web search able to get the definition but not the actually process explanation.</p>


问:
What's the best explanation of what Story Points are?
We're starting to use Story Points here for our Agile development but I find it hard to explain and also can't find any definitive answer to what they are. The best thing I can do is point to other sites (like this one) and give some vague generalization of what they are. I'm looking for a good explanation with some examples of use that would be helpful for others to use. Are there any good resources for explaining story points?</p>

答:
They are a waste of time.

http://www.amazon.com/Lean-Trenches-Managing-Large-Scale-Projects/dp/1934356859/

Interesting that this opinion now comes from the guy who wrote Scrum and XP from the Trenches and whose company name (Crisp) can be found on so many decks of planning poker cards used by so many teams around the world.

The last sentence of the OP: "Are there any good resources for explaining story points?"  Yes, this book is a good resource.  Food for thought.

ContentLicense: CC BY-SA 4.0


问:
Question about the use of the word 'porting' in programming
I'm currently in the process of modifying a C++ code that was written for UNIX system so that it works by compiling from Visual Studio. I had to change some built-in functions' names and I had to change the way dynamic arrays are defined.

My question is, can I say that I'm 'porting' this code from UNIX to Windows/Visual Studio or is 'porting' used only when changing from one programming language to another (porting from C++ to Java)?

答:
According to Wikipedia, and my own personal experience, the term "porting" refers to making software work for a platform for which it was not originally intended. This process sometimes requires a change in language, but not always.

The term is not generally applied to the process of adapting software to run with less memory on the same CPU and operating system, nor is it applied to the rewriting of source code in a different language (i.e. language conversion or translation).

When people say that Java programs are more "portable," they mean that it takes less additional work to make them compatible with a variety of different machines and operating systems.


答:
Both @John and @D Stanley's answers are excellent, although you should note that "Planning Poker" is not essential to estimating using user stories.  It is just a good way to bring the team to a consensus on valuations.

For the full scoop on User Stories, Mike Cohn's excellent book User Stories Applied: For Agile Software Development is the place to go.

Title: Queries in Agile process


问:
Object Oriented Programming Concepts and Interviews
I'm an Object Oriented Programming fanatic. I have always believed in modelling solutions in terms of objects. It is something that comes to me naturally. I work with a services start up that essentially works on application development using OOP languages. So I tend to test understanding of OOP in the candidate being interviewed.

To my shock, I found very very few developers who really understood OOP. Most candidates brainlessly spit out definitions they mugged up from some academic book on object oriented programming but they don't know squat about what they are saying. Needless to say I reject these candidates. However, over the course of time, I ended up rejecting almost 98% of the candidates. Now this gets me thinking if I'm being over critical about their OOP skills. I still believe OOP is fundamental and every programmer MUST GET it. Language knowledge and experience is secondary.

Do you think I'm being over critical or do I just get to interview bad programmers unfortunately?

EDIT:

I usually interview programmers with 2 to 5 years of experience. The position that I usually interview for is Ruby/Ruby on Rails application developer.

答:
I would like to answer the EDIT section of your question

I usually interview programmers with 2 to 5 years of experience.

If an interviewee has 2 to 5 year experience, OOP fundamentals is something that is expected and I don't think you are being over critical  but just having a reasonable expectation.


问:
Is "truthiness" a legitimate programming term?
SO has quite a few questions using the word "truthiness" to mean the truth value of an expression, when evaluated as a boolean, regardless of its original type. It's very useful in dynamic languages.

So my question is, is this a real term, and if so were we using it before Stephen Colbert made it popular? Or did we just adopt it afterward? In that case, what is the correct term with the definition I gave above?

答:
Truthiness is a legitimate and well defined term in Clojure, where it refers to the property of a value being considered true in a conditional statement.

So the conditional function below will only be called if value is "truthy"

```<code>  (if value
    (some-conditional-function))
</code>```

The only non-truthy values are false and nil, everything else is considered truthy.

I believe the philosophical justification for this is that nil can be taken to mean "does not exist", so the conditional statement is able to test for existence of a value.

Many other languages also have a similar concept of values that will be considered as true in a conditional context, so in conclusion I would argue that yes, truthiness should be regarded as a legitimate programming term when it is used in this way.

Body:
Truthiness is a legitimate and well defined term in Clojure, where it refers to the property of a value being considered true in a conditional statement.

So the conditional function below will only be called if value is "truthy"

  (if value
    (some-conditional-function))

The only non-truthy values are false and nil, everything else is considered truthy.

I believe the philosophical justification for this is that nil can be taken to mean "does not exist", so the conditional statement is able to test for existence of a value.

Many other languages also have a similar concept of values that will be considered as true in a conditional context, so in conclusion I would argue that yes, truthiness should be regarded as a legitimate programming term when it is used in this way.


问:
Which programming methodology would be a good fit for us?
Unfortunately, somebody has taught our upper management the word "Agile" and now they want us to move towards it. I have a peripheral understanding of agile (in principle) but have never used it in practice. From what I know, it will not be a good fit for our organization. Right now, things are pretty grungey. Here's how it is;

We're a very small team - two developers, one DBA, one designer. The company I work for makes a disproportionately large amount of money relative to its size, and nearly 95% of that is pure online sales.

From a development perspective, we are subjected to many desk invasions during a typical day (we're tech support as well as dev), work can regularly just fall out of the sky at a moments notice if a sales team member promises something to someone. We do undertake larger projects too, and they're a nightmare with the constant interruptions. Some of us are starting to tear our hair out! Project plans are drawn up by non technical managers in excel spreadsheets, where they try and break the task down into bite-sized sentences that they can understand and put a date beside each one. These dates are always hideously unrealistic and often missed, and our meetings (which we have around weekly) are regularly filled with awkward moments with people asking "why hasn't this been done yet".

I am pretty sure Agile isn't the one for us. Now, given that (and i have tried) this company will not change its ways, and only the dev team is willing to change, is there a development methodology that we could adopt which is a good fit for just saving us some sanity?

答:
On the contrary, it sounds to me like an Agile method is exactly what you need in order to deal with missed deadlines, unrealistic expectations, and poorly planned projects.

Your management have indicated that they are interested in this new Buzz word.  Most likely they will want to use it to hype up the marketing of your products. this isn't necessarily a bad thing, but it will need to be managed very carefully if you want to make an Agile method work for you.

Half the battle is getting buy-in from management.  Having them receptive to the very idea of Agile is most of the battle.  The rest is to make sure that their expectations are managed so that they continue to want you to be agile, and to avoid them becoming disenchanted when and if your managers feel as if their control over project management is largely slipping through their fingers.

Before your company decides anything, I would recommend getting in an Agile coach to do a half day seminar and workshop. Get you all thinking as a team - managers and developers alike - about what it is about Agile that you feel will work for you, and what you feel won't. If on the other hand the management trust your judgement, then you will need to become very familiar with a number of Agile practices and Methods, and create a seminar or your own. Personally, I'd steer towards getting an experienced coach in, so that you don't waste a lot of time, and to maintain the momentum. In the meantime, grab a copy of a couple of good Agile books as references, read them thoroughly, but also leave them hanging around your desk where management can see them. Subliminal psychology can work wonders in a situation like the one you've described.

I'd recommend at the very least to read the following:

Lean Software Development - Mary & Tom Poppendieck

Agile Software Development - Robert C. Martin

and for extra credit (because I think it's a great companion for the other books I mentioned):

Clean Code - Robert C. Martin


问:
Agile for the Solo Developer
How would someone implement Agile process concepts as a solo developer?  Agile seems useful for getting applications developed at a faster pace, but it also seems very team oriented...</p>

答:
Agile works just as well for individuals as it does for teams. It's about finding a process that works for you, and allowing you to adapt to changing circumstances once your project has already started. It's also about delivering value to your customer regularly, regardless of whether or not the software is actually "finished".

Agile processes are highly iterative. Work is done in short TimeBoxes/sprints/cycles/iterations. Some design work may be required up front, but can be refactored as you learn more about what it is you need a system to do. Unit testing is the backbone of nearly all Agile development methods, giving you an indication of whether your software is working, and if additions/changes to your software will break the existing code base.

If you adhere to BDD/TDD, allow your requirements to change with the wind and can adjust your feature priorities accordingly, if you build your entire system and run all of the tests often, and if you deliver working code at the end of each sprint, you are already Agile.

Title: Agile for the Solo Developer


问:
Does your company have a coding standard?
I recently saw that Microsoft released a coding standards document (All-In-One Code Framework Coding Standards) and it got me thinking...  The company that I work for has no formal coding standards at all.  There are only a few developers and we have been together long enough to have evolved into similar styles and its never been an issue.

Does the company you work for have a documented coding standards?  If no, why not?  Does having a standard make a difference?  Is it worth writing a standard from scratch or should you adopt another standard as your own (ie. make Microsoft's standards yours)?

答:
I think it's essential to have a coding standard, even if all it says is "we use 3-space indentation and open-brackets go on the next line."  A few benefits:

It makes reading through the whole code-base much easier, since switching between coding styles between files is annoying.

It makes reading a single file easier, since any file updated by two developers with conflicting styles will eventually tend to get those styles mixed.  Reading through a file that mixes tabs and spaces (and editing it later) is a pain in the ass.

It makes it easier for new developers to use good style if there's an explicit standard, rather than an implied one.

Consistent naming conventions make it much easier to find functions/variables.  Was it ArraySort or array_Sort or sortTheArray or doSortArray or...?

In terms of whether to adopt an existing standard, it doesn't really matter- consistency is what's important.  If your developers have a dozen different styles, you might as well pick an existing, published one.  If you've all evolved into a pretty consistent style, just write that down and use it.


问:
Advantages of Scrum for the developers themselves?
Scrum being a project management methodology, how would you 'sell' it to the developers in a team that is reasonably happy with its current situation?

It seems easy to me to explain to our Product Manager how Scrum will allow him to get regular releases, to amend requirements, and get the team to focus on the high-priority stories first.  I found it easy to explain what TDD or Continuous Integration bring in a developer's day-to-day life.

But how can developers be convinced to embrace Scrum?  How would Scrum make their life easier?

答:
Stack Ranks / Backlog keeps milestone ends from being death-marches

As a developer, the 'destructive pattern' I see most in software development is when some 'external controller' (e.g. project management, executive management) gets very excited over the fact that 'favorite feature' isn't going to make it on 'calendar date' and orders a death-march.

Scrum, because it ranks 'important features' high in a backlog list helps developers manage this tension proactively in two ways.  First, you can rank 'favorite feature' high in the backlog so that s/he is most likely to be happy.  Second, it gives a very visual and concrete answer to "since we moved 'blinking widgets' to rank 1, it's very likely that we're not going to get to 'bouncing bunnies' in this sprint since it is now rank 7.  Are you comfortable with this trade-off?"

I've also found that with short sprints, 'external controllers' are less upset about postponing work.  If 'blinking widgets' doesn't make it into 'milestone 1' and 'milestone 2' doesn't end until 9 months from now, the sponsor of 'blinking widgets' gets very upset.  But if 'blinking widgets' is stack ranked 7 instead of 1 because there really are 6 more important things that have to get done first, this means that we'll probably get to it in sprint + 1 or at worst sprint + 2 which means it will show up 12 or 18 weeks from now (using 6 week sprints).  In my experience, waiting 3 months is 'acceptable' to the impatient -- besides, back in the 'waterfall' model of 3+ month milestones, waiting until the next two sprints end is the same calendar time as waiting until the current milestone ends.

Finally, if we're reaching the end of the sprint and things took longer than expected, it's very nice to be able to push backlog items 5-6-7 to the next sprint and make sure we've completed 1-2-3-4 with high quality and without 70 hr weeks.  After all, we'll be sure to get to 5-6-7 next sprint.  Again, given the shorter timeframes involved in the postpone, 'external controllers' are generally more comfortable with this and don't insist that we slip the milestone two weeks and order dinners each night 'to just push through it'.