答:
I find Pete's answer very good and I would like to add some consideration and one example. A very interesting discussion regarding the use of exceptions versus returning special error values can be found in Programming in Standard ML, by Robert Harper, at the end of Section 29.3, page 243, 244.

The problem is to implement a partial function f returning a value of some type t. One solution is to have the function have type

```<code>f : ... -> t
</code>```

and throw an exception when there is no possible result. The second solution is to implement a function with type

```<code>f : ... -> t option
</code>```

and return SOME v on success, and NONE on failure.

Here is the text from the book, with small adaptation made by myself to make the text more general (the book refers to a particular example). The modified text is written in italics.

What are the trade-offs between the two solutions?

The solution based on option types makes explicit in the type of the function f the possibility of failure. This forces the programmer to explicitly test for failure using a case analysis on the
  result of the call. The type checker will ensure that one cannot use
  t option where a t is expected. The solution based on exceptions does not
  explicitly indicate failure in its type. However, the programmer is
  nevertheless forced to handle the failure, for otherwise an uncaught
  exception error would be raised at run-time, rather than compile-time.

The solution based on option types requires an explicit case analysis on the result of each call. If “most” results are
  successful, the check is redundant and therefore excessively costly.
  The solution based on exceptions is free of this overhead: it is
  biased towards the “normal” case of returning a t, rather than the
  “failure” case of not returning a result at all. The implementation of
  exceptions ensures that the use of a handler is more efficient than an
  explicit case analysis in the case that failure is rare compared to
  success.

[cut] In general, if efficiency is paramount, we tend to prefer exceptions if
  failure is a rarity, and to prefer options if failure is relatively
  common. If, on the other hand, static checking is paramount, then it
  is advantageous to use options since the type checker will enforce the
  requirement that the programmer check for failure, rather than having
  the error arise only at run-time.

This as far as the choice between exceptions and option return types is concerned.

Regarding the idea that representing an error in the return type leads to error checks spread all over the code: this need not be the case.
Here is a small example in Haskell that illustrates this.

Suppose we want to parse two numbers and then divide the first by the second. So there could be an error while parsing each number, or when dividing (division by zero). So we have to check for an error after each step.

```<code>import Text.Read

parseInt :: String -> Maybe Int
parseInt s = readMaybe s :: Maybe Int

safeDiv :: Int -> Int -> Maybe Int
safeDiv n d = if d /= 0 then Just (n `div` d) else Nothing

toString :: Maybe Int -> String
toString (Just i) = show i
toString Nothing  = "error"

main = do
         -- Get two lines from the terminal.
         nStr <- getLine
         dStr <- getLine

         -- Parse each string and divide.
         let r = do n <- parseInt nStr
                    d <- parseInt dStr
                    safeDiv n d

         -- Print the result.
         putStrLn $ toString r
</code>```

The parsing and the division are performed in the let ... block. Note that by using the Maybe monad and the do notation, only the success path is specified: the semantics of the Maybe monad implicitly propagates the error value (Nothing). No overhead for the programmer.

Body:
I find Pete's answer very good and I would like to add some consideration and one example. A very interesting discussion regarding the use of exceptions versus returning special error values can be found in Programming in Standard ML, by Robert Harper, at the end of Section 29.3, page 243, 244.

The problem is to implement a partial function f returning a value of some type t. One solution is to have the function have type

f : ... -> t

and throw an exception when there is no possible result. The second solution is to implement a function with type

f : ... -> t option

and return SOME v on success, and NONE on failure.

Here is the text from the book, with small adaptation made by myself to make the text more general (the book refers to a particular example). The modified text is written in italics.

What are the trade-offs between the two solutions?

The solution based on option types makes explicit in the type of the function f the possibility of failure. This forces the programmer to explicitly test for failure using a case analysis on the
  result of the call. The type checker will ensure that one cannot use
  t option where a t is expected. The solution based on exceptions does not
  explicitly indicate failure in its type. However, the programmer is
  nevertheless forced to handle the failure, for otherwise an uncaught
  exception error would be raised at run-time, rather than compile-time.

The solution based on option types requires an explicit case analysis on the result of each call. If “most” results are
  successful, the check is redundant and therefore excessively costly.
  The solution based on exceptions is free of this overhead: it is
  biased towards the “normal” case of returning a t, rather than the
  “failure” case of not returning a result at all. The implementation of
  exceptions ensures that the use of a handler is more efficient than an
  explicit case analysis in the case that failure is rare compared to
  success.

[cut] In general, if efficiency is paramount, we tend to prefer exceptions if
  failure is a rarity, and to prefer options if failure is relatively
  common. If, on the other hand, static checking is paramount, then it
  is advantageous to use options since the type checker will enforce the
  requirement that the programmer check for failure, rather than having
  the error arise only at run-time.

This as far as the choice between exceptions and option return types is concerned.

Regarding the idea that representing an error in the return type leads to error checks spread all over the code: this need not be the case.
Here is a small example in Haskell that illustrates this.

Suppose we want to parse two numbers and then divide the first by the second. So there could be an error while parsing each number, or when dividing (division by zero). So we have to check for an error after each step.

import Text.Read

parseInt :: String -> Maybe Int
parseInt s = readMaybe s :: Maybe Int

safeDiv :: Int -> Int -> Maybe Int
safeDiv n d = if d /= 0 then Just (n `div` d) else Nothing

toString :: Maybe Int -> String
toString (Just i) = show i
toString Nothing  = "error"

main = do
         -- Get two lines from the terminal.
         nStr <- getLine
         dStr <- getLine

         -- Parse each string and divide.
         let r = do n <- parseInt nStr
                    d <- parseInt dStr
                    safeDiv n d

         -- Print the result.
         putStrLn $ toString r

The parsing and the division are performed in the let ... block. Note that by using the Maybe monad and the do notation, only the success path is specified: the semantics of the Maybe monad implicitly propagates the error value (Nothing). No overhead for the programmer.


问:
Which file format should I use as an alternative to my current Excel worksheet?
My .NET application does its work and then creates a report (an Excel worksheet). That report contains thousands of short text strings [KEY - VALUE]. So Excel worksheets suites very well, one column holds the keys and another holds the values. It's easy to examine this reports.

But because of performance issues now, I'm trying to find another file format to create reports in .NET in a way that's easy to manually examine, like a table or plain text.

What kind of file format would you recommend?

答:
What about Comma-separated values(CSV)?

simple text-based format

can be edited via Text editor

Excel and a lot of other tools are able to read and/or write it

You just need to be aware of the fact, that not all CSV is CSV. There are a lot of flavours out there with different separators.

ContentLicense: CC BY-SA 3.0


问:
confusion on using nodejs within an actual web application or ide
I am new to using nodejs completely, and it seems to be pretty much the go to thing for everything right now. But I program in Visual Studio, and I'm a bit confused about how this works. I will cite an example;

One task I want to do is to get a list of all the files in a directory and all of its sub-directories, and return them as a string[] for a javascript .config file. I started searching for that and found a lot of answers, but they all kept going back to nodejs, for instance, this one, and this one, and this one.

I really wasn't looking for anything having to do with nodejs, it just seems to be part of every solution out there. I've installed it, and gotten it to where I can do some simple things like create a very basic server that listens to a port - thanks to simple tutorials written for a moron like me - but I'm having a hard time figuring out how to use these kinds of things in my real programs - specifically ASP.NET MVC. I've searched pretty hard on this topic too, and discovered things like iisnode and the like that do some partial integration.

But even with all of this, this wealth of information, I am extremely confused.

I understand that I can use it from a command line, like PowerShell, I can run commands from a terminal, and install packages into projects, but I'm having a hard time seeing and finding how this actually translates into literal, real usage in an existing application. I have scoured around for days and days for examples, I've read at least 3 books on nodejs, The Node Beginner Book, What is Node, and Professional Node.js and to be very honest I am still as lost as ever.

Everything I read keeps assuming I am doing things from the command line or a terminal, but all of the applications I see for node assume you're writing a web application. I'm having a really hard time wrapping my head around how you use it within an application. Can anyone assist me with this? Perhaps a working example of an actual program that uses node? I'll take almost anything at this point, though ASP.NET MVC is my core system of choice.

I was originally going to post this on StackOverflow, but someone suggested that this community was more appropriate for this question.

Update

I want to make a more clear example of what is confusing me, I'm already learning because of the 1 proposed answer, but let me give more examples.

I program in Visual Studio, it has no real concept of node.js - in fact, if I try to do things that will run against node, it gives me problems. I often have to code anything related to node in WebStorm from JetBrains.

I understand that I can 'compile' things with node, what I don't understand is how I can invoke it within my program, not inside of a command line. For example let's say there is a node module that takes an array and does something to it - for sake of example let's say that it sorts everything in the array alphabetically, and it is a module called supersort.

So if I were at the console, I would just type in ...

node supersort.js

Okay, but now I'm not at the command line. I have published my web application. My user is at a page, let's say /account/history and they are seeing a list of every product they have bought. For the sake of argument, say I've got that list as a object[] or string[] - I realize that is completely absurd and it would be far more complex, but just jive with me.

I want to run supersort on this page. But it's live! How do I do it? How do I run this module on their live, active data without manually being there at the console? Is there a set of javascript files I'm supposed to download and call http requests a certain way? Do I wire up a special IHttpHandler in IIS? I think you can start to see where I am lost.

Update 2

Attempting to further emphasize my question, I'll try and cite a more specific example. I want to use the library Q.js in my ASP.NET MVC application. Now, there is a version 1 that I can seem to run out of the box, but I want to try out version 2 - you can find it linked Q.js v2 (beta)

So I am using Visual Studio, and I'll download the q.js file and load it up, but immediately we already have trouble now - if you look at the file's source code right away I see this.

```<code>require("collections/shim");
var WeakMap = require("collections/weak-map");
var Iterator = require("collections/iterator");
var asap = require("asap");
</code>```

Now I certainly don't have folders with those names in my application - and even though I have node.js installed, putting this file in a

答:
node.js (not nodejs, as you seem to put it), is a server side technology.

In that respect, it is like Apache or IIS - web servers.

It can and mostly is used as a backend for web applications (and web based APIs) - it serves up whatever it is coded to serve up (in that respect, no different from Apache and IIS).

If you code up a web application (serving HTML and whatever else is involved in writing a web application) in node, that's what it would be serving, a web application.

The reason you see a lot of discussion of the command line/terminal is that there is no GUI for node. One is expected to use an editor to write the node application and run it from the command line. It is not wrapped up in a service for you, like IIS.


问:
How can a manager ensure developers are pushing up to the origin every day?
Our team has been using Git for a couple of years.  I love it, after previously using Visual Source Safe, SVN and TFS.  However, my manager has been getting increasingly agitated about it and is threatening to go back to SVN or TFS.

The problem is human nature: Developers forgetting to push up to the origin every day, then going sick or taking a holiday, and someone else having to pick up the project, and not knowing whether the latest code is in the origin, or whether it is sitting on the absent developer's machine.  There is no visibility of which developer was the last to work on which file, as there is with a centralized source control system.

I really want to avoid going back to SVN of TFS.  So my question is: How can a team use Git successfully in a way that takes into account human nature (forgetfulness, laziness, etc)?  How can I ensure that at the end of every day the latest code has been pushed to the origin so that someone else can step in and take over the next day, if need be?

Is the answer continuous integration?  I've read about workflows that include having to push to a CI branch on the origin to build the project.

答:
The more eyes are set on any given process, the more likely it is to improve.

Use a continuos integration tool like Jenkins. They will know you are looking at a web report showing their pushes, their amount of work done and the quality of their code.

You only sweep under the rug when nobody is watching.


问:
Good or bad practice to mask Java collections with meaningful class names?
Lately I've been in the habit of "masking" Java collections with human-friendly class names. Some simple examples:

```<code>// Facade class that makes code more readable and understandable.
public class WidgetCache extends Map<String, Widget> {
}
</code>```

Or:

```<code>// If you saw a ArrayList<ArrayList<?>> being passed around in the code, would you
// run away screaming, or would you actually understand what it is and what
// it represents?
public class Changelist extends ArrayList<ArrayList<SomePOJO>> {
}
</code>```

A colleague pointed out to me that this is bad practice, and introduces lag/latency, as well as being an OO anti-pattern.  I can understand it introducing a very tiny degree of performance overhead, but can't imagine it's at all significant. So I ask: is this good or bad to do, and why?

答:
I suggest you, as others already mentioned, to use composition over inheritance, so you can expose only methods that are really needed, with names that matches to intended use case. Do users of your class really need to know that WidgetCache is a map? And be able to do with it anything they want? Or they just need to know that is a cache for widgets?

Example class from my codebase, with solution to similar problem that you desribed:

public class Translations {

    private Map<Locale, Properties> translations = new HashMap<>();

    public void appendMessage(Locale locale, String code, String message) {
        /* code */
    }

    public void addMessages(Locale locale, Properties messages) {
        /* code */
    }

    public String getMessage(Locale locale, String code) {
        /* code */
    }

    public boolean localeExists(Locale locale) {
        /* code */
    }
}
```

You can see that internally it's "just a map", but public interface is not showing this. And it have "programmer-friendly" methods like appendMessage(Locale locale, String code, String message) for easier and more meaningful way of inserting new entries. And users of class can't do, for example, translations.clear(), because Translations is not extending Map.

Optionally, you can always delegate some of needed methods to internally used map.

Body:
I suggest you, as others already mentioned, to use composition over inheritance, so you can expose only methods that are really needed, with names that matches to intended use case. Do users of your class really need to know that WidgetCache is a map? And be able to do with it anything they want? Or they just need to know that is a cache for widgets?

Example class from my codebase, with solution to similar problem that you desribed:

public class Translations {

    private Map<Locale, Properties> translations = new HashMap<>();

    public void appendMessage(Locale locale, String code, String message) {
        /* code */
    }

    public void addMessages(Locale locale, Properties messages) {
        /* code */
    }

    public String getMessage(Locale locale, String code) {
        /* code */
    }

    public boolean localeExists(Locale locale) {
        /* code */
    }
}

You can see that internally it's "just a map", but public interface is not showing this. And it have "programmer-friendly" methods like appendMessage(Locale locale, String code, String message) for easier and more meaningful way of inserting new entries. And users of class can't do, for example, translations.clear(), because Translations is not extending Map.

Optionally, you can always delegate some of needed methods to internally used map.


问:
How to support multiple firmware versions?
I'm working on an app which talks to a bluetooth low energy (BLE) device and exchanges customized data with it. Our team has defined the data models and there's a method that will parse the data payload and assign values to the corresponding characteristics. It works all fine until we have introduced a new firmware.

In this new firmware some values in the data payload have been re-defined or the offset of a specific value has been changed. So the parsing method will need to be updated/re-written according to the new payload definition. Then here comes the problem: both two versions of the firmware need to be supported! Of course I could write a lot of if/else in the parsing method right now, but what happend if 3 other firmware updates arrive one after other? I can imagine the code will become hard to read and lose it's simplicity.

I'm wondering if there's an elegant way to manage the co-existence of firmware versions. Maybe a design pattern that can be adopted here?

To make it more specific:

In my model class Temperature I've the following properties:

```<code>@property (nonatomic, readonly) float temp_outside;
@property (nonatomic, readonly) float temp_inside;
</code>```

The library has to support 3 different firmware versions:

V1 does only support temp_outside

V2 does support temp_outside and temp_inside

V3 does support temp_outside and temp_inside, but temp_inside has to be obtained differently compared to V1 & V2

Assuming the firmware provides their information within the manufacturer data of the advertisings as raw data:

V1 firmware: 00 42 0a

(byte 1: sw id, byte 2: protocol id, byte 3: temp_outside)

V2 firmware: 00 43 0a 10

(byte 1: sw id, byte 2: protocol id, byte 3: temp_outside, byte 4: temp_inside)

V3 firmware: 00 44 10 0a

(byte 1: sw id, byte 2: protocol id, byte 3: temp_inside, byte 4: temp_outside)

What is the best way to implement this? There are several things to consider:

The model has values which might not be filled by a specific firmware; should I have separate models per firmware or how can I make sure that only supported properties will be accessed?

The method responsible for parsing the bytes into the model has to support all firmwares. Should there be one method / parser with several conditions based on the protocol id or several parser classes?

The usage of the library within view controllers should be as convenient as possible.

答:
Your problem isn't so much that you need to support different firmware versions, but rather that all these firmware versions use slightly different protocols to communicate.

If you have any influence on the protocol used by the device's firmware, you should aim for a protocol that is both backwards and forwards compatible, so that a newer sender can communicate with an older receiver and vice versa.

For the protocol versions that you already have, you can use the Strategy pattern, where you have a parser for each protocol version as a strategy and you select the right parser based on the identification fields in each message (or in the first message).

Inside your Model classes (and your Views), you should plan for the possibility that not all properties are guaranteed to be available. The two ways to handle this is to have a secondary boolean property/method for each property to indicate if the value is available, or to use a special, out-of-bounds marker value to indicate the value is not available.


问:
Working with Javascript classes the right way
Comparable questions have surely been asked before but I'd like to hear some words about my specific way of implementing Javascript classes.

Let me first start with a Javascript example taken from a real-life application I've been working on recently.

Example

```<code>PageControl= new function() {
  var self= this;

  // example additional control bound to page control
  var grid= new GridControl();

  self.initialise= function() {
    // initialise form fields, controls etc.
  };

  // example function
  self.load= function(id) {
    // reloads form with new data
  };

  $(document).ready(function() {
    self.initialise();
  });
};
</code>```

Each page has its own PageControl instance with specific tasks solely relevant for the given page.

Question:

I'm not looking for alternative ways of how to implement it, I'd just want to know if the above example is bad or wrong code. The above structure has worked great so far, even if I work with sub controls like PageControl.grid.reload(); but I don't want to stick to error-prone code.

答:
There is no "right way" to write objects in javascript. There are multiple different techniques each with pros and cons, or just different flavors.

I personally like the style that you have declare "public" functions in your example because by my experience it helps lowering the learning curve for people with OOP background.

But it penalizes because you are re-creating every function on each instantiation and that as a cost. It also makes your objects unstubbable through tools like Sinon.js, because there isn't a prototype for it to mess with.

OwnerDisplayName: fmsf


问:
How should object identification be managed?
I have a java/swing application in (hopefully good) MVC structure. Here is a overview of my model classes:

One or more workers may work at one working location and one worker may work at different working locations (not at the same time, of course). A worker may have different types of a date assigned. The working location has a list of all its workers. Each date has a reference to its worker. All model objects are mutable.

For managing purposes I implemented a Database.java which is responsible for storing the model classes in java collection classes and at program close saving all objects into an xml file (I use java simple xml framework for this task). It has the following three lists: List<Working location>, List<Worker> and List<Date>. So the procedure is:

Load xml file on program start

Add/edit/remove model-objects to/in/from database (working with the collections of Database.java

Save all model-objects from the Database collections into the xml file on program exit

(If there is something bad in my mindset until now, please tell me a better way! I will really appreciate it.)

Here is the question:

What is the proper way of identifying model-objects?

I can think of two possibilities:

Use object references

(+) There is no extra code for handling the generation of new unique ids

(-) "Everyone" can edit the objects (Because this is a private project "Everyone" means only me)

Use unique IDs for every object

(-) more code

(+) database may return copies of the model objects to be edited and only when the controller calls the database's methods with the copyied model objects they will be updated

EDIT:

There was an important part which I forgot to mention: Multi-Threading and Multi-User

Both of them can certainly be answered with "No". The application will be some kind of one user planning software to replace the current "pen-and-paper-planning". I would say the main requirement is to avoid budgeting workers who are on holiday or not to forget to budget workers who come back from holiday the next day. Because this are the mistakes that often happen.

Also there is no need for deeper analysis of the model objects and therefore no need for complex database queries at the moment. Therefore I like the idea of using XML to create a standalone application. Or is there a good reason to blow up the code to fulfill unlikely requirements?

答:
First, the recommendations:

Use a simple file-based in-proc DB such as H2 DB or SQLite. This is almost as convenient as an XML file - you can keep using the same workflow as you have today. It also future-proofs your software to an extent.

EDIT: If you feel that using a relational DB is overkill, I would still recommend using immutable model objects with a unique identifier. In this way, only your database class can update the actual persistent state. This keeps the process intentional and centralized. It eliminates accidental modifications of the data. This will also make it easier to migrate to another DB if required later.

Now, the "why":

Is your application multi-threaded or multi-user? Using reference-based identity can mess up the internals of a model object if two threads try to modify it at the same time.

EDIT: Do remember, multi-threading can also happen in a single-user application. Async tasks, timers, etc. all create threads and may access your database unsafely.

To avoid this, you can use Immutable objects with unique id parameters. This ensures consistency for that single object. However, different threads may still modify different objects and make them go out of sync. This destroys the integrity of the database. Also, an error or exception can leave operations half done, again causing errors in the DB.

These are of course, the standard reasons as to why an ACID database is essential. Transactions and locking are provided just for this purpose.

Also, as @Birfl mentioned, you will soon hit the point of having to run complex queries on your data. XPath can help to a point, but after that, you will have to write code to search for specific data sets. This might affect performance as well.


答:
I'm not sure if it's bad or wrong, but it is confusing.

Your PageControl is not a class, it's an instance of an anonymous class. In javascript a class is a function object intended to be used with the new keyword to create instances of that class.

Your code uses the new keyword on an anonymous function.

What you're trying to accomplish, I think, is usually done using the IIFE (Immediately-invoked function expression) pattern.

```<code>PageControl= (function() {
  // you can create private variables and functions for use between your
  // functions, or add them to the self object to make them available.

  // example additional control bound to page control
  var grid= new GridControl();

  // Create your singleton w/ its member functions and possibly other properties
  // these functions can use 'this' to reference other members of the self object.
  // do it here so it can be referenced in the function closure used by
  // $(document).ready
  var self = {
    initialise: function() {
      // initialise form fields, controls etc.
    },

    load: function(id) {
      // reloads form with new data
    },

    // example additional control bound to page control
    grid: grid
  };

  $(document).ready(function() {
    self.initialise();
  });

  return self;
})();

// your page can call those methods on the PageControl
PageControl.load("myId");
PageControl.grid.reload();
</code>```

The key to the IIFE pattern is that you define a function expression that returns an object and then immediately call (execute) that function (function() {})();.

Title: Working with Javascript classes the right way

Body:
Comparable questions have surely been asked before but I'd like to hear some words about my specific way of implementing Javascript classes.

Let me first start with a Javascript example taken from a real-life application I've been working on recently.

Example

```<code>PageControl= new function() {
  var self= this;

  // example additional control bound to page control
  var grid= new GridControl();

  self.initialise= function() {
    // initialise form fields, controls etc.
  };

  // example function
  self.load= function(id) {
    // reloads form with new data
  };

  $(document).ready(function() {
    self.initialise();
  });
};
</code>```

Each page has its own PageControl instance with specific tasks solely relevant for the given page.

Question:

I'm not looking for alternative ways of how to implement it, I'd just want to know if the above example is bad or wrong code. The above structure has worked great so far, even if I work with sub controls like PageControl.grid.reload(); but I don't want to stick to error-prone code.

Body:
I'm not sure if it's bad or wrong, but it is confusing.

Your PageControl is not a class, it's an instance of an anonymous class. In javascript a class is a function object intended to be used with the new keyword to create instances of that class.

Your code uses the new keyword on an anonymous function.

What you're trying to accomplish, I think, is usually done using the IIFE (Immediately-invoked function expression) pattern.

PageControl= (function() {
  // you can create private variables and functions for use between your
  // functions, or add them to the self object to make them available.

  // example additional control bound to page control
  var grid= new GridControl();

  // Create your singleton w/ its member functions and possibly other properties
  // these functions can use 'this' to reference other members of the self object.
  // do it here so it can be referenced in the function closure used by
  // $(document).ready
  var self = {
    initialise: function() {
      // initialise form fields, controls etc.
    },

    load: function(id) {
      // reloads form with new data
    },

    // example additional control bound to page control
    grid: grid
  };

  $(document).ready(function() {
    self.initialise();
  });

  return self;
})();

// your page can call those methods on the PageControl
PageControl.load("myId");
PageControl.grid.reload();

The key to the IIFE pattern is that you define a function expression that returns an object and then immediately call (execute) that function (function() {})();.


问:
Should a view call a function?
Should a view call a helper function?

Say I pass in data from the DB to the view. The data is a unix timestamp. Should I make a call in my view to convert it to a human readable TS or should I convert it in the controller before passing it in? OR should I make a method in the model that converts...

Looking for a "best practice" or "secure coding" concerned answer.

答: Since human readability depends on the target output device (big screen TV, dashboard display, watch face, voice synthesis, Morse code tones/blinks, etc.), it might be best to customize this readability in the object most closely associated with the physical output device, likely the view object.  The model objects can keep and pass on a binary encoded or computationally suitable form.</p>

Title: Should a view call a function?


问:
Translating views in MVC
What is the best practice, when it comes to views' translation in MVC design pattern, in multilingual website:

Always have only one view file and translate its particular strings with a framework translation function.

Always have as many views as website supports, directly translated, one for each language, and let framework internals load particular language-specific view file for language currently selected by user.

Which of these two options should I use (if there isn't any third one) and why?

答:
The proper choice is using the single view with the strings stored in the appropriate localization framework for the view.

There are two main reasons for this:

It's DRY.  There is one view that is used for all the languages.  Consider the joys you will have when you need to change the layout on the view if you have one for each language... you've likely got English and then the FIGS set... and possibly CJK too... That's eight copies of the same view.  You're going to miss one and you're going to make a mistake in another one.  One view.

The industry behind localization is based on taking a file of strings and translating that file.  You might have this person in house instead... either way, they aren't programers.  The markup for the view itself - be it php, jsp, erb, or a chunk of javascript.  You don't want to be sending them your code, and you don't want them making mistakes in translating your variables, styles, and structures (test becomes <fuente colorido="negro">prueba</fuente>).  You, the programmer understand what needs to be translated and what does and giving just this to the person doing the translation makes it less likely to introduce errors.

Use the localization framework.  It will make it easier for you, it will make it easier for the person doing the translations.

Title: Translating views in MVC

Body:
The proper choice is using the single view with the strings stored in the appropriate localization framework for the view.

There are two main reasons for this:

It's DRY.  There is one view that is used for all the languages.  Consider the joys you will have when you need to change the layout on the view if you have one for each language... you've likely got English and then the FIGS set... and possibly CJK too... That's eight copies of the same view.  You're going to miss one and you're going to make a mistake in another one.  One view.

The industry behind localization is based on taking a file of strings and translating that file.  You might have this person in house instead... either way, they aren't programers.  The markup for the view itself - be it php, jsp, erb, or a chunk of javascript.  You don't want to be sending them your code, and you don't want them making mistakes in translating your variables, styles, and structures (<font color="black">test</font> becomes <fuente colorido="negro">prueba</fuente>).  You, the programmer understand what needs to be translated and what does and giving just this to the person doing the translation makes it less likely to introduce errors.

Use the localization framework.  It will make it easier for you, it will make it easier for the person doing the translations.


问:
DTO - service layer - statelessness best practices interfering with each other
I am designing a REST API coupled with a service layer that takes DTOs as input and produces them as output. This works fine for most service calls where the DTO is used to access an underlying library (an embedded OLAP server) that does the work.

There is one service, however, where something seems wrong. The service is responsible for creating, manipulating, and optionally storing objects that represent reports (think excel reports). It does this through the underlying library, which does not expose reports as a resource. Since the reports don't represent a server-side resource unless they are persisted (persistence being my own implementation, not a concept in the library), the service needs to take a report object that holds all the information necessary to construct a report from scratch to be stateless.

I decided that the report service methods should take a ReportDTO, manipulate it, and return the modified version. (This would include operations such as swapping the row and column axes, sorting an axis, and filtering an axis.) My thinking was that since I have all the information available in the ReportDTO necessary to perform all these operations, I might as well perform them on the DTO and return a modified version rather than duplicate the DTO as a domain object. That is not to say the server doesn't interface with any model. Indeed, the server-side code involves validating the report using a third party library (i.e., the validation model is not my own -- i don't have a domain model for the report itself, just DTOs), saving the report if the user so chooses, and executing the report against a database to obtain fresh data. So there is work to be done besides manipulating DTOs, it's just that it's not work tied to a domain model I needed to design myself, but rather one provided to me.

After I implemented the aforementioned operations, I realized something. The operations are business logic operations, are they not? A DTO should not have this. I then had numerous other thoughts: "Okay, that's fine, I'll do the operations in the service layer... Oh, wait. The service layer should only coordinate domain objects that contain business logic, not have business logic itself. Alright, I'll make the ReportDTO a bonafide domain object. Crap, now I am exposing my domain objects from the service layer. This is an API, I should really stick with DTOs as the input and output for the service layer so that changes in my domain model (or changes in the 3rd party domain model I utilize) do not affect the contract with service clients. Fine, I'll have a Report and a ReportDTO.... that have exactly the same members because the ReportDTO already has all the necessary information to manipulate a report (just not execute, validate, or save it) due to the transient report decision I made for the sake of a RESTful API."

Clearly I have countered my every proposed solution. So, what the heck do I do? I don't want to make reports stateful because I really don't see them as a resource until they are actually saved. If I make them stateful I'll need to manage a map or cache of them in my service and deal with multiple clients trying to give their report the same name, implement security to ensure that a user can only see his own reports, etc. All these problems go away with a stateless approach. The side effects, however, are the aforementioned issues. Did I go wrong somewhere? Please help me tackle this design issue before it becomes a permanent part of my API. Thanks.

答:
Don't make the report stateless, make it stateful on your database and business logic layer. I had something similar at work, and my thoughts at that time were:

You should allow quick access to old reports

Let the user queue report requests into the service layer so they can do something else

Break down a report request into smaller DB requests so you can store the results (and requests) in your DB (store per user of course)


问:
Why would a C executable be smaller when compared to C++ executable
I'm trying to understand why the output file sizes are significantly different when using a C and a C++ compiler.

I was writing a small hello world program in C and C++, I noticed that in C version, the size of the executable was 93.7KB and in C++, the size of the same hello world program was 1.33MB. I am not sure why that is. I think it may be because C++ has more libraries and namespaces to use so I removed the using namespace std line and simply used std::cout and still the result was the same.

C

```<code>#include <stdio.h>

int main()
{
    printf("hello world");
    return 0;
}
</code>```

// size 93.7KB

C++

```<code>#include <iostream>

int main()
{
    std::cout<<"Hello world";
    return 0;
}
</code>```

// size 1.33MB

There doesn't seem to be much difference in the code above.  Is there some sort of compiler difference that creates the differing file sizes?

答:
There is actually quite a lot of difference. The C code uses unformatted, unlocalized output. The C++ equivalent has quite a lot of gunk in it for changing locales and that kind of thing. Functionally, they are far from equivalent. You just happen to be using only a tiny subset of the C++ interface.

However more generally, the larger code sizes are a defect of this particular portion of the Standard library in particular, which is well known to be over-engineered, slow, and large, rather than the C++ language in general.


问:
Using abstract methods to force subclasses to define values for member fields
Often in my designs I define an abstract superclass whose subclasses will vary mostly in their values for the fields defined in the superclass.

For example, in a game I'm developing there's an abstract class Missile with a number of subclasses. Each one defines a different value for member variables such as MAX_SPEED, MASS,  FLYING_FORCE, which are then used in calculations performed in the superclass.

I use abstract methods in Missile to force it's subclasses to define these variables. For example I simply have an abstract method defineMass() that forces subclasses to define their own value of mass.

A different example would be my Entity class (the superclass of all game-play classes) defining an abstract loadImage() method that forces subclasses to define an image for themselves.

Is this good practice? Is it common?

答:
I think inheritance deserves better purposes:

If the only thing varying between subclases, and between subclasses and its superclass are the values of some members, then you are abusing inheritance or using it wrong. You could use builder pattern to create missiles with different values. If builder pattern is too complex for the task, factory methods like buildMissileOfTypeA() and buildSuperMassiveMissile() would do.

You would be putting inheritance to good use if the abstract methods were related to behaviors that the subclasses would implement in potentially different ways, but not just to set a value of a member.

Besides, you are not really forcing subclasses to define their own value, they just can simply implement an empty method that doesn't change the value of the mass and the compiler will be happy with it.


问:
How can I keep Web services requests in a DAO layer without tying the code to the DOM?
I'm working on a single page application on the node-webkit desktop app platform, which means 99.9% of all of the logic is written in JavaScript. Since this is a reboot of a project we're working on, I wanted to approach the architecture from more of an MVC approach on the client side.

I'm planning on creating a DAO layer for access to localStorage, IndexedDB, as well as Web services via REST requests. The problem is, the first tool I reach for to make HTTPS requests to the server is jQuery AJAX. It feels a bit weird to use jQuery in the DAO layer, even though I don't plan to manipulate the DOM, but it works really well on node-webkit and is a tried and tested tool for retrieving and sending data to the servers.

Despite the popularity of certain JavaScript application frameworks that have a certain way of doing things, we're not planning on using any frameworks other than JavaScript libraries that are fairly lightweight and unobtrusive, such as jQuery, Underscore, Mustache, Node.js modules, but nothing that forces us to unequivocally exclude certain technologies.

I'm planning to inject jQuery into the DAO layer for the purposes of making calls via AJAX to the Web services. My question is this:

How should I approach Web services? Do I treat Web services as just another data source like the local database?

Or do I just simply use the raw XMLHttpRequest object? What's the proven method for dealing with this architectural problem on the client side, without JavaScript frameworks?

答:
Treat Web services the same as any other data access:

To approach client side MVC architecture, without frameworks, we treated Web services in the same manner as we did localStorage and the local IndexedDB database. All code that involves requests to remote servers or that query a database or that read/write to localStorage happen in the model layer as DAO objects.

These were written using either the prototype pattern, the module pattern, or in some cases a combination of the two, using a modified factory pattern to treat objects as singletons in production but allowing us to "reset" them when unit testing so we keep tests self-contained.

They're generalized so that no application logic exists in this layer, and most of the code at this level can essentially be reused across future applications.

The services layer encapsulates the DAO layer, keeping the specific storage technology separate from the controller logic. Thus, pushing data to a remote server is seen as the same as inserting data into IndexedDB.

Used raw XMLHttpRequest to interface with Web services:

We chose not to use jQuery AJAX. Instead, we wrote a wrapper around XMLHttpRequest. There's no right or wrong answer here, but choosing not to use jQuery here allows us to stay focused on the rule of having no DOM manipulations in this layer. By wrapping the AJAX logic inside a prototype class, we set certain default headers, since most of what Web services deals with in our case is application/json data.

However, we did make an exception for jQuery Deferred. It didn't seem to make sense to write our own Observer implementation simply to be purists, and our logic behind this decision is that future professional programmers who work on this project with us have a better chance of understanding $.Deferred than some hand-rolled implementation. Many developers, on the other hand, we argued would have been exposed to XMLHttpRequest at some point in time, so being a purist here seemed less risky from the perspective of communicating to other developers what a piece of code does.

Analysis:

Earlier, I mentioned rules. We wrote up a series of "rules" designed to keep the code maintainable. For instance, rule #1 is that jQuery DOM manipulations only happen in a "view" layer. So the only jQuery we use in other layers is the $.Deferred object and nothing else.

We use $.Deferred throughout the application to keep certain logic in the layers where that belongs. For instance, we keep a persistent $.Deferred observer in the DOM click handlers in order to "notify" the controller that a click event has occurred so the controller can then delegate to other layers of the application to get/set, fetch/store, or perform other actions.

Using TDD as a development methodology, we've created small functions, where the largest is never more than a page, and most layers have a great deal of test coverage.

After a few months, the jury is still out on whether we should have used a framework, as much of what we've done could be generalized further into a reusable framework. We've learned quite a bit trying this, and I'm hoping this experience helps others who wish to develop client-side applications that involve a lot of asynchronous operations.

To give credit where it's due, I took inspiration from the following people:

Ben Nadel's article on A Better Understanding of MVC Model View Controller

My colleague Varun Vairavan, who has written some tools for AngularJS and node-webkit, and who was heavily involved in many of these technical decisions based on his experiences with Backbone.js and AngularJS.

Joel Spolsky's Law of Leaky Abstractions, which we personally dealt with when using a specific JavaScript framework.

Ben Nadel's Using jQuery Deferred To Create Compound Objects From Multiple Asynchronous Data Sources

For further reading on going framework-less, see Joe Gregorio's Zero Framework Manifesto


问:
Need advise for porting linux script to Win command line
I am creating app(script) that is used similar to RSS reader for specific webpage that doesn't have RSS.

So my app downloads that html page in defined intervals, checks new items and parses them into messages that are sent over network.

But my app prototype is written in Bash (Linux is my primary OS), and I was asked that this app will be needed on Windows also - luckily WinXP 32bit only.

So I am deciding how rewrite it easily and without testing various scripting languages and technologies.

Currently my app is working with Bash, and calls for unix utilities like sed, wget and curl. I checked that these utilities are for win32 also.

So my question is about Windows commandline capabilities compared to linux bash. Does wincmd have similar capabilities like bash? In e.g. manipulating strings, cycles or something that might be a problem?

I also found Cygwin, but don't know if it works reliable and this is important in this case of app.

答:
Windows cmd is far more limited than bash. For example, 'if', 'for' and 'goto' are the only flow of control functions, and the versions provided by cmd are fare more limited than the ones in bash. You might eventually be able to write a Windows cmd shell script that duplicates the functionality of a complex bash script, but  it will take you ages, and you won't enjoy it. If you need to port a complex script, try using Microsoft Windows Powershell instead. It programming model is very different from bash, so it will need a complete re-write, but it has quite good capabilities.

If you want to stick to bash, then MinGw and Cygwin are your only choices. Both have been around for years and are quite reliable, but of course will require a separate and fairly extensive install process for the folks using your script


问:
Functional programming strategies in imperative languages
I've been convinced for awhile now that some strategies in functional programming are better suited to a number of computations (i.e immutability of data structures). However, due to the popularity of imperative languages, its unlikely that I will always be working on projects that are functionally implemented. Many languages (Matlab, Python, Julia) support using a functional paradigm, but it feels tacked on in many cases (looking at you, anonymous functions in Matlab).
That being said, what are functional methods and strategies that I can use even in OOP/Imperative code? How can I write solid functional code that does not allow side effects even in languages that have mutable state and global variables?</p>

答:
How can I write solid functional code that does not allow side effects even in languages that have mutable state and global variables?

The simple answer is, do not use global or mutable variables, or just because you can mutate them does not mean you have to.

Consider a class like this:

```<code>class ImmutableClass
{
    private int myImmutableField;

    public ImmutableClass(int fieldValue)
    {
        this.myImmutableField = fieldValue;
    }

    public int FieldValue { get { return this.myImmutableVariable; } }
}
</code>```

That class is immutable and even thread-safe.  There is no way to mutate the state after it is constructed, even though the field is technically mutable.

Body:
How can I write solid functional code that does not allow side effects even in languages that have mutable state and global variables?

The simple answer is, do not use global or mutable variables, or just because you can mutate them does not mean you have to.

Consider a class like this:

class ImmutableClass
{
    private int myImmutableField;

    public ImmutableClass(int fieldValue)
    {
        this.myImmutableField = fieldValue;
    }

    public int FieldValue { get { return this.myImmutableVariable; } }
}

That class is immutable and even thread-safe.  There is no way to mutate the state after it is constructed, even though the field is technically mutable.


答:
Mutable state is easily avoidable using immutable objects. In the same way, global variables are usually the choice of the developer (or a poorly implemented framework).

This being said, you may also want to use additional functional paradigms in non-functional languages. It's all about the expressiveness of your code. If you see that a list comprehension in Python makes your code easy, go for it. If you find it more readable in a particular case to have an immutable structure used through method chaining, great.

But don't forget, some people find imperative variants easier than functional ones, even if it means writing three times the original LOC and risking to introduce subtle bugs. More importantly, some programmers don't understand the basic concepts. Many C# programmers struggle with lazy evaluation and are completely unable to explain why, if you take an IEnumerable<T> which returns a bunch of elements from the database and you first count the number of elements, then loop through them, there would be not one, but two queries to the database. I'm not even talking about monads and other concepts which are mostly unused in mainstream non-functional languages.

Also, don't worry that you won't work with functional languages. Non-functional languages tend to be inspired the last few years by functional ones. C# is a great example. Python and JavaScript are two other mainstream languages which tend to introduce more and more functional aspects in them. In essence, any language which support lazy evaluation and lambda expressions is a good candidate for functional-style code.

Title: Functional programming strategies in imperative languages

Body:
I've been convinced for awhile now that some strategies in functional programming are better suited to a number of computations (i.e immutability of data structures). However, due to the popularity of imperative languages, its unlikely that I will always be working on projects that are functionally implemented. Many languages (Matlab, Python, Julia) support using a functional paradigm, but it feels tacked on in many cases (looking at you, anonymous functions in Matlab).
That being said, what are functional methods and strategies that I can use even in OOP/Imperative code? How can I write solid functional code that does not allow side effects even in languages that have mutable state and global variables?</p>


问:
Understanding and memorizing git rebase parameters
So far the most confusing portion of git is rebasing onto another branch. Specifically, it's the command line arguments that are confusing.

Each time I want to rebase a small piece of one branch onto the tip of another, I have to review the git rebase documentation and it takes me about 5-10 minutes to understand what each of the 3 main arguments should be.

git rebase <upstream> <branch> --onto <newbase>

What is a good rule of thumb to help me memorize what each of these 3 parameters should be set to, given any kind of rebase onto another branch?

Bear in mind I have gone over the git-rebase documentation again, and again, and again, and again (and again), but it's always difficult to understand (like a boring scientific white-paper or something). So at this point I feel I need to involve other people to help me grasp it.

My goal is that I should never have to review the documentation for these basic parameters. I haven't been able to memorize them so far, and I've done a ton of rebases already. So it's a bit unusual that I've been able to memorize every other command and its parameters so far, but not rebase with --onto.

答:
Let's skip --onto for the moment.  upstream and branch are pretty basic, and actually sort-of mimic checkout and branch - the second argument is optional:

```<code>git branch <newbranch>
git branch <newbranch> <base>
git checkout -b <newbranch>
git checkout -b <newbranch> <base>
git rebase <upstream>
git rebase <upstream> <branch>
</code>```

(Aside, the names of these arguments in rebase, "upstream" and "branch" aren't very descriptive IMO.  I typically think of them like peachoftree, <start> and <end>, which is how I'll be using them:  git rebase <start> <end>)

When the second branch is omitted, the result is almost the same as first checking out that branch and then doing it as though you had not specified that branch.  The exception is branch which doesn't change your current branch:

```<code>git checkout <base> && git branch <newbranch> && git checkout <previous_branch>
git checkout <base> && git checkout -b <newbranch>
git checkout <end>  && git rebase <start>
</code>```

As for understanding what rebase does when invoked, I first started by thinking of it as a special type of merge.  It's not really, but it helped when first starting to understand rebase.  To borrow peachoftree's example:

```<code>A--B--F--G master
    \
     C--D--E feature
</code>```

A git merge master results in this:

```<code>A--B--F-----G master
    \        \
     C--D--E--H feature
</code>```

While a git rebase master (while on branch feature!) results in this:

```<code>A--B--F--G master
          \
           C'--D'--E' feature
</code>```

In both cases, feature now contains code from both master and feature.  If you're not on feature, the second argument can be used to switch to it as a shortcut:  git rebase master feature will do the same thing as above.

Now, for the special --onto.  The important part to remember with this is that it defaults to <start> if not specified.  So above, if I specified --onto specifically, this would result in the same:

```<code>git rebase --onto master master
git rebase --onto master master feature
</code>```

(I don't use --onto without specifying <end> simply because it's easier to mentally parse, even thought those two are the same if already on feature.)

To see why --onto is useful, here's a different example.  Let's say I was on feature and noticed a bug, which I then started fixing - but had branched off of feature instead of master by mistake:

```<code>A--B--F--G master
    \
     C--D--E feature
            \
             H--I bugfix
</code>```

What I want is to "move" these commits for bugfix so that they're no longer dependent on feature.  As it is, any sort of merge or rebase shown above in this answer will take the three feature commits along with the two bugfix commits.

For example, git rebase master bugfix is wrong.  The range <start> to <end> happens to include all the commits from feature, which are replayed on top of master:

```<code>A--B--F--G master
    \     \
     \     C'--D'--E'--H'--I' bugfix
      \
       C--D--E feature
</code>```

What we actually want is the range of commits from feature to bugfix to be replayed on top of master.  That's what the --onto is for - specifying a different "replay" target than the "start" branch:

git rebase --onto master feature bugfix

```<code>A--B--F--G master
    \     \
     \     H'--I' bugfix
      \
       C--D--E feature
</code>```

Body:
Let's skip --onto for the moment.  upstream and branch are pretty basic, and actually sort-of mimic checkout and branch - the second argument is optional:

git branch <newbranch>
git branch <newbranch> <base>
git checkout -b <newbranch>
git checkout -b <newbranch> <base>
git rebase <upstream>
git rebase <upstream> <branch>

(Aside, the names of these arguments in rebase, "upstream" and "branch" aren't very descriptive IMO.  I typically think of them like peachoftree, <start> and <end>, which is how I'll be using them:  git rebase <start> <end>)

When the second branch is omitted, the result is almost the same as first checking out that branch and then doing it as though you had not specified that branch.  The exception is branch which doesn't change your current branch:

git checkout <base> && git branch <newbranch> && git checkout <previous_branch>
git checkout <base> && git checkout -b <newbranch>
git checkout <end>  && git rebase <start>

As for understanding what rebase does when invoked, I first started by thinking of it as a special type of merge.  It's not really, but it helped when first starting to understand rebase.  To borrow peachoftree's example:

A--B--F--G master
    \
     C--D--E feature

A git merge master results in this:

A--B--F-----G master
    \        \
     C--D--E--H feature

While a git rebase master (while on branch feature!) results in this:

A--B--F--G master
          \
           C'--D'--E' feature

In both cases, feature now contains code from both master and feature.  If you're not on feature, the second argument can be used to switch to it as a shortcut:  git rebase master feature will do the same thing as above.

Now, for the special --onto.  The important part to remember with this is that it defaults to <start> if not specified.  So above, if I specified --onto specifically, this would result in the same:

git rebase --onto master master
git rebase --onto master master feature

(I don't use --onto without specifying <end> simply because it's easier to mentally parse, even thought those two are the same if already on feature.)

To see why --onto is useful, here's a different example.  Let's say I was on feature and noticed a bug, which I then started fixing - but had branched off of feature instead of master by mistake:

A--B--F--G master
    \
     C--D--E feature
            \
             H--I bugfix

What I want is to "move" these commits for bugfix so that they're no longer dependent on feature.  As it is, any sort of merge or rebase shown above in this answer will take the three feature commits along with the two bugfix commits.

For example, git rebase master bugfix is wrong.  The range <start> to <end> happens to include all the commits from feature, which are replayed on top of master:

A--B--F--G master
    \     \
     \     C'--D'--E'--H'--I' bugfix
      \
       C--D--E feature

What we actually want is the range of commits from feature to bugfix to be replayed on top of master.  That's what the --onto is for - specifying a different "replay" target than the "start" branch:

git rebase --onto master feature bugfix

A--B--F--G master
    \     \
     \     H'--I' bugfix
      \
       C--D--E feature

ContentLicense: CC BY-SA 4.0


问:
Is template "metaprogramming" in Java a good idea?
There is a source file in a rather large project with several functions that are extremely performance-sensitive (called millions of times per second). In fact, the previous maintainer decided to write 12 copies of a function each differing very slightly, in order to save the time that would be spent checking the conditionals in a single function.

Unfortunately, this means the code is a PITA to maintain. I would like to remove all the duplicate code and write just one template. However, the language, Java, does not support templates, and I'm not sure that generics are suitable for this.

My current plan is to write instead a file that generates the 12 copies of the function (a one-use-only template expander, practically). I would of course provide copious explanation for why the file must be generated programmatically.

My concern is that this would lead to future maintainers' confusion, and perhaps introduce nasty bugs if they forget to regenerate the file after modifying it, or (even worse) if they modify instead the programmatically-generated file. Unfortunately, short of rewriting the whole thing in C++, I see no way to fix this.

Do the benefits of this approach outweigh the disadvantages? Should I instead:

Take the performance hit and use a single, maintainable function.

Add explanations for why the function must be duplicated 12 times, and graciously take the maintenance burden.

Attempt to use generics as templates (they probably don't work that way).

Yell at the old maintainer for making code so performance-dependent on a single function.

Other method to maintain performance and maintainability?

P.S. Due to the poor design of the project, profiling the function is rather tricky... however, the former maintainer has convinced me that the performance hit is unacceptable. I assume by this he means more than 5%, though that is a complete guess on my part.

Perhaps I should elaborate a bit. The 12 copies do a very similar task, but have minute differences. The differences are in various places throughout the function, so unfortunately there are many, many, conditional statements. There are effectively 6 "modes" of operation, and 2 "paradigms" of operation (words made up by myself). To use the function, one specifies the "mode" and "paradigm" of operation. This is never dynamic; each piece of code uses exactly one mode and paradigm. All 12 mode-paradigm pairs are used somewhere in the application. The functions are aptly named func1 to func12, with even numbers representing the second paradigm and odd numbers representing the first paradigm.

I'm aware that this is just about the worst design ever if maintainability is the goal. But it seems to be "fast enough", and this code hasn't needed any changes for a while... It's also worth noting that the original function has not been deleted (although it is dead code as far as I can tell), so refactoring would be simple.

答:
There is absolutely nothing wrong with the 'problem' you mentioned.
From what I know this is the exact kind of design and approach used by DB server to have good performance.

They have lot of special methods to make sure they can maximize the performance for all kinds of operations: join, select, aggregate, etc... when certain conditions apply.

In short, code generation like the one you think is a bad idea.
Perhaps you should look at this diagram to see how a DB solves a problem similar to yours:


问:
How do you run a sprint retrospective to maximize participation and honesty? And what about follow up on action items?
I've seen it done as a free-for-all where the scrum master just asks everyone to throw out comments. Or a time-boxed session where "anonymous" comments are posted on the walls bucketed by category. My current team is constrained by being spread out, so it has be done online/over the phone. What is everyone's best experience with soliciting constructive feedback? And how do you follow through on action items for improvement?</p>

答:
I have been part of Retrospectives where people were geographically located in different places. In such cases Retrospectives were conducted over video conference. We used an online tool (ideaboardz) to collect the retro points and action items. Rest of the activity used to be as it is. The usual stuff.

As for the honesty and participation is concerned, @Stephane's answer covers a good point about checkin question. The facilitator asks questions like:
On a scale of 1 to 10 how comfortable are we to express ourselves, 1 being least comfortable and 10 being utmost uncomfortable?

On getting the numbers, the facilitator gets a good idea about the mix of people in the room. Based on the numbers you can choose to have an open retrospective or an anonymous one. Thats where online tools like mentioned above helps.


问:
Algorithm for percentage without knowing total number
Suppose there are n lines for a hotline.

Whenever a customer calls the hotline, the call is forwarded to one of the n lines. And I want to assign  percentage of calling to each of the n lines. Suppose there are two lines and one line is assigned 60% and other is 40%, the total number of calls is 10 so the first line would receive 6 calls and second will get 4 calls.

I know the percentage of calling to each line in advance but the problem is that I don't know the number of calls that would be received in a day.

How can I distribute the number of calls without knowing the total calls?

答:
Assumptions as OP stated

The number of lines, n, is known and;

The % of each line is known

Algorithm Design

Define each line by its %

Sort each line by its position away from 0 defined as (current % of workers - assigned % of workers) or by random assignation if all lines = 0

Forward each call to largest line away from 0

Example: 3 lines with a % of 20, 30 and 50 respectively. At point x in time 1 person calls and since every line is 0 away from 0, it gets randomly assigned - say to line 2 which should hold 30% of all calls. Since line 2 should be holding 30% of all calls and now holds 100% of all calls, its position from 0 increases. The next caller would now be assigned to either line 1 or line 3 etc until equilibrium (0) and thus the loop repeats itself.


问:
CANopen and CAN Driver
CAN Driver means application program that interacts with CAN hardware and helps in initializing setup and communication.

CANopen Stack provides various APIs to deal with CAN communication.

Now this is confusing me so please let me know: Is CANopen Stack and CAN driver one and the same?

答:
The CAN Bus is based on the ISO/OSI layers 1 (physical) and 2 (data link) and is standardized in ISO 11898.

The CAN Driver is a software module that interacts with the CAN controller and the CAN transceiver. It provides an interface to higher layers for:

initializing the CAN Hardware

sending raw CAN messages

receiving raw CAN messages

notifying the higher layers about received CAN messages

controlling the operation mode (normal, standby, goto sleep, ...)

...

CANopen implements the ISO/OSI layers 3 (network) to 7 (application). It includes the following features:

transport layer, supports data segmentation/desegmentation, controls the sending and receiving of more than 8 data bytes

network management, controls the state machines of the nodes (pre-operational, operational, ...)

heartbeat protocol, used to monitor if a network node is alive

SDO, PDO, SYNC, EMCY, ... and a lot more

The CANopen Stack implements the above mentioned features in software. It uses the interface provided by the CAN Driver to access the CAN Bus.

The basic CANopen communication is described in the CiA 301. This specifications is a good starting point for understanding the basics of CANopen.

Title: CANopen and CAN Driver


问:
CAN Protocol Understanding
I have a task to convert CAN protocol Driver from Basic CAN to Full CAN. The project contains CANopen stack used in it. I have initiated the study of CANopen stack.

I want to know is it necessary to study CANopen Stack and to how much depth should I study CANopen stack?

Please note- Major task is to improve the drive code by converting it into Full CAN implementation

答:
Basic CAN and Full CAN are CAN controller types, so it is a hardware feature.

A Full CAN controller has several (e.g. 16) mailboxes. A mailbox can be configured as a receive- or a transmit buffer for CAN messages. Among others, a Full CAN controller is responsible for filtering of the received messages and for copying the content of the received messages into a predefined RAM section.

A Basic CAN controller has only one receive buffer. CAN message filtering, by periodically reading the receive buffer, has to be done by the host controller (CPU).
The host controller is also responsible for copying of the received messages into the RAM.

Conclusion

One of the advantages of the Full CAN concept is a lower CPU load.

It should not be necessary to study the CANopen Stack to re-implement or refactor a CAN protocol driver. As stated here, the CANopen Stack depends on the CAN protocol driver interface, but not the other way around.

Title: CAN Protocol Understanding


答:
It's a pattern I've seen and used often, and I see it as a form of the Template Method pattern.

Consider a BasePlugin class, for instance, that defines an abstract Name and SupportedTypes properties. These properties are used as part of the base class shared implementations - using the Name for logging, maybe, or using SupportedTypes for validation. This might be in addition to the overridden logic of ExecutePlugin or whatever.

One change I would make from your design is to define a getMass method (or, if in C# or a similar language, a property with a getter) rather than your defineMass. getMass's name implies that its usage is as a getter, used anywhere in the base class code where the value is neede. defineMass implies that it will be called in the constructor, and it will, itself, store a value in a field in the base class. That seems unnecessary, and makes defineMass either have side effects (possibly affecting multithreaded code) or, alternately, just not being a very descriptive name, assuming you did intend for it to be a getter.

Rather than "force the derived class to define the values", which is just a roundabout way of saying "I need the derived class's values", simply ask the derived class for the value and let it do whatever it needs to give it to you.

Title: Using abstract methods to force subclasses to define values for member fields

Body:
Often in my designs I define an abstract superclass whose subclasses will vary mostly in their values for the fields defined in the superclass.

For example, in a game I'm developing there's an abstract class Missile with a number of subclasses. Each one defines a different value for member variables such as MAX_SPEED, MASS,  FLYING_FORCE, which are then used in calculations performed in the superclass.

I use abstract methods in Missile to force it's subclasses to define these variables. For example I simply have an abstract method defineMass() that forces subclasses to define their own value of mass.

A different example would be my Entity class (the superclass of all game-play classes) defining an abstract loadImage() method that forces subclasses to define an image for themselves.

Is this good practice? Is it common?


问:
In Java, why use bit hacks when non-bitwise technique it is more readable?
Is there any legitimate use for bit manipulation hacks in higher-level languages such as Java?

I can see them being useful in speed-sensitive low-level and computation-intensive programs, e.g. graphics processing or crypto functions. I guess that's why all collections of them are in C. However, getting to think about them in terms of higher-level design I cannot think of any point where I would, for example, write the following in a Java program:

```<code>r = y ^ ((x ^ y) & -(x < y));
</code>```

rather than:

```<code>r = (x < y) ? x : y;
</code>```

The first line looks more like an obfuscation than an improvement. And most applications have different kinds of bottlenecks - most commonly networks or disc access, so much so that any potential improvement gained by using a bitwise hack would be so tiny that it is completely ignorable.

This line of thought was provoked by a recent SO question in which someone was asked about a bitwise hack in Java during a interview.

I agree as much as anyone that it's always better to write faster code, but considering that it becomes much less readable, especially by someone not familiar with bit hacks, is there any kind of application in which it is legitimately worth it?

This question is not about bitwise operators in general, but more specifically about bitwise hacks, and even more specifically about bitwise hacks in Java.

By bitwise hack I mean a manipulation that has a trivial and/or obvious implementation, but which can be done slightly faster/better with some clever bitwise manipulation -- which in most cases makes it near-unreadable to someone not used to bitwise hacks.

There are similar looking questions: Importance of bitwise thinking and What are bit operators good for? The answers in these questions talk about bit manipulations in general, which yes, have a lot of clear and useful applications; especially in other languages like C. While this may seem similar, my question was about having them versus using the non-bitwise technique in Java. In the other questions this is not addressed at all.

答:
Sometimes, the specification of an algorithm is based on bit operations.  This is especially true in crypto work.

Crypto has another attribute to it that is important - that the operation takes exactly the same amount of time no matter what the parameters are.  This is to try to avoid leaking any data with timing attacks (there are even attacks based on the sounds the computer makes while doing cryptography).

Thus, for cryptography, it is of paramount importance that the code takes exactly the same amount of time and does the same things.  Bitwise operations can play a significant role in that area in that they are not often or easily optimized by the compiler.  With things were you can short circuit the expression or decide to follow one branch or another that has a different timing these are avenues of timing attacks.

The code

```<code>if(x < y) {
  r = x;
} else {
  r = y;
}
</code>```

Can take different amounts of time based on the branch prediction and branching itself.  While

```<code>r = y ^ ((x ^ y) & -(x < y));
</code>```

takes exactly the same amount of time each time through the code.  Branch prediction doesn't play a role because there are no branches in there.

With graphics work, there are similar areas of concern.  Some systems (especially older ones) had the CRT refresh tied with the clock cycle (for example the Amiga had 4 clock cycles per refresh line).  This meant that when you wrote code that was specifically tailored to the graphics of the system you knew exactly where the screen refresh was and could improve the appearance of the system.  This isn't quite as much of an issue now (the GForce GTX 780 can do 40,0000 operations per pixel per frame refresh), but it is something to be considered.

Secondly, there's also deep magic within fitting things into various caches on various systems.  Doing as much as possible with the cache can improve that.  This often means doing bitwise work rather than trying to load and store things or send them off to the ALU.

In Java, this can be difficult to know for certain, but again, maintaining a consistent frame rate based on the scene is something that is often very important with graphics.

Body:
Sometimes, the specification of an algorithm is based on bit operations.  This is especially true in crypto work.

Crypto has another attribute to it that is important - that the operation takes exactly the same amount of time no matter what the parameters are.  This is to try to avoid leaking any data with timing attacks (there are even attacks based on the sounds the computer makes while doing cryptography).

Thus, for cryptography, it is of paramount importance that the code takes exactly the same amount of time and does the same things.  Bitwise operations can play a significant role in that area in that they are not often or easily optimized by the compiler.  With things were you can short circuit the expression or decide to follow one branch or another that has a different timing these are avenues of timing attacks.

The code

if(x < y) {
  r = x;
} else {
  r = y;
}

Can take different amounts of time based on the branch prediction and branching itself.  While

r = y ^ ((x ^ y) & -(x < y));

takes exactly the same amount of time each time through the code.  Branch prediction doesn't play a role because there are no branches in there.

With graphics work, there are similar areas of concern.  Some systems (especially older ones) had the CRT refresh tied with the clock cycle (for example the Amiga had 4 clock cycles per refresh line).  This meant that when you wrote code that was specifically tailored to the graphics of the system you knew exactly where the screen refresh was and could improve the appearance of the system.  This isn't quite as much of an issue now (the GForce GTX 780 can do 40,0000 operations per pixel per frame refresh), but it is something to be considered.

Secondly, there's also deep magic within fitting things into various caches on various systems.  Doing as much as possible with the cache can improve that.  This often means doing bitwise work rather than trying to load and store things or send them off to the ALU.

In Java, this can be difficult to know for certain, but again, maintaining a consistent frame rate based on the scene is something that is often very important with graphics.


问:
How often should a manager meet with his subordinate who is a team leader?
Ours is a software concern and we have a team structured like so: manager->team leads->team members. We are following the agile programming model and trying to develop a product in a collaborative fashion. We have daily morning meetings with team members and their team leads to discuss progress and issues.

When it comes to TL->Manager, most of the time they do not have items to discuss on a daily basis since TL goals would be for weekly plan and such. Most of the time, we just discuss about resources and it is less technical. I just want suggestions on how the manager & team lead interaction should be and whether the current system we have is fine. Please share your thoughts or ideas.

答:
Depends upon if you are referring to project management or personnel management. From the personnel management I've heard that most good managers will usually have a standing meeting once a week with their subordinates so there is time for to make sure everything is running smoothly and to provide an opportunity for mentor-ship.

From the project management standpoint, the team leader should meet with the manager as often as is needed to keep them up to date on the status of the project. Generally having a standing meeting is a good idea as it keep the upper level management from being surprised if there is a delay in the project.

ContentLicense: CC BY-SA 2.5


答: If you want to force a subclass to set the right member field, you might specify a constructor with all the needed parameters in the superclass and thus forcing the subclasses to call the constructor (provided that your language of choice forces you to call super constructors).</p>


问:
How can a manager ensure developers are pushing up to the origin every day?
Our team has been using Git for a couple of years.  I love it, after previously using Visual Source Safe, SVN and TFS.  However, my manager has been getting increasingly agitated about it and is threatening to go back to SVN or TFS.

The problem is human nature: Developers forgetting to push up to the origin every day, then going sick or taking a holiday, and someone else having to pick up the project, and not knowing whether the latest code is in the origin, or whether it is sitting on the absent developer's machine.  There is no visibility of which developer was the last to work on which file, as there is with a centralized source control system.

I really want to avoid going back to SVN of TFS.  So my question is: How can a team use Git successfully in a way that takes into account human nature (forgetfulness, laziness, etc)?  How can I ensure that at the end of every day the latest code has been pushed to the origin so that someone else can step in and take over the next day, if need be?

Is the answer continuous integration?  I've read about workflows that include having to push to a CI branch on the origin to build the project.

答:
Firstly, let me say that trying to coerce software developers into adopting any practice is likely to backfire.  Software developers as a group are intelligent, educated people who like to be treated as professionals, and respond much better to management techniques that respect this, and treat them as valued collaborators.

So the key is to convince your developers, with logical arguments, that pushing code up daily is a good practice and will benefit them. To do this, adopt processes that facilitate the daily push-up, and get your developers to be their strongest advocates by demonstrating their advantages. Continuous Integration has been mentioned, and it is a good practice to adopt. Some of the key benefits to developers are:

Improved integration at release time. If the code base is
continuously being integrated, the risk of stressful big-bang
integration at release time, with a plethora of bugs being introduced
as multiple branches are frantically integrated, is much reduced.

Catching and fixing bugs soon after they are introduced. If a new
revision introduced a failed unit or regression test, or a new bug
not covered by these tests, it can be fixed sooner, not later when it
comes time to release, when it will be much harder to find and more stressful on the
developers. And the unit and regression tests should also be continuously refined and improved as the development proceeds.

Improved developer collaboration. As you pointed out, if everyone
commits daily, it is easier to know which developer committed the
most recent code to a specific module. What you want to do is get the
developers collaborating with each other on improving and fixing each
others code.

Daily commits make for small commits. The less code is committed, the
less likelihood it contains a large amount of bugs.

Of course for Continuous Integration to succeed, it is not just a matter of tools. It is a matter of processes  there are prerequisites that need to be in place such as a good suite of unit and regression tests, and a culture of developer peer reviews of design and code. If your organization has weaknesses in any of these areas, it is to your advantage to seek training for yourself and for the team in Continuous Integration and/or processes that support it, such as Agile development.

What you want to do to succeed,  is get your developers on board with Continuous Integration to the point where peer enforcement of practices like the daily commit/build/unit and regression test takes hold, and management intervention is hardly necessary. To this end as a manager you must:

Convince them of the benefits to themselves - so that they will do
the right thing out of enlightened self interest.

Involve them directly in the enforcement of the process - this means
peer reviews of design, build, and test, always and continuously.

Get them the  tools and training needed to support Continuous
Integration.

Lead by example. If you are involved in design and development at
all, make sure you are following the processes and being visible
about it. Point out how the processes are making your work less
stressful,and constantly encourage your developers to follow suit.


问:
Suggested method for extracting a standalone C library from an existing R package?
My group has been developing an R package to simulate plant growth (see GitHub repository). The R package uses .Call to interface with C.

We have decided that it would be worthwhile to create a standalone C library. The two key reasons are 1) to use familiar C debugging tools and 2) a large portion of the developer / user community is familiar with compiled languages (mostly models in the class are written in C or Fortran). However, the R package is accessible to many outside this community, so we want to maintain its functionality.

I have reviewed some related questions, e.g. https://stackoverflow.com/q/12328156/199217, that discuss R packages with C library dependencies, but have not found one that deals specifically with decoupling an existing R package.

A proposed approach

(what we have come up with so far ... a strawman)

Write tests for existing functionality

keep the C library inside the src/ folder

Place R-specific C code (e.g. SEXP, loading R libraries, etc) into 'R wrapper' files prepended with R_*

create separate functions for reading configuration files in C

create a 'main' C function to replace functionality in R

write a makefile for the C library that ignores R wrapper files

Once the C library works independently and equivalently to the R package, we could consider moving the C functions to a separate repository, that would be a dependency for the R package

Questions:

Is this effort misguided?

Are we overlooking any potential pitfalls?

Is there a better way to develop both the R and C libraries in parallel?

Are there any examples of C libraries that have been decoupled from R packages?

How might we write tests to compare equivalent functions in R and C?

答:
Generally speaking, this is a fine idea and many packages do this. You might look at RSQLite for inspiration -- they package up sqlite and just include some wrapper functions. Similar for rhdf5 and hdf5

Regarding your points:

Write tests for existing functionality

Always a good idea!

Keep the C library inside the src/ folder

Yes -- or you could consider inst/include if you ever went the 'header-only' route, a la Rcpp

Place R-specific C code (e.g. SEXP, loading R libraries, etc) into 'R wrapper' files prepended with R_*

Seems sensible enough.

Create separate functions for reading configuration files in C

Not exactly sure what you mean here.

Create a 'main' C function to replace functionality in R

This seems odd to me. Why do you need a main -- aren't you just developing a library of callable functions? Let R be your main :)

Write a makefile for the C library that ignores R wrapper files

Yes, you will probably need a more involved Makefile to handle this -- I again suggest looking at the source code for RSQLite, and also R-exts may be helpful.

Once the C library works independently and equivalently to the R package, we could consider moving the C functions to a separate
  repository, that would be a dependency for the R package

Yes, this seems sensible -- have the R package retrieve the C source code as necessary when building / developing the package. This way they can be effectively decoupled.

OwnerDisplayName: David


问:
How could your company's learning/development department best serve you?
I'll preface my question with a disclaimer - I am not an engineer, I'm just someone who works with them full-time, in a learning and development capacity.

Given that, one of the comments I get regularly from the engineers I'm tasked with developing is that they feel that they're having solutions (both technical and non-technical) for development "pushed" at them vs. anyone from my field consulting with them to determine what they really need.

So my question is - if you could give your company a list of the top 3-5 things they could do - in a classroom, or elsewhere - to develop meaningful skills that would help you be a better engineer, a better employee, and one more likely to STAY with the company for the long haul, what would make the cut and why?

Thanks in advance for your responses.

答:
Sponsor courses for professionals available from CMU etc

Have the entire MIT courseware and the likes downloaded on the local network

Arrange for professional trainers for advanced training

Get expert speakers like Steve Mcconnell et al to talk to the engineers


答:
TBH if you have a centralised system when pushing to origin is necessary then you're really using git like it was SVN/TFS (ie a centralised system) in the first place. You would be better off going back to such a SCM.

However, you could migrate to Fossil which is a centralised decentralised SCM and I think is the next-gen of SCM systems.

You should also have CI implemented anyway, if you do not want to force process upon the devs, then the next best thing is to encourage them to engage with the process - and the best way to do that for many developers is to gamify it. So you have leaderboards of commits, builds, bugfixes and build failures. People often want to be at the top of such a leaderboard and will compete to get there (see SO's reputation system for an example!)

But that can only work in some cases, in most professional jobs, the boss simply has to mandate the results he wants and tells the staff to make it happen. In this case, daily commits for backup purposes and collaboration, so daily pushes have to start happening. I imagine most people simply don't do it because they forget when it comes to home time (fossil would fix this as it continually syncs changes with origin).

Title: How can a manager ensure developers are pushing up to the origin every day?

Body:
Our team has been using Git for a couple of years.  I love it, after previously using Visual Source Safe, SVN and TFS.  However, my manager has been getting increasingly agitated about it and is threatening to go back to SVN or TFS.

The problem is human nature: Developers forgetting to push up to the origin every day, then going sick or taking a holiday, and someone else having to pick up the project, and not knowing whether the latest code is in the origin, or whether it is sitting on the absent developer's machine.  There is no visibility of which developer was the last to work on which file, as there is with a centralized source control system.

I really want to avoid going back to SVN of TFS.  So my question is: How can a team use Git successfully in a way that takes into account human nature (forgetfulness, laziness, etc)?  How can I ensure that at the end of every day the latest code has been pushed to the origin so that someone else can step in and take over the next day, if need be?

Is the answer continuous integration?  I've read about workflows that include having to push to a CI branch on the origin to build the project.


问:
Database Password problem when using GIT to manage project that uses Spring to initiate Datasource
I use Spring Framework to code my Web Service, using Dependency injection to inject a DataSource bean into the DAO bean that will be used by the Web Service. I have all the database properties(Url, Password, Username, the stuff I don't want people to see) written in the DataSource Bean XML!

I have git setup to commit my entire project....Including my DataSource Bean XML which has my password written in plain text. I thought of using the .gitignore but the Bean XML is a crucial component in my Web Service project and it shouldn't be ignored. But I also don't want the world to see my password.

How do I commit my bean files without showing the world my password.

答:
Anything you put into the Spring XML is static and compiled into the binary. If there is some information which can change, it is always a good idea to externalize it into a properties file. Spring can read the properties file and then use the values as inputs to its beans.

You need to use a concept called the property placeholder to inject these properties. First, create a properties file, say, MyApp.properties and place it into a known directory, say, /settings/MyApp. The contents of the file will be in the format:

```<code>databaseUsername=USER
databasePassword=PWD
property3=value3
property4=value4
...
</code>```

In your Spring XML, add the following tag:

```<code><context:property-placeholder location="file:///settings/MyApp/MyApp.properties"/>
</code>```

Now, you can simply use these external properties in your spring objects:

```<code><bean id="dataSource" class="...">
    <property name="username" value="${databaseUsername}">
    <property name="password" value="${databasePassword}">
</bean
</code>```

Now you can safely check in your Spring XML (but not MyApp.properties) and make sure that other users have their own MyApp.properties at the configured location.

There are other things you can do to make the property file lookup more dynamic. See this link for more details:

6 Tips for Managing Property Files with Spring

Body:
Anything you put into the Spring XML is static and compiled into the binary. If there is some information which can change, it is always a good idea to externalize it into a properties file. Spring can read the properties file and then use the values as inputs to its beans.

You need to use a concept called the property placeholder to inject these properties. First, create a properties file, say, MyApp.properties and place it into a known directory, say, /settings/MyApp. The contents of the file will be in the format:

databaseUsername=USER
databasePassword=PWD
property3=value3
property4=value4
...

In your Spring XML, add the following tag:

<context:property-placeholder location="file:///settings/MyApp/MyApp.properties"/>

Now, you can simply use these external properties in your spring objects:

<bean id="dataSource" class="...">
    <property name="username" value="${databaseUsername}">
    <property name="password" value="${databasePassword}">
</bean

Now you can safely check in your Spring XML (but not MyApp.properties) and make sure that other users have their own MyApp.properties at the configured location.

There are other things you can do to make the property file lookup more dynamic. See this link for more details:

6 Tips for Managing Property Files with Spring