问:
Building a Redundant / Distributed Application
This is more of a "point me in the right direction" question.

My team of three and I have built a hosted web app that queues and routes customer chat requests to available customer service agents (It does other things as well, but this is enough background to illustrate the issue).

The basic dev architecture today is:

a single page ajax web UI (ASP.NET MVC) with floating chat windows (think Gmail)

a backend Windows service to queue and route the chat requests

this service also logs the chats, calculates service levels, etc

a Comet server product that routes data between the web frontend and the backend
Windows service

this also helps us detect which Agents are still connected
(online)

And our hardware architecture today is:

2 servers to host the web UI portion of the application

a load balancer to route requests to the 2 different web app servers

a third server to host the SQL Server DB and the backend Windows service responsible for queuing / delivering chats

So as it stands today, one of the web app servers could go down and we would be ok.  However, if something would happen to the SQL Server / Windows Service server we would be boned.

My question - how can I make this backend Windows service logic be able to be spread across multiple machines (distributed)?  The Windows service is written to accept requests from the Comet server, check for available Agents, and route the chat to those agents.  How can I make this more distributed?  How can I make it so that I can distribute the work of the backend Windows service can be spread across multiple machines for redundancy and uptime purposes?  Will I need to re-write it with distributed computing in mind?

I should also note that I am hosting all of this on Rackspace Cloud instances - so maybe it is something I should be less concerned about?

Thanks in advance for any help!

答:
Make sure the Windows Service is loosely coupled to the instance of the DB server.  This will allow you to move to a N:1 ratio of Windows Service : DB server.  There's a whole host of techniques that can be used to make your DB server more robust, but that's not really what you're getting at in your Q.

Isolate the following information:

What data is required for the Windows Service to function

How would the Windows Service act if it didn't have an immediate feed of that information

How would the Windows Service share that information with other instances of itself

Identify what is dependent upon the Windows Service and why.  How would those elements react if a load balancer was inserted between them and the Windows Service?  What needs to change in order for those elements to play nicely with a load balancer?

Start analyzing what might happen to existing chats and incoming chat requests should the Windows Service go down.  Ideally, all you would lose on an existing chat is the logging information.  Incoming chats would be routed to a different Windows Service instance.

Ultimately, the answer to your question is identifying the assumptions and requirements that are binding your layers together.  Loosen those requirements / make the layers more independent and you'll be on your way to scaling and distributing your application.

I'm assuming for your mainline path that only the Windows Service interacts directly with the DB server.  If that's not true, you'll need to consider if you want to continue with that model or change it.


问:
How do tight timelines and scheduling pressure affect TCO and delivery time?
A friend's father, who is a software engineering manager, said, emphatically, "The number one cause of scheduling overruns is scheduling pressure."

Where does the research stand? Is a moderate amount of scheduling pressure invigorating, or is the manager I mentioned right or wrong, or is it a matter of "the more scheduling pressure you have, the longer the delivery time and the more TCO?" Is it one of those things where ideally software engineering would work without scheduling pressure but practically we have to work with constraints of real-world situations?

Any links to software engineering literature would be appreciated.

答:
Time, quality, resources, and the number of features are all connected. You can fix any three of them, and get the last one as the output of your scheduling process.

The way your question is formulated implies that the time is your variable, and the other three (the quality, the resources, and the number of features) are all fixed. The question may benefit from changing the perspective a little by fixing the time*, and letting the quality float.

Now your question becomes this: "Do timing constraints negatively impact quality"? The answer to this question is a resounding "Yes": research confirms that people do worse under pressure on math-related problems** that they have not extensively practiced before (i.e. attempted fifty times or more), so your friend's father is right.

* A top manager at one of my previous companies used to say that the time is an input to scheduling process, not its output. He was letting the number of features float, though, insisting on the uniformly high quality of the deliverables.

** There is an implicit assumption here that programming is similar to doing math; I think this assumption is fair.

ContentLicense: CC BY-SA 3.0


问:
OS choice for functional developing
I'm mainly a .NET developer so I normaly use Windows/VisualStudio (that means: I'm spoiled) but I'm enjoying Haskell and other (mostly functional) languagues in my spare time.

Now for Haskell the windows-support is ok (you can get the Haskell-Platform) but latley I tried to get a basic Clojure/Scheme environment set up and it's just a pain on windows.

So I'm thinking about trying out another OS for better tooling and languague support.
Of course that leaves me with MacOS or some Linux distribution.

I never used MacOS before and of course Linux would be cheaper (free) and I don't think I can parallel-boot MacOS on your normal PC-Hardware (can you?).
PLUS: I don't have a clue about the tools you can use on those (to me) forign OSs.

To make it short: I want to explore more Haskell, Clojure, Scala, Scheme and of course need at least good tooling for JavaScript/HTML5/Css.
Support for .NET/Mono/F# would be great but for this I will still have my Win7 boot.

So I like to know:
 - what is your prefered OS, Distribution (is Ubuntu viable?)
 - what Editor/IDE are you using

Thank you for your help!

PS: I'm not sure if this is the right place for this question but I surely hope so - if not please let me know where I should move this to (StackOverflow don't seem to be the right place IMHO)

答:
I've used Haskell on Windows, OS X, and (Ubuntu) Linux, so I can offer a few remarks about that. Now, anything you can get from the Haskell Platform is probably going to work just fine no matter what, but after that:

Relatively few Haskell programmers use Windows. You will find things on Hackage that assume a unix-like environment without really stating that explicitly.

Lots of useful stuff comes from FFI bindings to C libraries, and the lack of an even vaguely consistent and reliable C compilation toolchain on Windows means that, in my experience, installing FFI bindings from hackage is a crapshoot at best.

Anything necessarily platform-specific, which amusingly enough includes cross-platform GUI libraries, is more likely to "just work" on Linux.

Cygwin doesn't help as much as you think.

In summary: Everything tends to work on Linux, most things work on OS X but a few things are weird, and on Windows you should expect to encounter lots of interesting headaches when using libraries.

If you just want to have fun experimenting with stuff and learning Haskell, do yourself a favor and use an Ubuntu VM or something.

As far as editors and such go--emacs and vim are popular as always. I never learned to use either (though I really should...) and don't care for most IDEs, so I generally stick with SciTE--it's a thin wrapper around an editor widget called Scintilla, which you might know as being what Notepad++ uses.

Title: OS choice for functional developing


问:
How to negotiate with software vendors who do not follow HL7 standards
Take, for instance the "", I'd hope that anyone who has spent any time in dealing with HL7 messages knows that the "" signifies that something should be deleted.  "" is not an empty string, it's not a filler etc... But occasionally, one may meet a vendor who persists in sending "" instead of just sending nothing at all.

Since, I work for a small business and have an extremely flexible HL7 interface, I can ignore ""'s in received messages.  But these things are adding up.

Some vendors like to send custom formatted fields with psuedo-components that they leave others to interpret themselves.

Some vendors send all their information in note segments and assume you're going to only show users the information they send in a monospace font.

Some vendors even have the audacity to send Carriage Return Line Feeds at the end of each line of a file interface.

Some vendors absolutely refuse to send decimal numbers and in-so-doing refuse to send any numbers.

So, with all this crippling humanity against the simple plastic software man, how does one bend without breaking*?  Or better yet, how does one fight back and still make money?

*my answer is usually to create an interface for the interface and keep the HL7 processing pure, but I don't think this is the best solution

答:
The core of your question is "how to negotiate" and ultimately, the answer there is pretty simple.  You provide an interface specification and request them to follow that.  You can put penalties for non-conformance in your contract specification, but I suspect that's not a feasible option.

I think your real question is what to do with all of the one-off rules that are generated because the vendors aren't strictly following the interface specification.

Gnat's link to the anti-corruption layer is a good start to solving that challenge.  More specifically, I think I would generate a list of rules / filters that can be applied to incoming transmissions.  Each non-conforming vendor will then have a list of transformation rules that need to be applied.  As new vendors come in, you can simply re-use existing rules and add to the never-ending list of variants as necessary.

The variant with the fixed font is a little more annoying as it will require some downstream work past message reception in order to make it work, but hopefully that's the minority exception case.


答:
The number one cause of scheduling overruns is scheduling pressure.

I disagree. The number one cause of scheduling overruns is a schedule that doesn't reflect reality, and in an overly optimistic manner. Human nature dictates that some scheduling pressure is an absolute necessity. Just a couple of the problems that arise without some amount of scheduling pressure are interesting problems and "the best is the enemy of good enough." We technical people would far prefer to work on the problems that interest us rather than the problem that needs to be solved to get the product out the door. Take away deadlines (aka schedule pressure) and we will work on those interesting problems, to the detriment of the product.

Another problem is that the product needs to be "good enough". It does not need to be perfect. Engineers and scientists see the simplifying assumptions that aren't quite valid in some special case circumstances. Graphics designers see aliasing problems that are invisible to everyone else. Programmers see warts in their architectures that have zero impact on the product's behavior. "The best is the enemy of good enough," which means that sometimes we have to live with those problems that aren't really problems.

Lack of scheduling pressure will lead to a product with a very high cost of ownership. What causes overruns is bad schedules. This can come in a variety of forms. Underestimating effort needed, failing to account for dependencies, adding people to an already late project. Just to name a few.

Title: How do tight timelines and scheduling pressure affect TCO and delivery time?

Body:
A friend's father, who is a software engineering manager, said, emphatically, "The number one cause of scheduling overruns is scheduling pressure."

Where does the research stand? Is a moderate amount of scheduling pressure invigorating, or is the manager I mentioned right or wrong, or is it a matter of "the more scheduling pressure you have, the longer the delivery time and the more TCO?" Is it one of those things where ideally software engineering would work without scheduling pressure but practically we have to work with constraints of real-world situations?

Any links to software engineering literature would be appreciated.


问:
What are the advantages of a $ SKU of VS2012 over Express?
I will be using Visual Studio only for creating C#/XAML Windows Store apps. Is there any reason for me to purchase a "Professional" SKU of VS 2012 rather than just using the Express (free) "Metro apps with C#/XAML" version?

The only thing I can think of is that I won't be able to use Resharper in the Express version (which I've already purchased a license for, but I use it at work, so that won't be a waste of money if I can't use it at home) - plus, I believe that even the Express SKU of VS 2012 will have similar code quality utility built in.

答:
http://msdn.microsoft.com/en-us/library/zcbsd3cz(v=vs.80).aspx

Basically no mobile device support, no class diagram support, Database design tools (local only)

No way to develop visual studios packages, or deploy those packages, No 64 bit integration or SQL 2005 support.

So, I'd recommend getting a Visual Studios Professional MSDN account!

Hope the link helps.


问:
WCF/webservice architecture question
I have a requirement to create a webservice to expose certain items from a CMS as a web service, and I need some suggestions - the structure of the items is as such:

```
item
- field 1
- field 2
- field 3
- field 4
```

So, one would think that the class for this will be:

```<code>public class MyItem
{
  public string ItemName { get; set; }
  public List<MyField> Fields { get; set; }
}

public class MyField
{
  public string FieldName { get; set; }
  public string FieldValue { get; set; } //they are always string (except - see below)
}
</code>```

This works for when its always one level deep, but sometimes, one of the fields is actually a point to ANOTHER item (MyItem) or multiple MyItem (List<MyItem>), so I thought I would change the structure of MyField as follows, to make FieldValue as object;

```<code>public class MyField
{
  public string FieldName { get; set; }
  public object FieldValue { get; set; } //changed to object
}
</code>```

So, now, I can put whatever I want in there. This is great in theory, but how will clients consume this? I suspect that when users make a reference to this web service, they won't know which object is being returned in that field? This seems like a not-so-good design. Is there a better approach to this?

答:
What about changing the structure of MyField class to have a property of type MyFieldValue which has a simple string property and a list of MyItem (to contain a single MyItem or many) e.g.

```<code>public class MyField
{
    public string FieldName { get; set; }
    public MyFieldValue FieldValue { get; set; }
}

public class MyFieldValue
{
    public string Text { get; set; }
    public List<MyItem> Items { get; set; }
}
</code>```

Or a simpler option might be to add the various options as properties to MyField e.g.

```<code>public class MyField
{
    public string FieldName { get; set; }
    public string FieldValue1 { get; set; } // With better property names
    public MyItem FieldValue2 { get; set; } // This property may be redundant as you could just add a single instance to the list below
    public List<MyItem> FieldValue3 { get; set; }
}
</code>```

It would then be up to the consumer to check each property.

Title: WCF/webservice architecture question

Body:
What about changing the structure of MyField class to have a property of type MyFieldValue which has a simple string property and a list of MyItem (to contain a single MyItem or many) e.g.

public class MyField
{
    public string FieldName { get; set; }
    public MyFieldValue FieldValue { get; set; }
}

public class MyFieldValue
{
    public string Text { get; set; }
    public List<MyItem> Items { get; set; }
}

Or a simpler option might be to add the various options as properties to MyField e.g.

public class MyField
{
    public string FieldName { get; set; }
    public string FieldValue1 { get; set; } // With better property names
    public MyItem FieldValue2 { get; set; } // This property may be redundant as you could just add a single instance to the list below
    public List<MyItem> FieldValue3 { get; set; }
}

It would then be up to the consumer to check each property.


问:
Significance and role of Node.js in Web development
I have read that Node.js is a server-side javascript enviroment. This has put few thought and tinkers in my mind.

Can we develop a complete data-drivent web application utilizing just JavaScript (along with node.js), HTML5 and CSS? Do we still need to use some server-side scripting language (e.g. C#, PHP)?

In case we still need to use other scripting languages, what is node.js worth for, or useful?

NOTE: Pardon with my knowledge about node.js.

答:
Can we develop a complete data-drivent web application utilizing just
  JavaScript

The answer is Yes. And it is starting already.

It is called FULL-STACK-JAVASCRIPT(FSJS).

Job openings are beginning to open for this position as one indicator.


问:
The importance of Design Patterns with Javascript, NodeJs et al
With Javascript appearing to be the ubiquitous programming language of the web over the next few years, new frameworks popping up every five minutes and event driven programming taking a lead both server and client side:

Do you as a Javascript developer consider the traditional Design Patterns as important or less important than they have been with other languages / environments?.

Please name the top three design patterns you, as a Javascript developer use regularly and give an example of how they have helped in your Javascript development.

答:
Do you as a Javascript developer consider the traditional Design
  Patterns as important or less important

They are vital.

This is because concepts for reusable solutions can transcend language.
  - syntax changes
  - implementation changes
  - Notion for pattern still exists.

Developers from any language can learn advanced JS by learning patterns, not syntax.
  Those who do not know this are missing out.

Please name the top three design patterns you, as a Javascript
  developer use regularly

There are patterns that are used frequently which some would "argue" against. However, they are good to know because they are extremely common and powerful in advanced JS.

1- Namespace - wrap your code in an object.

var x = (function(){})();

2- ObjectConfiguration, Factory-like pattern. -Pass an object to a function, not a bunch of vars.

var product = factory({});

3- Callback function. - Pass a function as a parameter, to be called when task is complete.

function longTask(function(){//call me when done});

Like I said, some may argue that these are not patterns, but they are very common and very powerful, and should be mentioned because they are indeed very useful reusable solutons to common problems. Which is the definition of Design Pattern.

Excellent question.

Hope that helps.

OwnerDisplayName: Lewis


问:
Is there a better way to handle data abstraction in this example?
I'm building an application that retrieves Sharepoint list data via a web service SPlists.Lists.  To create an instance of the web service, I have the following class:

```<code>   class SharepointServiceCreator
   {

        public SPlists.Lists createService()
        {
            listsService.Url = "http://wss/sites/SPLists/_vti_bin/lists.asmx";
            listsService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            SPlists.Lists listsService=new SPlists.Lists();
        }

   }
</code>```

I'm concerned that this isn't good OOP abstraction, though, because in order to create this service elsewhere in my application, I would need the following code:

```<code>class someClass
{
 public void someMethod()
 {
  SharepointServiceCreator s=new SharepointServiceCreator()
  SPlists.Lists listService=s.createService()
 }
}
</code>```

Having to use declare the instance of listService in someMethod as type SPlists.Lists seems wrong, because it means that someClass needs to know about how SharepointServiceCreator is implemented.  Or is this ok?

答: This is an example of the factory pattern. To adhere to existing conventions, rename SharepointServiceCreator to SharepointServiceFactory and perhaps make it static so that you don't need to create an instance every time to need a reference to the service.</p>


问:
What branch of computing involves object recognition in images?
Several applications of this is text recognition (OCR), face recognition (biometrics), camera guided missiles (targetting systems).  Each involves analyzing images and making out some object of interest.  Is there a term that describes this branch of programming?

答:
You're looking for Computer Vision:

...a field that includes methods for acquiring, processing, analyzing, and understanding images and, in general, high-dimensional data from the real world in order to produce numerical or symbolic information, e.g., in the forms of decisions. A theme in the development of this field has been to duplicate the abilities of human vision by electronically perceiving and understanding an image. This image understanding can be seen as the disentangling of symbolic information from image data using models constructed with the aid of geometry, physics, statistics, and learning theory...

As a scientific discipline, computer vision is concerned with the theory behind artificial systems that extract information from images. The image data can take many forms, such as video sequences, views from multiple cameras, or multi-dimensional data from a medical scanner...


问:
Participate in open source project
Currently, I am through a very creative phase as a developer. I think it's a good time to contribute to an open source project. Not as "permanent" developer to a project but in a "help wanted" manner in many projects.

The open source hosting services that I know are SourceForge and CodePlex. Any suggestions that will help me on this direction?

答:
If you are interested in taking a more introverted approach to contributing to open source projects, then I think Github would be a good place for you to start.  You can fork anyone's repository and get your very own local copy.  Then you can make the changes you want to make and send them a pull request to get your code back in sync with their project.

All you need to do is find a project that looks interesting, check out their issues page to see if they need help fixing anything, fork, fix, pull request, and that's it!

Also, some larger projects could prefer documentation or unit test contributions if you are interested as well.

Title: Participate in open source project


问:
Removing an element not currently in a list: ValueError?
This is something that's bothered me for a while, and I can't figure out why anyone would ever want the language to act like this:

```<code>In [1]: foo = [1, 2, 3]

In [2]: foo.remove(2) ; foo  # okay
Out[2]: [1, 3]

In [3]: foo.remove(4) ; foo  # not okay?
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/home/izkata/<ipython console> in <module>()

ValueError: list.remove(x): x not in list
</code>```

If the value is already not in the list, then I'd expect a silent success.  Goal already achieved.  Is there any real reason this was done this way?  It forces awkward code that should be much shorter:

```<code>for item in items_to_remove:
   try:
      thingamabob.remove(item)
   except ValueError:
      pass
</code>```

Instead of simply:

```<code>for item in items_to_remove:
   thingamabob.remove(item)
</code>```

As an aside, no, I can't just use set(thingamabob).difference(items_to_remove) because I do have to retain both order and duplicates.

答:
As an aside: unless your list is extremely large and the list of items to remove is excessively small in comparison, you can create a new list with the items excluded in one readable line:

```<code>filtered_list = [x for x in source_list if x not in set(items_to_remove)]
</code>```

Obviously it preserves order and duplicates as you want. Very probably it is also faster.

Very often not mutating data greatly simplifies the way you think about an algorithm.

Body:
As an aside: unless your list is extremely large and the list of items to remove is excessively small in comparison, you can create a new list with the items excluded in one readable line:

filtered_list = [x for x in source_list if x not in set(items_to_remove)]

Obviously it preserves order and duplicates as you want. Very probably it is also faster.

Very often not mutating data greatly simplifies the way you think about an algorithm.


答:
To take it as step further, you could create an interface, and then pass in your implementation. This kind of takes it to the next level of flexible, and you can do this later down the line when you discover the functions you're actually going to need. A factory  could be used at a higher level to determine which implementation you pass "someClass" in the constructor argument, Or you can use the factory all over the place (probably not my 1st choice)

Create the interface:

```<code>Interface ICreateService {
   CreateService();
}
</code>```

and get some fancy-pants Dependency Injection going, which could be automated with some kind of "Container" to go even further

```<code>class someClass
{
     ICreateService SharePointServices;

     //constructor injection
     public someClass(ICreateService SharepointCreateServiceImplemented)
     {
          SharePointServices = SharepointCreateServiceImplemented;
     }
     public void someMethod()
     {
          SPlists.Lists listService=SharePointServices.createService()
     }

 }
</code>```

Now you can use this class for any object which implements ICreateService.

You could definitely do this with a factory to, it will depend on where you want to locate your implementation:

```<code>class someClass
{

     public void someMethod()
     {
         SPlists.Lists listService= (ICreateService)GetServiceFactory("SharePointServiceCreateor").createService()
     }

 }
</code>```

Where the factory would look like this:

```<code>ICreateService GetServiceFactory(string ImplentationStringOrEnum)
{
    switch(ImplentationStringOrEnum)
    {
        case "SharePointServiceCreator":
            return (ICreateService) new SharePointServiceCreateor();
    }
}
</code>```

The whole principle is to define your implementations outside of the classes which are using  them, that way you can switch in and out easily:

Title: Is there a better way to handle data abstraction in this example?

Body:
I'm building an application that retrieves Sharepoint list data via a web service SPlists.Lists.  To create an instance of the web service, I have the following class:

```<code>   class SharepointServiceCreator
   {

        public SPlists.Lists createService()
        {
            listsService.Url = "http://wss/sites/SPLists/_vti_bin/lists.asmx";
            listsService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            SPlists.Lists listsService=new SPlists.Lists();
        }

   }
</code>```

I'm concerned that this isn't good OOP abstraction, though, because in order to create this service elsewhere in my application, I would need the following code:

```<code>class someClass
{
 public void someMethod()
 {
  SharepointServiceCreator s=new SharepointServiceCreator()
  SPlists.Lists listService=s.createService()
 }
}
</code>```

Having to use declare the instance of listService in someMethod as type SPlists.Lists seems wrong, because it means that someClass needs to know about how SharepointServiceCreator is implemented.  Or is this ok?

Body:
To take it as step further, you could create an interface, and then pass in your implementation. This kind of takes it to the next level of flexible, and you can do this later down the line when you discover the functions you're actually going to need. A factory  could be used at a higher level to determine which implementation you pass "someClass" in the constructor argument, Or you can use the factory all over the place (probably not my 1st choice)

Create the interface:

Interface ICreateService {
   CreateService();
}

and get some fancy-pants Dependency Injection going, which could be automated with some kind of "Container" to go even further

class someClass
{
     ICreateService SharePointServices;

     //constructor injection
     public someClass(ICreateService SharepointCreateServiceImplemented)
     {
          SharePointServices = SharepointCreateServiceImplemented;
     }
     public void someMethod()
     {
          SPlists.Lists listService=SharePointServices.createService()
     }

 }

Now you can use this class for any object which implements ICreateService.

You could definitely do this with a factory to, it will depend on where you want to locate your implementation:

class someClass
{

     public void someMethod()
     {
         SPlists.Lists listService= (ICreateService)GetServiceFactory("SharePointServiceCreateor").createService()
     }

 }

Where the factory would look like this:

ICreateService GetServiceFactory(string ImplentationStringOrEnum)
{
    switch(ImplentationStringOrEnum)
    {
        case "SharePointServiceCreator":
            return (ICreateService) new SharePointServiceCreateor();
    }
}

The whole principle is to define your implementations outside of the classes which are using  them, that way you can switch in and out easily:


问:
What's the first thing you write when trying out a new language?
I think everyone has their own program or set of features beyond "Hello World!", that they use when trying out a new language.

Mine is a guessing game:

```<code>I'm thinking of a number 1-10, guess what it is!
Guess: 3
Nope, too low!
Guess: 7
Nope, too high!
Guess: 5
Yes, You win!
Play again (Y/N)? N
</code>```

What do you write?

答: I like to do some I/O exercises(both file system and console), then a text adventure game, because it helps me understand the way data structures are used in that language (it really helped when I was working on Lisp). They're also fun to make.</p>

ContentLicense: CC BY-SA 2.5


问:
Working with vectors and transformations
I am going to write an graphical 2D application that allows user to create polygons and transform them through transformation such as rotation an so on. I was hoping someone can give pro and cons arguments for the different choices I got in my mind. (Its all in Java btw!)

a). Represent vectors by filling matrices with 'real' numbers. This means making a matrix datas tructure that supports multiplication, transposing etc

b). Make a own vector class, such that I can make a matrix class that support those vectors.

答:
For 2D transforms you only need 2-tuple vectors and a 2x2 matrix. Both are trivial to implement. Things like matrix to vector multiplication would take a one-line formula rather than a proper loop.

Since matrices are so small I think it would be easier to store 4 numbers in a matrix and not a list of vectors. At least I'd try this approach first. If you need you can directly accept vectors in a constructor or a factory method (e.g. to create an offset matrix).


答: My personal preference (for my own personal project) is to have separate classes for matrices and vectors.  This allows the language to do a bit more typechecking than if everything was a matrix.</p>

Title: Working with vectors and transformations

Body:
I am going to write an graphical 2D application that allows user to create polygons and transform them through transformation such as rotation an so on. I was hoping someone can give pro and cons arguments for the different choices I got in my mind. (Its all in Java btw!)

a). Represent vectors by filling matrices with 'real' numbers. This means making a matrix datas tructure that supports multiplication, transposing etc

b). Make a own vector class, such that I can make a matrix class that support those vectors.


问:
what are the advantages and disadvantages of putting code for an unfinished project on github
I'm stating to work on a project that I intend to release as open source via the githubs. What are the advantages of putting the code on github from the outset, as opposed to waiting until the project is in a working state before publishing.

If it matters, this particular project is a C# app/service, and I have only a free github account (so I can't make it private and then pull back the covers later)

答:
The quicker you make your code publicly available, the quicker you can gain feedback and people to help you.  If your intention is to make the project open source from the beginning, then I would recommend starting your project out as public by default.

Github is full of small and unfinished projects so your project should fit right in.  The more details you put in the readme file the better as it will help other developers/consumers get up to speed on your project quickly.

At the very least, your private projects should be under some sort of version control.  If you don't want to pay for a service, then I'd recommend using Dropbox to back up your private local repositories.  This way you have file backup and version control on your project which will save you from hours of pain in the future. More recently, GitHub and its competitors have released free private repositories, so you can use your version control solution of choice privately without a paid subscription.

ContentLicense: CC BY-SA 4.0


答:
Short Answer: You may still host it freely in Github without any issues.

Your advantage would be getting feedback of users and interested developers who might wanna join your team, provide helpful idea and move this project forward.

However, to avoid most dis-advantages, it will make sense to write a Note mentioning that project is till in development phase. And what features are expected to be functional on initial Beta release.

Title: what are the advantages and disadvantages of putting code for an unfinished project on github

Body:
I'm stating to work on a project that I intend to release as open source via the githubs. What are the advantages of putting the code on github from the outset, as opposed to waiting until the project is in a working state before publishing.

If it matters, this particular project is a C# app/service, and I have only a free github account (so I can't make it private and then pull back the covers later)


问:
Git branching and tagging best practices
I am currently learning to use Git by reading Pro Git. Right now I'm learning about branching and tags. My question is when should I use a branch and when should I use a tag?

For example, say I create a branch for version 1.1 of a project. When I finish and release this version, should I leave the branch to mark the release version? Or should I add a tag? If I add a tag, should I delete the version branch (assuming that it is merged into master or some other branch)?

答:
A branch is used if you have 2 different versions of repository at the same time.  A tag is a way to mark a point in time in your repository.

You should add a tag to mark a released version.  If you then need to make bug fixes to that release you would create a branch at the tag.

You only want to delete branches that have been merged back into the HEAD [or some other branch].


答:
The mentioned open-source project sites ares still good. The SourceForge and CodePlex were there for many years, and they are still functional. Some of Git’s predecessors, such as CVS and Subversion, have a central “repository” of all the files associated with a project. The SourceForge and CodePlex, code-sharing sites are using  central repository pattern.

However, Git is different. It is build on a distributed version control system design. As it is also mentioned on Git's official website:

It outclasses SCM tools like Subversion, CVS, Perforce, and ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows.

In recent years there is a trend to migrate open-source projects to GITHub. Thus, it is becoming the next HOT Spot for open-source community to share their goodies.

In summary, you may get more attention and more projects needing contributors to help.

Title: Participate in open source project

Body:
Currently, I am through a very creative phase as a developer. I think it's a good time to contribute to an open source project. Not as "permanent" developer to a project but in a "help wanted" manner in many projects.

The open source hosting services that I know are SourceForge and CodePlex. Any suggestions that will help me on this direction?


答:
In short: Best practice is branch out, merge often and keep always in sync.

There are pretty clear conventions about keeping your code in a separate branches from master branch:

You are about to make an implementation of major or disruptive change

You are about to make some changes that might not be used

You want to experiment on something that you are not sure it will work

When you are told to branch out, others might have something they need to do in master

Rule of thumb is after branching out, you should keep in sync with the master branch. Because eventually you need to merge it back to master. In order to avoid a huge complicated mess of conflicts when merging back, you should commit often, merge often.

Good practices to follow

A successful Git branching model by Vincent Driessen has good suggestions. If this branching model appeals to you consider the flow extension to git. Others have commented about flow.

Tagging practices

As you already know, Git gives you commit identifiers like 1.0-2-g1ab3183 but those are not tags! Tagging is done with git tag, and the tags that are created using git tag are the base for the commit identifiers git describe creates.
In another words, in Git you don't tag branches. You are tagging commits. It is correct to say that tag is just an annotated pointer to a commit.

Lets look at practical example that demonstrated it,

```
                        /-- [v1.0]
                       v
---.---.---.---S---.---A     <-- master
                         \
                           \-.---B     <-- test
```

Let's commit 'S' be commit pointed by tag 'v1.0'.  This commit is both on branch 'master' and on branch 'test'.  If you run "git describe" on top of commit 'A' (top of 'master' branch) you would get something like v1.0-2-g9c116e9.  If you run "git describe" on top of commit 'B' ( aka the 'test' branch) you would get something like v1.0-2-g3f55e41 , that is the case with default git-describe configuration.  Note that this result is slightly different.  v1.0-2-g9c116e9 means that we are at commit with sortened SHA-1 id of 9c116e9, 2 commits after tag v1.0.  There is no tag v1.0-2!

If you want your tag to appear only on branch 'master', you can create new commit (e.g. only update default / fallback version information in GIT-VERSION-FILE) after branching point of 'test' branch.  If you tag commits on 'test' branch with e.g. 'v1.0.3` it would be visible only from 'test'.

References

I have found many, many, useful blogs and posts to learn from. However, the ones that are professionally illustrated are rare ones. Thus, I would like to recommend a post - A successful Git branching model by @nvie. I have borrowed his illustration :)

Title: Git branching and tagging best practices

Body:
I am currently learning to use Git by reading Pro Git. Right now I'm learning about branching and tags. My question is when should I use a branch and when should I use a tag?

For example, say I create a branch for version 1.1 of a project. When I finish and release this version, should I leave the branch to mark the release version? Or should I add a tag? If I add a tag, should I delete the version branch (assuming that it is merged into master or some other branch)?

Body:
In short: Best practice is branch out, merge often and keep always in sync.

There are pretty clear conventions about keeping your code in a separate branches from master branch:

You are about to make an implementation of major or disruptive change

You are about to make some changes that might not be used

You want to experiment on something that you are not sure it will work

When you are told to branch out, others might have something they need to do in master

Rule of thumb is after branching out, you should keep in sync with the master branch. Because eventually you need to merge it back to master. In order to avoid a huge complicated mess of conflicts when merging back, you should commit often, merge often.

Good practices to follow

A successful Git branching model by Vincent Driessen has good suggestions. If this branching model appeals to you consider the flow extension to git. Others have commented about flow.

Tagging practices

As you already know, Git gives you commit identifiers like 1.0-2-g1ab3183 but those are not tags! Tagging is done with git tag, and the tags that are created using git tag are the base for the commit identifiers git describe creates.
In another words, in Git you don't tag branches. You are tagging commits. It is correct to say that tag is just an annotated pointer to a commit.

Lets look at practical example that demonstrated it,

                        /-- [v1.0]
                       v
---.---.---.---S---.---A     <-- master
                         \
                           \-.---B     <-- test

Let's commit 'S' be commit pointed by tag 'v1.0'.  This commit is both on branch 'master' and on branch 'test'.  If you run "git describe" on top of commit 'A' (top of 'master' branch) you would get something like v1.0-2-g9c116e9.  If you run "git describe" on top of commit 'B' ( aka the 'test' branch) you would get something like v1.0-2-g3f55e41 , that is the case with default git-describe configuration.  Note that this result is slightly different.  v1.0-2-g9c116e9 means that we are at commit with sortened SHA-1 id of 9c116e9, 2 commits after tag v1.0.  There is no tag v1.0-2!

If you want your tag to appear only on branch 'master', you can create new commit (e.g. only update default / fallback version information in GIT-VERSION-FILE) after branching point of 'test' branch.  If you tag commits on 'test' branch with e.g. 'v1.0.3` it would be visible only from 'test'.

References

I have found many, many, useful blogs and posts to learn from. However, the ones that are professionally illustrated are rare ones. Thus, I would like to recommend a post - A successful Git branching model by @nvie. I have borrowed his illustration :)


问:
Improving without mentor
Although I consider myself not much experienced, I keep landing in jobs as the leader somehow (in the current one I am tech director of the company, in a previous one I was the R&D head).

I understand why this happen (I have a certain specific set of skills, and I use some uncommon programming languages), my issue is: I cannot find a mentor...

I know there must be stuff to me learn, and I notice as I work over the years that I am slowly learning more and more, but I believe that there are some way to get better much faster than just coding...

So, how I improve when there are no other person in the company to teach me, or to me read their code? (or fix their code even...)

I think I am beyond books, but way below a "master" level, so I don't know where to learn more.

答:
how I improve when there are no other person in the company to teach me, or to me read their code?

When i am using very "specific tools or uncommon programming language/framework" then i look for some special interest groups. Of course, there is an online community for most technology/frameworks that are currently in use. Thus, i use all means of online communication to stay in touch with the latest posts in:

LinkedIn groups

Tweeter - follow professional people

Forums - where problems discussed

Blogs - community wiki pages and announcements

Special interest user groups - like Gmail or Yahoo groups

One of the best approach to learn good practices of "uncommon programming languages" is to find some developer blog (preferable 4-5) and subscribe to them.

Title: Improving without mentor


答:
What about:

Advanced books

Users Groups

Conferences

Check out also answers to How to Really Master a Programming Language

Title: Improving without mentor

Body:
Although I consider myself not much experienced, I keep landing in jobs as the leader somehow (in the current one I am tech director of the company, in a previous one I was the R&D head).

I understand why this happen (I have a certain specific set of skills, and I use some uncommon programming languages), my issue is: I cannot find a mentor...

I know there must be stuff to me learn, and I notice as I work over the years that I am slowly learning more and more, but I believe that there are some way to get better much faster than just coding...

So, how I improve when there are no other person in the company to teach me, or to me read their code? (or fix their code even...)

I think I am beyond books, but way below a "master" level, so I don't know where to learn more.


答:
Some hints:

Learn other languages. Then compare them to the language(s) you already know, and try to look at the ways you can improve your coding skills in those languages by using things you learnt from other languages. "Free your mind" before learning those new languages, and don't try to simply clone the concepts of one into another.

Read code. I don't know what uncommon language(s) are you using precisely at your jobs, but I'm pretty sure you can find high quality open source code written in those languages by very skillful developers.

Stay with the community. If you don't have colleagues who use your language(s) at work, it's not an excuse to not sharing the knowledge through websites like Stack Overflow, where there are questions and answers even for very uncommon languages. Try to search for those questions by tag and see if you understand all the answers. If the questions are unanswered, answer them.

Teach. Teach your coworkers. Write a blog. Whatsoever. By explaining something to others, you'll learn it better.

Title: Improving without mentor


答:
My dear friend </p>

<p>Let me tell you it is very rarely found that some one is teaching another person the nuances of programming . Programming is something which has to be learnt by yourself. If you concentrate on a singular topic and try it out and join various forums which support that topic , then sooner or later you are going to become master of that topic. Kindly do remember you yourself are the best person to know how good you have become . In the kind of industry and world we are, we must become our own mentors, for what we teach ourselves stays with us for ever . </p>

Title: Improving without mentor

Body:
My dear friend

Let me tell you it is very rarely found that some one is teaching another person the nuances of programming . Programming is something which has to be learnt by yourself. If you concentrate on a singular topic and try it out and join various forums which support that topic , then sooner or later you are going to become master of that topic. Kindly do remember you yourself are the best person to know how good you have become . In the kind of industry and world we are, we must become our own mentors, for what we teach ourselves stays with us for ever .


问:
Should I comment Tables or Columns in my database?
I like to comment my code with various information, and I think most people nowadays do so while writing some code.

But when it comes to database tables or columns, I have never seen anyone setting some comments, and, to be honest, I don't even think of looking for comments there.

So I am wondering if some people are commenting their DB strcuture here, and if I should bother commenting, for instance when I create a new column to an existing table?

答:
Totally.

Microsoft SQL Server supports comments on both tables and columns, and it's pretty easy to set them through the IDE (Microsoft SQL Management Studio). Many other databases support comments as well.

Commenting tables and columns is as, if not more critical as commenting code. Having external documentation is great, but it's easy to forget to update the external documentation at every change. You can also forget to update the comment of a column, but it's more complicated (and it's also much easier to update the comment of a column rather than searching for the place to update in the external documentation).

You may wonder why you don't see too much comments. For the same reason that:

Most databases are completely undocumented. No comments. No external documentation. Nothing.

Most databases lack constraints, so you never know what are the values which can be saved, and what values will make the application relying on the database crash.

Most databases don't have correct indexes, primary keys, etc.

Most databases don't follow any naming convention.

Most companies don't have DBAs, don't have money and don't understand that having a high quality, well maintained database is critical for them.


问:
Are regular expressions a programming language?
In the academic sense, do regular expressions qualify as a programming language?

The motivation for my curiosity is an SO question I just looked at which asked "can regex do X?" and it made me wonder what can be said in the generic sense about the possible solutions using them.

I am basically asking, "are regular expressions Turing complete"?

答:
Regular Expressions are a particular kind of formal grammar used to parse strings and other textual information that are known as "Regular Languages" in formal language theory. They are not a programming language as such. They are more of a shorthand for coding that would otherwise be extremely tedious to implement and even more confusing than the sometimes arcane looking Regex.

Programming Languages are typically defined as languages that are Turing Complete. Such languages must be able to process any computable function. Regex does not fit into this category.

If you want a language that looks like Regex, try J.


问:
How can I get my progress reviewed as a solo junior developer
I am currently working for a 2 person company, as the solo primary developer. My boss gets the clients, mocks up some png design templates and hands them over to me.

This system has been working fine and i'm really enjoying it.

The types of projects I work on are for small - medium sized businesses and they usually want a CMS system. Developed from scratch i'll build a customised backend for the client to add/edit/remove categories, tags, products etc and then output them to the front end according to the design template handed to me. As time has gone on, the projects have increased in complexity, with shopping cart / ordering features and other common e-commerce type features.

Again, this system has been working fine and i'm really enjoying it.

My issue is my personal development as a programmer. I spend a lot of my spare time reading programming blogs, checking through stackexchange, reading suggested programming books (currently on 'The Pragmatic Programmer', really good so far), doing brain exercises (lumosity.com and khanacademy math problems), doing lots of physical exercise and other personal development type activities.

I can't help but feel though, that I'm missing out on feedback, critique. My boss is great and never holds back on praise in regards to my work, but he unfortunately is either to busy to check my code, or to be honest, I don't think it's one of his specialties and so can't provide feedback.

I want to know what i'm doing wrong and what i'm doing right. Should I be putting that much logic in the controller, am I modulating my code enough etc.

So what I have done is developed a little 'Family Budgeting' app and tried to do it as cleanly and effectively as I currently know how.

What i'm wanting to know is, is there somewhere I can submit this app, and have some seasoned developers provide feedback. It's not just a subsection of my code like 'codereview.stackexchange' appears to require, it's my entire workflow that I want critiqued.

I know this is a lot to ask, and I expect the main advice given will be to look for a job within a team, which is certainly something I will look into later down the track, but for now I want to persist with my current employment situation, but just don't want to develop too many bad habits.

Let me know if I can provide any further information to help clarify, or if this isn't the right place for this type of question I apologise in advance. Didn't want to use reddit as I felt this community fosters more well thought out responses.

答:
You may wish to check out https://codereview.stackexchange.com/

That would be a great place to get feedback about your code or design from seasoned professionals.


答:
My main solutions to that over the past 2 years have been:

networking socially:  I have particularly found that meetup.com is a great way to find programming groups in your area.  Twitter is also great for this.  When you find people you like and respect, follow them.

Using http://www.stackoverflow.com  I initially used it for occasional questions.  Now it is my daily companion for both giving and receiving advice.  Also use the sister sites like https://codereview.stackexchange.com/

Working:  Although probably not applicable for you (but good general advice for others) If you are good enough to get some kind of job in the area you want, seek out senior people, be nice to them and try to get them to mentor you.

Books.  O'Reilly, Pragmatic Programmer and others still have good books and you can choose paper and/or digital versions.  Here is a truly great list: https://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read with some of the best 'classics' out there in case you haven't already read them.  I can recommend clean code and code complete.

Tutorials.  There are now some fantastic sites on the net such as

http://www.codeschool.com,

http://www.codeacademy.com

http://code.google.com/edu/

Title: Improving without mentor


答:
Yes, it is quite unusual. This is mostly down to:

People don't know it's possible- progressively people deal less with RDBMSs directly and know less and less features, preferring to do everything on the main (non-SQL) codebase. ORM users, for instance, comment their models

Tools rarely show the comments easily, they tend to be buried and thus people don't see them

Well-designed databases tend to be self-explanatory for someone who knows the "business". Proper table and column naming mean that most tables and columns might not need comments- redundant comments are bad; "this table contains students" as a comment on the "students" table is worse than useless. Constraints can also make some comments redundant (i.e. "this column must be null if that column equals 3" can be implemented using a CHECK constraint- and constraints can be easily listed).

I believe database documentation is useful; I like autogenerated documentation such as that generated by tools like SchemaSpy; these often make comments pretty visible. However, my experience is that documentation is mostly useful when learning the database- a few months in any project and you'll know the schema by heart, unless it is extremely complex, thus docs are not that useful for reference.

Title: Should I comment Tables or Columns in my database?

Body:
I like to comment my code with various information, and I think most people nowadays do so while writing some code.

But when it comes to database tables or columns, I have never seen anyone setting some comments, and, to be honest, I don't even think of looking for comments there.

So I am wondering if some people are commenting their DB strcuture here, and if I should bother commenting, for instance when I create a new column to an existing table?


答: Commenting database columns is part of the modeling task. There are many steps to prepare a data model from concept to production. Describing each column is part of that process and almost all first class ERD tools will carry forward the comments from the modeling environment to the physical database environment. There is a difference between column description and column comment. Comments are usually short where descriptions are comprehensive and long. If you have a description, you'd rarely need comments. It is arguable as what should you put in the description. Part of your project standards should cover this in the meta data policy. </p>


答: There are no disadvantages. As long as you have a readme file that clearly states the project is in flux nobody will hold it against you if you make breaking changes as the project progresses.</p>


问:
Single statement if block - braces or no?
Which is better/more generally accepted?

This:

```<code>if(condition)
{
  statement;
}
</code>```

Or:

```<code>if(condition)
  statement;
</code>```

I tend to prefer the first one, because I think it makes it easier to tell what actually belongs in the if block, it saves others from adding the braces later (or creating a bug by forgetting to), and it makes all your if statements uniform instead of some with braces and some without.  The second one, however, is still syntactically correct and definitely more compact.  I'm curious to see which is more generally preferred by others though.

答:
I personally prefer the second. The first one looks ugly, awkward, and wastes horizontal space. The main problems with the second one are macros and people modifying your code at a later point getting it wrong.

To this, I say "don't use macros". I also say, "indent your damn code correctly". Considering how every text editor/IDE used for programming does indentation automatically, this shouldn't be that hard to do. When writing code in Emacs, I would use the auto-indent to identify if I wrote something wrong on a previous line. Anytime Emacs starts screwing up indentation, I usually know I've done something wrong.

In practice, I end up following whatever coding convention has been set before me. But these ones annoy me (and makes me much happier when I code in Python and this entire bracket disaster is gone):

```<code>if (condition) {
    statement;
} // stupid extra brace looks ugly
</code>```

Then

```<code>if (condition) // the brackets have now just become noise
{ statement; } // also can't see the indentation, harder to read
</code>```

Although honestly, two statements in an if statement annoy me far more than a single statement. Mostly because then brackets are required and it still looks funny with only two statements in the if statement.

Body:
I personally prefer the second. The first one looks ugly, awkward, and wastes horizontal space. The main problems with the second one are macros and people modifying your code at a later point getting it wrong.

To this, I say "don't use macros". I also say, "indent your damn code correctly". Considering how every text editor/IDE used for programming does indentation automatically, this shouldn't be that hard to do. When writing code in Emacs, I would use the auto-indent to identify if I wrote something wrong on a previous line. Anytime Emacs starts screwing up indentation, I usually know I've done something wrong.

In practice, I end up following whatever coding convention has been set before me. But these ones annoy me (and makes me much happier when I code in Python and this entire bracket disaster is gone):

if (condition) {
    statement;
} // stupid extra brace looks ugly

Then

if (condition) // the brackets have now just become noise
{ statement; } // also can't see the indentation, harder to read

Although honestly, two statements in an if statement annoy me far more than a single statement. Mostly because then brackets are required and it still looks funny with only two statements in the if statement.


答:
Just because I'm reading quite a bit of hierarchy in(to) your question:

Learn from the people under you.  Software development is about communication, between humans, often through the medium of code.  Since good communication should go both ways, learn from the people you program with. (my assumption is that you're not at a 1-man company)

Title: Improving without mentor


问:
Rules and advice for logging?
In my organization we've put together some rules / guildelines about logging that I would like to know if you can add to or comment.

We use Java but you may comment in general about loggin - rules and advice

Use the correct logging level

ERROR: Something has gone very wrong and need fixing immediately

WARNING: The process can continue without fixing. The application should tolerate this level but the warning should always get investigated.

INFO: Information that an important process is finished

DEBUG. Is only used during development

Make sure that you know what you're logging.

Avoid that the logging influences the behavior of the application

The function of the logging should be to write messages in the log.

Log messages should be descriptive, clear, short and concise.

There is not much use of a nonsense message when troubleshooting.

Put the right properties in log4j

Put in that the right method and class is written automatically.

Example:

Datedfile -web

```<code>log4j.rootLogger=ERROR, DATEDFILE
log4j.logger.org.springframework=INFO
log4j.logger.waffle=ERROR
log4j.logger.se.prv=INFO
log4j.logger.se.prv.common.mvc=INFO
log4j.logger.se.prv.omklassning=DEBUG

log4j.appender.DATEDFILE=biz.minaret.log4j.DatedFileAppender
log4j.appender.DATEDFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.DATEDFILE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%C{1}.%M] - %m%n

log4j.appender.DATEDFILE.Prefix=omklassning.
log4j.appender.DATEDFILE.Suffix=.log
log4j.appender.DATEDFILE.Directory=//localhost/WebSphereLog/omklassning/
</code>```

Log value.

Please log values from the application.

Log prefix.

State which part of the application it is that the logging is written from, preferably with something for the project agreed prefix e.g. PANDORA_DB

The amount of text.

Be careful so that there is not too much logging text. It can influence the performance of the app.

Loggning format:

-There are several variants and methods to use with log4j but we would like a uniform use of the following format, when we log at exceptions:

logger.error("PANDORA_DB2: Fel vid hämtning av frist i
TP210_RAPPORTFRIST", e);

In the example above it is assumed that we have set log4j properties so that it automatically write the class and the method.

Always use logger and not the following:

System.out.println(), System.err.println(), e.printStackTrace()

If the web app uses our framework you can get very detailed error information from EJB, if using try-catch in the handler and logging according to the model above:

In our project we use this conversion pattern with which method and class names are written out automatically . Here we use two different pattents for console and for datedfileappender:

```<code>log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.appender.DATEDFILE.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
</code>```

In both the examples above method and class wioll be written out. In the console row number will also be written our.

toString()

Please have a toString() for every object.
EX:

```<code>@Override
public String toString() {
  StringBuilder sb = new StringBuilder();
  sb.append(" DwfInformation [ ");
  sb.append("cc: ").append(cc);
  sb.append("pn: ").append(pn);
  sb.append("kc: ").append(kc);
  sb.append("numberOfPages: ").append(numberOfPages);
  sb.append("publicationDate: ").append(publicationDate);
  sb.append("version: ").append(version);
  sb.append(" ]");
  return sb.toString();
}
</code>```

instead of special method which make these outputs

```<code>public void printAll()
{
    logger.info("inbet: " + getInbetInput());
    logger.info("betdat: " + betdat);
    logger.info("betid: " + betid);
    logger.info("send: " + send);
    logger.info("appr: " + appr);
    logger.info("rereg: " + rereg);
    logger.info("NY: " + ny);
    logger.info("CNT: " + cnt);
}
</code>```

So is there anything you can add, comment or find questionable with these ways of using the logging? Feel free to answer or comment even if it is not related to Java, Java and log4j is just an implementation of how this is reasoned.

答:
One thing to keep in mind is to check the logging level before you do any kind of string operations for logging.  That is, don't go to all the work of setting up a date formatter or concatenating a bunch of strings to create the log message if you aren't actually going to log it.  That's just wasted work that slows your application down.

FYI, the Apache Commons project has a ToStringBuilder class that simplifies creating your toString() methods.

Title: Rules and advice for logging?


答: I believe that you will learn a good deal by teaching those that you lead.  You will gain a firmer understanding of what you teach them because you will be forced to think about why/how the easy things work (which you probably avoided doing in the beginning because you just wanted it to work)</p>

Title: Improving without mentor


答:
Just to add the all the Above good answers..

What I do is Maintain my Descriptions\Comments in the BD, But because no one looks there (or may not have access) I use those comments to auto-generate a Data dictionary, that I can then keep with the rest of my Docs!


问:
If-Else V.S. Switch end of flow
I was wondering the if if-else statements, is like a switch statement that does have a break statement.

```<code>if( boolean_expression_1 )
  statement_1
else if( boolean_expression_2 )
  statement_2
else
  default_statement
</code>```

Is the same as:

```<code>switch( controlling_expression )
{
case: ( boolean_expression_1 )
{
     statement_1
     break;
}
case: ( boolean_expression_2 )
{
     statement_2
     break;
}
default:
{
     default_statement
}
</code>```

答:
Programming languages often provide many different constructs which allow you to express similar logic using different syntax.

if/else statements do not "fall through" to each another unconditionally;   the else keyword prevents any further else-if conditions being evaluated just as a break at the end of a case-block gets you out of a switch, however creating a set of standalone ifs (without using else) will cause each if condition to be evaluated on its own.

Coversely, removing the break keyword from the end of your case blocks will cause the flow of execution to unconditionally keep falling through to the next case until either a break/return/goto is encountered or the end of the switch block has been reached.

There are (rarely) situations where switch-case fallthrough is considered to be useful; however its more common, and usually more idiomatic to want each case block to be treated on its own.

if-else and switch-case are both constructs which allow you to express selection (decision making) in a programming language;  sometimes the choice between the two is down to personal style, other times there are compelling reasons to choose one over the other - A similar choice exists when choosing for-vs-while to express repetition.

Title: If-Else V.S. Switch end of flow


答:
I was wondering the if if-else statements, is like a switch statement that does not have a break statement.

That's backwards. Kind of.

An if, else if, ... else sequence in which all of the tests are all simple equality tests on the same variable of the form (variable == value) or ((variable == value1) || (variable == value2) ...) can be converted to a switch statement on that variable. The (variable == value) tests become case value:, and the body of the if (or else if) becomes the body of the case, but you need to add a break statement at the end of the case body. The ((variable == value1) || (variable == value2) ...) tests become a sequence of cases of the form case value1: case value2: ... case valuen: An if sequence with more complex tests is in general distinct from a switch statement.

If every case in a switch statement ends with break, that switch statement can always be rewritten as an if, else if, ... sequence. This conversion from a switch to an if sequence is also possible when fall through is limited to things such as case A: case B: ... case N: do_something(); break; Fall through in which a non-empty body falls through to another non-empty body is not directly convertible to an if sequence.

Title: If-Else V.S. Switch end of flow

Body:
I was wondering the if if-else statements, is like a switch statement that does have a break statement.

```<code>if( boolean_expression_1 )
  statement_1
else if( boolean_expression_2 )
  statement_2
else
  default_statement
</code>```

Is the same as:

```<code>switch( controlling_expression )
{
case: ( boolean_expression_1 )
{
     statement_1
     break;
}
case: ( boolean_expression_2 )
{
     statement_2
     break;
}
default:
{
     default_statement
}
</code>```


答:
Although thinking about an if-else block as being like a switch statement without a break might be a helpful abstraction for a new programmer, it is not a perfect comparison.

Switch is probably closer related to "goto". Granted, Java doesn't have Goto, but the language was built upon ideas from other languages like C that did. The "case" and "default" labels are not really any different than any other jump target for a goto statement, so the expected behavior would be to continue executing the next line of code within the block (the entire switch statement is the block). This is explained further in one of the answers on a related question: Why do we have to use break in switch? So we end up with the case that you need a break statement to tell your program you're done executing this block. You could use break in other types of statements such as a for or while loop similarly.

In languages such as java that use short-circuiting, in an if-elseif-else block, if the condition for the first case of the if statement is true, the else if and else block conditions will not be evaluated. After an if it is expected that you will either find a block of code enclosed braces {} or a single statement. By definition, else means "otherwise" or that the previous condition was not true, it would be a bit contradictory to let the code fall through.

Title: If-Else V.S. Switch end of flow


问:
Why do .Net books talk about stack vs heap memory allocation?
It seems like every .net book talks about value types vs reference types and makes it a point to (often incorrectly) state where each type is stored - the heap or the stack.  Usually it's in the first few chapters and presented as some all-important fact.  I think it's even covered on certification exams. Why does stack vs heap even matter to (beginner) .Net developers?  You allocate stuff and it just works, right?</p>

答: You have to understand how memory allocation works to use it efficiently even if you don't have to manage it explicitly. This applies to pretty much every abstraction in computer science.</p>


问:
Is a coding standard even needed any more?
I know that it's been proven that a coding standard helps enormously.  However, there are many different tools and IDEs that will format to whatever standard the programmer prefers.  So long as the code's neat/commented (and not a spaghetti mess), I don't see the need for a coding standard.

Are there any arguments for the development of a coding standard (we don't have one, but I was looking into creating one)?

答:
Coding standards are not just about the favored parameters for indent -- they also include naming conventions, commenting conventions, and a large number of possible recommendations for idioms, language feature use, etc.

More to the point, you still need to document all this somewhere.  And finally, not everyone will want to use an IDE that reformats code that way...


答:
If you use a consistent style within a team, your code becomes easier to read. When your code becomes easier to read then your team will be more productive. They will be more productive because they don't have to mentally parse the code, and can focus on the logic rather than the syntax when reviewing and maintaining the code.

If each person lets the IDE reformat the code to their choosing you have one of two problems: either you must make sure you always convert it back to the original format when saving, or suffer from the fact your diff's will show a lot of noise, making it harder to see what has changed in the logic of the code.

Title: Is a coding standard even needed any more?

Body:
I know that it's been proven that a coding standard helps enormously.  However, there are many different tools and IDEs that will format to whatever standard the programmer prefers.  So long as the code's neat/commented (and not a spaghetti mess), I don't see the need for a coding standard.

Are there any arguments for the development of a coding standard (we don't have one, but I was looking into creating one)?


答:
Mentoring Can Be Cross Functional

Mentors don't always need to be experts in what you are focused on.  If you use an unusual programming language, that still leaves about 99 non-language topics in software development that you could be coached in.  Some of my recent mentors have been involved in business development, hardware, or systems engineering, even though I am primarily involved in software.

Many Kinds of People Can Be Your Mentor

A good thing to look for is someone who is now where you would like to be in five years.  A mentor like this is not always available, so other alternative include a sage who has way more experience, but might not be in a formal leadership role anymore, a reverse mentor who is less experienced (or heaven-forbid, younger) but has perspectives on tools and techniques that can be of benefit.

Is Your Mentor Also Your Sponsor?

In addition to mentors, sometimes it is critical to have a sponsor.  If you are trying to move up in an organization, if you have a mentor who gives great advice but does not influence your chain of command in your favor, you may be disadvantages relative to someone who has a mentor who sponsors them as the lead, project owner, or manager of a project that earns them a more influential role or a promotion.

Cross Company Mentors and Networking

If you are already the tech director, you may need to look outside your company for your mentor.  There is strength in numbers, so networking with many people in a shallow way can be surprisingly valuable.  I have generally thought that to be valuable, your engagement with other professionals needed to have the depth that comes from working together or extensive, frequent, or lengthy association.

How Big is Your Pond?

You mention that you have been R & D head and tech director, but you don't feel like you are that experienced.  Confession is good for the soul, if not the reputation.  I have a similar confession.

At one point, I considered my career to have been divided into two parts.  In the first, I worked on a lot of teams where I was either the only software developer or the developer with the most college.  The second started when I hired on with a Fortune 100 company and worked with a distinctly higher grade of developer.  The contrast was essentially like being a big fish in a small pond to being a small fish in a big pond.

Trading Up

Making the change from small independent companies meant that I had much less status in the organization.  But there still was some status.  Developers were still valued both with higher pay and a fairly high degree of control over the work.  I could also influence fellow team members (although not from the top).  There were a lot of role models.  Having plenty of competition forced me to toughen up technically and in understanding how what I did provided value to the organization and my teams.

I have previously ignored my gut instinct about roles and mentors and paid a price.  Intuition is sometimes a feeling that comes out of a synthesis of experience.  My vote would be that if it feels wrong, it probably is wrong and deserves attentive investigation.  It sounds like you are concerned about your experience and lack of a mentor, explore your options.

Would you perhaps find growth, satisfaction, and other benefits by migrating to a bigger, more aggressive company?  Bigger is not always better, but sometimes has the advantage of diverse people that results in diverse working relationships, and diverse project experiences.  Many of the luminaries of Silicon Valley have had or have served as mentors to people who as a result can chart their way to success more quickly and efficiently.  One of my classmates from grad school followed the call to join Linked In and is experiencing that culture, playing a much higher level game.

Mentor Benefits

While a mentor can be like a professor, I think that unless you have one who looks at your work product frequently, or serves like a master in the master/apprentice relationship, skill training and professional education are secondary.  I think the greatest things mentors share include advice about growth, role modeling of good decisions and balance between workplace values, and steady, objective and sound judgment in times of crisis.

A piece of advice my grandfather gave me many times was that people are only teachable when they are humble.  Be careful about statements like "I am way beyond books", and try to learn from everyone.  To build a relationship with a mentor, be sure that you are respectful and receptive and that you show appreciation.  It will also be important to follow their advice because unless they are extremely patient, they generally will invest their time where it will be turned to action.

Title: Improving without mentor


答:
Short Answer: Yes, it does reflect the quality.

What is it and why we need it?

Coding standards are very important piece of high quality software. They do increase productivity in the development process, make code easier to maintain, and keep code from being tied to one person or team. Consistency in coding standard also differentiate prematurely created code from well crafted art.

OK, every developer knows that coding conventions are good. But where should standards come from?

It is mostly dictated by the vendor who owns the product. Every developer can choose from many industry coding standards. Some companies Microsoft, Oracle and Sun Microsystems offer guidelines.

Are there any arguments for the development of a coding standard (we don't have one, but I was looking into creating one)?

Yes, there are industry standards that are recommended to be used. However, each coding standard is specific for the development platform. Thus, coding standards are mostly language specific. For example, Java has a different standard than .NET. For example C# .NET is using that standards in the this reference.

Common standards

The common standards do not have dependencies on any programming language. In addition to the vendor offered standards, aka the mentioned industry coding standards, there are different programming notations like Hungarian Notation or CamelCase. I think Microsoft .NET coding standards were initially based on CamelCase notations.

Team coding standards and guidelines

In think, every development team should agree on coding standards as soon as project is started. The coding guidelines is usually created by Team Lead or chief Architect of the company. It is usually an open document to be followed and improved upon a need. For example, in our company we have Wiki pages where this document is uploaded and available for the company developers.


答:
However, there are many different tools and IDEs that will format to whatever standard the programmer prefers.

Good luck with that. My experience, there are a tiny number of tools (zero!) that can properly reformat code from format X to format Y. There are just too many things that get in the way. Tabs vs spaces, multi-line statements, etc. Just look at GNU's implementation of the C++ standard library files. What you can do is make your IDE do is to always use spaces instead of tabs and just don't bother reformatting foreign code. Now your code looks the way you like it, and the foreign code looks the way the original author wrote it.

A specific indentation style is the last thing a coding standard should specify. That's verging on starting a programming religious war. IMO, a coding standard should specify a reasonable suite of acceptable indentation styles, but leave the specifics to the authors of a package. Indentation style is, or should be, a tiny part of a coding standard. Rule number zero of coding standards: Don't sweat the small things. Indentation style is a small thing.

Bigger things:

How do I name things?

Are certain parts of the language off limits?

Does the code need to compile clean, and with what compiler settings?

Does the code have to pass certain metrics?

What kind of testing is needed?

What kind of documentation is needed, both in the code (comments) and elsewhere?

Most important, how do I get a waiver to the standard?

Addendum

Perhaps even more important is what not to put in a coding standards. Topics such as how to write requirements do not belong in the coding standards. Details on testing do not belong, either. A project should not use the coding standards as a stand-in for the project management plan, the test management plan, the verification and validation plan, etc. The goal of the coding standards is to improve code safety, quality, understandability, maintainability, and other "ilities". There are lots of ways to ensure that this won't happen. Just a few: Making the standards a book as complex as some country's tax laws, inciting programming religious wars, having bad naming conventions.

Coding standards can have unintended consequences. Example: Some fool of a project engineer is going to interpret the "no magic numbers rule" to mean that if (index == 0) {...} and for (ii = 0; ii < 3; ++ii) {...} must be changed to if (ZERO == index) {} and for (ii = ZERO; ii < NUMBER_OF_DIMENSIONS_IN_THE_UNIVERSE; ++ii) {...} Don't laugh. I've seen it happen. Nowadays when I write a coding standard it's a "no magic numbers guideline" rather than a rule to counteract this kind of foolishness.

The coding standard is not the number one defense against bad programming style / dangerous coding practices. The code review is. Despite many years of automation, there is still nothing better than a having somewhat subjective set of human eyes look at and pass judgement on a chunk of code.


答: I Google for a tutorial on the language and follow that, usually.  If there isn't one somewhere on the language's website then that's not a great sign.  More often than not, I've looked up some examples before even downloading the language toolkit in order to get a feel for what to expect (there's so many languages popping up that you can't hope to try them all, so best to stick to languages with features you find interesting).</p>

Title: What's the first thing you write when trying out a new language?

Body:
I think everyone has their own program or set of features beyond "Hello World!", that they use when trying out a new language.

Mine is a guessing game:

```<code>I'm thinking of a number 1-10, guess what it is!
Guess: 3
Nope, too low!
Guess: 7
Nope, too high!
Guess: 5
Yes, You win!
Play again (Y/N)? N
</code>```

What do you write?


问:
How to convince a non-technical client that their application spec needs to be simplified?
Often times I am faced with the situation where a new client comes to me with an application that has literally 100s of unnecessary features and it is quite clear that things need to be drastically simplified for the project to have any chance of succeeding. How do you convince the client to take a more Minimum Viable Product (MVP) approach and simplify?

edit:

So the current top answer is to provide the client with a time/cost estimate for the huge application. I'm not too fond of this answer because it doesn't address the real problem with this situation. And that is - it's a bad practice to spec out a massive application and then try and build it from the get go. I feel much more comfortable initially building a small, simple MVP foundation. And then adding small features to that foundation one by one. So how do I convince the client to approach building software in this way?

答:
A historical example of an application that ended up over budget and behind schedule due to excessive requirements is the FBI's Virtual Case File. It was intended to replace several dozen existing applications, and they all had to work completely, at once, on switch over. The project was ultimately cancelled. What would have been successful was to architect a framework, and incrementally replace individual applications into the new system. Instead, politics and infighting lead to every application stakeholder declaiming that their app was the most important one, and everyone goldbricked their specs with "must haves" from all the features they wanted added to the existing app. By the end, the volume of change requests written each day exceeded the amount of code actually written each day.

I've seen the "I gotta have it all" work in 2 cases. In one, the large financial client (using waterfall of all things), had 40 different systems (our company made one of the 40) get replaced and made operational in one fell swoop. Integration testing and communication were huge issues. My estimate is that they burned about $100k/day in conference calls (when you count the billing rate of everyone on the calls). In both of the cases, it took strong negotiators to hammer out a list of what was going to be delivered and then nailed everyone's feet to the ground. There was no moving of goalposts, no renegotiation. Both jobs ended up on-time, and on-spec. One was way over budget, the other was on-budget. For this you need very good project managers who know what their teams can deliver (the sort who can say that feature Q takes 3.5 weeks to make and test - and are at least 90% accurate in delivery promises).

Lacking the excellent PMs, negotiators and metrics, I'd advise pushing the client towards incremental deliveries. If they still want the entire gold brick at once, they might be better served by helping them find some other consultancy. Sometimes the best answer is "we can't help you."


答:
I'm going to take the controversial opinion and say no you don't need a coding standard. Either the rules are, as you say, IDE enforcable guidelines, general best practices that everyone at every company should follow, or they are case-by-case per-team judgement calls that should be made by more than one person on a capable team via pair programming or code reviews.

Things like How should we name this variable? What language features should we use? Should we avoid? What testing is best? These are best left unanswered until we encounter the narrowly defined problem that we are working on right now.

Crystallized from these minute decisions, informal standards/patterns within teams may arise, based on the intersection with the current problem domain and the technologies in use. Codifying these means we think that things like the naming standard, appropriate language subset, etc used on these projects, based on hundreds of micro decisions, and informally adopted by these teams should guide every project moving forward.

In principal it sounds like a great thing, but in reality it just becomes a magnet for politics. What tools can we force everyone to use? What do I want to force other people to avoid? If everyone agreed on these questions, we wouldn't need a standard. We'd just do it. In my experience standards come out of a desire for one subset of the developers to exercise control over another subset. Typically this type of politics and the technological policing that follows it only stifles innovation rather then providing guidance.

If you want real guidance, instead of reading a standard with a bunch of unhelpful rules, go find capable members of your team and ask them what they think. What have they been burned by? How do they suggest you write code? You'll get a variety of useful answers with a lot of valuable experience to back it up. You'll see a lot of intersection based on common experience. Instead of the monoculture enforced by the standard, you'll also see a lot of diversity which can only help you see lots of valid ways to solve problems.

And when somebody tells you not to do something cause of a rule in the "standard" but has no experience or reasonable backup to their claim, ignore them. Here the standard hasn't served anyone or made anyone a better developer.


答:
It seems like you just need

```<code>struct xy {float x; float y}
</code>```

and

```<code>class affine_transformation
{
  float m[6];

  xy transform(xy input) {...}
  ...
  methods rotate(), shear(), scale(), translate()
};
</code>```

See
http://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm

Body:
It seems like you just need

struct xy {float x; float y}

and

class affine_transformation
{
  float m[6];

  xy transform(xy input) {...}
  ...
  methods rotate(), shear(), scale(), translate()
};

See
http://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm


问:
Should coding standards be enforced by the continuous integration server?
Should coding standards/style be enforced by the continuous integration server running static analysis tools (ex. PMD, StyleCop/FxCop) and failing the build if the standards are not followed? What types of rules should not be used to fail the build?</p>

答:
It will depend on your ultimate goal and strategy.

Forcing all good mentioned standards in CI server might seem very lucrative. However, it might not be practical for the big (more than 6 developers) development team, if it is done on each commit to the server. Waiting your server to respond after commit should NOT be long delay. It may potentially cause some down-time.

However, It is totally legitimate to block a commit if code (the actually change-set) has dependency issues or does not compile. However, failing code because of code layout and some naming convention might be too sever and not vital restriction for the CI server commit rules.

But it is very likely to be helpful rule if applied during the evening build.

In addition, re-factoring tools can assist in implementing and learnig standards - like the Resharper or JustCode usage by developers.


答:
Coding Standards should be there for a reason... and non-compliance should be checked.

However, not all violations should be considered as errors - just as not all compilation violations are.  Where you draw the line has to be a company and a tool decision.

For example, MISRA defines its rules as Required and Advisory... I would suggest that Advisories would allow the build to proceed.

Title: Should coding standards be enforced by the continuous integration server?

Body: Should coding standards/style be enforced by the continuous integration server running static analysis tools (ex. PMD, StyleCop/FxCop) and failing the build if the standards are not followed? What types of rules should not be used to fail the build?</p>


答:
It's not completely unheard of and you will know if it will work for you only by trying it out. There are some steps that you could be taken before that.

First the team should decide on the standards together. Then tools such as ReSharper should be used to tell developers if they are not adhering to standards. Doing peer reviews on every task could further help.

After those steps have been taken it could be considered to put coding standard checks to CI-server. However it should still be considered if it's wise to have build break for not adhering to coding standards. The risk is that you will have lot of broken builds which might dillute the meaning of broken build.

Instead of making the build break, you could run the tools and have them create reports. If coding standard violations seem to be increasing, you can get the team together and figure out why it's happening.


答:
As to WHY do they cover the topic, I agree with @Kirk that it's an important concept, that you have to understand. The better you know the mechanisms, the better you can do to make great applications that performs smoothly.

Now Eric Lippert seems to agree with you that the topic is not correctly covered by most authors. I recommend you read his blog to achieve a great understanding of what's under the hood.

Title: Why do .Net books talk about stack vs heap memory allocation?

Body: It seems like every .net book talks about value types vs reference types and makes it a point to (often incorrectly) state where each type is stored - the heap or the stack.  Usually it's in the first few chapters and presented as some all-important fact.  I think it's even covered on certification exams. Why does stack vs heap even matter to (beginner) .Net developers?  You allocate stuff and it just works, right?</p>


答: There is https://bitbucket.org or https://github.com/ if you want free private repositories using git, and when you're done you can turn it public.</p>


问:
OS choice for functional developing
I'm mainly a .NET developer so I normaly use Windows/VisualStudio (that means: I'm spoiled) but I'm enjoying Haskell and other (mostly functional) languagues in my spare time.

Now for Haskell the windows-support is ok (you can get the Haskell-Platform) but latley I tried to get a basic Clojure/Scheme environment set up and it's just a pain on windows.

So I'm thinking about trying out another OS for better tooling and languague support.
Of course that leaves me with MacOS or some Linux distribution.

I never used MacOS before and of course Linux would be cheaper (free) and I don't think I can parallel-boot MacOS on your normal PC-Hardware (can you?).
PLUS: I don't have a clue about the tools you can use on those (to me) forign OSs.

To make it short: I want to explore more Haskell, Clojure, Scala, Scheme and of course need at least good tooling for JavaScript/HTML5/Css.
Support for .NET/Mono/F# would be great but for this I will still have my Win7 boot.

So I like to know:
 - what is your prefered OS, Distribution (is Ubuntu viable?)
 - what Editor/IDE are you using

Thank you for your help!

PS: I'm not sure if this is the right place for this question but I surely hope so - if not please let me know where I should move this to (StackOverflow don't seem to be the right place IMHO)

答:
Simon Peyton-Jones, one of the creators of Haskell is a Windows user and from what I gather, Haskell has excellent windows support.

Your question is a little vague to be honest, your choice of OS is not tied to the paradigm of the language you are using.

Personally I believe that outside of the C# and Java world (where development environment is dictated by your IDE), a development environment should always be a flavour of Unix, whether it be BSD, Linux or OSX.

Title: OS choice for functional developing


答:
Well, I thought that's the whole point of managed environments. I'd even go as far as calling this an implementation detail of the underlying runtime that you should NOT make any assumptions about, because it could change at any time.

I don't know much about .NET, but as far as I know, its JITted before execution. The JIT for example could perform escape analysis and what not and all of a sudden you'd be having objects lying on the stack or merely in some registers. You cannot know this.

I suppose some books cover it simply because the authors attribute great importance to it, or because they assume their audience does (e.g. if you wrote a "C# for C++ programmers" you probably should cover the topic).

Nonetheless, I think there is not much more to say than "memory is managed". Otherwise people might draw wrong conclusions.


答:
Should coding standards/style be enforced by the continuous integration server running static analysis tools (ex. PMD, StyleCop/FxCop) and failing the build if the standards are not followed?

Those continuous integration checks need to be very, very fast. Any significant delays will mean your programmers are going to commit and lose track of their thought process while waiting for the results. Make it longer and they will commit and get a cup of coffee or chat with their office mates about the latest bungled performance of some sports team. Those delays are highly counterproductive. Some things are best left to the nightly build or the code review.

What types of rules should not be used to fail the build?

The subjective ones, to start with. How do you enforce the "Code shall be self-documenting or well-commented" rule? The "no magic numbers" rule? Those are things best left to the code review.

Another category is violations to the rules that have already been granted a waiver. Given any sizable code base, there is inevitably going to be some chunk of code where violating the standard is exactly the right thing to do.