问:
How to avoid excessive method overloading?
We have quite a lot of places in the source code of our application , where one class has many methods with same names and different parameters. Those methods always have all the parameters of a 'previous' method plus one more.

It's a result of long evolution (legacy code) and this thinking (I believe):

"There is a method M that does thing A. I need to do A + B. OK, I know ... I will add a new parameter to M, create a new method for that, move code from M to the new method with one more parameter, do the A + B over there and call the new method from M with a default value of the new parameter."

Here is an example (in Java-like-language):

```<code>class DocumentHome {

  (...)

  public Document createDocument(String name) {
    // just calls another method with default value of its parameter
    return createDocument(name, -1);
  }

  public Document createDocument(String name, int minPagesCount) {
    // just calls another method with default value of its parameter
    return createDocument(name, minPagesCount, false);
  }

  public Document createDocument(String name, int minPagesCount, boolean firstPageBlank) {
    // just calls another method with default value of its parameter
    return createDocument(name, minPagesCount, false, "");
  }

  public Document createDocument(String name, int minPagesCount, boolean firstPageBlank, String title) {
    // here the real work gets done
    (...)
  }

  (...)
}
</code>```

I feel like this is wrong. Not only that we can't keep adding new parameters like this forever, but the code hard to extend/change because of all the dependencies between methods.

Here are few ways how to do this better:

Introduce a parameter object:

```<code>class DocumentCreationParams {

  String name;
  int minPagesCount;
  boolean firstPageBlank;
  String title;

  (...)
}

class DokumentHome {

  public Document createDocument(DocumentCreationParams p) {
    // here the real work gets done
    (...)
  }
}
</code>```

Set the parameters to the DocumentHome object before we call createDocument()

```<code>  @In
  DocumentHome dh = null;

  (...)

  dh.setName(...);
  dh.setMinPagesCount(...);
  dh.setFirstPageBlank(...);

  Document newDocument = dh.createDocument();
</code>```

Separate the work into different methods and call them as needed:

```<code>  @In
  DocumentHome dh = null;

  Document newDocument = dh.createDocument();
  dh.changeName(newDocument, "name");
  dh.addFirstBlankPage(newDocument);
  dh.changeMinPagesCount(new Document, 10);
</code>```

My questions:

Is the described problem really a problem?

What do you think about suggested solutions? Which one would you prefer (based on your experience)?

Can you think of any other solution?

答:
Using a parameter object is a good way to avoid (excessive) overloading of methods:

it cleans up the code

seperates the data from the functionality

makes the code more maintainable

I would, however, not go too far with it.

Having an overload here and there is not a bad thing. It is supported by the programming language, so use it to your advantage.

I was unaware of the builder pattern, but have used it "by accident" on a few occasions. Same applies here: don't overdo it.
The code in your example would benefit from it, but spending a lot of time implementing it for every method that has a single overload method is not very efficient.

Just my 2 cents.


问:
ID properties on Domain objects in DDD
In my domain I have an Account object.

e.g.

class Account
{
    public string Number;
    public string SortCode;
}
```

Within the context of DDD, should this account object have an ID property? The ID would be a primary key, basically a database artefact.

答:
It depends. If your Account class shall be mapped to a relational database, then its not just a good idea, but proven practice, to use technical IDs for every table as PKs (and FKs, referencing those PKs). To my experience, separating the technical PK of all tables from the "domain keys" (like the "bank account number") works very well and helps you to avoid all kind of technical issues. I typically name those PKs not just ID, but <class-Name>Id, so in your case AccountID.

If your class above will just be used as an input to a code generator which will generate the "real" code of your implementation language as well as your CREATE TABLE statements, some CRUD code etc., you probably don't need to add the ID attribute in the class code directly. If you are going to use an ORM, it depends on the ORM if it can add ID attributes as PKs automatically, or if it expects you to add those IDs manually.

In a DDD context, it may probably be helpful to hide those technical details when discussing the model with your domain experts, but show them when you change your viewpoint to the implementation of the model. If your tool set allows to display the model in those different levels of abstraction, make use of it. But if the tool set does not allow it, add the ID attributes and tell your domain experts that those are just "technical attributes".

ContentLicense: CC BY-SA 4.0

Title: ID properties on Domain objects in DDD

ContentLicense: CC BY-SA 3.0


问:
When using MVVM, should you create new viewmodels, or swap out the models?
Say I have a viewmodel like this:

```<code>public class EmployeeViewModel
{
    private EmployeeModel _model;

    public Color BackgroundColor { get; set; }
    public Name
    {
        get { return _model.Name; }
        set
        {
            _model.Name = value;
            NotifyPropertyChanged(Name);
        }
    }
}
</code>```

So this viewmodel binds to a view that displays an employee. The thing to think about is, does this viewmodel represent an employee, or a "displayable" employee. The viewmodel contains some things that are view specific, for instance the background color. There can be many employees, but only one employee view.

With this in mind, when changing the displayed employee, does it make sense to create a new EmployeeViewModel and rebind to the view, or simply swap out the EmployeeModel. Is the distinction even important, or is it a matter of style?

I've always leaned toward creating new viewmodels, but I am working on a project where the viewmodels are created once and the models are swapped out. I'm not sure how I feel about this, though it seems to work fine.

答:
I would suggest using a generic BaseViewModel and then having subsequent ViewModels inherit from that one. In order for the BaseViewModel to work, you would have to use reflection.

```<code>public class BaseViewModel<T> : IViewModel
where T: new(), class
{
    // I handle most of the logic for the ViewModels and I can process
    // any model using reflection. I don't even know property names or
    // how many properties a model has, the Reflect class I refer to helps
    // me process everything
}

public EmployeeViewModel : BaseViewModel<EmployeeModel>
{
    // I have very little to do here if anything
}

public ManagerViewModel : BaseViewModel<ManagerModel>
{
    // I have a little to do so I'll add a few new methods
    // and perhaps override my parent methods
}
</code>```

My BaseViewModel, without knowing anything about the generic models handles much of my heavy lifting (ie SelectedRecord, CurrentRecord, AddRecord, DeleteRecord, ValidRecord). And after implementing my Reflection class, you never have to know anything about which properties are being used by the model.

In my model, it is VERY important that my property attributes contain type info, names, etc. or else my Reflect class would be useless.

It makes adding new View/ViewModels (I use the same logic for my Views) so simple and the only time I have to add properties and methods to my child view model is when it behaves differently than the rest.

Everything is dynamic. The only time I have to refer to properties in my Model, like in your example, is when Im designing my model. Once I've created my model, creating my views and viewmodels are simple. Sample model

```<code>public EmployeeModel: BaseModel
{
    [Column(Title = "#", Field = "employee_id"...)]
    public ID{ get; set;}
    ...
}
</code>```

Body:
I would suggest using a generic BaseViewModel and then having subsequent ViewModels inherit from that one. In order for the BaseViewModel to work, you would have to use reflection.

public class BaseViewModel<T> : IViewModel
where T: new(), class
{
    // I handle most of the logic for the ViewModels and I can process
    // any model using reflection. I don't even know property names or
    // how many properties a model has, the Reflect class I refer to helps
    // me process everything
}

public EmployeeViewModel : BaseViewModel<EmployeeModel>
{
    // I have very little to do here if anything
}

public ManagerViewModel : BaseViewModel<ManagerModel>
{
    // I have a little to do so I'll add a few new methods
    // and perhaps override my parent methods
}

My BaseViewModel, without knowing anything about the generic models handles much of my heavy lifting (ie SelectedRecord, CurrentRecord, AddRecord, DeleteRecord, ValidRecord). And after implementing my Reflection class, you never have to know anything about which properties are being used by the model.

In my model, it is VERY important that my property attributes contain type info, names, etc. or else my Reflect class would be useless.

It makes adding new View/ViewModels (I use the same logic for my Views) so simple and the only time I have to add properties and methods to my child view model is when it behaves differently than the rest.

Everything is dynamic. The only time I have to refer to properties in my Model, like in your example, is when Im designing my model. Once I've created my model, creating my views and viewmodels are simple. Sample model

public EmployeeModel: BaseModel
{
    [Column(Title = "#", Field = "employee_id"...)]
    public ID{ get; set;}
    ...
}


答:
I don't think that id is a database artefact. How do you know that account you are working with is correct? You know it's a correct account because it probably has a unique identifier. In your case the unique identifier is called "Id", so naturally you think it's a database artefact. Because of this I think that it's perfectly fine to have Id property in your domain model.

On a side note, I would NOT have a foreign key property in a domain model. For example, instead of having AddressId in the domain model, I would have an Address property and that would contain the address id.

Title: ID properties on Domain objects in DDD

Body:
In my domain I have an Account object.

e.g.

class Account
{
    public string Number;
    public string SortCode;
}
```

Within the context of DDD, should this account object have an ID property? The ID would be a primary key, basically a database artefact.


答:
As the requirements change your view model will have to adapt to these requirements.

It might be the case that you want to display employee in multiple screens. If that's the case, then I would re-use the same view model. You may want to rename this view model to DisplayEmployeeViewModel, which is perfectly fine.

Later on you may have to create UpdateEmployeeViewModel and RemoveEmployeeViewModel.

On a side note, having a BackgroundColor in the view model might not be a good idea. Anything to do with presentation (colours, visibility, font size etc) normally lives in the view.

With regards to swapping out view models - I normally just swap out the models. For example, I have a view model that lists potential mail recipients. When recipient is selected, I store it in the SelectedRecipient property (which is a model). At no point I renew the view model.

Title: When using MVVM, should you create new viewmodels, or swap out the models?

Body:
Say I have a viewmodel like this:

```<code>public class EmployeeViewModel
{
    private EmployeeModel _model;

    public Color BackgroundColor { get; set; }
    public Name
    {
        get { return _model.Name; }
        set
        {
            _model.Name = value;
            NotifyPropertyChanged(Name);
        }
    }
}
</code>```

So this viewmodel binds to a view that displays an employee. The thing to think about is, does this viewmodel represent an employee, or a "displayable" employee. The viewmodel contains some things that are view specific, for instance the background color. There can be many employees, but only one employee view.

With this in mind, when changing the displayed employee, does it make sense to create a new EmployeeViewModel and rebind to the view, or simply swap out the EmployeeModel. Is the distinction even important, or is it a matter of style?

I've always leaned toward creating new viewmodels, but I am working on a project where the viewmodels are created once and the models are swapped out. I'm not sure how I feel about this, though it seems to work fine.


问:
How to break these long C++ lines in a neat way?
I'm on my first bigger C++ project and find that I have some really long lines. My goal is to break them to 79 columns, but I do not really know how to do this in a neat way. Are there some guidelines to break lines like these:

```<code>VectorHistogram::VectorHistogram(size_t bins, size_t cache) : bins(std::vector<double>(bins)), cache(std::min(cache, MAX_CACHE_ENTRIES)) {
</code>```

or

```<code>VectorHistogram position_histogram {settings.position_hist_bins, settings.time_sites * settings.iterations};
</code>```

or

```<code>MetropolisDriver::MetropolisDriver(Settings settings) : settings(settings), system(HarmonicOscillator {settings.time_step, settings.mass, settings.mu_squared}), trajectory(ListQuantity {settings.time_sites}), ma(MetropolisAlgorithm {trajectory, system, settings.position_seed, settings.accept_seed}) {
</code>```

答:
I would break them so each line is conveying a different concern such as superclass constructor invocation or an expression. This might not be 79 characters, but with modern widescreen, high resolution monitors is that truly necessary anymore?

Whenever possible, let the IDE format it for you. Some are better at this than others: for example, I have found that Eclipse likes to break expressions in weird places. Sometimes (rarely) I need to resort to manual formatting, and I try to break code the way I described above.

Anyway, here is how I would format the code in your question:

```<code>VectorHistogram::VectorHistogram(size_t bins, size_t cache)
    : bins(std::vector<double>(bins)),
      cache(std::min(cache, MAX_CACHE_ENTRIES)) {

VectorHistogram position_histogram {
  settings.position_hist_bins, settings.time_sites * settings.iterations
};

MetropolisDriver::MetropolisDriver(Settings settings)
    : settings(settings),
      system(HarmonicOscillator {settings.time_step, settings.mass, settings.mu_squared}),
      trajectory(ListQuantity {settings.time_sites}),
      ma(MetropolisAlgorithm {trajectory, system, settings.position_seed, settings.accept_seed}) {
</code>```

Body:
I would break them so each line is conveying a different concern such as superclass constructor invocation or an expression. This might not be 79 characters, but with modern widescreen, high resolution monitors is that truly necessary anymore?

Whenever possible, let the IDE format it for you. Some are better at this than others: for example, I have found that Eclipse likes to break expressions in weird places. Sometimes (rarely) I need to resort to manual formatting, and I try to break code the way I described above.

Anyway, here is how I would format the code in your question:

VectorHistogram::VectorHistogram(size_t bins, size_t cache)
    : bins(std::vector<double>(bins)),
      cache(std::min(cache, MAX_CACHE_ENTRIES)) {

VectorHistogram position_histogram {
  settings.position_hist_bins, settings.time_sites * settings.iterations
};

MetropolisDriver::MetropolisDriver(Settings settings)
    : settings(settings),
      system(HarmonicOscillator {settings.time_step, settings.mass, settings.mu_squared}),
      trajectory(ListQuantity {settings.time_sites}),
      ma(MetropolisAlgorithm {trajectory, system, settings.position_seed, settings.accept_seed}) {


问:
Localization in php, best practice or approach?
I am Localizing my php application. I have a dilemma on choosing best method to accomplish the same.

Method 1: Currently am storing words to be localized in an array in a php file

```<code><?php

$values = array (
                        'welcome' => 'bienvenida'
                );

?>
</code>```

I am using a function to extract and return each word according to requirement

Method 2: Should I use a txt file that stores string of the same?

```<code><?php
$welcome = 'bienvenida';
?>
</code>```

My question is which is a better method, in terms of speed and effort to develop the same and why?

Edit: I would like to know which method out of two is faster in responding and why would that be? also, any improvement on the above code would be appreciated!!

答:
First off, gettext is a good way to go, so don't dismiss if it doesn't sound easy at first; However there are other options as well that be useful to know. Before explaining that let's take a look at your suggestions first:

In your array-way of doing this, you have a pretty much straightforward solution. The good thing is that you can store your translations in a data storage, then load it into your PHP script as an array, and that's it. However if you want to store your array statically in a PHP file, then editing it needs a) PHP programmer or an exprienced user who is familiar with the PHP syntax, just to edit the file b) syncing between even four or five different language files could be quite annoying and prone to errors.

What you need to consider here is: How can later add new elements to the language file? Can I leave it up to a translator or there should be a PHP programmer?

Your variable-way of doing it is not practical. Why? I assume you will have couple of functions at least in your application, right? Then you need to pass all of these variables when you call the function, or you need to global them. If you think you will have more than ten variables like this, then I strongly discourage you to do this. There might be name-conflict as well -- you can potentially override the value of another variable with the same name, however this could be solved by adding a prefix even as simple as a an underscore , so you will have $_welcome for example. Anyways, if I were you I wouldn't think about it even; Don't do it.

One good way of doing it is to define Constants with a prefix. So for example in your en.lang.php you will have something like define( 'LABEL_WELCOME', 'Welcome' ); and in your no.lang.php you will have define ( 'LABEL_WELCOME', 'Velkommen' );. The good thing about using constant instead of variables is that they're always available in your script. So you don't need to inject or global them. In comparison to both arrays and variables, they are faster because of the way PHP handles them -- they take up less space in the memory. The drawback is that you can't pass them to the translator, so again you need a PHP developer. Also syncing between files could be a bit of pain again.

The other option is to have a Function or Class/Method to retrieve the translation. It will be less efficient -- however I don't think you need that kinda of micro-optimization at all, but the added advantage is that you can apply a custom logic while retrieving the translation. For example imagine someday your beloved project manager comes to you asking if you could covert all of those texts to uppercase. You can't refuse to do it, so having a function in between could help you a lot when you need to apply/change a pattern to all of your translations.

To wrap it up:

Think about how translators can use it and come up with a working-KISS solution for them.

Think about how you can stay sync between different languages.

Think about if the same translation might be needed, let say for the mobile app. A cross platform solution could save your time. Don't dismiss JSON and ordinary Databases.

Think about how you can apply/change the logic when retrieving the translations.

Forgot about the performance. 99.9% of times you won't get that far to do micro-optimization like Constant vs. Variables vs. Function Calls. I assume your time as a developer/staff is more expensive rather than a processor time.

Update #1

My goodness, I post an answer for a year old question. Why no one is saying anything here? We need alerts for these cases.

Update #2

On the right side it says it's a year old question; However it's been asked two years ago! Everything is misleading here!


问:
Design MVC site such that UI developer can work without access to data tier?
I'm working on an ASP.NET MVC site (using Team Foundation Service for source control) that I've divided into a few separate projects under one solution:

```<code>Project.WebAPI (Main entrypoint, contains "Views","Scripts" folders
Project.Data (abstract interfaces for backend data access)
Project.Data.SqlServer (concrete implementations for data access)
</code>```

For my UI designer to work, he shouldn't need access to much. Pretty much the only thing that he's working on is the "Views" and "Scripts" folders of the main project. But "Project.WebAPI" takes parameters that live in Project.Data, so there's a dependency there.

The app is SPA-style, so I could easily store a fake JSON payload which would entirely remove the need for logging in and pulling real data. My ultimate goal would be to be able to share a subset of the source with the UI designer allowing him to check changes directly into the overall project rather than create a separate instance just for his work which I would have to manually merge in. Does anyone have any experience with this type of thing?

Edit: for clarity: The purpose is to protect the intellectual property of the solution so that the front-end developers don't have access to the entire solution. I hope that helps...

答:
You want to use the DependencyResolver Class.

http://msdn.microsoft.com/en-us/library/system.web.mvc.dependencyresolver(v=vs.118).aspx

In your global asax, you set the resolver and wire up fake implementations of interfaces that your data access layer also implments

Then in your controller, you create 2 constructors

public Controller() : this(DependencyResolver.Resolve<IPersonDataAccessLayer>()) {}
public Controller(IPersonDataAccessLayer layer)
{
   __layer = layer;
}

Then you can set up a fake implementation in your global.asax on your designers machine.


问:
What hat should a programmer not wear?
In my experience, software developers tend to wear multiple hats and fill multiple roles with different responsibilities.  From not only coding, but sometimes also writing SQL, designing the user-interface, designing the database, graphics manipulation, to even QA testing.

If the primary role is to write software/code, what roles should the developer not take on?  Are there any?

The intention of this question is not because a developer is incapable of filling another role-- but having the additional role actually works against the primary role, or should really be a dedicated role of someone who does not primarily program.

答:
that hat with the beer cans on the side with a straw.  bad idea if you get caught.

edit:

Here's the hat I hate but that has great reward - it's a big sign on me that says if this thing breaks it's all your fault....ah, but if it's good, then you my son are the good boy we all know you are - now go back to the basement...good boy...that's it.

The blame hat.

ContentLicense: CC BY-SA 2.5

Title: What hat should a programmer not wear?


问:
How To Invoke A Method When It's Class is Accessed (Any Method) - "OnClassEnter"
I am working on a C# net micro framework project, in particular an I2C bus management/class.

I have several different I2C devices each defined in separate classes which contain all of the devices' unique methods. In my case, I can only have ONE I2CDevice object "active" to communicate with and to switch to another I2C device to communicate with it requires a call like I2CBus.Config = DeviceConfig1.

For example (pseudo-code):

```<code>Class Device1
-DeviceConfig1
-Method 1
-Method 2
-Method 3

Class Device2
-DeviceConfig2
-Method 1
-Method 2
-Method 3

Main Program
{
I2cBus = new I2CDevice(configuration)
Device1.Method1
Device2.Method3
}
</code>```

So, somewhere between Device1.Method1; and Device2.Method3; When switching between devices, I need to change the I2CDevice.Config property. I call it an "OnClassEnter event" that would check that the device settings are correct before it proceeds.  I'm looking for an elegant way such that whenever I call a Method for a Device, that the I2CBus.Config is automatically checked and changed. Is there a way that I don't need to re-type this config code in each method? Have a separate internal method that's called each time I access any of those methods? Maybe something inherited from a base class or Interface, but where I don't have to remember call it from each method in the Device class.

答:
Disclaimer: My C# experience is probably less than 8 hours total so the syntax that follows may not be accurate.

So, somewhere between Device1.Method1; and Device2.Method3; When switching between devices, I need to change the I2CDevice.Config property.

You could arrange it so the only way to get a device is through a method like

```<code>public void With(DeviceConfig config, Action<Device> function) {
    // configure the hardware
    Device device = /* get the device */
    function(device);
}
</code>```

So that you could do this:

```<code>With(device1Config, (device1) => {
    device1.Method1();
    device1.Method2();
    device1.Method3();
});
With(device2Config, (device2) => {
    device2.Method1();
    device3.Method2();
});
</code>```

That would ensure you can't get a hold of a device without first configuring it, but would enable you to make multiple calls without reconfiguration.

Body:
Disclaimer: My C# experience is probably less than 8 hours total so the syntax that follows may not be accurate.

So, somewhere between Device1.Method1; and Device2.Method3; When switching between devices, I need to change the I2CDevice.Config property.

You could arrange it so the only way to get a device is through a method like

public void With(DeviceConfig config, Action<Device> function) {
    // configure the hardware
    Device device = /* get the device */
    function(device);
}

So that you could do this:

With(device1Config, (device1) => {
    device1.Method1();
    device1.Method2();
    device1.Method3();
});
With(device2Config, (device2) => {
    device2.Method1();
    device3.Method2();
});

That would ensure you can't get a hold of a device without first configuring it, but would enable you to make multiple calls without reconfiguration.


答:
Instead of attempting to capture when control passes into your class and update the config then, explicitly update the configuration just before the I2CDevice is used.

Write a wrapper for I2CDevice which takes your DeviceConfig and I2CDevice as parameters to its constructor.

The wrapper can provide its own versions of the I2CDevice methods (looks like there are only 3), it would then ensure I2C configuration before executing the corresponding I2CDevice method.

You would then use this wrapper inside your Device1, Device2 classes in lieu of using I2CDevice directly.

```<code>public class I2CDeviceWrapper
{
   private readonly I2CDevice _i2cdevice;
   private readonly DeviceConfig _config;

   public I2CDeviceWrapper(DeviceConfig config, I2CDevice device)
   {
       _config = config;
       _i2cdevice= device;
   }
   private void EnsureConfiguration()
   {
       //verify or set configuration so this wrapper's device is active.
   }
   public int Execute(I2CTransaction[] xActions, int timeout)
   {
       EnsureConfiguration();
       return _i2cdevice.Execute(xActions, timeout);
   }
   public I2CReadTransaction CreateReadTransaction (byte[] buffer)
   {
        EnsureConfiguration();
        return _i2cdevice.CreateReadTransaction(buffer);
   }
   public I2CWriteTransaction CreateWriteTransaction (byte[] buffer)
   {
        EnsureConfiguration();
        return _i2cdevice.CreateWriteTransaction(buffer);
   }

}
</code>```

EDIT: if the I2CDevice is passed into the wrapper, the wrapper should not attempt to manage its lifecycle.
I2CDevice provides a Dispose() method, in my experience (which does not include the micro framework) this indicates you risk a resource leak if it is not called. If this holds for the micro framework, you would want to provide one for the wrapper as well that calls the I2CDevice one.

Wrapper as Abstract Base:

If you use the wrapper as a base for each of your Device1, Device2 classes, the visibility of the Execute, I2CGetReadTransaction, I2CGetWriteTransaction methods and perhaps the _config field should be made protected.

```<code>public class Device1: I2CDeviceWrapper
{
    public Device1(DeviceConfig config, I2CDevice device):base(config, device)
    {}

    public something Method1()
    {
        ...
        Execute(...);
        ...
    }
}
</code>```

Wrapper as member field:
If the wrapper is a member of your Device1, Device2 classes, you would still pass your i2cBus as a parameter to those constructors, create A per Device wrapper using that devices' configuration and i2cBus and then use it going forward as you previously would have used i2cBuss.

```<code>public class Device1
{
    private readonly I2CDeviceWrapper _i2cBus;

    public Device1(I2CDevice i2cBus)
    {
         var config = //set up configuration
         _i2cBus = new I2CDeviceWrapper(config, i2cBus);
    }
    public void Method1()
    {
        ...
        _i2cBus.Execute(...);
        ...
    }
}
</code>```

Title: How To Invoke A Method When It's Class is Accessed (Any Method) - "OnClassEnter"

Body:
I am working on a C# net micro framework project, in particular an I2C bus management/class.

I have several different I2C devices each defined in separate classes which contain all of the devices' unique methods. In my case, I can only have ONE I2CDevice object "active" to communicate with and to switch to another I2C device to communicate with it requires a call like I2CBus.Config = DeviceConfig1.

For example (pseudo-code):

```<code>Class Device1
-DeviceConfig1
-Method 1
-Method 2
-Method 3

Class Device2
-DeviceConfig2
-Method 1
-Method 2
-Method 3

Main Program
{
I2cBus = new I2CDevice(configuration)
Device1.Method1
Device2.Method3
}
</code>```

So, somewhere between Device1.Method1; and Device2.Method3; When switching between devices, I need to change the I2CDevice.Config property. I call it an "OnClassEnter event" that would check that the device settings are correct before it proceeds.  I'm looking for an elegant way such that whenever I call a Method for a Device, that the I2CBus.Config is automatically checked and changed. Is there a way that I don't need to re-type this config code in each method? Have a separate internal method that's called each time I access any of those methods? Maybe something inherited from a base class or Interface, but where I don't have to remember call it from each method in the Device class.

Body:
Instead of attempting to capture when control passes into your class and update the config then, explicitly update the configuration just before the I2CDevice is used.

Write a wrapper for I2CDevice which takes your DeviceConfig and I2CDevice as parameters to its constructor.

The wrapper can provide its own versions of the I2CDevice methods (looks like there are only 3), it would then ensure I2C configuration before executing the corresponding I2CDevice method.

You would then use this wrapper inside your Device1, Device2 classes in lieu of using I2CDevice directly.

public class I2CDeviceWrapper
{
   private readonly I2CDevice _i2cdevice;
   private readonly DeviceConfig _config;

   public I2CDeviceWrapper(DeviceConfig config, I2CDevice device)
   {
       _config = config;
       _i2cdevice= device;
   }
   private void EnsureConfiguration()
   {
       //verify or set configuration so this wrapper's device is active.
   }
   public int Execute(I2CTransaction[] xActions, int timeout)
   {
       EnsureConfiguration();
       return _i2cdevice.Execute(xActions, timeout);
   }
   public I2CReadTransaction CreateReadTransaction (byte[] buffer)
   {
        EnsureConfiguration();
        return _i2cdevice.CreateReadTransaction(buffer);
   }
   public I2CWriteTransaction CreateWriteTransaction (byte[] buffer)
   {
        EnsureConfiguration();
        return _i2cdevice.CreateWriteTransaction(buffer);
   }

}

EDIT: if the I2CDevice is passed into the wrapper, the wrapper should not attempt to manage its lifecycle.
I2CDevice provides a Dispose() method, in my experience (which does not include the micro framework) this indicates you risk a resource leak if it is not called. If this holds for the micro framework, you would want to provide one for the wrapper as well that calls the I2CDevice one.

Wrapper as Abstract Base:

If you use the wrapper as a base for each of your Device1, Device2 classes, the visibility of the Execute, I2CGetReadTransaction, I2CGetWriteTransaction methods and perhaps the _config field should be made protected.

public class Device1: I2CDeviceWrapper
{
    public Device1(DeviceConfig config, I2CDevice device):base(config, device)
    {}

    public something Method1()
    {
        ...
        Execute(...);
        ...
    }
}

Wrapper as member field:
If the wrapper is a member of your Device1, Device2 classes, you would still pass your i2cBus as a parameter to those constructors, create A per Device wrapper using that devices' configuration and i2cBus and then use it going forward as you previously would have used i2cBuss.

public class Device1
{
    private readonly I2CDeviceWrapper _i2cBus;

    public Device1(I2CDevice i2cBus)
    {
         var config = //set up configuration
         _i2cBus = new I2CDeviceWrapper(config, i2cBus);
    }
    public void Method1()
    {
        ...
        _i2cBus.Execute(...);
        ...
    }
}


问:
Maintaining indices for location in a sorted list in database rows
I have a fairly simple data structure like this:

```<code>create table project (id int auto increment primary key, name text);

create table item (id int auto increment primary key, name text,
    project_id int not null,
    project_sort_index int not null,
    sort_index int not null,
    foreign key fk_project(project_id) references project(id));
</code>```

A project can have many items. Items have two different fields for maintaining sort order, project_sort_index and sort_index.

These sort order fields apply in the following way. When I view all items belonging to a project, I need a sort order specific to each project for the items. When I view all items globally, I need a sort order for them globally.

I have a couple of questions as to how best to maintain and modify sort order for these items. Lets say that I have moved an item at index 4 to index 2. How do I propagate that change to my database efficiently?

For example, how do I now update all index numbers >= 2 to move everything down, yet close the gap left in place 4? Is there a better way of sorting lists in SQL?

答:
For a small number of items (lets say <50,000) the most effective and simple solution is probably to load all items into memory, let the user reorder them the way he/she likes, regenerate the indexes and afterwards update all changed records in a single transaction. If you expect only a fraction of elements to be changed this way, you should keep track of the changed records and update only those. Otherwise, just update them all.

If you need a solution which avoids the loading of all records into memory, and allows "small movements" to be applied very effectively, you could first assign index numbers with "gaps" like 10, 20, 30, ... to your records. When you have to move item number 4 (with number 40) to the 2nd position, you try to assign the median value from the first and the new third element (which means in this example 15) to item number 4. This will allow a lot of small reorderings, until you reach the point where there is no "free space" any more between two consecutive numbers. That's the point where you renumber all items in steps of 10 again. This strategy could be further improved, for example, by "partial renumberings", or by using floats (thanks to Dan Pichelman's comment), and it will make the need of changing many records a (hopefully) seldom event. But to know if this works for your case, you should have a notion about the kind of reorderings you expect.


问:
Using GPL software with closed-source hardware
Does it violate the GPL v3 if I were to use a gpl licensed firmware with my closed-source hardware that I am selling? Or do both have to be open-source, or do I just have to make the firmware source freely available?

Thanks!

答:
There are lots of cases of consumer devices using GPL'd firmware.  TiVo was the big name one because certain people were annoyed that even though TiVo released their changes, you couldn't take that and make your own changes and put it on your TiVo because they locked their boxes.  In fact that's what caused the "TiVo'isation" clause in the next version of the GPL (v3).

However, even GPLv3 doesn't require that the hardware be open source (to the best of my knowledge, IANAL).  The GPLv3 seems to say that if you pulled a TiVo then you'd have to release the software changes you made and provide instructions/tools to allow people to replace the firmware on the device with new firmware that they create with their own changes.

Pretty much any CPU out there isn't open source, so how could vendors sell any hardware that had GPL software on it?

That said, you should thoroughly read the license before using it.  I have read it, and I don't recall anything about requiring the hardware to be open source.


问:
How should the database schema be migrated?
I am using a bunch of freelance programmers to develop a web application. We are in the early stages of development, meaning that we are making many changes to our database schema. We have one test database and one production database, we also have a replica of the live database, which gets a clone of the live database every night (mostly used to make it easier to recreate bugs found in the live web application. Since I use many freelancers, which I do not know, I often do not trust their database skills and they do not have any understanding of the outmost importance of the data in our live database.

My question is what kind of process you would recommend after a freelancer determines the need to make a change in a database. They will currently commit change to our database schema together with their pull request (on GitHub), so I can review their proposed database changes. They are also free to apply the changes to our live database. My question is then how I should migrate the live data to the new schema. I thought about asking the developer of a patch to also create an alter table statement, which I would run on the live database, but I do not trust that they will be careful enough. I prefer such migration to be automatic (at least in most cases) in order to be able to deploy on a daily basis, but I do not know whether that is at all realistic. I also need to have a process that I trust so much that I do not need to make any tests on the live system if I have tested a pull request on our test system (working with our test database).

How can this be done?

答:
This sounds like you could benefit from a separation of architecture, system design, user experience and engineering.

The Architects provide general guidance for the tech solution, such as "we'll use a .NET SOAP Web Service here" and "let's use an off the shelf application for this."

The System Design team takes the guidance from the Architects and creates a concrete tech solutions:

Create a Products web service:

WCF, .NET 4.5

Need a "products" table with columns x, y and z

Authentication is handled by Foo

Then you engage User Experience to design the User Interface.

Finally, you hand all this information and visual designs to the untrusted freelancer Engineers who put fingers to keyboard and make this happen.

In this way, the Engineers aren't making design and architectural decisions --- which is not to say they shouldn't be allowed do make these decisions. If an Engineer comes up with a problem that System Design or User Experience didn't account for, they need to talk with the lead developer (you). From there you will need to grab the developer and chat with System Design or UX to hash out the solution, which the engineer then implements.

You might not have individual people for each role. Smaller software shops will probably have people wearing more than one hat (architect, system design and lead developer might be one person), but clearly defining those roles and who fills them can help manage a disjointed engineering workforce.


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答: goto: although ok in rare cases, it is more often misused and leads to hard to read programs.</p>


答:
Sales.

Some poor bugger has to do it, but it sure shouldn't be the developers.

Title: What hat should a programmer not wear?

Body:
In my experience, software developers tend to wear multiple hats and fill multiple roles with different responsibilities.  From not only coding, but sometimes also writing SQL, designing the user-interface, designing the database, graphics manipulation, to even QA testing.

If the primary role is to write software/code, what roles should the developer not take on?  Are there any?

The intention of this question is not because a developer is incapable of filling another role-- but having the additional role actually works against the primary role, or should really be a dedicated role of someone who does not primarily program.


问:
Is there a purely SQL alternate to looping?
Historically, I probably would have written a script (php or something) to loop through all spreadsheet rows and perform some calculations.

I'm looking for a pure SQL solution on the presumption that SQL has better options than loops.

How should I approach this problem while using a pure SQL approach?

DATA OVERVIEW:

We have a list (currently in a spreadsheet) of items for which we want to check trending.

Let's pretend that that spreadsheet contains these three items; 111111, 222222, and 888888.

In the DB, we have a table of vendors' inventory snapshots. Here's a simplified example:

(see the fiddle here).

```<code>CREATE TABLE inventory_snapshots
    ([id] int, [vendor_id] int, [item] int, [brand] varchar(1), [inventory_version] int, [quantity] int);

INSERT INTO inventory_snapshots
    ([id], [vendor_id], [item], [brand], [inventory_version], [quantity])
VALUES
    (1, 111, 111111, 'A', 5, 45),
    (2, 111, 111111, 'B', 5, 43),
    (3, 111, 222222, 'X', 5, 12),
    (4, 222, 111111, 'B', 4, 5),
    (5, 222, 888888, 'C', 4, 50),
    (6, 222, 111111, 'D', 5, 10),
    (7, 222, 888888, 'C', 5, 100),
    (8, 111, 111111, 'A', 6, 40),
    (9, 111, 222222, 'X', 6, 10);
</code>```

Notice that a vendor can have multiple rows of an item in a given inventory version because of brand differences.

GOAL:

Our goal is to see the trending over all vendors.

That means comparing a list (currently in spreadsheet form) of items against the DB to retrieve:

item number

starting qty (sum of qty's from the MIN version number for each

vendor, items grouped by vendor_id,inventory_version) total increases
(sum of each vendors version-over-version increases in qty) total

increases (sum of each vendors version-over-version increases in qty)

ending qty (sum of qty's from the MAX version number for each vendor,
items grouped by vendor_id,inventory_version)

For another example, see the comment in the fiddle.

SUMMARY:

It sounds like SQL Server can do some looping, but that it's impractical.

What's a better way to approach this?

答:
Depending on your version of SQL Server, windowing functions will do what you want. 2008 has limited support but 2012 adds nearly all of the standard. The over clause is used for things exactly like this, it is also available in the express versions as well.

http://technet.microsoft.com/en-us/library/ms189461.aspx

Windowing functions are used to perform high-level aggregation, ranking and statistical analysis. They are often used to split and show similarities in a data set.

The over clause can partition a column and provide a running sum like you describe in a T-SQL Statement.

```<code>SELECT [id], [vendor_id], [item], [brand], [inventory_version], SUM([quantity])
    OVER (PARTITION BY [vendor_id], [item]
        ORDER BY [vendor_id], [item], [inventory_version]) AS qty_Totals
FROM inventory_snapshots
ORDER BY [vendor_id], [item], [inventory_version]
</code>```

Code is untested but should work. What it does is take the recordset, partitions it by the vendor_id and item. This effectively resets the sumation to 0 when that combination changes. We make sure to order the results in a logical manner to show the running totals easily. This will show the progression of item versions per manufacturer starting at the lowest and going straight through to the last.

Hopefully this clears things up a bit.

Body:
Depending on your version of SQL Server, windowing functions will do what you want. 2008 has limited support but 2012 adds nearly all of the standard. The over clause is used for things exactly like this, it is also available in the express versions as well.

http://technet.microsoft.com/en-us/library/ms189461.aspx

Windowing functions are used to perform high-level aggregation, ranking and statistical analysis. They are often used to split and show similarities in a data set.

The over clause can partition a column and provide a running sum like you describe in a T-SQL Statement.

SELECT [id], [vendor_id], [item], [brand], [inventory_version], SUM([quantity])
    OVER (PARTITION BY [vendor_id], [item]
        ORDER BY [vendor_id], [item], [inventory_version]) AS qty_Totals
FROM inventory_snapshots
ORDER BY [vendor_id], [item], [inventory_version]

Code is untested but should work. What it does is take the recordset, partitions it by the vendor_id and item. This effectively resets the sumation to 0 when that combination changes. We make sure to order the results in a logical manner to show the running totals easily. This will show the progression of item versions per manufacturer starting at the lowest and going straight through to the last.

Hopefully this clears things up a bit.


问:
how to design a stack without using java library or using list
I have a question how to design a stack without using list or array?

This is one question that I want to think about as I want to better understand stack.

答:
A stack is really just an interface, which provides at least the following operations:

push a new element onto the stack

pop an element off the stack

The underlying implementation can be anything that satisfies these operations. Arrays and lists are common implementations for stacks, but you could create an (inefficient) stack using a hash table, or files on disk, or even numbered pieces of paper scattered around a room. As long as the ability to push and pop are available somehow, it's a stack.


问:
What is the path to JavaScript mastery?
I know how we start with JavaScript, we cut-and-paste a snippit to gain a little client-side functionality or validation.

But if you follow this path in trying to implement rich interactive behavior, it doesn't take long before you realize that you are creating a Big Ball Of Mud.

So what is the path towards expertise in programming the interaction layer?  What books, tutorials, exercises, and processes contribute towards the ability to program robust, maintainable JavaScript?

We all know that practice is important in any endeavor, but I'm looking for a path similar to the answer here: https://stackoverflow.com/questions/2573135/

答: I hated JavaScript until I discovered jQuery.  Now I love it and use it all the time.  Probably too much.</p>

Title: What is the path to JavaScript mastery?


问:
Are closures considered impure functional style?
Are closures considered impure in functional programming?

It seems one can generally avoid closures by passing values directly to a function. Therefore should closures be avoided where possible?

If they are impure, and I am correct in stating that they can be avoided, why do so many functional programming languages support closures?

One of the criteria for a pure function is that "The function always evaluates the same result value given the same argument value(s)."

Suppose

```<code>f: x -> x + y
</code>```

f(3) will not always give the same result. f(3) depends on the value of y which is not an argument of f. Thus f is not a pure function.

Since all closures rely on values which are not arguments, how is it possible for any closure to be pure? Yes, in theory the closed value could be constant but there is no way of  knowing that just by looking that the source code of the function itself.

Where this leads me to is that the same function may be pure in one situation but impure in another. One cannot always determine if a function is pure or not by studying its source code. Rather, one may have to consider it in context of its environment at the point when it is being called before such distinction can be made.

Am I thinking about this correctly?

答:
Very quickly: a substitution is "referentially transparent" if "substituting like leads to like" and a function is "pure" if all of its effects are contained in its return value. Both of those can be made precise, but it's vital to note that they are not identical nor even does one imply the other.

Now let's talk about closures.

Boring (mostly pure) "closures"

Closures occur because as we evaluate a lambda term we interpret (bound) variables as environment lookups. Thus, when we return a lambda term as the result of an evaluation the variables inside it will have "closed over" the values they took when it was defined.

In plain lambda calculus this is sort of trivial and the whole notion just vanishes. To demonstrate that, here's a relatively lightweight lambda calculus interpreter:

```<code>-- untyped lambda calculus values are functions
data Value = FunVal (Value -> Value)

-- we write expressions where variables take string-based names, but we'll
-- also just assume that nobody ever shadows names to avoid having to do
-- capture-avoiding substitutions

type Name = String

data Expr
  = Var Name
  | App Expr Expr
  | Abs Name Expr

-- We model the environment as function from strings to values,
-- notably ignoring any kind of smooth lookup failures
type Env = Name -> Value

-- The empty environment
env0 :: Env
env0 _ = error "Nope!"

-- Augmenting the environment with a value, "closing over" it!
addEnv :: Name -> Value -> Env -> Env
addEnv nm v e nm' | nm' == nm = v
                  | otherwise = e nm

-- And finally the interpreter itself
interp :: Env -> Expr -> Value
interp e (Var name) = e name          -- variable lookup in the env
interp e (App ef ex) =
  let FunVal f = interp e ef
      x        = interp e ex
  in f x                              -- application to lambda terms
interp e (Abs name expr) =
  -- augmentation of a local (lexical) environment
  FunVal (\value -> interp (addEnv name value e) expr)
</code>```

The important part to notice is in addEnv when we augment the environment with a new name. This function gets called only "inside" of the interpreted Abstraction term (lambda term). The environment gets "looked up" whenever we evaluate a Var term and so those Vars resolve to whatever the Name referred to in the Env which got captured by the Abstraction containing the Var.

Now, again, in plain LC terms this is boring. It means that bound variables are just constants as far as anyone cares. They get evaluated directly and immediately as the values they denote in the environment as lexically scoped up to that point.

This is also (almost) pure. The only meaning of any term in our lambda calculus is determined by its return value. The only exception is the side-effect of non-termination which is embodied by the Omega term:

```<code>-- in simple LC syntax:
--
-- (\x -> (x x)) (\x -> (x x))
omega :: Expr
omega = App (Abs "x" (App (Var "x")
                          (Var "x")))
            (Abs "x" (App (Var "x")
                          (Var "x")))
</code>```

Interesting (impure) closures

Now to certain backgrounds the closures described in plain LC above are boring because there's no notion of being able to interact with the variables we've closed over. In particular, the word "closure" tends to invoke code like the following Javascript

```<code>> function mk_counter() {
  var n = 0;
  return function incr() {
    return n += 1;
  }
}
undefined

> var c = mk_counter()
undefined
> c()
1
> c()
2
> c()
3
</code>```

This demonstrates that we've closed over the n variable in the inner function incr and calling incr meaningfully interacts with that variable. mk_counter is pure, but incr is decidedly impure (and not referentially transparent either).

What differs between these two instances?

Notions of "variable"

If we look at what substitution and abstraction mean in the plain LC sense we notice that they are decidedly plain. Variables are literally nothing more than immediate environment lookups. Lambda abstraction is literally nothing more than creating an augmented environment to evaluate the inner expression. There is no room in this model for the kind of behavior we saw with mk_counter/incr because there's no variation allowed.

To many this is the heart of what "variable" means—variation. However, semanticists like to distinguish between the kind of variable used in LC and the kind of "variable" used in Javascript. To do so, they tend to call the latter a "mutable cell" or "slot".

This nomenclature follows the long historical usage of "variable" in mathematics where it meant something more like "unknown": the (mathematical) expression "x + x" does not allow for x to vary over time, it instead is meant to have meaning regardless of the (single, constant) value x takes.

Thus, we say "slot" to emphasize the ability to put values into a slot and to take them out.

To add further to the confusion, in Javascript these "slots" look the same as variables: we write

```<code>var x;
</code>```

to create one and then when we write

```<code>x;
</code>```

it indicates us looking up the value currently stored in that slot. To make this more clear, pure languages tend to think of slots as taking names as (mathematical, lambda calculus) names. In this case we must explicitly label when we get or put from a slot. Such notation tends to look like

```<code>-- create a fresh, empty slot and name it `x` in the context of the
-- expression E
let x = newSlot in E

-- look up the value stored in the named slot named `x`, return that value
get x

-- store a new value, `v`, in the slot named `x`, return the slot
put x v
</code>```

The advantage of this notation is that we now have a firm distinction between mathematical variables and mutable slots. Variables may take slots as their values, but the particular slot named by a variable is constant throughout its scope.

Using this notation we can rewrite the mk_counter example (this time in a Haskell-like syntax, though decidedly un-Haskell-like semantics):

```<code>mkCounter =
  let x = newSlot
  in (\() -> let old = get x
             in get (put x (old + 1)))
</code>```

In this case we're using procedures which manipulate this mutable slot. In order to implement it we'd need to close over not only a constant environment of names like x but also a mutable environment containing all of the needed slots. This is closer to the common notion of "closure" people love so much.

Again, mkCounter is very impure. It's also very referentially opaque. But notice that the side-effects do not arise from the name capture or closure but instead the capture of the mutable cell and the side-effecting operations on it like get and put.

Ultimately, I think this is the final answer to your question: purity is not affected by (mathematical) variable capture but instead by side-effecting operations performed on mutable slots named by captured variables.

It's only that in languages which do not attempt to be close to LC or do not attempt to maintain purity that these two concepts are so often conflated leading to confusion.

Body:
Very quickly: a substitution is "referentially transparent" if "substituting like leads to like" and a function is "pure" if all of its effects are contained in its return value. Both of those can be made precise, but it's vital to note that they are not identical nor even does one imply the other.

Now let's talk about closures.

Boring (mostly pure) "closures"

Closures occur because as we evaluate a lambda term we interpret (bound) variables as environment lookups. Thus, when we return a lambda term as the result of an evaluation the variables inside it will have "closed over" the values they took when it was defined.

In plain lambda calculus this is sort of trivial and the whole notion just vanishes. To demonstrate that, here's a relatively lightweight lambda calculus interpreter:

-- untyped lambda calculus values are functions
data Value = FunVal (Value -> Value)

-- we write expressions where variables take string-based names, but we'll
-- also just assume that nobody ever shadows names to avoid having to do
-- capture-avoiding substitutions

type Name = String

data Expr
  = Var Name
  | App Expr Expr
  | Abs Name Expr

-- We model the environment as function from strings to values,
-- notably ignoring any kind of smooth lookup failures
type Env = Name -> Value

-- The empty environment
env0 :: Env
env0 _ = error "Nope!"

-- Augmenting the environment with a value, "closing over" it!
addEnv :: Name -> Value -> Env -> Env
addEnv nm v e nm' | nm' == nm = v
                  | otherwise = e nm

-- And finally the interpreter itself
interp :: Env -> Expr -> Value
interp e (Var name) = e name          -- variable lookup in the env
interp e (App ef ex) =
  let FunVal f = interp e ef
      x        = interp e ex
  in f x                              -- application to lambda terms
interp e (Abs name expr) =
  -- augmentation of a local (lexical) environment
  FunVal (\value -> interp (addEnv name value e) expr)

The important part to notice is in addEnv when we augment the environment with a new name. This function gets called only "inside" of the interpreted Abstraction term (lambda term). The environment gets "looked up" whenever we evaluate a Var term and so those Vars resolve to whatever the Name referred to in the Env which got captured by the Abstraction containing the Var.

Now, again, in plain LC terms this is boring. It means that bound variables are just constants as far as anyone cares. They get evaluated directly and immediately as the values they denote in the environment as lexically scoped up to that point.

This is also (almost) pure. The only meaning of any term in our lambda calculus is determined by its return value. The only exception is the side-effect of non-termination which is embodied by the Omega term:

-- in simple LC syntax:
--
-- (\x -> (x x)) (\x -> (x x))
omega :: Expr
omega = App (Abs "x" (App (Var "x")
                          (Var "x")))
            (Abs "x" (App (Var "x")
                          (Var "x")))

Interesting (impure) closures

Now to certain backgrounds the closures described in plain LC above are boring because there's no notion of being able to interact with the variables we've closed over. In particular, the word "closure" tends to invoke code like the following Javascript

> function mk_counter() {
  var n = 0;
  return function incr() {
    return n += 1;
  }
}
undefined

> var c = mk_counter()
undefined
> c()
1
> c()
2
> c()
3

This demonstrates that we've closed over the n variable in the inner function incr and calling incr meaningfully interacts with that variable. mk_counter is pure, but incr is decidedly impure (and not referentially transparent either).

What differs between these two instances?

Notions of "variable"

If we look at what substitution and abstraction mean in the plain LC sense we notice that they are decidedly plain. Variables are literally nothing more than immediate environment lookups. Lambda abstraction is literally nothing more than creating an augmented environment to evaluate the inner expression. There is no room in this model for the kind of behavior we saw with mk_counter/incr because there's no variation allowed.

To many this is the heart of what "variable" means—variation. However, semanticists like to distinguish between the kind of variable used in LC and the kind of "variable" used in Javascript. To do so, they tend to call the latter a "mutable cell" or "slot".

This nomenclature follows the long historical usage of "variable" in mathematics where it meant something more like "unknown": the (mathematical) expression "x + x" does not allow for x to vary over time, it instead is meant to have meaning regardless of the (single, constant) value x takes.

Thus, we say "slot" to emphasize the ability to put values into a slot and to take them out.

To add further to the confusion, in Javascript these "slots" look the same as variables: we write

var x;

to create one and then when we write

x;

it indicates us looking up the value currently stored in that slot. To make this more clear, pure languages tend to think of slots as taking names as (mathematical, lambda calculus) names. In this case we must explicitly label when we get or put from a slot. Such notation tends to look like

-- create a fresh, empty slot and name it `x` in the context of the
-- expression E
let x = newSlot in E

-- look up the value stored in the named slot named `x`, return that value
get x

-- store a new value, `v`, in the slot named `x`, return the slot
put x v

The advantage of this notation is that we now have a firm distinction between mathematical variables and mutable slots. Variables may take slots as their values, but the particular slot named by a variable is constant throughout its scope.

Using this notation we can rewrite the mk_counter example (this time in a Haskell-like syntax, though decidedly un-Haskell-like semantics):

mkCounter =
  let x = newSlot
  in (\() -> let old = get x
             in get (put x (old + 1)))

In this case we're using procedures which manipulate this mutable slot. In order to implement it we'd need to close over not only a constant environment of names like x but also a mutable environment containing all of the needed slots. This is closer to the common notion of "closure" people love so much.

Again, mkCounter is very impure. It's also very referentially opaque. But notice that the side-effects do not arise from the name capture or closure but instead the capture of the mutable cell and the side-effecting operations on it like get and put.

Ultimately, I think this is the final answer to your question: purity is not affected by (mathematical) variable capture but instead by side-effecting operations performed on mutable slots named by captured variables.

It's only that in languages which do not attempt to be close to LC or do not attempt to maintain purity that these two concepts are so often conflated leading to confusion.


答:
You dont have to use an array or a list, you can create a simple stack by doing the following:

create a class called StackEntry, which contains a reference to the next stack entry only.

create a class called MyStack, which contains the last stack entry, and two functions:

push(value):

creates a new stack entry.

sets it to refer to the current stack entry,

and set it to be the current replacing the existing one.

pop:

uses the current stack entry and gets its referenced stack entry,

sets the current to be the referenced stack entry

returns the old "current" entry

Title: how to design a stack without using java library or using list

Body:
I have a question how to design a stack without using list or array?

This is one question that I want to think about as I want to better understand stack.


答:
Since you tag the question as java we solve the question with.....Objects! We're actually pretty much going to be implementing a singularly linked list. A stack can either be empty (which is really easy to write), or it can not be empty in which case it has a top item and a pointer to the rest of the stack.

Below is code for an immutable stack (one in which pushing or popping returns a new stack instead of modifying the existing one). You'll have to forgive the formatting, I don't know how to correctly enter the code into the editor here.

First you have an interface saying what constitutes a stack

```<code>public interface IStack<A> {

public boolean isEmpty();

public A peek();

public IStack<A> push(A a);

public IStack<A> pop();
}
</code>```

There are 2 kinds of IStacks. Those which are empty, and those which aren't. Let's look at the EmptyStack first because it's easier.

```<code>import java.util.EmptyStackException;

public class EmptyStack<A> implements IStack<A> {

//Since all empty stacks are the same, you would want it to follow the singleton pattern instead of relying on the default constructor

public boolean isEmpty() {
    return true;
}

public A peek() {
    throw new EmptyStackException();
}

public IStack<A> push(A a) {
    return new Stack<A>(this, a);
}

public IStack<A> pop() {
    throw new EmptyStackException();
}
}
</code>```

Now let's look at a Stack which isn't empty.

```<code>public class Stack<A> implements IStack<A>{

private IStack<A> _stack;
private A _a;

public Stack(IStack<A> stack, A a) {
    _stack = stack;
    _a = a;
}

public boolean isEmpty() {
    return false;
}

public A peek() {
    return _a;
}

public IStack<A> push(A a) {
    return new Stack<A>(this, a);
}

public IStack<A> pop() {
    return _stack;
}
}
</code>```

Let's try using it

```<code>public class Test {

public static void printInfo(String stackName, IStack<?> stack){
    System.out.println("-----------");
    System.out.println(stackName + ":");
    boolean isEmpty = stack.isEmpty();
    System.out.println("Is Empty: " + isEmpty);
    if(!isEmpty){
        System.out.println("Item: " + stack.peek());
    }
}

public static void main(String[] args) {
    IStack<Character> empty1 = new EmptyStack<Character>();
    IStack<Character> aStack1 = empty1.push('a');
    IStack<Character> abStack = aStack1.push('b');
    IStack<Character> aStack2 = abStack.pop();
    IStack <Character> empty2 = aStack2.pop();

    printInfo("empty1", empty1);
    printInfo("aStack1", aStack1);
    printInfo("abStack", abStack);
    printInfo("aStack2", aStack2);
    printInfo("empty2", empty2);
}
}
</code>```

Output from the test is

```<code>-----------
empty1:
Is Empty: true
-----------
aStack1:
Is Empty: false
Item: a
-----------
abStack:
Is Empty: false
Item: b
-----------
aStack2:
Is Empty: false
Item: a
-----------
empty2:
Is Empty: true
</code>```

Body:
Since you tag the question as java we solve the question with.....Objects! We're actually pretty much going to be implementing a singularly linked list. A stack can either be empty (which is really easy to write), or it can not be empty in which case it has a top item and a pointer to the rest of the stack.

Below is code for an immutable stack (one in which pushing or popping returns a new stack instead of modifying the existing one). You'll have to forgive the formatting, I don't know how to correctly enter the code into the editor here.

First you have an interface saying what constitutes a stack

public interface IStack<A> {

public boolean isEmpty();

public A peek();

public IStack<A> push(A a);

public IStack<A> pop();
}

There are 2 kinds of IStacks. Those which are empty, and those which aren't. Let's look at the EmptyStack first because it's easier.

import java.util.EmptyStackException;

public class EmptyStack<A> implements IStack<A> {

//Since all empty stacks are the same, you would want it to follow the singleton pattern instead of relying on the default constructor

public boolean isEmpty() {
    return true;
}

public A peek() {
    throw new EmptyStackException();
}

public IStack<A> push(A a) {
    return new Stack<A>(this, a);
}

public IStack<A> pop() {
    throw new EmptyStackException();
}
}

Now let's look at a Stack which isn't empty.

public class Stack<A> implements IStack<A>{

private IStack<A> _stack;
private A _a;

public Stack(IStack<A> stack, A a) {
    _stack = stack;
    _a = a;
}

public boolean isEmpty() {
    return false;
}

public A peek() {
    return _a;
}

public IStack<A> push(A a) {
    return new Stack<A>(this, a);
}

public IStack<A> pop() {
    return _stack;
}
}

Let's try using it

public class Test {

public static void printInfo(String stackName, IStack<?> stack){
    System.out.println("-----------");
    System.out.println(stackName + ":");
    boolean isEmpty = stack.isEmpty();
    System.out.println("Is Empty: " + isEmpty);
    if(!isEmpty){
        System.out.println("Item: " + stack.peek());
    }
}

public static void main(String[] args) {
    IStack<Character> empty1 = new EmptyStack<Character>();
    IStack<Character> aStack1 = empty1.push('a');
    IStack<Character> abStack = aStack1.push('b');
    IStack<Character> aStack2 = abStack.pop();
    IStack <Character> empty2 = aStack2.pop();

    printInfo("empty1", empty1);
    printInfo("aStack1", aStack1);
    printInfo("abStack", abStack);
    printInfo("aStack2", aStack2);
    printInfo("empty2", empty2);
}
}

Output from the test is

-----------
empty1:
Is Empty: true
-----------
aStack1:
Is Empty: false
Item: a
-----------
abStack:
Is Empty: false
Item: b
-----------
aStack2:
Is Empty: false
Item: a
-----------
empty2:
Is Empty: true


问:
Real time unit testing - or "how to mock now"
When you are working on a feature that depends on time... How do you organize unit testing ? When your unit tests scenarios depend on the way your program interprets "now", how do you set them up ?

Second Edit: After a Couple of days reading your experience

I can see that the techniques to deal with this situation usually revolve around one of these three principles:

 Add (hardcode) a dependency: add a small layer over the time function/object, and always call your datetime function through this layer. This way, you can get control of time during the test cases.

 Use mocks: your code stays exactly the same. In your tests, you replace the time object by a fake time object. Sometimes, the solution involves modifying the genuine time object that is provided by your programming language.

 Use dependency injection: Build your code so that any time reference is passed as a parameter. Then, you have control of the parameters during the tests.

Techniques (or libraries) specific to a language are very welcome, and will be enhanced if an illustrative piece of code comes along. Then, most interesting is how similar principles may be applied on any platform.
And yes... If I can apply it straight away in PHP, better than better ;)

Let's start with a simple example: a basic booking application.

Let's say we have JSON API and two messages: a request message, and a confirmation message.
A standard scenario goes like this:

You make a request. You get a response with a token. The resource that is needed to fulfill that request is blocked by the system for 5 minutes.

You confirm a request, identified by the token. If token was issued within 5 minutes, it will be accepted (the resource is still available). If more than 5 minutes have passed, you have to make a new request (the resource was freed. You need to check for its availability again).

Here come the corresponding test scenario:

I make a request. I confirm (immediately) with the token I received. My confirmation is accepted.

I make a request. I wait 3 minutes. I confirm with the token I received. My confirmation is accepted.

I make a request. I wait 6 minutes. I confirm with the token I received. My confirmation is rejected.

How can we get to program these unit tests ? What architecture should we use so that these functionalities remain testable ?

Edit Note: When we shoot a request, the time is stored in a database in a format that looses any information about milliseconds.

EXTRA - but maybe a bit verbose: Here come details about what I found out doing my "homework":

I Built my feature with a dependency on a time function of my own. My function VirtualDateTime has a static method get_time() that I call where I used to call new DateTime(). This time function allows me to simulate and control what time is "now", so that I can build tests like: "Set now to 21st jan 2014 16h15. Make a request. Move ahead 3 minutes. Make confirmation.". This works fine, at the cost of the dependency, and "not so pretty code".

A little more integrated solution would be to build a myDateTime function of my own that extends DateTime with additional "virtual time" functionnalities (most importantly, set now to what I want). This is making the first solution's code slightly more elegant (use of new myDateTime instead of new DateTime), but ends up to be very similar: I have to build my feature using my own class, thus creating a dependency.

I have though about hacking the DateTime function, to make it work with my dependency when I need it. Is there any simple and neat way to replace a class by another, though ? (I think I got an answer to that: See namespace below).

In a PHP environment, I read "Runkit" may allow me to do this (hack the DateTime function) dynamically. What is nice is that I would be able to check I am running in test environment before modifying anything about DateTime, and leave it untouched in production [1]. This sounds much safer and cleaner than any manual DateTime hack.

Dependency injection of a clock function in each class that uses time [2]. Is this not overkill ? I see that in some environments it gets very usefull [5]. In this case, I do not like it so much, though.

Remove dependency of time in all the functions [2]. Is this always feasible ? (See more examples below)

Using namespaces [2][3] ? This looks quite good. I could mock DateTime with my own DateTime function that extends \DateTime... Use DateTime::setNow("2014-01-21 16:15:00"), and DateTime::wait("+3 minutes"). This covers pretty much what I need. What if we use the time() function though ? Or other time functions ? I still have to avoid their use in my original code. Or I would need to make sure any PHP time function I use in my code is overridden in my tests... Is there any library available that would do just this ?

I have been looking for a way to change the system time just for a thread. It seems that there is none  [4]. This is a pity: a "simple" PHP function to "Set time to 21st jan 2014 16h15 for this thread" would be a great feature for this kind of tests.

Change the system date and time for the test, using exec(). This can work out if you are not afraid to mess up with other things on the server. And you need to set back the system time after you ran your test. It can do the trick in some situations, but feels quite "hacky".

This looks like a very standard problem to me. However, I still miss a simple an generic way to deal with it. Maybe I missed something ?
    Please share your experience !

NOTE: Here are some other situations where we may have similar testing needs.

Any feature that works with some kind of timeout (e.g. chess game ?)

processing a queue that triggers events at a given time (in the above scenario we could keep going like this: one day before the reservation starts, I want to send a mail to the user with all the details. Test scenario...)

You want to set up a test environment with data collected in the past - you would like to see it like if it was now. [1]

1 https://stackoverflow.com/questions/3271735/simulate-different-server-datetimes-in-php

2 https://stackoverflow.com/questions/4221480/how-to-change-current-time-for-unit-testing-date-functions-in-php

3 http://www.schmengler-se.de/en/2011/03/php-mocking-built-in-functions-like-time-in-unit-tests/

4 https://stackoverflow.com/questions/3923848/change-todays-date-and-time-in-php

5 Unit testing time-bound code

答:
I'm going to use Python-like pseudocode based around your test cases to (hopefully) help explain this answer a little, rather than just expositing.  But in short:  This answer is basically just an example of small, single-function-level dependency injection / dependency inversion, instead of applying the principle to an entire class/object.

Right now, it sounds like your tests are structured as such:

```<code>def test_3_minute_confirm():
    req = make_request()
    sleep(3 * 60)  # Baaaad
    assertTrue(confirm_request(req))
</code>```

With implementations something along the lines of:

```<code>def make_request():
    return { 'request_time': datetime.now(), }

def confirm_request(req):
    return req['request_time'] >= (datetime.now() - timedelta(minutes=5))
</code>```

Instead, try forgetting about "now" and tell both functions what time to use.  If it's most of the time going to be "now", you can do one of two main things to keep the calling code simple:

Make time an optional argument that defaults to "now".  In Python (and PHP, now that I reread the question) this is simple - default "time" to None (null in PHP) and set it to "now" if no value was given.

In other languages without default arguments (or in PHP if it becomes unwieldy), it might be easier to pull the guts of the functions out into a helper that does get tested.

For example, the two functions above rewritten in the second version might look like this:

```<code>def make_request():
    return make_request_at(datetime.now())

def make_request_at(when):
    return { 'request_time': when, }

def confirm_request(req):
    return confirm_request_at(req, datetime.now())

def confirm_request_at(req, check_time):
    return req['request_time'] >= (check_time - timedelta(minutes=5))
</code>```

This way, existing parts of the code don't need to be modified to pass in "now", while the parts you actually want to test can be tested much more easily:

```<code>def test_3_minute_confirm():
    current_time = datetime.now()
    later_time = current_time + timedelta(minutes=3)

    req = make_request_at(current_time)
    assertTrue(confirm_request_at(req, later_time))
</code>```

It also creates additional flexibility in the future, so less needs to change if the important parts need to be reused.  For two examples that pop into mind:  A queue where requests might need to be created moments too late but still use the correct time, or confirmations have to happen to past requests as part of data sanity checks.

Technically, thinking ahead like this might violate YAGNI, but we're not actually building for those theoretical cases - this change would just be for easier testing, that just happens to support those theoretical cases.

Is there any reason you would recommend one of these solutions over another?

Personally, I try to avoid any sort of mocking as much as possible, and prefer pure functions as above.  This way, the code being tested is identical to the code being run outside of tests, instead of having important parts replaced with mocks.

We've had one or two regressions that no one noticed for a good month because that particular part of the code was not often tested in development (we weren't actively working on it), was released slightly broken (so there were no bug reports), and the mocks used were hiding a bug in the interaction between helper functions.  A few slight modifications so mocks weren't necessary and a whole lot more could be easily tested, including fixing the tests around that regression.

Change the system date and time for the test, using exec(). This can work out if you are not afraid to mess up with other things on the server.

This is the one that should be avoided at all costs for unit testing.  There's really no way of knowing what kinds of inconsistencies or race conditions might be introduced to cause intermittent failures (for unrelated applications, or co-workers on the same development box), and a failed/errored test might not set the clock back correctly.

Body:
I'm going to use Python-like pseudocode based around your test cases to (hopefully) help explain this answer a little, rather than just expositing.  But in short:  This answer is basically just an example of small, single-function-level dependency injection / dependency inversion, instead of applying the principle to an entire class/object.

Right now, it sounds like your tests are structured as such:

def test_3_minute_confirm():
    req = make_request()
    sleep(3 * 60)  # Baaaad
    assertTrue(confirm_request(req))

With implementations something along the lines of:

def make_request():
    return { 'request_time': datetime.now(), }

def confirm_request(req):
    return req['request_time'] >= (datetime.now() - timedelta(minutes=5))

Instead, try forgetting about "now" and tell both functions what time to use.  If it's most of the time going to be "now", you can do one of two main things to keep the calling code simple:

Make time an optional argument that defaults to "now".  In Python (and PHP, now that I reread the question) this is simple - default "time" to None (null in PHP) and set it to "now" if no value was given.

In other languages without default arguments (or in PHP if it becomes unwieldy), it might be easier to pull the guts of the functions out into a helper that does get tested.

For example, the two functions above rewritten in the second version might look like this:

def make_request():
    return make_request_at(datetime.now())

def make_request_at(when):
    return { 'request_time': when, }

def confirm_request(req):
    return confirm_request_at(req, datetime.now())

def confirm_request_at(req, check_time):
    return req['request_time'] >= (check_time - timedelta(minutes=5))

This way, existing parts of the code don't need to be modified to pass in "now", while the parts you actually want to test can be tested much more easily:

def test_3_minute_confirm():
    current_time = datetime.now()
    later_time = current_time + timedelta(minutes=3)

    req = make_request_at(current_time)
    assertTrue(confirm_request_at(req, later_time))

It also creates additional flexibility in the future, so less needs to change if the important parts need to be reused.  For two examples that pop into mind:  A queue where requests might need to be created moments too late but still use the correct time, or confirmations have to happen to past requests as part of data sanity checks.

Technically, thinking ahead like this might violate YAGNI, but we're not actually building for those theoretical cases - this change would just be for easier testing, that just happens to support those theoretical cases.

Is there any reason you would recommend one of these solutions over another?

Personally, I try to avoid any sort of mocking as much as possible, and prefer pure functions as above.  This way, the code being tested is identical to the code being run outside of tests, instead of having important parts replaced with mocks.

We've had one or two regressions that no one noticed for a good month because that particular part of the code was not often tested in development (we weren't actively working on it), was released slightly broken (so there were no bug reports), and the mocks used were hiding a bug in the interaction between helper functions.  A few slight modifications so mocks weren't necessary and a whole lot more could be easily tested, including fixing the tests around that regression.

Change the system date and time for the test, using exec(). This can work out if you are not afraid to mess up with other things on the server.

This is the one that should be avoided at all costs for unit testing.  There's really no way of knowing what kinds of inconsistencies or race conditions might be introduced to cause intermittent failures (for unrelated applications, or co-workers on the same development box), and a failed/errored test might not set the clock back correctly.


问:
What is "the refactoring method" for understanding code wrote by someone else?
I wrote code, but I myself many times don't even understand the code i wrote. I heard people using "refactoring method" to help them to understand others' code.

I just knew a very little about refactoring. That is using the combined key Alt Shift R in eClipse, but it will automatically change all the related code & thus does not make any benefit for understand code.

So, what is "the refactoring method" (for understanding code wrote by someone else) that people talk about?

答:
Refactoring just means making changes that improve readability but don't change the functionality of code.  IDEs like eclipse will help you do it, but it doesn't have to be done automatically.

Where refactoring comes into play in understanding other people's code, is when that code is very poorly written.  Say you have a 1000 line function with a lot of repetition that is very difficult to understand.  Look for ways to break it up into smaller functions, remove the repetition, and find good names for those smaller functions.

Interestingly, it's usually possible to do this even if you don't understand the big picture at the start.  Once you get all the noise out of the way through refactoring, then the big picture becomes easier to see.


答:
Refactoring is not limited to using IDE commands (although they help a lot in refactoring).  This is the technical definition:
"Code refactoring is the process of restructuring existing computer code – changing the factoring – without changing its external behavior." ([Wikipedia)1

Refactoring to understand code is when and while you are reading code, you try to understand the intent of the programmer and make changes to the code:

Renaming variables or methods with better names

Extract methods or inlining methods

Shortening methods that are too long

and so on.   Here is a site that summarizes all of the different refactoring techniques: http://sourcemaking.com/refactoring

The reason this exercise helps you understand code better is that instead of just consuming the code and trying to understand the code for yourself, you are attempting to redesign the code so others can understand your code.

Title: What is "the refactoring method" for understanding code wrote by someone else?

Body:
I wrote code, but I myself many times don't even understand the code i wrote. I heard people using "refactoring method" to help them to understand others' code.

I just knew a very little about refactoring. That is using the combined key Alt Shift R in eClipse, but it will automatically change all the related code & thus does not make any benefit for understand code.

So, what is "the refactoring method" (for understanding code wrote by someone else) that people talk about?


问:
Good practice to separate Git Repo from published Repo?
We have a central Git repo from which developers fetch and push changes. They make changes on the default master branch. Our Continuous Integration (CI) tool builds artifacts off this default master branch and is the entity responsible for promoting something we want to be tested to a "UAT" branch (this is in reality done by a build-master person clicking a button on the CI tools web page that will do the promotion). The CI tool is also responsible for promoting code from UAT to the "Production" branch. The purpose of the UAT and Production branches is to capture what was promoted to UAT and to Production. No development occurs on the UAT branch and Production will only contain "development" in the form of infrequent "hot-fixes" as our development/release iterations are very fast (1 week iterations).

If we can do it easily, we'd like to put in a control that will prevent someone mistakenly making development changes to UAT and Production branches directly. One thought is to have a hook on the central server that makes sure that only the CI tool user can make changes to UAT and Production. We also thought we could have a central repo that developers use that only contains the master branch and have a second repo that contains the UAT and Production branches. The CI tool will communicate with both repos-- it will look at the development to repo to see when there are changes and use the second repo to do its promotion to the UAT and Production branches.

Is this what folks typically do (separate repos for purposes of development versus promotion?) Would it be better than the server hook approach?

答:
No, not necessarily. Usually one repo is used of one project with proper branch management. This separates the code life cycle into 'stages' which helps to keep unwanted changes being deployed to the wrong places. You could have a look at something like git-flow to help your code move from development to deployed on production, using one Repo.

Git-flow can also be facilitated by tools such as Atlassian's Stash and Jenkins.

PS: Depending on the tools used (like Stash) you can lock branches down so that a Pull Request is required before code is merged back to master etc. This could allow code review to take place.


问:
Pulling changes from master to my work branch?
There's two of us working on something. We're using this branch structure

master

dev-A

dev-B

We both work on separate branches (dev-A,B) and whenever we're done - we promote our changes to master.

But the drawback of this is we can't get changes the other developer makes. Everything exists in the master tree - but we can't get the latest updates the other developer made.

Is there a way to resolve this or should we change our branch structure (per feature?)?

答:
If dev-A and dev-B are different branches for different project then what @scaryrawr answered would be best.

But if dev-A and dev-B is actually precisely the same code (same project) then an alternative would be that both work on one of the branches. For example you create a branch off master called 'devWork'. You both checkout devWork, work on it, commit and push changes. Pushed changes would not be on Master but in devWork, then the other users of the branch simply need to do a PULL locally to get pushed changes.

You could then follow standard methods to get work done on devWork back to Master etc.


问:
UML class diagram notations: Differences between Association, Aggregation and Composition
I'm confused about some of the notations of UML class diagrams.

Pretty sure I know what Association means. Any relationship between instances of two classes, where an instance of one class needs to know about an instance of the second class in order to perform it's work - is an Association relationship. An Association often means class A has a reference (field) to an instance of class B.

However, I'm having trouble understanding what the Aggregation and Composition arrows mean. Part of my confusion was caused by encountering different definitions of these notations.

Two definitions of the Aggregation notation:

Definition 1: An Aggregation notation between two classes is suitable whenever an instance of class A holds a collection of instances of class B (e.g. a List, Array, whatever).

Definition 2: An Aggregation link between two classes is suitable if an instance of class A holds a reference to an instance of class B, and the B instance is dependent on the lifecycle of the A instance. Meaning: When the instance of class A get's deleted, so will the instance of class B. The instance of class B is entirely contained by the instance of class A, as opposed to the instance of class A simply owning a reference to the instance of class B (which is regular Association).

Regarding what the Composition notation means and how it differs from the Aggregation notation, I'm not sure.

Please clarify the definitions and help me understand. Concrete examples would be welcome.

答:
The three links Association, Aggregation and Composition form a kind of scale on how closely two classes are related to each other.

On the one end of the scale, there is Association, where objects of the two classes can know about each other, but they do not affect each others lifetime. The objects can exist independently and which class A object knows about which class B objects can vary over time.

On the other end of the scale, there is Composition. Composition represents a part -- whole relationship such that class B is an integral part of class A. This relationship is typically used if objects of class A can't logically exist without having a class B object.

The Aggregation relation is somewhere between those two ends, but nobody seems to agree where exactly, so there is also no universally agreed definition of what an Aggregation means. In that sense, both definitions that you found are correct and if you ask 10 people, you risk getting 11 different definitions.


问:
Tracking translations in localized software
I created and maintain an open source Android app. Recently someone offered to translate my app into several other languages. At the same time, development continues on the app which can sometimes add string resources which need to be translated.

How can I ensure that the additional string resources are translated with as little pain as possible? In particular, the translator seems to have very minimal technical skills. I think that teaching him version control won't be very helpful. Also asking him to manually comb through the updated English resources for changes can be error prone.

Any suggestions would be greatly appreciated.

答:
The most low tech solution I can think of:

Use a program like Diff or Meld (or whatever you like) to view the differences between the latest version of the program and the latest fully translated version.

This makes the differences a lot clearer to see than manually checking the files, whilst not being too technically challenging.

This is assuming all the translatable text are in string rescource files and not directly in the sourcecode, just like Philipp suggests.


问:
How to restrict user submitted CSS within

We are having rich text editor in which we can insert html. if any input contains

答:
Yes, it is possible. HTML 5 supports the scoped attribute on style tags, which restricts styles defined within to being applied only to the descendants of its parent. An example below (shamelessly pulled and edited from the MDN article).

You could check your user input for style tags and add the scoped attribute, if not already present, either before the content is stored, or before you render it to the page.

```<code><article>
    <div>
        The scoped attribute allows for you to include style elements mid-document.
        Inside rules only apply to the parent element.
    </div>
    <p>This text should be black. If it is red your browser does not support the scoped attribute.</p>
    <section>
        <style scoped>
            p { color: red; }
        </style>
        <p>This should be red.</p>
        <div>
            <p>This should also be red</p>
        </div>
    </section>
</article>
</code>```

Title: How to restrict user submitted CSS within <div>

Body:
Yes, it is possible. HTML 5 supports the scoped attribute on style tags, which restricts styles defined within to being applied only to the descendants of its parent. An example below (shamelessly pulled and edited from the MDN article).

You could check your user input for style tags and add the scoped attribute, if not already present, either before the content is stored, or before you render it to the page.

<article>
    <div>
        The scoped attribute allows for you to include style elements mid-document.
        Inside rules only apply to the parent element.
    </div>
    <p>This text should be black. If it is red your browser does not support the scoped attribute.</p>
    <section>
        <style scoped>
            p { color: red; }
        </style>
        <p>This should be red.</p>
        <div>
            <p>This should also be red</p>
        </div>
    </section>
</article>


答:
I already have posted an answer on Stackoverflow.

Basically, an aggregation is stronger than a simple association but aggregated objects can go on  "living" without each other as with a simple association.

A composition is even stronger than an aggregation because the aggregated class cannot be aggregated by other classes. Its "life" depends on the container.

Title: UML class diagram notations: Differences between Association, Aggregation and Composition

Body:
I'm confused about some of the notations of UML class diagrams.

Pretty sure I know what Association means. Any relationship between instances of two classes, where an instance of one class needs to know about an instance of the second class in order to perform it's work - is an Association relationship. An Association often means class A has a reference (field) to an instance of class B.

However, I'm having trouble understanding what the Aggregation and Composition arrows mean. Part of my confusion was caused by encountering different definitions of these notations.

Two definitions of the Aggregation notation:

Definition 1: An Aggregation notation between two classes is suitable whenever an instance of class A holds a collection of instances of class B (e.g. a List, Array, whatever).

Definition 2: An Aggregation link between two classes is suitable if an instance of class A holds a reference to an instance of class B, and the B instance is dependent on the lifecycle of the A instance. Meaning: When the instance of class A get's deleted, so will the instance of class B. The instance of class B is entirely contained by the instance of class A, as opposed to the instance of class A simply owning a reference to the instance of class B (which is regular Association).

Regarding what the Composition notation means and how it differs from the Aggregation notation, I'm not sure.

Please clarify the definitions and help me understand. Concrete examples would be welcome.