问:
Data structure for accessing units of measure
TL;DR - I'm trying to design an optimal data structure to define units within a unit of measure.

A Unit of measure is essentially a value (or quantity) associated with a unit.  SI Units have seven bases or dimensions.  Namely: length, mass, time, electric current, temperature, amount of substance (moles), and luminous intensity.

This would be straightforward enough, but there are a number of derived units as well as rates that we frequently use.  An example combined unit would be the Newton: kg * m / s^2 and an example rate would be tons / hr.

We have an application that relies heavily upon implied units.  We'll embed the units within the variable or column name.  But this creates problems when we need to specify a unit of measure with different units.  Yes, we can convert the values at input and display but this generates a lot of overhead code that we'd like to encapsulate within its own class.

There are a number of solutions out on codeplex and other collaborative environments.  The licensing for the projects is agreeable but the project itself usually ends up being too lightweight or too heavy.  We're chasing our own unicorn of "just right."

Ideally, I could define a new unit of measure using something like this:

UOM myUom1 = new UOM(10, volts);

  UOM myUom2 = new UOM(43.2, Newtons);

Of course, we use a mix of Imperial and SI units based upon our clients' needs.

We also need to keep this structure of units synchronized with a future database table so we can provide the same degree of consistency within our data too.

What's the best way of defining the units, derived units, and rates that we need to use to create our unit of measure class?  I could see using one or more enums, but that could be frustrating for other developers.  A single enum would be huge with 200+ entries whereas multiple enums could be confusing based upon SI vs Imperial units and additional breakdown based upon categorization of the unit itself.

Enum examples showing some of my concerns:

myUnits.Volt

  myUnits.Newton

  myUnits.meter

SIUnit.meter

  ImpUnit.foot
  DrvdUnit.Newton

  DrvdUnitSI.Newton

  DrvdUnitImp.FtLbs

Our set of units in use is pretty well defined and it's a finite space.  We do need the ability to expand and add new derived units or rates when we have client demand for them.  The project is in C# although I think the broader design aspects are applicable to multiple languages.

One of the libraries I looked at allows for free-form input of units via string.  Their UOM class then parsed the string and slotted things accordingly.  The challenge with this approach is that it forces the developer to think and remember what the correct string formats are.  And I run the risk of a runtime error / exception if we don't add additional checks within the code to validate the strings being passed in the constructor.

Another library essentially created too many classes that the developer would have to work with.  Along with an equivalent UOM it provided a DerivedUnit and RateUnit and so on.  Essentially, the code was overly complex for the problems we're solving.  That library would essentially allow any:any combinations (which is legitimate in the units world) but we're happy to scope our issue (simplify our code) by not allowing every possible combination.

Other libraries were ridiculously simple and hadn't even considered operator overloading for example.

In addition, I'm not as worried about attempts at incorrect conversions (for example: volts to meters).  Devs are the only ones who will access at this level at this point and we don't necessarily need to protect against those types of mistakes.

答:
There is a good article in a magazin unfourtunatly it is in German: http://www.dotnetpro.de/articles/onlinearticle1398.aspx

Base idea is to have a Unit class like Length with a BaseMeasurement. The class contains the conversion factor, operator overloads, ToString overloads, parser of strings and an implementation as an indexer. We've even implemented even the Architectual view but it's not release as a library.

```<code>public class Length : MeasurementBase
    {
        protected static double[] LengthFactors = { 1, 100, 1000, 0.001, 100 / 2.54 };
        protected static string[] LengthSymbols = { "m", "cm", "mm", "km", "in" };
...
      public virtual double this[Units unit]
        {
            get { return BaseValue * LengthFactors[(int)unit]; }
            set { BaseValue = value / LengthFactors[(int)unit]; }
        }
...

        public static ForceDividedByLength operator *(Length length, Pressure pressure1)
        {
            return new ForceDividedByLength(pressure1[Pressure.Units.kNm2] * length[Units.m], ForceDividedByLength.Units.kNm);
        }

...
</code>```

So you see the usage with the Pressure operator or just:

```<code>var l = new Length(5, Length.Units.m)
Area a = l * new Length("5 m");
a.ToString() // -> 25 m^2
double l2 = l[Length.Units.ft];
</code>```

But as you said, I didn't find the unicorn either :)

Body:
There is a good article in a magazin unfourtunatly it is in German: http://www.dotnetpro.de/articles/onlinearticle1398.aspx

Base idea is to have a Unit class like Length with a BaseMeasurement. The class contains the conversion factor, operator overloads, ToString overloads, parser of strings and an implementation as an indexer. We've even implemented even the Architectual view but it's not release as a library.

public class Length : MeasurementBase
    {
        protected static double[] LengthFactors = { 1, 100, 1000, 0.001, 100 / 2.54 };
        protected static string[] LengthSymbols = { "m", "cm", "mm", "km", "in" };
...
      public virtual double this[Units unit]
        {
            get { return BaseValue * LengthFactors[(int)unit]; }
            set { BaseValue = value / LengthFactors[(int)unit]; }
        }
...

        public static ForceDividedByLength operator *(Length length, Pressure pressure1)
        {
            return new ForceDividedByLength(pressure1[Pressure.Units.kNm2] * length[Units.m], ForceDividedByLength.Units.kNm);
        }

...

So you see the usage with the Pressure operator or just:

var l = new Length(5, Length.Units.m)
Area a = l * new Length("5 m");
a.ToString() // -> 25 m^2
double l2 = l[Length.Units.ft];

But as you said, I didn't find the unicorn either :)


问:
How to spawn multiple "monsters" from a single class
How to spawn multiple "monsters" from a single class? Can store it in an array, ok, but later on, how can I paint it? Because if I do:

```<code>enemy = new Enemy();
enemy2 = new Enemy();
</code>```

I create two instances of the object, but after how can I paint it?

I use:

```<code>g2d.drawImage(Enemy.getImage(), Enemy.getX(), Enemy.getY(), this);
</code>```

But obviously it uses the class, not the variable.

Images will not be overlaid because coordinates are random.

Enemy's structured like:

```<code>public class Enemy {
static Random randomGenerator = new Random();
private int x;
private int y;
private Image image;
private int dx;
private int dy;
private int i;
private int strength=10;
private static int hp=100;
public String EnemyP = "/image/cazzillo_base_definitivo_000.png";

public Enemy() {    //Set skin and enemy position

    ImageIcon ii = new ImageIcon(this.getClass().getResource(EnemyP));
    image = ii.getImage();
    x = randomGenerator.nextInt(1024);
    y = randomGenerator.nextInt(700);
}

public int getX() { //Get function
    return x;
}

public int getY() {
    return y;
}

public Image getImage() {
    return image;
}

public void move() {    //Movement with delay
    if(i==6){
    x += dx;
    y += dy;
    }
}
public void follow () { //Function that follow the main character
    if (Cazzillo.getX()>x)  //Cazzillo it's the character class
        dx=1;
    else if (Cazzillo.getX()<x)
        dx=-1;
    else
        dx=0;
    if (Cazzillo.getY()>y)
        dy=1;
    else if (Cazzillo.getY()<y)
        dy=-1;
    else
        dy=0;
    if(i<6)
        i++;
    else
        i=0;
}

public void attack () { //Attack function not implemented yet
}
public void attacked (){    //Function that is activated when enemy's attacked
    hp -=Cazzillo.getS();
    if (hp<=0)
        death();
}
public void death (){
        x=randomGenerator.nextInt(1024);
        y=randomGenerator.nextInt(700);
        hp=100;
}
}
</code>```

答:
But obviously it use the class, not the variable.

Well, that is obviously wrong. You do have to use the instance:

```<code>g2d.drawImage(enemy.getImage(), enemy.getX(), enemy.getY(), this);
g2d.drawImage(enemy2.getImage(), enemy2.getX(), enemy2.getY(), this);
</code>```

Of course that means that those methods need to be instance methods and their data stored in non-static fields. That's what OOP is all about: having separate objects which hold their own data and have methods that operate on the object's data. Classes are just templates for multiple object instances. Class/static methods (and especially fields) are an aberration that should be avoided.

ContentLicense: CC BY-SA 3.0

Body:
But obviously it use the class, not the variable.

Well, that is obviously wrong. You do have to use the instance:

g2d.drawImage(enemy.getImage(), enemy.getX(), enemy.getY(), this);
g2d.drawImage(enemy2.getImage(), enemy2.getX(), enemy2.getY(), this);

Of course that means that those methods need to be instance methods and their data stored in non-static fields. That's what OOP is all about: having separate objects which hold their own data and have methods that operate on the object's data. Classes are just templates for multiple object instances. Class/static methods (and especially fields) are an aberration that should be avoided.


问:
Pluggable UI Components in Java Web Applications
I will try to explain my question with an example. Let us say that we are writing a hotel reservation system which is web based using Java. We will have different payment methods, say Paypal, Master Card and Visa Card. Different customers of our product will use different payment methods only. (Hotel XYZ, who is our customer, will only want to use Paypal and hotel ABC will only want to show the Master Card and Visa options).

In this kind of scenario, the normal way of doing things would be to have the different payment methods as plugins. And install only the needed plugins in a customer environment.

My question is, how to achieve this in a web application? From my understanding, the folder structure for a Java web application is as shown here. But if we have pluggable payment methods, the plugins themselves should be able to register the user interface components rather than having them in the main application. (For example let us say there is master_card.jsp file which handles the master card payments and visa.jsp etc..). With the above linked kind of folder structure, it seems to me that we would have to put in those jsp files in the webapp even though some customers might not need it.

Can someone please let me know whether

if my above observation is correct

how to have above kind of plugin structure with Java/Java EE?

are there any frameworks in Java that
supports above kind of thing?

答:
Whether you can use the file structure to configure enabled or not depends on how you deploy your web application.

Will the web app be deployed on the customers server? Then you can use the file structure.
Will you deploy the web app on your own server? Then you won't be able to use file structure.

In any case it's probably less complicated to include all views (e.g. JSP or JSF pages) and then have a configuration table in your database for each customer that tells you which plugins are enabled. Then in your view (JSP or JSF) you use conditional rendering based on those config values.

In other words in JavaEE you dynamically generate html, so you for each payment method you can check in your database whether it's enabled and then only render the enabled ones to your final html output.

Update:
One way to have different builds where you include/exclude the code might be to use maven and set up different profiles for the different payment options. This solution would only work if you deploy your webapp on your customers servers. I still think that the cleanest solution would be to use configuration.


问:
How best to implement HTML5 support for my validation library
I have created an annotation-based validation library called regula. There seems to be some amount of interest around the framework and the next thing I'd like to do is to support HTML5 validation. Originally I figured that I would check to see if the browser supported the HTML5 validation that has been specified and to either emulate or delegate to built-in regula equivalents. This is trivial for things like required, but once you start getting into the date-validation, it gets tricky (date widgets, localization, etc.). So I have a few options in front of me:

Full HTML5 Shim along with widgets (for date stuff etc.): I feel like this is overkill and essentially reinventing the wheel since this is already covered by things like modernizr.

Use HTML5 validation if available (either native, or provided by shim; otherwise ignore): What this means is that if HTML5 validation is available (natively or through a shim) I will use it, otherwise I will ignore it.

I'm leaning towards the latter since currently if someone wants to use HTML5 validation, they will most probably require a shim since not all browsers support HTML5.

Which option do you think is better?

答:
I am actually in the process of planning/building my own validation library and I had a similar dilemma. Basically, is it a validation library or a form/UI library? This is an important distinction.

Type of Library

Validation Library

Your second point more relates to this.

In my case I was looking more purely at validation before, looking at the intricacies of checking XYZ data is of the right format/type etc. I wanted to validate JavaScript objects, not forms (more on that a little later), so I am designing an architecture that allows me to map my validation requirements in the nicest possible way.

This is not to say a validation library doesn't interact with forms. Take jQuery Validate for example: it binds to the form element, can auto-add validation items based on attributes on the input or select elements and shows error messages in the form. The thing jQuery Validate doesn't do is have custom date pickers, colour swatches etc.

Form/UI Library

Your first point more relates to this.

Basically, you are attempting to use the native HTML5 controls where you can but otherwise providing some sort of custom interface for people to enter inputs on a form. While this definitely has uses, this isn't validation (not entirely anyway).

A form library may or may not have its own validation system though it can get about this another way. Take a custom date picker field for example, you might have a calendar and someone can just click the day they want but they have no other method via the UI to add arbitrary values. You've effectively limited it so you will "always" have a valid date.

While this method works, it isn't ideal. Having a well implemented validation system in place is good for future maintainers, they don't need to deal that the validation works because we are using ABC calendar instead of ZYX calendar.

HTML5 Validation

OK, the next question is do you really want to use/support HTML5 fields/validation when your library is being used?

This might come across strange but if you want consistency between the browsers, HTML5 fields might not be the way to go. This isn't so much because of the browser support for the various HTML5 fields but more so the little things like when they trigger validation (do you want it on blur or on submit?) and how the validation looks (you can partially get around this with CSS but it really depends on your design for how you want errors to look).

However HTML5 does have some really nice things like mobile devices changing the keyboard based on the input type, email validation (have you read RFC 5322? Getting a 100% correct method for email validation can be hard though that doesn't mean the browsers are 100% correct either), date pickers for date fields, colour swatch field and number field. These are all great but it really depends what you want to trade for that.

Putting that aside, it goes back to whether you want a form/UI library or a validation library.

How does this solve the my question?

In the end, your question is somewhat open-ended. You mentioned you want HTML5 support and you are already leaning to your second option. From what I can tell from your description, your second option is the fastest to implement and will save you hassles for your use case.

For those reasons, I would recommend you go that path.

However, I find "reinventing the wheel" isn't always as bad as what people think/say it is. Building a system from scratch, using the knowledge gained from working with other systems can have something amazing be built as a result. Obviously there is a lot of time involved in such project and many different things need to be accounted for though if you want consistency with how things look/act/work while having complete flexibility, this would be the way to go.

For my validation library, I have no intention to do any crazy date calculations myself. There is a great library called Moment.js which I intend to integrate with my validation system. I get the flexibility of my own validation system (fine grain control when validation fires, how the validation appears, its extendability) while getting the usefulness of work already built by others (and of course, crediting them).

Notes

I mentioned I wanted to validate JavaScript objects, not forms. This actually came from a big project I worked on where we started with plain jQuery Validate and eventually turned it into a hybrid monster that combined client-side and server-validation (by the power of ASP.Net, reading/writing attributes to inputs) while also working under very specific conditions (like multiple "forms" within a form tag - thanks ASP.Net WebForms!).

What I mentioned about HTML5 validation was from my own experiences over the years. With the browser support still evolving, this may change in the future.

Also, I am aware the question was asked 2 years ago. I do hope this answer is somewhat useful to whoever has a similar question in the future.


问:
How to deal with multiple "entry points" for an action in a REST API?
Let's say we have two kinds of resources, user and group.

Every user can belong to multiple groups and each group can have many members.

Thus I can model my API like this

```<code>/
|_ /users/{id}
|   |_ groups
|
|_ /groups/{id}
    |_ members
</code>```

Let's say our resources exposes only two actions. You could either add a user to a group or remove one from it.

When it comes to the implementation I could think of two possible requests for each action.

You could PUT a new user in a group's members collection, or PUT a new group in a user's groups collection.

Should I implement both "entry points"? Is this expected in RESTful applications? If not, which one should I implement?

答:
REST doesn't have any expectations on this. You can implement both or only one of them. Also there is a possible third options to have a resource user_group_relation which handles this functionality.

Which one you need or want to implement depends on your needs. If it's for a pure API one should be enough (I would go for adding a member to a group, since this feels more natural).

But if you have a web site or app that offers both options for editing and has two very distinct types of response it may be more comfortable to implement both. Say a user page has a list of groups where you can add groups and at the same time your groups show lists of users where you can add new members. Both lists are very different, both actions would have to return very different responses to update those lists (and maybe more info specific to those pages like number of groups for the user, number of users for the group).


答:
I'd recommend using only one method of adding/removing users in groups. To keep it simple, in a well design API there should be only one path to achieve each action. Moreover, that path should be the shortest possible.

Now to choose what is the right path (PUT /users/{idu}/groups/{idg} or PUT /groups/{idg}/users/{idu}). It's up to you, but I'd rather use the second one. Because it's the answer of who owns who ? Or What is composed of what ?

It is not a dogmatic answer, there could be reasons to choose the first one especially if you you consider the fact that being in group is property of the user.

Title: How to deal with multiple "entry points" for an action in a REST API?

Body:
Let's say we have two kinds of resources, user and group.

Every user can belong to multiple groups and each group can have many members.

Thus I can model my API like this

```<code>/
|_ /users/{id}
|   |_ groups
|
|_ /groups/{id}
    |_ members
</code>```

Let's say our resources exposes only two actions. You could either add a user to a group or remove one from it.

When it comes to the implementation I could think of two possible requests for each action.

You could PUT a new user in a group's members collection, or PUT a new group in a user's groups collection.

Should I implement both "entry points"? Is this expected in RESTful applications? If not, which one should I implement?


问:
Manage ClickOnce releases for different parties
I'm struggling with release management of a piece of software. First some general information:

It is a ClickOnce application

I follow the release often practice

There are about 30 parties served with this software

I need full control which update will be delivered to which party

Not each party is allowed to get the latest update/release

Each party has multiple clients that are all allowed to get the latest update, served for the specific party

So that's what my requirements are in a rough description. So let me explain what I was thinking about how to solve this.

I would like to create a "deployment" website (asp.net) that will handle all the requests

There are two endpoints one for download the client and one where the client checks for updates

So each party has a separate endpoint like DeploymentSite/party1 and another for DeploymentSite/party2

The Application Files should still be stored centralized

So I thought it would be manageable with mage.exe with the following steps

Build application and store new release into Application Files Repository/Folder

Get parties that should be updated (config file, database what ever)

Run mage.exe to create a new application and deployment manifest for each party in the update list with new Application File Location (1.0.2)

Actually I'm really struggling with this mage.exe staff. I can't create the appropriate files with the needed codebase.

How to handle thes requirements?

答:
What you want is possible, but not quite in the way you mention.

A published ClickOnce package is controlled by two manifest files - the application manifest called [product name].application housed in the root folder of the published deployment, and the version manifest called [application name].exe.manifest, which of course resides in the codebase folders for the specific versions.

To to cut a long story short, you can publish as many versions as you like - in fact that is the easy bit - but you will then need a copy of the application manifest for each 'party' that you have. You can then update them independently by updating their application manifest, once you have done that any client machine will auto update - this is part of the functionality of ClickOnce (the installed ClickOnce application checks the application manifest for updates every time you run it (or at the period you specify as part of the publish)).

All you need to do is control which application manifest any particular party originally installs from, you can do this simply by checking their credentials then redirecting them to the appropriate application manifest (which will then launch the install prompt).
You don't need to be messing round with Mage to achieve this - you can accomplish this using the publish functionality built into Visual Studio - you can publish to a neutral location then copy the generated neutral application manifest over top of the appropriate party specific application manifests.

Note that party specific application manifests are necessary because ClickOnce is an installation framework, it knows nothing about authentication and authorisation, so you have to take care of that bit. Technically you could house the application manifest files all in the same folder if you name them individually - but this does require a knowledge of Mage and isn't a simple task. Additionally you could automate some of this with Release Management and one or two custom tasks.


问:
Why PATCH method is not idempotent?
I was wondering about this.

Suppose I have a user resource with id and name fields.
If I want to update a field I could just do a PATCH request to the resource like this

```<code>PATCH /users/42
{"name": "john doe"}
</code>```

And then the application will update user 42 name.

But why if I repeat this request the outcome would be different?

According to RFC 5789

PATCH is neither safe nor idempotent

答:
A PATCH request can be idempotent, but it isn't required to be. That is the reason it is characterized as non-idempotent.

Whether PATCH can be idempotent or not depends strongly on how the required changes are communicated.

For example, if the patch format is in the form of {change: 'Stock' add: -1}, then any PATCH request after the first one would have a different effect than the first request, i.e. a further decrease in the assumed stock of the product.

Another reason for non-idempotency can be that applying the modification on something else than the original resource can render the resource invalid. This would then also be the case if you apply the change multiple times.

Title: Why PATCH method is not idempotent?

ContentLicense: CC BY-SA 4.0


问:
Methods for structuring JavaScript SDKs
I've built a REST API and have been using Backbone models throughout a couple different applications to communicate to it.

I would really like to build a single JS SDK that can be used in any application that contains that reusable code.

I have started by creating an npm, bower, and component.json so that it can be easily installed.

From what I can gather the goal is to create a single object attached to the window for access within other applications. At which point everything in is encapsulated.

I have a couple questions and concerns:

Is there anything I need to avoid to prevent conflicts with other libraries?

How do I handle dependencies? Should I encapsulate them or let the user know they have to add it?

Are there any methods of structuring SDKs that provide similar benefits to, say, MVC within a web app?

NOTE: If this is question doesn't follow the guidelines for programmers.stackexchange.com please provide guidance on how to change it rather than just closing it. Thanks much.

答:
Is there anything I need to avoid to prevent conflicts with other libraries?

Simple answer is maybe, depending on your situation.

Example

jQuery by default adds itself as jQuery on the window object as well as $. While it is unlikely that another library is going to call itself jQuery (more on that later), the $ global is actually quite a common shortcut.

What jQuery does is save the variables $ and jQuery internally and on calling $.noConflict() will restore the previous set variables. [Reference]

Here is one very simple way of programming this:

var jQuery = function(){ return 1; };

(function()
{
    var _jQuery = jQuery;

    jQuery = function()
    {
        return 2;
    }

    jQuery.noConflict = function()
    {
        jQuery = _jQuery;
    }
})();

//Prints "2"
console.log(jQuery());

var jQuery2 = jQuery;
jQuery2.noConflict();

//Prints "1"
console.log(jQuery());

//Prints "2"
console.log(jQuery2());
```

My questions would be:

Are you wanting to use a common global variable (eg. $)?

What types of scenarios do you see with people working with your library?

If your SDK is going to use a common global variable and or you think people could be slinging a dozen different libraries while using your code, you may want to consider it. I will note that if you design your object/functions well enough, it shouldn't be hard to add such functionality as I showed above later in your project.

How do I handle dependencies? Should I encapsulate them or let the user know they have to add it?

How many dependencies are you thinking they might need? Are the dependencies quite common (ie. jQuery)?

Personally, if there are one or two dependencies, I would just state it in docs for your SDK. There is no need for you to go out and keep a copy of your dependencies internally maintained and tested.

Most jQuery plugins require jQuery (obviously) but don't bundle it simply because they don't need to. Generally these plugins state a minimum version of jQuery they support/have tested but not much beyond that.

While saying this, bundling can be useful especially if the API of your dependency isn't very stable. There is one library I have used called Kalendae which bundles Moment.js. In this case, I have found it being bundled quite useful.

There are downsides to bundling linking back to your first point, they can cause conflicts if the person is already including a particular version of XYZ library. If you do bundle, do it in a way to cause the least amount of annoyance for future developers.

Without knowing what your specific dependencies are, I can't really help you with whether under your case should you bundle or not.

Are there any methods of structuring SDKs that provide similar benefits to, say, MVC within a web app?

I'm not exactly what you are asking here in relating SDK structure to MVC within a web app.

Depending what your SDK does and how people would likely integrate with it would explain how best to structure it.

In terms of general things to do:

Keep the global variables down to a minimum. Possibly wrap your code in a closure to avoid doing this (depending how your lay out your code).

Allow flexibility by allowing callbacks and events. Given you are doing a REST API, you might want to look into JS Promises. There are many libraries that provide such functionality and hopefully soon, browsers will provide this natively. [More info about futures/promises/delay in Computer Science]

Allow easy configuration/options to be passed to your functions. While it can be useful to add 20 different functions onto your object that configure a bunch of settings, it is far easier to allow the user to dump a JS object into a constructor or other function to do it all at once.

If you can explain more about that 3rd point, I might be able to provide a better answer.

Note

I mentioned that another library wouldn't call itself jQuery in the global space. While that would generally hold true, if the person is using two different versions of jQuery on the same page (believe me, it happens) then it would run into issues. By default, calling $.noConflict() will only fix the $ reference in the global scope however $.noConflict has an optional parameter for also doing the same thing to the jQuery object.

Title: Methods for structuring JavaScript SDKs

Body:
Is there anything I need to avoid to prevent conflicts with other libraries?

Simple answer is maybe, depending on your situation.

Example

jQuery by default adds itself as jQuery on the window object as well as $. While it is unlikely that another library is going to call itself jQuery (more on that later), the $ global is actually quite a common shortcut.

What jQuery does is save the variables $ and jQuery internally and on calling $.noConflict() will restore the previous set variables. [Reference]

Here is one very simple way of programming this:

var jQuery = function(){ return 1; };

(function()
{
    var _jQuery = jQuery;

    jQuery = function()
    {
        return 2;
    }

    jQuery.noConflict = function()
    {
        jQuery = _jQuery;
    }
})();

//Prints "2"
console.log(jQuery());

var jQuery2 = jQuery;
jQuery2.noConflict();

//Prints "1"
console.log(jQuery());

//Prints "2"
console.log(jQuery2());

My questions would be:

Are you wanting to use a common global variable (eg. $)?

What types of scenarios do you see with people working with your library?

If your SDK is going to use a common global variable and or you think people could be slinging a dozen different libraries while using your code, you may want to consider it. I will note that if you design your object/functions well enough, it shouldn't be hard to add such functionality as I showed above later in your project.

How do I handle dependencies? Should I encapsulate them or let the user know they have to add it?

How many dependencies are you thinking they might need? Are the dependencies quite common (ie. jQuery)?

Personally, if there are one or two dependencies, I would just state it in docs for your SDK. There is no need for you to go out and keep a copy of your dependencies internally maintained and tested.

Most jQuery plugins require jQuery (obviously) but don't bundle it simply because they don't need to. Generally these plugins state a minimum version of jQuery they support/have tested but not much beyond that.

While saying this, bundling can be useful especially if the API of your dependency isn't very stable. There is one library I have used called Kalendae which bundles Moment.js. In this case, I have found it being bundled quite useful.

There are downsides to bundling linking back to your first point, they can cause conflicts if the person is already including a particular version of XYZ library. If you do bundle, do it in a way to cause the least amount of annoyance for future developers.

Without knowing what your specific dependencies are, I can't really help you with whether under your case should you bundle or not.

Are there any methods of structuring SDKs that provide similar benefits to, say, MVC within a web app?

I'm not exactly what you are asking here in relating SDK structure to MVC within a web app.

Depending what your SDK does and how people would likely integrate with it would explain how best to structure it.

In terms of general things to do:

Keep the global variables down to a minimum. Possibly wrap your code in a closure to avoid doing this (depending how your lay out your code).

Allow flexibility by allowing callbacks and events. Given you are doing a REST API, you might want to look into JS Promises. There are many libraries that provide such functionality and hopefully soon, browsers will provide this natively. [More info about futures/promises/delay in Computer Science]

Allow easy configuration/options to be passed to your functions. While it can be useful to add 20 different functions onto your object that configure a bunch of settings, it is far easier to allow the user to dump a JS object into a constructor or other function to do it all at once.

If you can explain more about that 3rd point, I might be able to provide a better answer.

Note

I mentioned that another library wouldn't call itself jQuery in the global space. While that would generally hold true, if the person is using two different versions of jQuery on the same page (believe me, it happens) then it would run into issues. By default, calling $.noConflict() will only fix the $ reference in the global scope however $.noConflict has an optional parameter for also doing the same thing to the jQuery object.


问:
What can one do to improve readability of math-oriented code in C#, Java, and similar?
As both a C programmer and a C# programmer, one of the things I don't like about C# is how verbose math functions are. Every time you would have to use a Sin, cosine, or power function for example, you'd have to prepend the Math static class. This leads to very long code when the equation itself is pretty simple. The problem becomes even worse if you need to typecast data types. As a result, in my opinion, the readability suffers. For example:

```<code>double x =  -Math.Cos(X) * Math.Sin(Z) + Math.Sin(X) * Math.Sin(Y) * Math.Cos(Z);
</code>```

As opposed to simply

```<code>double x = -cos(X) * sin(Z) + sin(X) * sin(Y) * cos(Z);
</code>```

This is also the case in other langauges like Java.

I'm not sure if this question actually has a solution, but I would like to know if there are any tricks C# or Java programmers use to improve readability of Math code. I realize however that C#/Java/etc. are not math-oriented languages like MATLAB or similar, so it makes sense. But occasionally one would still need to write math code and it'll be great if one could make it more readable.

答:
Use Scala!  You can define symbolic operators, and you don't need parens for your methods.  This makes math way easier to interpret.

For example, the same calculation in Scala and Java could be something like:

```<code>// Scala
def angle(u: Vec, v: Vec) = (u*v) / sqrt((u*u)*(v*v))

// Java
public double angle(u: Vec, v: Vec) {
  return u.dot(v) / sqrt(u.dot(u)*v.dot(v));
}
</code>```

This adds up pretty quickly.

Body:
Use Scala!  You can define symbolic operators, and you don't need parens for your methods.  This makes math way easier to interpret.

For example, the same calculation in Scala and Java could be something like:

// Scala
def angle(u: Vec, v: Vec) = (u*v) / sqrt((u*u)*(v*v))

// Java
public double angle(u: Vec, v: Vec) {
  return u.dot(v) / sqrt(u.dot(u)*v.dot(v));
}

This adds up pretty quickly.


问:
Explicitly define enum values, even if the default value is the same?
There are times when an enum's values are important: it is not necessary for them to be unique, they also need to have specific values. In such cases, should the values be explicitly defined, even if they coincide with the defaults? An example:

```<code>enum Car {
    DeLorean = 0,
    Lada = 1
};
</code>```

Imagine that for whatever reason your application assumes that DeLorean and Lada have those specific values. Incidentally, they are the same as the default values but does that mean it is no longer necessary to use explicit definitions?

Leaving them implicit makes me uneasy. It seams to me that having them explicitly defined is communicating to future programmers that the specific values are important and it helps prevent mistakes like this:

```<code>enum Car {
    Dacia,
    DeLorean,
    Lada
};
</code>```

In the example above, another programmer who is not aware of the restriction I mentioned introduces a new enum value and, wanting to keep the code tidy, puts it in alphabetical order. However, DeLorean and Lada now have different numerical values and a potentially silent bug has been introduced.

My reasoning seems correct to me (obviously), but the code review team for a company I used to work with didn't agree. Am I wrong?

答:
With enums, there are three philosophies that work, and one that doesn't

Value agnostic - use default values for ALL options with the underlying values irrelevant

Sequence specific - define the first value leaving all others as increments

Value specific - specify values for ALL options and the value is important (eg comms message IDs)

The one that doesn't

Some specified - some values are specified, and some are not

Option (4) is deprecated by MISRA C (and other such standards)... likewise, the purist in me questions why (2) should be necessary (other than for the default = 0) but there are probably legitimate reasons for this.

Of course, where a value is specified, then there should be adequate documentation to explain why!

IMHO it is quite dangerous to rely on knowing the underlying value of an enumeration, and even more so to assume a sequence - the problems you can get into incrementing and decrementing an enum type...


答:
C#: A variation on Randall Cook's answer, which I like because it maintains the mathematical "look" of the code more than extension methods, is to use a wrapper but use function references for the calls rather than wrap them. I personally think it makes the code look cleaner, but it is basically doing the same thing.

I knocked up a little LINQPad test program including Randall's wrapped functions, my function references, and the direct calls.

The function referenced calls basically take the same time as the direct calls. The wrapped functions are consistently slower - although not by a huge amount.

Here's the code:

```<code>void Main()
{
    MyMathyClass mmc = new MyMathyClass();

    System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();

    for(int i = 0; i < 50000000; i++)
        mmc.DoStuff(1, 2, 3);

    "Function reference:".Dump();
    sw.Elapsed.Dump();
    sw.Restart();

    for(int i = 0; i < 50000000; i++)
        mmc.DoStuffWrapped(1, 2, 3);

    "Wrapped function:".Dump();
    sw.Elapsed.Dump();
    sw.Restart();

    "Direct call:".Dump();
    for(int i = 0; i < 50000000; i++)
        mmc.DoStuffControl(1, 2, 3);

    sw.Elapsed.Dump();
}

public class MyMathyClass
{
    // References
    public Func<double, double> sin;
    public Func<double, double> cos;
    public Func<double, double> tan;
    // ...

    public MyMathyClass()
    {
        sin = System.Math.Sin;
        cos = System.Math.Cos;
        tan = System.Math.Tan;
        // ...
    }

    // Wrapped functions
    public double wsin(double x) { return Math.Sin(x); }
    public double wcos(double x) { return Math.Cos(x); }
    public double wtan(double x) { return Math.Tan(x); }

    // Calculation functions
    public double DoStuff(double x, double y, double z)
    {
        return sin(x) + cos(y) + tan(z);
    }

    public double DoStuffWrapped(double x, double y, double z)
    {
        return wsin(x) + wcos(y) + wtan(z);
    }

    public double DoStuffControl(double x, double y, double z)
    {
        return Math.Sin(x) + Math.Cos(y) + Math.Tan(z);
    }
}
</code>```

Results:

```<code>Function reference:
00:00:06.5952113

Wrapped function:
00:00:07.2570828

Direct call:
00:00:06.6396096
</code>```

Title: What can one do to improve readability of math-oriented code in C#, Java, and similar?

Body:
As both a C programmer and a C# programmer, one of the things I don't like about C# is how verbose math functions are. Every time you would have to use a Sin, cosine, or power function for example, you'd have to prepend the Math static class. This leads to very long code when the equation itself is pretty simple. The problem becomes even worse if you need to typecast data types. As a result, in my opinion, the readability suffers. For example:

```<code>double x =  -Math.Cos(X) * Math.Sin(Z) + Math.Sin(X) * Math.Sin(Y) * Math.Cos(Z);
</code>```

As opposed to simply

```<code>double x = -cos(X) * sin(Z) + sin(X) * sin(Y) * cos(Z);
</code>```

This is also the case in other langauges like Java.

I'm not sure if this question actually has a solution, but I would like to know if there are any tricks C# or Java programmers use to improve readability of Math code. I realize however that C#/Java/etc. are not math-oriented languages like MATLAB or similar, so it makes sense. But occasionally one would still need to write math code and it'll be great if one could make it more readable.

Body:
C#: A variation on Randall Cook's answer, which I like because it maintains the mathematical "look" of the code more than extension methods, is to use a wrapper but use function references for the calls rather than wrap them. I personally think it makes the code look cleaner, but it is basically doing the same thing.

I knocked up a little LINQPad test program including Randall's wrapped functions, my function references, and the direct calls.

The function referenced calls basically take the same time as the direct calls. The wrapped functions are consistently slower - although not by a huge amount.

Here's the code:

void Main()
{
    MyMathyClass mmc = new MyMathyClass();

    System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();

    for(int i = 0; i < 50000000; i++)
        mmc.DoStuff(1, 2, 3);

    "Function reference:".Dump();
    sw.Elapsed.Dump();
    sw.Restart();

    for(int i = 0; i < 50000000; i++)
        mmc.DoStuffWrapped(1, 2, 3);

    "Wrapped function:".Dump();
    sw.Elapsed.Dump();
    sw.Restart();

    "Direct call:".Dump();
    for(int i = 0; i < 50000000; i++)
        mmc.DoStuffControl(1, 2, 3);

    sw.Elapsed.Dump();
}

public class MyMathyClass
{
    // References
    public Func<double, double> sin;
    public Func<double, double> cos;
    public Func<double, double> tan;
    // ...

    public MyMathyClass()
    {
        sin = System.Math.Sin;
        cos = System.Math.Cos;
        tan = System.Math.Tan;
        // ...
    }

    // Wrapped functions
    public double wsin(double x) { return Math.Sin(x); }
    public double wcos(double x) { return Math.Cos(x); }
    public double wtan(double x) { return Math.Tan(x); }

    // Calculation functions
    public double DoStuff(double x, double y, double z)
    {
        return sin(x) + cos(y) + tan(z);
    }

    public double DoStuffWrapped(double x, double y, double z)
    {
        return wsin(x) + wcos(y) + wtan(z);
    }

    public double DoStuffControl(double x, double y, double z)
    {
        return Math.Sin(x) + Math.Cos(y) + Math.Tan(z);
    }
}

Results:

Function reference:
00:00:06.5952113

Wrapped function:
00:00:07.2570828

Direct call:
00:00:06.6396096


问:
500 databases or 1 database with 500 tables or just 1 table with all the records?
I currently have an application that is used by a single end customer. For ease of discussion assume the application only needs a single database table for all records. I now need to support multi-tenancy and so in the future I will have about 500 customers using the same database server.

1) A possible solution is to have a separate database for each customer. As there will be around 500 customers that means having MySQL/SQL Server/Oracle/etc... host 500 separate databases. This sounds like overkill for a database server running on an average cloud based server.

2) Another solution is to stick with the single database I already have but to have 500 different tables, one for each end customer. Each customer only averages around 2000 records in their own table. This is easy to implement and I would guess makes it easy to migrate the customer to another server, just move the entire table data over.

3) Lastly I could stick to using a single table in the single database. Instead I add an additional column that identifies the customer the record belongs to. But then the table ends up with about 1,000,000 records which is the aggregate of all 500 customers that average 2,000 each.

I do not know enough about performance and scaling to know 1, 2, 3 is going to give the best performance. Any ideas?

答:
IMHO it will make a difference if you design a new application from scratch with multi-tenancy in mind, or if you are going to use a complex, existing application which was not designed for multi-tenancy.

For the first situation, the "one DB & one table" approach will probably be the best, as the others wrote. For the second, adding multi-tenancy to the application afterwards can be so hard that using different databases can be indeed the better alternative, since it avoids the need to change anything in your application. Of course, "different databases" results in a different overhead when using an Oracle system compared to an MS SQL server system or a MySQL server. In an Oracle System, there is also the option of "different schemas", and from Oracle 12c, there is a specific "Multitenant" option allowing you to create a container DB holding lots of "pluggable databases".

As long as you have really only one table, I expect your application not be so complex that multi-tenancy could not be implemented afterwards, but you wrote

For ease of discussion assume the application only needs a single database table for all records.

so I guess the real thing does have more tables, and you have to decide how hard it is to make the relevant changes to your application.


问:
negative boolean expressions and eager boolean OR
I come across these kinds of expressions and I have hard time reading it.
How do you read it properly to see if it is the right logic when debugging.</p>

```<code>if (!(userLoggedIn || isAdmin)) {
    console.log('User does not have rights');
    }
</code>```

答:
Generally, !(a || b) => (!a && !b),

so !(userLoggedIn || isAdmin) => !userLoggedIn && !isAdmin,

which is much clearer to me, probably due to the lack of parentheses.


答:
To me the underlying logic is:

userLoggedIn || isAdmin reads "user must be logged in or in admin mode".

if(!...) reads "If it is not the case, then ...".

Taken together your code means "if it is not the case that the user is logged in or is in admin mode, then print the error message".

This makes me wonder if you didn't mean that the user must be logged in and have admin rights.  In that case, you should replace || by &&.

Title: negative boolean expressions and eager boolean OR

Body:
I come across these kinds of expressions and I have hard time reading it.
How do you read it properly to see if it is the right logic when debugging.</p>

```<code>if (!(userLoggedIn || isAdmin)) {
    console.log('User does not have rights');
    }
</code>```


答:
With C# 6.0 you can use the feature of Static Import.

Your code could be:

```<code>using static System.Math;
using static System.Console;
namespace SomeTestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            double X = 123;
            double Y = 5;
            double Z = 10;
            double x = -Cos(X) * Sin(Z) + Sin(X) * Sin(Y) * Cos(Z);
            WriteLine(x); //Without System, since it is imported
        }
    }
}
</code>```

See: Static Using Statements (A C# 6.0 Language Preview)

Another C# 6.0 “syntactic sugar” feature is the introduction of using
  static. With this feature, it’s possible to eliminate an explicit
  reference to the type when invoking a static method. Furthermore,
  using static lets you introduce only the extension methods on a
  specific class, rather than all extension methods within a namespace.

EDIT: Since Visual Studio 2015, CTP released in January 2015, static import requires explicit keyword static. like:

```<code>using static System.Console;
</code>```

Body:
With C# 6.0 you can use the feature of Static Import.

Your code could be:

using static System.Math;
using static System.Console;
namespace SomeTestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            double X = 123;
            double Y = 5;
            double Z = 10;
            double x = -Cos(X) * Sin(Z) + Sin(X) * Sin(Y) * Cos(Z);
            WriteLine(x); //Without System, since it is imported
        }
    }
}

See: Static Using Statements (A C# 6.0 Language Preview)

Another C# 6.0 “syntactic sugar” feature is the introduction of using
  static. With this feature, it’s possible to eliminate an explicit
  reference to the type when invoking a static method. Furthermore,
  using static lets you introduce only the extension methods on a
  specific class, rather than all extension methods within a namespace.

EDIT: Since Visual Studio 2015, CTP released in January 2015, static import requires explicit keyword static. like:

using static System.Console;


答:
There's more to evaluate than just performance when considering multitenancy.  I'd recommend reading over this MSDN article for more details.

Broadly speaking, you need to consider these factors before you settle on a particular approach.

System administration costs

Database server costs (aka hardware)

Database licensing costs (aka software)

Complexities involved in writing code

Complexities involved in maintaining code

Validating security and environment separation

Expected Performance and SLAs

Per client and aggregated data usage

And as you noted, there's essentially three approaches to consider:

Dedicated databases for each client

Shared database, separate schemas

Shared database, shared schema

And a quick summary of pros and cons:

Dedicated database for each client

Higher costs across the board, but simpler code and easier to validate on the security side.  Trivial to upgrade a particular environment as a client's data usage increases.

Shared database, separate schemas

Decreased costs as compared to the dedicated database approach, but at the trade-off of increased complexity in the code.  And you'll need to be more diligent to make sure the schemas remain separate.  You'll potentially have more repetitive code here since you'll sometimes have to copy / paste things on a per-client basis.  Again, relatively trivial to migrate a client if their data usage justifies an upgrade.

Shared database, shared schema

Also has decreased costs, but code complexity becomes greater in order to make sure that things remain secure.  You run a higher risk of inadvertent data exposure if you make a mistake in the security access layer.  On the other hand, you'll have less repetitive code as you're not duplicating things across schemas.  A downside is that this approach has the most complicated migration path when a client's data usage exceeds the existing environment's abilities.

The second two approaches are what I have seen most commonly used due to the decrease in costs.

Organizations that have clients with widely different data usage tend to use the second approach.

Organizations with consistent and lower data usage lean towards the third.

Title: 500 databases or 1 database with 500 tables or just 1 table with all the records?

Body:
I currently have an application that is used by a single end customer. For ease of discussion assume the application only needs a single database table for all records. I now need to support multi-tenancy and so in the future I will have about 500 customers using the same database server.

1) A possible solution is to have a separate database for each customer. As there will be around 500 customers that means having MySQL/SQL Server/Oracle/etc... host 500 separate databases. This sounds like overkill for a database server running on an average cloud based server.

2) Another solution is to stick with the single database I already have but to have 500 different tables, one for each end customer. Each customer only averages around 2000 records in their own table. This is easy to implement and I would guess makes it easy to migrate the customer to another server, just move the entire table data over.

3) Lastly I could stick to using a single table in the single database. Instead I add an additional column that identifies the customer the record belongs to. But then the table ends up with about 1,000,000 records which is the aggregate of all 500 customers that average 2,000 each.

I do not know enough about performance and scaling to know 1, 2, 3 is going to give the best performance. Any ideas?


问:
When should I refactor a private class into a package-private class?
When I began implementing a class in my system (let's call it A), I realized I needed some kind of object that does something. So I needed a new class (let's call it B), but I made it a private static class of A.

Now, B is still only ever used by A, but A grew much bigger. Including the code for B, it's 320 LoC long.

The question is, should I move B outside of A, into a separate package-private class? It's still only ever used by A, but since A is getting big I think I should split it into smaller parts.

答:
I try to avoid inner classes in general unless they are simple lambdas, listeners with one or two lines of code, etc.

Once an inner class has a life of its own and performs more complex functions, I refactor it into its own top-level class. I will use either a standard interface or create my own for the class that used to enclose it (A). I then construct the B class and pass in a reference to the interface that A now implements and is used by B.

While A and B are tightly coupled, they probably do not need to be. Severing that coupling and using interfaces and references rather than an implicit outer-class this pointer/reference now means B is one step closer to being reusable. There is now an abstraction between them.

Often the reason for introducing another class is that the enclosing class needs to do additional work that it cannot do itself. That additional work is likely (in my experience) to violate the Single Responsibility Principle. Moving it into an inner class is one step toward fixing that, but is (in my opinion) a suboptimal fix. Refactoring as I mentioned above will fix the tight coupling and "multiple responsibility" concerns.

One final reason to split into multiple top-level classes is it makes the source files shorter. This has nothing to do with OOP principles and is purely aesthetic.


答:
Use all three.  One size does not fit all.

The shared model/shared server could be used for small implementations or for those customers who want the least amount of data security.  Probably need application chanages for this one.

Cost:   $

The exclusive model/shared server allows for increases data segregation but client share the same resources (server).

Cost:   $$$

The exclusive model/exclusive model allows for a unique silo.

Cost:   $$$$$

This model allows clients to pick and choose the best model that suits them (depending on size and security concerns).  Just need to figure out how much to charge for each to keep profitable.


答:
Number 1 is best performance, number 3 is worst. But really, as many other answers have stated - that is the last thing you need to be worried about, specially with the amount of data you posted in your question.

The things I would be worried about:

Who owns the data and how proprietary is it?

Are there realistically going to be schema changes and/or different live versions?

What type of maintenance will you need to do?

Any inter-client aggregation you need?

What's the budget here?

Are there any legal requirements? Can there be in the future?

To expand on each of these:

Who owns the data and how proprietary is it?

If this is your data, then this should not be an issue. However, if this is corporate data of the client, or any kind of personal data, or data that absolutely must not leak - number 3 is out of the question. Unless you waive in some magic to make only a subset of rows unreadable, you're allowing any client to access any other clients data. Your customers might not appreciate this. In fact - if you're a juicy target, then simply execution time or table stats (such as number of rows) already give more information than you may want to expose.

Number 2 is OK, as long as you get your permissions and users right.

Are there realistically going to be schema changes and/or different live versions?

The answer to this question is - of course there are, sooner or later. Unless you just have 1 text field in your DB where you put everything.

There are ways to change the schema gracefully - make sure the new version of the code works with both the old and new schema version, or vice-versa. You will also need to make sure all clients are updated timely. However this also means that you either need to force update the client, or span your schema change across 2 major updates.

How the above relates to your situation? Well, in number 3, you have to synchronize all updates of all clients. That is a nightmare to say the least. Numbers 1 and 2 are easier in this sense, since you can do problematic clients one-by-one without turning them off.

Number 3 is also hell in case one of the clients requests an older version of the app, because the new one doesn't suit them.

What type of maintenance will you need to do?

Backup is the first thing that comes to mind. Here option 3 outshines everything - just dump the table and you're done! Number 2 is OK - a full DB backup is not too difficult. Number 1 is bad - you have to setup a backup on EACH DB. It's incredibly easy to forget or fudge something. However providing a client a backup of their data on request is trivial in 1 and 2, but a bit involved in 3.

How often will you need to change queries to the DB? For number 3 they will be more complicated - or rather - they're as simple, but they have an incredible number of places you can screw up because you forgot the AND clientId = :clientId.

Any inter-client aggregation you need?

If the case of 1, you better hope you've got a good team of developers and an enterprise server. There is no way to do this that is both easy, reliable and cost-effective.

Number 2 is OK as long as you can generate your queries properly.

Number 3 is easiest.

You'd have to pose the question to your analytics department (if you have one).

What's the budget here?

Lots of DBs may need lots of licenses. And lots of open ports and possibly virtual machines. This depends on what exactly are you using and what hosting is it.

Are there any legal requirements? Can there be in the future?

There are sometimes legal requirements on where data can physically reside. If all your clients are from one country that shouldn't be a problem, but should you go world-wide it may. This is especially applicable to financial and personal data.

A question not mentioned here - are there requirements on latency for the DB? Your Australian or Russian client may not be very happy about their queries going all the way to NY (say).

Another one is resilience and DDoS - physically separated services for separate clients is just that much more difficult to take down.

TL;DR

All in all - I would say if you are using this as a small storage mostly for non-proprietary and non-critical data, and don't expect much growth (as in the amount of data, not company growth) or change in formats - use Number 3. Less hassle, less cost, less admins involved. If this is going to grow into proper datastores with possibly touchy stuff in them - use number 1. Number 2 is somewhere in between.


答:
All things equal, option #3 - all in one table (or set of tables).

In addition to some of the other reasons provided - easier maintenance and performance shouldn't be noticeably different if correctly indexed - there's also the issue of future proofing.

Consider the migration of data.  If you go with option 3, then in the future, its straight forward to migrate that to 1 or 2 if you really need to.  For example, if a customer ends up needing significant customizations such that they then need their own database.  You can just move their data into a new table, keeping ID's all the same.  On the other hand, it would be much tougher to go from 1 or 2 to option 3 if you discover reasons you need that data to be shared.  Its always easier to split data than combine it.


问:
Does it make sense to standardize including a created date and last updated date field on all DB tables?
My boss is currently attempting to apply some development standards to our team, so we had a meeting yesterday to discuss the standards which was mostly going well until she brought up:

All DB tables will have a CreatedDate and LastUpdatedDate column, updated by triggers.

At this point our team suffered an opinion schism; one half of us think that doing this on all tables is a large amount of work with little benefit (we work on fixed-budget projects so any cost comes from our company's profits); the second half believe it will help with support of the projects.

I am firmly in the former camp. While I appreciate that some outside cases would cause the extra columns to improve supportability, in my opinion the amount of work that would be required to add the columns in the first place, as well as maintenance, would cause us to spend less time on more important things like Unit- or Load-Testing. Also, I'm fairly sure that these extra columns would make it more awkward to use an ORM - bearing in mind that we mainly use C# and Oracle, which isn't very ORM-happy to start with.

So, my question is twofold:

Am I in the right camp? I don't claim to have world-renowned database skills, so this might be a trivially easy addition with no adverse side-affects.

How would you deal with a situation where a meeting about standards devolves into a slagging match? How can I really sell that this standard is not going to help us in the long term?

答:
I agree wholeheartedly. Almost every table in every database should have at least 2 fields:  the creation date and update date.  There are many reasons that you should put a create date and update date. For obvious reasons that prior people stated…which is audit.

I have been designing systems and databases for 25 years and have worked for hundreds of clients.  There is not a single client that did NOT need this.

There are 2 basic ways to do this:

1 - The first practice is letting database do the work and put it directly into the table design.  Which is the bare minimum, I would recommend.

2 - The other practice, which I prefer....is using a replication tool to handle this.  There is little overhead and no cost to DEV teams.  However the tools are expensive. One additional advantage is the delete process can be audited much easier with this type of tool. Without a replication tool you would need to create an audit table and fire triggers for deletes - not a good practice in my opinion.

Another benefit to having these fields is the data warehouse and ODS that is ALWAYS built for any OLTP system.  You cannot effectively pull incremental data without it. Otherwise you risk having to reload the entire DB every day.

There is an enormous number of other business reasons for putting in these 2 dates, which I will not delve into here.  Do your homework and I’m sure 3-6-12-48 months down the road you will be very happy you put in these 2 simple fields.

I have implemented and usually recommend both solutions where possible.


答:
It is purely a software coding guidelines call (process compliance call).

enumerated values are crux of many algorithms and it should be handled with utmost care. One another option of usage is that it is better that the name of the enumeration constant conveys the value via its name itself to make the understanding clear.

Example :

```<code>enum retries {
    RETRY_ZERO,
    RETRY_ONE,
    RETRY_TWO,
    RETRY_THREE
};
</code>```

Title: Explicitly define enum values, even if the default value is the same?

Body:
There are times when an enum's values are important: it is not necessary for them to be unique, they also need to have specific values. In such cases, should the values be explicitly defined, even if they coincide with the defaults? An example:

```<code>enum Car {
    DeLorean = 0,
    Lada = 1
};
</code>```

Imagine that for whatever reason your application assumes that DeLorean and Lada have those specific values. Incidentally, they are the same as the default values but does that mean it is no longer necessary to use explicit definitions?

Leaving them implicit makes me uneasy. It seams to me that having them explicitly defined is communicating to future programmers that the specific values are important and it helps prevent mistakes like this:

```<code>enum Car {
    Dacia,
    DeLorean,
    Lada
};
</code>```

In the example above, another programmer who is not aware of the restriction I mentioned introduces a new enum value and, wanting to keep the code tidy, puts it in alphabetical order. However, DeLorean and Lada now have different numerical values and a potentially silent bug has been introduced.

My reasoning seems correct to me (obviously), but the code review team for a company I used to work with didn't agree. Am I wrong?

Body:
It is purely a software coding guidelines call (process compliance call).

enumerated values are crux of many algorithms and it should be handled with utmost care. One another option of usage is that it is better that the name of the enumeration constant conveys the value via its name itself to make the understanding clear.

Example :

enum retries {
    RETRY_ZERO,
    RETRY_ONE,
    RETRY_TWO,
    RETRY_THREE
};


问:
How to prevent third party misuse of what is intended to be a private api (avoiding what happened to Snapchat)?
I have never used Snapchat and do not intend to but I have been reading up about what happened to them with respect to the recent media coverage about pictures being leaked especially because I am also writing an api for my app right now and I want to avoid this from ever happening to me.

Having looked into what happened it seems Snapchat has not actually done anything wrong. It appears a third party web app sniffed out their api calls - not something to be surprised about, anyone can do it, and that's why apis should require authentication, how this is done can vary but probably through some kind of token.

In any case, Snapchat api did require authentication so I thought they would have been safe but it turns out that the third party apps got users to voluntarily enter their usernames and passwords into the app, thereby allowing login and authentication.

Remember this was a third party app, not the official snapchat app. I would never have expected users to do something like this, it's like giving away the keys to your car to anyone who passes by instead of the hotel valet.

Now to the point, are they any techniques to avoid this from happening that I can apply for my api? I am not sure how I can prevent myself from ending up in the same situation.

答: One possible solution (but with a small trade-off) would be to limit the number of valid tokens a specific user is allowed to have at any given time. This will not STOP a third party's ability to access the site, however it would introduce a level of annoyance for a user that is using your API in an inappropriate way. If you set this limit to 1, then when the 3rd party app logs into the user's account, it would deauthorize any other sessions.</p>


问:
Testing for object equality by comparing the toString() representations of objects
Following on from this question - how do you explain to someone that this is just crazy!:

```<code>boolean someMethod(Map<String, Object> context) {
    Object object = context.get("someProperty")
    Object another = context.get("anotherProperty")

    return object.toString().equals(another.toString());
}
</code>```

Apparently the reason for why Object.equals(...) is not used is that "what's contained in the Map is not concretely known, but is definitely known to be one of the primitive wrappers i.e. String, Double, Boolean, etc... and that Boolean.TRUE is required to be equal(...) to the String "TRUE"".

答:
The indicated method would be very odd as part of a public API.  Whether or not it is crazy as a private or protected part of a class would depend upon how it was being used.  The method appears to encapsulate two different quirky aspects, either of which could plausibly be justifiable in some contexts but not others; while it would seem unlikely that both would be justifiable, there's no particular reason why they couldn't be.

The first quirky aspect is the fact that the method is searching for particular fixed strings within the maps.  Such behavior is generally ugly (and it would probably be better if the strings were defined as constants) but could be justifiable if:

The map is never exposed to code outside the package.

It is necessary to use some collection type to store aggregates, each of which consists of a mapping plus a few other bits of information).

The use of the encapsulated mapping is such that no key could possibly conflict with the strings that are used for the "few other bits of information".

The mapping is used so much more than the other bits of information stored within the advocate that using a class which contained a Map along with the other bits of information would be much more cumbersome than using a map which has a few bits of information associated with magic keys.

Some languages and frameworks would provide alternate means of attaching supplemental information to a type, but the approach indicated here is sometimes the most practical one given Java's type system.

The second ugly aspect is that the code is comparing two objects' ToString values as a means of comparing the objects.  In most cases, either the objects will be strings (in which case one could just compare them), or they would be some other type which has some attribute of type String such a name, in which case one should cast the objects to that other type, call GetName on both instances, and compare the resulting strings.  If, however, the majority of table entries would only need to store strings, but a few might need to have an entry which combines a string with a small amount of supplemental information, it may in some cases be easier to store things in the table as type Object with the expectation that every entry will either be a String, or be some known kind of object.  Since Java's type system has no concept of "thing which will either be type1 or type2", using Object, though ugly, may be the only practical alternative in cases where one of the types is something like String which would share no common ancestor--other than Object--with any user class.


问:
I made an HTML5/Javascript game. Do I have to license it?
So I created an HTML5/Javascript online game. I host it on my website for anyone to play for free. I am still currently working on it. Do I need to license my game? And if so, what license do you recommend? I was looking at some open source licenses like GPLv3, but i'm not sure if I even need a license?

If I need a license, I need one that allows:

my game to be totally free to play

my game to be embedded on other websites

no one else can re-distribute my game, unless it is under my name and not theirs

Also, if I need a license, where do I include it? Do I just have to state somewhere that the game is licensed under "xxxxx license"? Or do I have to include a link to the license file hosted on my server? OR even include the license file in my game (i.e. in the games javascript file, or under a game menu, etc.)?

答:
You want it free? Just pick a license. From that Jeff's post:

Because I did not explicitly indicate a license, I declared an implicit copyright without explaining how others could use my code. Since the code is unlicensed, I could theoretically assert copyright at any time and demand that people stop using my code. Experienced developers won't touch unlicensed code because they have no legal right to use it. That's ironic, considering the whole reason I posted the code in the first place was so other developers could benefit from that code. I could have easily avoided this unfortunate situation if I had done the right thing and included a software license with my code.

If you want it as free as possible and whatever, then go with WTFPL.

OwnerDisplayName: Jacob


问:
If someone offers you an unverified statement regarding software development practices, do you respond with "citation needed"?
Recently I attended a lecture given by Greg Wilson (Chief Scientist of Software Carpentry). From the abstract:

The idea that claims about software development practices should be based on evidence is still foreign to software developers,
  but this is finally starting to change: any academic who claims that a particular tool or practice makes software development
  faster, cheaper, or more reliable is now expected to back up that claim with some sort of empirical study.

Overall, the lecture was very informative and left me thinking quite deeply about my approach to development. In particular, I now find myself looking for citations to back up a lot of statements. Previously, I had slipped into the habit of simply repeating offered truths, with perhaps a mental note to go check up on it later.

Putting it bluntly, I was being gullible.

Here's an example taken from the lecture:

"If more than 25% of the code needs refactoring, it's quicker to rewrite it".

Sounds plausible, but is it true? Where's the study backing this up? Is it true for all languages? And so on.

OK, it's quite possible to take this to an extreme and not believe anything by anyone unless you have derived it yourself from
first principles. That way lies madness (or maybe mathematics ;-) ). But, if someone comes up to you with a statement along the
lines of "Hey, by doing this in [pick language of moment] we'll be able to boost productivity by [pick multiple of 10]%" are you
inclined to just accept it, or are you going to ask for proven evidence?

If it's the latter (and I hope it is) then

where would you go to find this evidence?

how stringent would you be?

In short, if someone offers you an unverified statement, will you respond with "citation needed"?

答:
Many developers base their moment to moment decisions on experience in the trenches working with code and the customers which that code serves.

When a class or method has become so fragmented by bug fixes and customer change requests that it has become unmaintainable, a developer will sometimes make the decision to rewrite it rather than refactor, under the theory that he will save time and effort over the long term, because the resulting code will be of higher quality.

This kind of experience intelligence is what HR departments call "human capital." It is one of the things that makes experienced developers valuable, and one of the reasons that good companies do things to try and preserve the longevity of their people.

It doesn't seem fair or even practical to ask experienced developers to come up with a study and empirical data as proof that their techniques are valid.  Experience doesn't work that way.  To the contrary, experience is something of a "felt sense."  In the refactoring world, we often call it "smell."

Ultimately, a statement like "If more than 25% of the code needs refactoring, it's quicker to rewrite it" cannot be proven to work under all circumstances, so the statement [citation-needed] is really a way to inform the dogmatic programmer who seeks to force his views on others that it's not always "His Way or the Highway."

ContentLicense: CC BY-SA 2.5


问:
Is it a good practice to run unit tests in version control hooks?
From the technical point of view it is possible to add some pre/post push hooks which will run unit tests before allowing some specific commit to be merged to remote default branch.

My question is - is it better to keep unit tests in build pipeline (thus, introducing broken commits to repo) or it's better just not to allow "bad" commits to happen.

I do realize that I'm not limited with this two options. For instance, I can allow all commits to branched and tests before pushing merge commit to repo. But if you have to choose between exactly this two solutions, which one you'll choose and for what exactly reasons?

答:
I would say it depends on the project and the scope of the automated tests that are run on the "commit".

If the tests you like to run in the check-in trigger are really fast, or if the developer workflow will force some administrative work after such a check-in anyway, the I think it should not matter much and force the devs to only check in stuff that absolutely runs the most basic tests. (I'm assuming you would only run the most basic tests on such a trigger.)

And I think, speed/workflow permitting, it is a good thing to not push changes to other developers that fail the tests - and you only know if they fail if you run them.

You write "commit ... to remote branch" in the question, which would imply to me this is (a) not something a dev does every few minutes, so a small wait may be very well acceptable
, and (b) that after such a commit the code changes may impact other devs, so additional checks may be in order.

I can agree with the other answers on "don't make your devs twiddle thumbs while waiting" for such an operation.


答:
Let me be the one to disagree with my fellow answerers.

This is known as Gated Check-ins in the TFS world, and I expect elsewhere. When you attempt to check-in to a branch with the gated check-in, the shelveset is sent off to the server, which makes sure your changes build and the specified (read: all) unit tests pass. If they don't, it notifies you that you're a bad monkey who broke the build. If they do, the changes go into source control (yay!).

In my experience, gated check-ins are one of the most important processes for successful unit testing - and by extension, software quality.

Why?

Because gated check-ins force people to fix broken tests. As soon as broken tests become something people can do rather than must do, they become de-prioritized by lazy engineers and/or pushy business people.

The longer a test is broken, the harder (and costlier) it is to fix.

Because as soon as people should run the tests rather than must run the tests, running the tests are circumvented by lazy/forgetful engineers and/or pushy business people.

Because as soon as unit tests impact your commit time, people really start caring about making their tests unit tests. Speed matters. Reproducability matters. Reliability matters. Isolation matters.

And of course, there's the benefit you brought up originally - when you have gated check-ins and a solid suite of tests, every single changeset is "stable". You save all that overhead (and potential for error) of "when was the last good build?" - all builds are good enough to develop against.

Yes, it takes time to build and run the tests. In my experience 5-10 minutes for a good sized C# app and ~5k unit tests. And I don't care about that. Yes, people should check-in frequently. But they should also update their tasks frequently, or check their email, or get some coffee or dozens of other "not working on code" things that make up a software engineer's job to occupy that time. Checking out bad code is far more costly than 5-10 minutes.

Title: Is it a good practice to run unit tests in version control hooks?

Body:
From the technical point of view it is possible to add some pre/post push hooks which will run unit tests before allowing some specific commit to be merged to remote default branch.

My question is - is it better to keep unit tests in build pipeline (thus, introducing broken commits to repo) or it's better just not to allow "bad" commits to happen.

I do realize that I'm not limited with this two options. For instance, I can allow all commits to branched and tests before pushing merge commit to repo. But if you have to choose between exactly this two solutions, which one you'll choose and for what exactly reasons?


问:
is it a bad programming practice to return a new object in a property
I've always had this question and I think it is time to settle the answer, is it a heavy load to do this :

```<code>    public Rect Bounds
    {
        get
        {
            var Top = (_targetPosition + _translationY) - _size / 2.0f;
            return new Rect(callOutStarMargin, Top, _size, _size);
        }
    }
</code>```

as an alternative of this :

```<code>    private Rect _boundsRect = new Rect();

    public Rect Bounds
    {
        get
        {
            var Top = (_targetPosition + _translationY) - _size / 2.0f;
            _boundsRect.Y = Top;
            return _boundsRect;
        }
    }
</code>```

doing this I'm avoiding to create a new Rect everytime the property is invoked, I'm not sure if doing this in the first way would create an extra memory/speed overweight, if lets say this property is accessed 1 or 2 times on a list of 100 items each second.

So which one should I choose ?

EDIT:

I think I'm not being clear here, my real question is How heavy is it making this new instructions of simple objects like Rect, How efficient is C# garbage collector for example in this scenario of 100 new rects per second , and the cpu cycle difference between one or the other way

答:
The simple test I would suggest for whether it should be acceptable for a property (vs a method) to a new object in a given situation is whether callers would be expected to care whether they receive a new object or a pre-existing one that happened to have the right characteristics.  If callers would expect to receive a new object, then the code in question should be a method.  If callers would expect to receive a pre-existing object, then the code should supply one.  Code which may return a new object should only be a property if callers will not particularly expect to receive a new object, but won't mind if they do get one.

Generally, there are two situations where callers will have such non-expectation:

The first call will lazily create the object which will be returned by that and all future calls, and nothing about the object will indicate when it was actually created.  Further, code should ensure that there's no way two calls could return different objects, even if they are performed simultaneously by different threads [use locking or CompareExchange to ensure this].

The object being constructed is immutable, and callers are expected to care only about the data contained therein, rather than its identity.  Strings are a prime example of this.

For performance reasons, any properties which return objects that are expensive to create should cache the most-recently-created object to ensure that consecutive repeated calls which should report the same state can reuse the same object; it may sometimes be useful to cache additional objects in cases where a property's state might revert to an earlier value, but the performance benefit of doing that in different situations may range anywhere from "worse than nothing" to "drastic".  Except when caching would be impractical, however, the question of whether to use a property or method should be primarily determined by semantics.


答:
You should return a new object. Always.

The overhead is minimal in all modern languages. But even if it weren't, reusing an existing static object is tantamount to returning the value in a global variable. And that will lead to BAD THINGS.

Even if program is not threaded/concurrent, its very feasible that a function (or different functions in a call chain) will want to examine the bounds of multiple rectangles, logically at the same time. If you have just the one global object, you will get very wrong answers. If your program is at all multi-threaded, things will get even worse. Either way, errors will happen and it will be confusing to figure out why a simple "what are the bounds of this?" call does not seem to have a temporally stable, consistent set of values.

Title: is it a bad programming practice to return a new object in a property

Body:
I've always had this question and I think it is time to settle the answer, is it a heavy load to do this :

```<code>    public Rect Bounds
    {
        get
        {
            var Top = (_targetPosition + _translationY) - _size / 2.0f;
            return new Rect(callOutStarMargin, Top, _size, _size);
        }
    }
</code>```

as an alternative of this :

```<code>    private Rect _boundsRect = new Rect();

    public Rect Bounds
    {
        get
        {
            var Top = (_targetPosition + _translationY) - _size / 2.0f;
            _boundsRect.Y = Top;
            return _boundsRect;
        }
    }
</code>```

doing this I'm avoiding to create a new Rect everytime the property is invoked, I'm not sure if doing this in the first way would create an extra memory/speed overweight, if lets say this property is accessed 1 or 2 times on a list of 100 items each second.

So which one should I choose ?

EDIT:

I think I'm not being clear here, my real question is How heavy is it making this new instructions of simple objects like Rect, How efficient is C# garbage collector for example in this scenario of 100 new rects per second , and the cpu cycle difference between one or the other way


问:
How do you learn a language without actual tools?
I will bring a concrete case here.

I have a project involving Sketch and Arduino. Since I was they only guy willing in the group, I had to take the Sketch part. The problem is that our informatics group is part of an bigger organisation, and the organisation doesn't allow us to take the Arduinos with us at home. We are there for only 2 hours of week or so, and learning anything there is out of the question (Noise, other projects, etc). So I am stuck here without anything physical, only books. I don't even have a book at that, by the way.

The same case can be made for learning iPhone developing without running the apps, or whatnot. So how do you proceed here?

答:
It's great when you can have hands-on experience allowing interactive exploration and experimentation. But it is by no means an essential part of learning a technique or technology--in computing or most other fields of human endeavor.

While you're not going to be able to master skills requiring kinesthetics (e.g. music, dance, kung fu) without doing them, programming is as much about imagining how a machine's state is arranged and how it can be guided as it is about typing commands or running code. The task needs think-time as much as touch-time, even if you have the physical gear handy and available.

There are many historical examples of students learning apart from the computer. While we've been use to having our own personal, immediately-available computers for the past 35 years, in the first half of the IT industry, machine time was very scarce and the equipment highly shared. Students programmed offline as a matter of course, then submitted their runs to the datacenter in a highly indirect fashion. This workflow continues to be common to this day with embedded devices and with new computer systems, sufficient equipment for which is simply not available for each developer to own and constantly interact with.

So your situation may not be ideal, but it's hardly intractable or unprecedented. So buckle down and learn the language by reading about it. Imagine programs you'd like to run and write them down. Then when you do get hands-on time, you'll be ready to try your ideas.

Btw, this is not just a theory. I've learned a number of languages (including Ada, Algol, APL, Fortran, Icon, Modula-2, MOT68K assembler, PL/I, Self, Smalltalk, and SNOBOL) for which I did not have a place to run code at the time. I got better later when I had more access, but the ability to run your code  is manifestly not a requirement to learn at least a large swath of a programming language.


问:
How much should I break up my unit tests?
I recently learned about unit tests and TDD and have started going back to add unit tests to my code (and thank god, it's proven that some things I've written are much more broken than I thought).

That being said, I'm having a hard time figuring out how much (or little) should go into each test.  For example, consider a class I wrote with several methods.  Right now I do something like

```<code>class test_myclass(unittest.TestCase):

    def setUp(self):
        ...
    def test_func1(self):
        ...
    def test_func2(self):
        ...
    etc
    def tearDown(self):
        ...
</code>```

But what if each (or at least some) method can fail in a lot of different ways, or has a lot of edge cases?  Then I'm stuck doing something like

```<code>def test_func1(self):
    self.assertEqual(func1(working_input), expected_value)
    self.assertRaises(Some_error, func1, args)
    self.assertRaises(Some_other_error, func1, args)
    etc
</code>```

And it could get pretty hairy, and rather unclear where things are failing.  So I thought I might break it up more, and devote a class to each function (that has enough test cases to be worth it) but that seems like a lot of work, and more time than I should probably be spending on testing.

I also considered writing multiple tests for a given method, such as

```<code>def test_func1(self):
    self.assertEqual(func1(working_input), expected_val)
def test_func1_bad_input_1(self):
    self.assertRaises(error, func1, bad_args)
def test_func1_bad_input_2(self):
    self.assertRaises(error2, func1, bad_args_2)
...
</code>```

And this seems cleaner than a unit testing class per method, but still seems like it might be to little in any given test.

How much testing is too much?

While my example was given in python, I'm open to language agnostic answers

答:
In an ideal world, a single unit test has only one thing that can cause it to fail, and that one thing can only cause that test to fail.

I'm not sure I've seen that ever be true though... A more attainable approach is that a single unit test tests a single path though a function. The concept of code coverage is helpful here, but the gist of it is that any decision Your code makes represents (at least) a different path. Some paths may be too difficult (or actually impossible) to unit test, but that is the level of granularity to work towards.

The benefit is that when a test fails, you spend less time and effort figuring out why.

And yes, it seems like a bit more work, but once you're used to it, the tests are quick and easy to write - and they'll save you tons of time.


问:
Separating UI from logic
I'm trying to develop a little game and for this I'd like to separate the UI from the game logic.

So I'm thinking of using an "Animator" class that will be responsible for rendering the objects, but I have a bit of a dilemma here. I can think of 2 options to implement it:

Option 1:
for each object the "Animator" will have a ObjectAnimator class which will expose a "Render(IAnimatedObject)" method.
It will receive the entire object and render it according to its current state.
The problem I see here is that each object will have to hold the animation state inside him which increases the coupling between the object and the animation.
The benefit of this approach is that the object doesn't know its ObjectAnimator...

Option 2:
Each object will expose a "GetAnimator" method which will give us its animating object.
the problem I see here is that if I have hundreds of objects, I'll need to have hundreds of ObjectAnimator objects as well.
It will also increase the coupling between the object and the animation object because the object will have to know it animator.
On the other hand, the object itself won't have to hold it animation state.

which option is better?
Is there
an even better option than those I wrote?

答:
Steal an idea from gui libraries: every drawable object implements Drawable which has one method:

```<code>draw(graphics_context)
</code>```

This approach has been in almost every gui hierarchy I can recall, including canvases.

Title: Separating UI from logic

Body:
Steal an idea from gui libraries: every drawable object implements Drawable which has one method:

draw(graphics_context)

This approach has been in almost every gui hierarchy I can recall, including canvases.


问:
Issues about static injection in Spring?
I use spring-boot with spring xml in my project.
I wrapper the DAOs in a DataAccessService class to serve as a DB service layer, both the service and the DAOs are injected in spring xml and used by Autowired.

Now I want to have a XXXutils class to provide some static useful functions.
Some of the functions need to access the database. But I can't access the DB service or the DAO in static method.

How should I do this? Can I Autowire a static DB service or the DAO in XXXUtils class? May be it not a good practice?

I even don't know whether Spring support the static injection.

Is there any good practice about this?

答:
You can do like this:

```<code>public class XXXUtils
{

    @Autowired
    private DataAccessService dsService;

    private static XXXUtils utils;

    @PostConstruct
    public void init()
    {
        utils = this;
        utils.dsService = this.dsService;
    }

    public DataAccessService getDsService()
    {
        return dsService;
    }

    public void setDsService(DataAccessService dsService)
    {
        dsService = dsService;
    }

    public static XXX fun1()
    {

    }

    public static String getDBData()
    {

        return utils.dsService.DsServiceFunc();
    }
</code>```

Then you can use the XXXXUtils.getDBData() to access the DB.

and in spring xml you can config like this:

```<code><bean id="xxxUtils" class="package of the XXXXUtils" init-method="init">
    <property name="dsService" ref="dsService"/>
</bean>
</code>```

Hopes this can help you :-)

Body:
You can do like this:

public class XXXUtils
{

    @Autowired
    private DataAccessService dsService;

    private static XXXUtils utils;

    @PostConstruct
    public void init()
    {
        utils = this;
        utils.dsService = this.dsService;
    }

    public DataAccessService getDsService()
    {
        return dsService;
    }

    public void setDsService(DataAccessService dsService)
    {
        dsService = dsService;
    }

    public static XXX fun1()
    {

    }

    public static String getDBData()
    {

        return utils.dsService.DsServiceFunc();
    }

Then you can use the XXXXUtils.getDBData() to access the DB.

and in spring xml you can config like this:

<bean id="xxxUtils" class="package of the XXXXUtils" init-method="init">
    <property name="dsService" ref="dsService"/>
</bean>

Hopes this can help you :-)