问:
Implementing a generic/dynamic custom property system in C#
I have an architecture design problem which I think is appropriate for this site.

Note that I have made an EDIT to this post below, reflecting my latest potential solution to this problem.

General problem description:

My primary goal is to design a software library/program (C#) to automate a very particular type of microscopy experiments. Our experimental setups consists of many distinct hardware devices that generally fall into a limited number of categories:

Point detector

XY sample stage

Autofocus device

...

The natural choice is to design an interface IDevice with some basic properties shared by all devices such as e.g. IDevice.Initialize(), IDevice.Name, ...

We can even design an abstract class, inheriting IDevice, e.g. DeviceBase implementing some functionalty common to all devices.

Likewise, we can also design interfaces for specific devices, each time implementing the common stuff (IXYSampleStage might hold e.g. IXYSampleStage.Move(posX, posY) or IXYSampleStage.AxisXStepSize).

Ultimately, I can implement all these interfaces in the final classes representing specific devices. I think I know what to do there.

However, not all devices of a class are exactly the same. Some manufacturers offer rich functionality on top of the standard stuff. An XY Stage might have e.g. any number of optional/non-standard parameters to set such as e.g. channel delays, PID control values or whatever.

To tackle this,

I need a mechanism to add additional properties (not methods,
  properties will suffice) to specific device classes. Higher level
  code, interacting with the devices should understand these added
  properties, be able to get/set them, however many there might be.

So much for the basic design problem.

What exists already

There is an OS software program, Micro Manager, which has such a system implemented, be it in C++ (full source here and no, I cannot use this SW directly for my purposes):

```<code>class PropertyBase
{
public:
   virtual ~PropertyBase() {}

   // property type
   virtual PropertyType GetType() = 0;

   // setting and getting values
   virtual bool Set(double dVal) = 0;
   virtual bool Set(long lVal) = 0;
   virtual bool Set(const char* Val) = 0;

   virtual bool Get(double& dVal) const = 0;
   virtual bool Get(long& lVal) const = 0;
   virtual bool Get(std::string& strVal) const = 0;

   // Limits
   virtual bool HasLimits() const = 0;
   virtual double GetLowerLimit() const = 0;
   virtual double GetUpperLimit() const = 0;
   virtual bool SetLimits(double lowerLimit, double upperLimit) = 0;

   // Some more stuff left out for brevity
   ...
};
</code>```

Subsequently, the Property class implements some of the pure virtual functions related to the limits.

Next, StringProperty, IntegerProperty and FloatProperty implement the Get()/Set() methods. These kinds of properties are defined in an enum which allows only these three kinds of property.

Properties can next be added to a PropertyCollection which is basically a kind of dictionary that is part of a device class.

This all works nicely. We use MM a lot in the lab for other types of experiments but when trying to do similar things in my C# solution I stumbled about a few more fundamental questions. Most of these have to do with not being quite sure how to leverage specific features offered by C#/.NET (generic but definitely also dynamics, ...) to perhaps improve the existing C++ implementation.

The questions:

First question:

To limit the types of properties allowed, MM defines an enum:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```

Whereas C# has reflection and a lot of built-in support for types/generics. I therefore considered this:

```<code>public interface IProperty<T>
{
   public T value { get; set; }

   ...
}
</code>```

I could next do an abstract PropertyBase<T> and ultimately

```<code>IntegerProperty : PropertyBase<int>
StringProperty : PropertyBase<string>
FloatProperty : PropertyBase<double>
</code>```

But this gets me in trouble when trying to put them into a collection because in .NET following is not possible:

```<code>PropertyCollection : Dictionary<string, IProperty<T>>
</code>```

Unless, perhaps, I adopt this strategy, i.e. have a non generic base class that only returns a type and then yet more base classes to actually implement my property system. However, this seems convoluted to me. Is there a better way?

I think that utilising the generic language features might allow me to do away with needing all these Get()/Set() methods in the MM example above, as I would be able to know the backing type of my property value.

I realise this is a very broad question but, there is a big gap between understanding the basics of some language features and being able to fully make the correct design decisions from the outset.

Second question

I am contemplating making my final device classes all inherit from a kind of DynamicDictionary (e.g. similar to the one from here):

```<code>    public class DynamicDictionary : DynamicObject
    {
        internal readonly Dictionary<string, object> SourceItems;

        public DynamicDictionary(Dictionary<string, object> sourceItems)
        {
            SourceItems = sourceItems;
        }
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (SourceItems.ContainsKey(binder.Name))
            {
                SourceItems[binder.Name.ToLower()] = value;
            }
            else
            {
                SourceItems.Add(binder.Name.ToLower(), value);
            }
            return true;
        }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (SourceItems != null)
            {
                if (SourceItems.TryGetValue(binder.Name.ToLower(), out result))
                {
                    return true;
                }
            }
            result = null;
            return true;
        }
    }
}
</code>```

but instead of <string, object> I would then like to use <string, MyPropertyBase> where the string would be the alias for my property (which would correspond to the design choice from Q1).

Would doing such a thing make sense from a design standpoint?

I would actually only need to add custom properties to devices at design time (i.e. when writing a custom device driver). At runtime, I would only need to inspect my custom properties or get/set their values.

the C++ MM solves this by using a bunch of CreateProperty("alias", Property) methods in the device constructor, which again, works so maybe using dynamics here is overkill. But again, I am wondering if somebody could provide insight in possible advantages but certainly also disadvantages of going down the dynamic route.

To summarize

Are there .NET features (4.5) which I could leverage to implement some of the MM concepts in a more elegant way with a focus on the above mentioned specific matters?

Again, I do realise this is a very broad question and perhaps some of the possible answers are more a matter of taste/style than anything els but if so (this making the question unsuited for this platform), please provide feedback/comments such that I can adjust accordingly.

EDIT

I have spent some more thinking about this and tried to solve it in the following way:

First, an enum specifying the allowed propertytypes:

```<code>public enum PropertyType
{
    Undefined,
    String,
    Float,
    Integer
}
</code>```

Second, an interface IPropertyType that is responsible for checking values fed to a property of a specific type:

```<code>public interface IPropertyType
{
    Type BackingType { get; }

    PropertyType TypeAlias { get; }

    bool IsValueTypeValid(object value);
}
</code>```

Then, a base class implementing IPropertyType:

```<code>public bool IsValueTypeValid(object value)
    {
        if (value == null)
        {
            return true;
        }

        Type type = value.GetType();

        if (type == this.BackingType)
        {
            return true;
        }

        return false;
    }

...

public Type BackingType
    {
        get
        {
            switch (this.TypeAlias)
            {
                case PropertyType.Integer:
                    return typeof(long);
                case PropertyType.Float:
                    return typeof(double);
                case PropertyType.String:
                    return typeof(string);
                default:
                    return null;
            }
        }
    }
</code>```

I then have three IPropertyType: StringPropertyType, IntegerPropertyType and FloatPropertyType where each time, the property PropertyTypeAlias is set to one of the enum values.

I can now add my IPropertyType to IProperty types:

```<code>public interface IProperty
{
    string Alias { get; }

    /// If we want to limit the property to discrete values.
    Dictionary<string, object> AllowedValues { get; }

    bool HasLimits { get; }

    bool HasValue { get; }

    bool IsReadOnly { get; }

    /// Callback for HW operations using the property value.
    Func<PropertyFuncType, bool> PropertyFunction { set; }

    PropertyType TypeAlias { get; }

    object Value { get; set; }

    void AddAllowedValue(string alias, object value);

    void ClearAllowedValues();

    // On numeric properties, it might be usefull to limit the range of values.
    void SetLimits(object lowerLimit, object upperLimit);

    // These will do stuff on the HW...
    bool TryApply();

    bool TryUpdate();
}
</code>```

Here, the Value setter will run the validation on input value as defined by the IPropertyType.

IProperty is almost fully implemented in PropertyBase which also has a field of IPropertyType which gets set upon instance creation (and cannot be changed thereafter; a property cannot change type.

From the base class e.g.:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```0

That only leaves specific IProperty classes: StringProperty, IntegerProperty and FloatProperty where there is only one override, SetLimits() because it relies on comparison of values. Everything else can be in the base class:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```1

This way, I think I have a system that allows me to have a collection of IProperty that can actually hold data of different types (int, float or string) where for each type of IProperty I have the ability to implement value limits etc (i.e. stuff that is different, depending on the data type)...

However, I still have the impression that there are either better ways to do this sort of thing or that I am over engineering things.

Therefore, any feedback on this is still welcome.

EDIT 2

After more searching online I believe the last bits of code posted here in the previous edit are leaning towards the Adaptive Object Model "pattern" (if it really is that).

However, most resources on this topic seem to be quite old and I'm wondering if there are now better ways to achieve these types of things.

答:
If properties will only ever be used in GUI and as read/set for HW, then there is no need for generics or reflection. Just use simple OOP classes. What you should focus is not how internals of the properties will be, but on how they will be used. How do you want to have those properties editable from GUI or how you want to save or retrieve them to the HW device?

```<code>public interface PropertyBase
{
    string Name {get;} // name of this property

    void SetToDevice(); // sets the value to device
    void ReadFromDevice(); // read from device

    GUIEditor GetEditor(); // returns editor for this property
}

public class PropertyContainer // device can implement or contain this
{
    public List<PropertyBase> Properties;
}

public interface IntProperty : PropertyBase
{
    public IDevice Device {get;set;}
    public string Name {get;set;} // name of this property

    public int Value {get;set;}

    void SetToDevice()
    {
        Device.SetInt(Name, Value);
    }
    void ReadFromDevice()
    {
        Value = Device.ReadInt(Name);
    }

    GUIEditor GetEditor()
    {
        return new IntEditor(this); // IntEditor can get/set value itself
    }
}
</code>```

The GUIEditor will be way for GUI to know how to edit the specific property. If you have dependency problems, you could use Visitor pattern to move this logic into View. The major advantage of this approach is that you have are open to add new device-specific properties without having to change existing code.

Body:
If properties will only ever be used in GUI and as read/set for HW, then there is no need for generics or reflection. Just use simple OOP classes. What you should focus is not how internals of the properties will be, but on how they will be used. How do you want to have those properties editable from GUI or how you want to save or retrieve them to the HW device?

public interface PropertyBase
{
    string Name {get;} // name of this property

    void SetToDevice(); // sets the value to device
    void ReadFromDevice(); // read from device

    GUIEditor GetEditor(); // returns editor for this property
}

public class PropertyContainer // device can implement or contain this
{
    public List<PropertyBase> Properties;
}

public interface IntProperty : PropertyBase
{
    public IDevice Device {get;set;}
    public string Name {get;set;} // name of this property

    public int Value {get;set;}

    void SetToDevice()
    {
        Device.SetInt(Name, Value);
    }
    void ReadFromDevice()
    {
        Value = Device.ReadInt(Name);
    }

    GUIEditor GetEditor()
    {
        return new IntEditor(this); // IntEditor can get/set value itself
    }
}

The GUIEditor will be way for GUI to know how to edit the specific property. If you have dependency problems, you could use Visitor pattern to move this logic into View. The major advantage of this approach is that you have are open to add new device-specific properties without having to change existing code.


问:
Best practice for unused inherited virtual functions (implementing superclass methods)
Let's assume I have a hierarchy of several classes each derived from each other using virtual functions. The base class acts as an interface and defines functions, which may not be required by all of the derived classes. Now I wonder what the best practice is for such intermediate functions. Should those still be implemented and simple chain down to the base class, or should they be skipped?
The problem I have is, that implementing such a function, when it isn't needed, simply adds noise to the code. On the other hand, when using a higher class, in C++ you can not simply call a superclass method (like in Java), so you need to know in which base class the method is really implemented. And to my mind, this would violate encapsulation, because I would need to know some implementation details of the base class.

To illustrate what I mean here is an artifical exmaple:

```<code>class MyInterface
{
    virtual void foo(bool) = 0;
    virtual void foo1(int) = 0;
};

class Base : public MyInterface
{
    void foo(bool param) override
    {
        // do some stuff here.
    }

    void foo1(int param) override
    {
        // do some stuff here.
    }
};

class A : Base
{
    void foo(bool param) override
    {
        // do some stuff here.
        Base::foo(param);
    }
    // class doesn't need foo1() here so it is not implemented.
};

class B : A
{
    void foo(bool param) override
    {
        // do some stuff here.
        A::foo(param);
    }

    void foo1(int param) override
    {
        // This class needs foo1() but as A doesn't have it implemented
        // I have to knwo this and skip A going directly to Base
        Base::foo1(1);
    }
};
</code>```

Here the class B needs to know that A doesn't implement foo1 and has to skip it. Of course this can be seen in the header, but if I want to later change class A it shouldn't be neccessary to touch all the other classes that are derived from it (encapsulation and isolation principle) So even worse, if I implement now foo1() in A later, B would still skip it and never realise that the functionality has changed.

So from an object model point of view I would assume that such empty functions should still be designed into a class?

答:
You're right, this is a flaw in the language itself which means that despite all the advantages which come from inheritance, you still have to know how it is implemented.  It would be ideal to be able to call super within the method and have it call the appropriate method, whatever that might be.  This is one of the things that Java tried to improve upon.

As you said, you could get around it by implementing every method in class A, and so in doing so, you prevent complications later on.  It is a bit of a pain, but I suppose it is a necessary evil for creating a proper library to be used by others.  Note that only the class being made available in the library for use has to implement all virtual methods, and not any internally used classes unless you require otherwise.

While not a solution, a slightly friendlier approach (albeit a little hacky) might be to typedef "super" as a private type definition for the base class.  As in the case of class B, you'd have:

```<code>private:
    typedef A super;
</code>```

Likewise in class A, you could define:

```<code>private:
    typedef Base super;
</code>```

At least if you're the one writing the code, rather than have to know the name of the class, you could do:

```<code>class B : A
{
    void foo(bool param) override
    {
        // do some stuff here.
        super::foo(param);
    }

    void foo1(int param) override
    {
        super::super::foo1(1);
    }
};
</code>```

Again, while this doesn't fix your problem, it makes it slightly more manageable.

See here for more details.

ContentLicense: CC BY-SA 3.0

Body:
You're right, this is a flaw in the language itself which means that despite all the advantages which come from inheritance, you still have to know how it is implemented.  It would be ideal to be able to call super within the method and have it call the appropriate method, whatever that might be.  This is one of the things that Java tried to improve upon.

As you said, you could get around it by implementing every method in class A, and so in doing so, you prevent complications later on.  It is a bit of a pain, but I suppose it is a necessary evil for creating a proper library to be used by others.  Note that only the class being made available in the library for use has to implement all virtual methods, and not any internally used classes unless you require otherwise.

While not a solution, a slightly friendlier approach (albeit a little hacky) might be to typedef "super" as a private type definition for the base class.  As in the case of class B, you'd have:

private:
    typedef A super;

Likewise in class A, you could define:

private:
    typedef Base super;

At least if you're the one writing the code, rather than have to know the name of the class, you could do:

class B : A
{
    void foo(bool param) override
    {
        // do some stuff here.
        super::foo(param);
    }

    void foo1(int param) override
    {
        super::super::foo1(1);
    }
};

Again, while this doesn't fix your problem, it makes it slightly more manageable.

See here for more details.


问:
Git-based storage and publishing, infrastructure advice
I wanted to get some advice on moving a system to "the cloud" ... specifically, I'm looking to move into some of Windows Azure's managed services, as right now I'm managing a VM. Basically, the system operates on some data stored in a github git repository. I'll describe the current architecture:

Current system (all hosted on a single server):

GitHub - configured with a webhook pointing at ...

ASP.NET MVC application - to accept the webhook from git. It pushes a message onto ...

Azure service bus Queue - which is drained by ...

Windows Service - pulls the message from the queue and ...

Fetches the latest data from the git repository (using GitLib2Sharp) onto the local disk and finally ...

Operates on the data in git to produce a static HTML website hosted/served by IIS.

The system works really well, actually ... but I would like to get out of the business of managing the VM, and move to using some combination of Azure web and worker roles. But because the system relies so heavily on the git repository on the local filesystem, I'm finding it difficult to figure out how to architect in the cloud. I know you can get file system access, so in theory I could just fetch the repository if there's nothing on disk ... but the performance/responsiveness of the system sort of depends on the repository being available and only having to fetch diffs, which is relatively quick. As opposed to periodically having to fetch the entire (somewhat large) git repository if the web or worker role was recycled, or something.

So I would love some advice on how you would architect such a system :) Ultimately, the only real requirement is to be able to serve HTML content that's been produced from the contents of a git repository (in a relatively responsive manner, from a publishing perspective) ... please feel free to ask any clarifying questions if there's something I omitted. Thanks!

答:
Made an example because it did not fit the comments: It's PHP but I believe quite readable for you to understand the concept.

```<code><?PHP

/**
 * Simple example of loading the git repository
 * Then do a conversion on some files
 * Then publish them in the /public repository
 *
 * Handles loading the repository from github and understands whether it
 * needs to clone because it's the first run or update.
 *
 * Timing on slow internet connection:
 *
 * update: 0.96 - 1.53 seconds
 * new clone: ~100 seconds
 *
 * Clearly most time happens in the downloading of the repository.
 *
 * Uses rename() as atomic function to allow updating and processing to
 * happen without the users having issues. When processing is totally complete
 * the public directory is instantly replaced.
 *
 */

$time_start = microtime(true);

//git repo
$repoDir=__DIR__.'/linux/';

//public directory
$publicationDir=__DIR__.'/public/';

//temporary directory for publication to be built
$newPublicationDir=__DIR__.'/tmp-'.time().'/';

//archive location for old version (for fallback in case of errors)
$archiveDir=__DIR__.'/archive-'.time().'/';

//ensure we have all directories, yes ugly without error catching
@mkdir($repoDir);
@mkdir($newPublicationDir);
@mkdir($archiveDir);

//detect a new install or an update of the repository
if(!file_exists($repoDir.'.git')) {
    //new install
    exec('git clone git://github.com/torvalds/linux.git --depth 1');
}else{
    //update
    exec('cd '.$repoDir.'; git fetch --depth 1');
}

//processing your contents (no idea what you do on them)
//in example we convert newlines of a textdocument to <br> tags
$documentationFile=$repoDir.'Documentation/aoe/aoe.txt';

file_put_contents(
    $newPublicationDir.'index.html',
    '<h1>Converted document from git</h1>'.nl2br(file_get_contents($documentationFile))
);

//back-up the current publication
if(file_exists($publicationDir)) {
    rename($publicationDir, $archiveDir);
}else{
    @mkdir($publicationDir);
}

//add the new publication
rename($newPublicationDir, $publicationDir);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "ready in $time seconds\n";
</code>```

This example works with the linux repository which is quite big in my opinion with a lot of irrelevant history. It uses the ideas discussed in the comments. Generally this thing will update in 2 seconds. So, while waiting for your exact numbers about repository size and processing times, I think this should be sufficient to solve your problem.

queue

I understand you now use a queue etcetera. You can keep all of that if you want and process it like the example.

simpler alternative

Other more simple alternative (in my opinion) is: Just web servers, no workers.

Start one or more web workers. They process the script at boot time. When they are done (validate if public directory is full) they open the port and they are ready for service. Maybe they should notify some load balancer or whatever to let system know they are ready for requests.

Then just run a cron (scheduled task) to update them every x minutes/seconds whatever. That will ensure you don't run the task multiple times at once and you don't have to configure your hooks.

If that is not allowed you can also choose to use the hooks etcetera with your queue but I think it makes the process just too complex if your question is correct and with all relevant information.

processing in workers

Now you could choose to put a separate layer in between with the workers, to parse the data from the repository, if you really need that. You could use the same principles but just publish on a shared disk. The web servers read that disk and you are done.

Alternative to the shared disk you could put the worker results also into a git repository and use the same script pointing to a azure hosted git repository which just loads the results.

On Azure you could process this script I think with: http://www.hanselman.com/blog/IntroducingWindowsAzureWebJobs.aspx

For the shared storage you can take a look at File Storage in this document:
http://azure.microsoft.com/en-us/documentation/articles/storage-introduction/
There is also a quite clear listing of the alternatives. In general you can share the storage on azure between multiple types and multiple instances of servers which fits your needs.

beware I put in archive directories, remove that for sure in production cause it keeps filling your filesystem.

Body:
Made an example because it did not fit the comments: It's PHP but I believe quite readable for you to understand the concept.

<?PHP

/**
 * Simple example of loading the git repository
 * Then do a conversion on some files
 * Then publish them in the /public repository
 *
 * Handles loading the repository from github and understands whether it
 * needs to clone because it's the first run or update.
 *
 * Timing on slow internet connection:
 *
 * update: 0.96 - 1.53 seconds
 * new clone: ~100 seconds
 *
 * Clearly most time happens in the downloading of the repository.
 *
 * Uses rename() as atomic function to allow updating and processing to
 * happen without the users having issues. When processing is totally complete
 * the public directory is instantly replaced.
 *
 */

$time_start = microtime(true);

//git repo
$repoDir=__DIR__.'/linux/';

//public directory
$publicationDir=__DIR__.'/public/';

//temporary directory for publication to be built
$newPublicationDir=__DIR__.'/tmp-'.time().'/';

//archive location for old version (for fallback in case of errors)
$archiveDir=__DIR__.'/archive-'.time().'/';

//ensure we have all directories, yes ugly without error catching
@mkdir($repoDir);
@mkdir($newPublicationDir);
@mkdir($archiveDir);

//detect a new install or an update of the repository
if(!file_exists($repoDir.'.git')) {
    //new install
    exec('git clone git://github.com/torvalds/linux.git --depth 1');
}else{
    //update
    exec('cd '.$repoDir.'; git fetch --depth 1');
}

//processing your contents (no idea what you do on them)
//in example we convert newlines of a textdocument to <br> tags
$documentationFile=$repoDir.'Documentation/aoe/aoe.txt';

file_put_contents(
    $newPublicationDir.'index.html',
    '<h1>Converted document from git</h1>'.nl2br(file_get_contents($documentationFile))
);

//back-up the current publication
if(file_exists($publicationDir)) {
    rename($publicationDir, $archiveDir);
}else{
    @mkdir($publicationDir);
}

//add the new publication
rename($newPublicationDir, $publicationDir);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "ready in $time seconds\n";

This example works with the linux repository which is quite big in my opinion with a lot of irrelevant history. It uses the ideas discussed in the comments. Generally this thing will update in 2 seconds. So, while waiting for your exact numbers about repository size and processing times, I think this should be sufficient to solve your problem.

queue

I understand you now use a queue etcetera. You can keep all of that if you want and process it like the example.

simpler alternative

Other more simple alternative (in my opinion) is: Just web servers, no workers.

Start one or more web workers. They process the script at boot time. When they are done (validate if public directory is full) they open the port and they are ready for service. Maybe they should notify some load balancer or whatever to let system know they are ready for requests.

Then just run a cron (scheduled task) to update them every x minutes/seconds whatever. That will ensure you don't run the task multiple times at once and you don't have to configure your hooks.

If that is not allowed you can also choose to use the hooks etcetera with your queue but I think it makes the process just too complex if your question is correct and with all relevant information.

processing in workers

Now you could choose to put a separate layer in between with the workers, to parse the data from the repository, if you really need that. You could use the same principles but just publish on a shared disk. The web servers read that disk and you are done.

Alternative to the shared disk you could put the worker results also into a git repository and use the same script pointing to a azure hosted git repository which just loads the results.

On Azure you could process this script I think with: http://www.hanselman.com/blog/IntroducingWindowsAzureWebJobs.aspx

For the shared storage you can take a look at File Storage in this document:
http://azure.microsoft.com/en-us/documentation/articles/storage-introduction/
There is also a quite clear listing of the alternatives. In general you can share the storage on azure between multiple types and multiple instances of servers which fits your needs.

beware I put in archive directories, remove that for sure in production cause it keeps filling your filesystem.


问:
How should be the approach to start thinking about multi thread programming
I am an experienced java developer.Of now I have started learning multithreading in java.I am able to grasp most of the concepts but still I am unable to visualize applications running on threads.I know the concept but somewhere if I am given a problem statement, I am unable to think or visualize it in threads.How should my approach be in order to start visualizing applications in threading and start coding the applications in threads?</p>

答:
I think the best way to deal with parallel programming is to keep in mind the global data you're dealing with and not so much the code you're writing on. As soon as you stumble upon global data (such as a member variable), you have to think to yourself: Is it possible that this variable get's accessed by multiple threads?

The advantage of this approach is that you're thinking about what's essential to multithreading, which is accessing global data, and not your code. It doesn't matter what code is accessing it; it could be the code you're currently typing, or a code somewhere else. I don't think about whether my code will be executed in parallel, I'm just caring about the variable I'm acessing.


问:
Which algorithms do I need to look into?
First things first: I need to apologize in advance about the bad choice of title for this question, but I really couldn't come up with something meaningful. I'm actually looking for suggestions as to what this kind of problem in called, so that I can do some research on my own. I will gladly change the title once the suggestions will start to come in.

It's not even a real problem, it's just an exercise I made up in order to explore algorithms I have never had the chance to deal with.

Let's say we want to write a program that will help us to optimize the logistics of an arbitrary number of music bands that have to perform one after the other on the same stage during the same night.

Here's the problem: the bands share players, meaning that any given player can play in more than one band. Were the bands all made of different players, we wouldn't need a program at all, but since all the musicians know each other, they will form many bands with different combinations of them.

What we want to do is to arrange all the bands in such a way that groups that share the greatest number of members will "cluster" together and play one after the other, so that we can minimize the number of musicians involved with each change of band. In other words, the largest number possible of musicians should be already on stage each time a band finishes its set and the next one comes on stage.

Is this just another form of the famous staff rostering / scheduling problem?

Or is it simpler?

I admittedly haven't yet though hard about how one might solve it, it's just a problem that I thought of today.

If I had to take a stab at it, it looks like the problem boils down to figuring out which bands have the most members in common, and sort them accordingly.

But how is this called in CS parlance?

And, is that all there is to it?

Arranging bands by the number of musicians is the only requirement we have. I sense that, if we had to take into account other kinds of constraints like, say, one particular band would really prefer playing at the beginning and another right in the middle, this might turn into a full-fledged scheduling problem.

In its simplest form, though, this appears to be a simple problem but, like I said, I don't know the name of the family of algorithms that would enable me determine which bands have the most musicians in common.

答:
This just comes to my mind as I was working with a different problem.
When I came back I realized that Falk Huffner has already mentioned the tip.

Anyway, no more fingering, one can show the reduction as follows to the decision version of the problem
(whether there is an ordering of bands so that you have a value x)

First use a modified version of Hamiltonian path, in which you are given a start and end vertices.

Make each vertex a band and each edge a person. If there is a modified Hamiltonian path then obviously, there is an ordering that gives you value that is the number of bands - 1.
The proof for the inverse is also not hard to see.

The second part is about proving reduction between the modified Hamiltonian and the regular one. The idea is that one simply uses a vertex as starting candidate. Split this vertex into 2 vertices called start and end. For the start and end vertices, split again into outter nodes and inner nodes. The outer node will connect with all other nodes as in the original graph, the inner node connects only with the corresponding outer nodes. This ensures that once a path enters the start or end node the candidate node in the original graph is visited only once. Thus you have a Hamiltonian path iff there is a modified Hamiltonian path.


问:
"Ever change the value of 4?" - how did this come into Hayes-Thomas quiz?
In 1989 Felix Lee, John Hayes and Angela Thomas wrote a Hacker's test taking the form of a quiz with many insider jokes, as “Do you eat slime-molds?”

I am considering the following series:

```<code>0015 Ever change the value of 4?
0016 ... Unintentionally?
0017 ... In a language other than Fortran?
</code>```

Is there a particular anecdote making the number “4” particular in the series?

Did some Fortran implementation allow to modify the value of constants?  Was this possible in other languages in common use at that time?

答:
In the old days (1970s and before) some computers did not have any MMU (and this is true today for very cheap microcontrollers).

On such systems, there is no memory protection so no read-only segment in the address space, and a buggy program could overwrite a constant (either in data memory, or even inside the machine code).

The Fortran compilers at that time passed formal arguments by reference. So if you did CALL FUN(4) and the SUBROUTINE FUN(I) has its body changing I - e.g. with an statement I = I + 1 in its body, you could have a disaster, changing 4 into 5 in the caller (or worse).

This was also true on the first microcomputers like the original IBM PC AT from 1984, with MS-DOS

FWIW, I'm old enough to have used, as a teen ager in early 1970s, such computers: IBM1620 and CAB500 (in a museum: these are 1960s era computers!). The IBM1620 was quite fun: it used in memory tables for additions and multiplications (and if you overwrote these tables, chaos ensued). So not only you could overwrite a 4, but you could even overwrite every future 2+2 addition or 7*8 multiplications (but I really forgot these dirty details so could be wrong).

Today, you might overwrite the BIOS code in flash memory, if you are persevering enough. Sadly, I don't feel that fun any more, so I never tried. (I'm even afraid of installing some LinuxBios on my motherboard).

On current computers and operating systems passing a constant by reference and changing it inside the callee will just provoke a segmentation violation, which sounds familiar to many C or C++ developers.

BTW: to be nitpicking: overwriting 4 is not a matter of language, but of implementation.


答: In FORTRAN, when a constant is passed to another procedure, it is no longer protected. That is what they refer to. Other popular programming languages in that same time were C and Pascal which didn't (and still don't) have this issue. Maybe there are older programming languages which I'm not aware of that have the same issue. </p>

Title: "Ever change the value of 4?" - how did this come into Hayes-Thomas quiz?

Body:
In 1989 Felix Lee, John Hayes and Angela Thomas wrote a Hacker's test taking the form of a quiz with many insider jokes, as “Do you eat slime-molds?”

I am considering the following series:

```<code>0015 Ever change the value of 4?
0016 ... Unintentionally?
0017 ... In a language other than Fortran?
</code>```

Is there a particular anecdote making the number “4” particular in the series?

Did some Fortran implementation allow to modify the value of constants?  Was this possible in other languages in common use at that time?


问:
Deeper understanding of event loops and timers
I have a basic grasp of accepting clients without creating a thread for each connection using tools such as select and modern equivalents (kqueue, epoll).

But where do I go from here? e.g async I/O and (periodic) timers. I could crack open the source to libev and friends but that's a little overwhelming to me to say the least.

I've looked around for textbooks on this subject but didn't come up with anything useful.

The basic objective is to write a small toy implementation of an evented library with timers and async I/O. Just for getting a better grasp on the subjects.

I'm not looking to reinvent the wheel. This is solely for learning/educational purposes. (not homework either)

答:
A linux application would use select() or poll() in a loop and then forward to the correct handler for each file-descriptor + event pair. A similar construct with the GetMessage() function is used in windows.

Boost contains a stand-alone version of async IO with event timers (though in classic Boost form it's a bit complicated).


问:
Why is Throwable initCause designed to be called only once?
I find it really odd that the initCause method of Java's Throwable class can only be called once, or even not at all (if the constructor accepting a Throwable was used). This makes exception chaining not as easy as I think it should be.

```<code>private Throwable cause = this;

public Throwable(String message, Throwable cause) {
    ...
    this.cause = cause;
}

public Throwable getCause() {
    return (cause==this ? null : cause);
}

public synchronized Throwable initCause(Throwable cause) {
    if (this.cause != this)
        throw new IllegalStateException("Can't overwrite cause");
    if (cause == this)
        throw new IllegalArgumentException("Self-causation not permitted");
    this.cause = cause;
    return this;
}
</code>```

It leads to ugly boilerplate code that has to take care of edge cases where the method may have already been called, but the part of the code where you want to call it again, you're not sure.

What is worse is that the getCause method does not correctly tell you whether initCause method had been called or not. This is because someone else could have called initCause(null) and this would make getCause to return null while at the same time have initCause fail with IllegalStateException (because null != this is true).

The result is a boilerplate code as follows:

```<code>try {
    exp1.initCause(exp2);
} catch (IllegalStateException ise) {
    // do something or ignore
} catch (IllegalArgumentException iae) {
    // do something or ignore
}
</code>```

Whereas I should be able to simply call exp1.initCause(exp2); without caring whether it's the same exception or the method had already been called (and let the method take care of what to do if either of the condition was true; for example simply ignore the new cause).

What is the reason behind such an odd design?

Edit:

I would like to clarify that I don't have a problem with the cause being immutable. My problem is that, ensuring such immutability is not violated is made a burden for the programmers, rather than being handled automatically by the implementation.

It would have made more sense to me if the cause was implemented as follows:

```<code>private Throwable cause; // null means no cause

public Throwable(String message, Throwable cause) {
    ...
    this.cause = cause;
}

public Throwable getCause() {
    return cause;
}

public synchronized Throwable initCause(Throwable cause) {
    if (this.cause == null)
        this.cause = cause;
    return this;
}
</code>```

Or even if the original implementation was kept, a handy method could have been added:

```<code>public boolean hasCause() {
    return (this.cause != this);
}
</code>```

So that I could reduce the boilerplate code to simply:

```<code>if (!exp1.hasCause()) exp1.initCause(exp2);
</code>```

I would also like to clarify that this is not a question of which Java version I should be using, or whether I should continue using versions of Java that have reached their support's end-of-life. There are many reasons why older versions of Java continue to be used other than "lazy to upgrade" or "don't care about security". :)

答:
What is the reason behind such an odd design?

It is not an odd design. The cause should be immutable since user code playing with the cause will most likely always cause more harm than good and will break the semantic of the cause.

The explanation of the existence of the initCause method can be found in the Throwable javadoc:

Because the initCause method is public, it allows a cause to be associated with any throwable, even a "legacy throwable" whose implementation predates the addition of the exception chaining mechanism to Throwable.

Indeed, exception chaining has only been added in Java 1.4. Before that, an exception did not had a cause.

They had to add this method for compatibility reason. You could still use an old exception without the cause parameter in the constructor but still set the cause later on.

Regarding your use case, what you want to use are suppressed exceptions. They have been added in Java 7 to handle your exact use case (see try-with-catch documentation for example).

If you are using an end-of-life version of Java, you can add a similar mechanism to your own exception (or upgrade to a non end-of-life version).

If you really really want to break the exception chaining semantic you can always create a new exception with a composite/hacked cause and throw it.

TL;DR: Cause should be immutable that's why this check is done in initCause. Hacking the cause is not the good way to handle suppressed exceptions and will usually cause lot of trouble. It was a major flaw of Java older than version 7, like the lack of chained exceptions was before Java 1.4.


问:
2D linked list vs. multidimensional array/vector
I hope that programmers is the correct stack exchange for this, as it is quite a concept based question.

I'm working on a data structure in C++ that is a represents data in 3D space. The x-y plane is large (say 0 - 10 000) while the z-axis has a very small range (0 - 10). All the data is located on integer (x,y,z) points. However there can be more than one than one data point on an (x,y,z) coordinate.

I have thought of three ways of approaching this subject, and don't have the necessary experience to choose between them.

Using a 2D linked list inside vectors (dynamic arrays) vector<vector<structureA*>> Data where the first list item for that (x,y) point can be accessed using Data[x][y]. structureA contains an its z value, its actual data, as well as a pointer to the next structure in the list (that may, or may not have a different z coordinate, but is located  on the same line defined by x and y). Accessing elements at the middle and end of this list is slow.

Using a three dimensional array/vector: vector<vector<vector<structureB>>> Data. In this case the first two vectors define the x and y coordinates (as before) and the third vector gives us an array of all of the elements on that line defined by x and y. We can quickly determine how many elements are on this line (by querying the third vector) and can iterate from the back and the front. structureB contains, the point's z value and its data. This seems like a fairly good and safe (regarding memory allocation) solution to me.

Using a three dimensional array/vector and a linked list. In this case the data could be accessed as such: Data[x][y][z] and would point to the first element of a linked list of data that resides at this coordinate. The structure pointed to would not contain its z value here as this is already dealt with in its address in the array. However, many (x,y,z) points have no data, whereas most of those that do have data have 10+ data structures. (All lines defined by a specific (x,y) contain at least one structure). This seems the worst solution to me as in many cases I would have to iterate through empty z coordinates, before hitting a linked list to iterate through.

The emphasis in this program is speed, my data set is less than 100MB on a modern computer, so even an inefficient method of storing it in RAM is fine. Option 2 seems the best to me, although in the past I've normally seen people more inclined to go with option 1. I'm interested to hear your opinions on the best way to handle this along with your reasoning.
Many Thanks.

Update

Thanks for the responses, I stand to learn quite a lot from your comments as I am a hobby programmer, having taken only one short course on the fundamentals of C a few years back.

@MorphingDragon The array is not jagged, all z "slices" have the same range of x and y. The values also don't seem sparse enough for a hash table (which IIRC slow down significantly on hash collision - which is guaranteed as multiple elements have the same (x,y,z)). The dimensions of the set are known on file load (they are included in the file header along with an md5 hash of the file for error checking and a few bit relevant to the analysis).

@J Trana / Florian F The data set is pre-built and is infrequently modified by the program - a piece of data may need to be moved or deleted. For adjusting data particularly just adjusting its z-value (or removing it), which are the most frequent operations. The linked list will be faster as these operations are O(1) as opposed to O(n) in a vector. However, I believe these changes are infrequent enough that having O(n) for changes may be worthwhile if the lookup speed is even marginally faster (as this is the more frequent operation).

The majority of the time the data will be accessed iteratively, taking an n*p slice  from the x-y plane. Pseudocode example:

```<code>for each y between startY and (startY + p)
  for each x between startX and (startX + n)
    read all nodes in Data[x][y] //gets nodes for each z on an (x,y) line
    analyse(&nodes) //possibly modify the nodes, possibly just compute something based on their values
</code>```

Data access is always related to the (x,y) line an element is on, but we  don't always need all the nodes on that line (dependant on their z). So we either have a structure that doesn't require us to retrieve all of them (just the ones we want) or we perform a secondary sort. The data on file represents a sorted list in ascending z for each (x,y).

I will also look into those other data structures. I've never met them, as with very little training, my method is to use STL vectors or lists for everything. I'd like to spend the time to do this properly this time though.

I spent a fair amount of time thinking about this last night after posting the question and seeing the first responses. I realised that "if one piece of data from a point (x,y,z) is required, then all elements from that point are required at the same time." This has led me to think that option 3, my least preferred when I started this yesterday afternoon, is actually the best of the options I've enumerated. If I use a three-dimensional dynamic array of pointers to linked list, I don't exactly lose much speed or heap space setting a pointer to NULL rather than attaching a struct. This also allows full access to any 3d, which while not currently required may reduce some operations from O(n) to O(1).

Having had a brief look over octaves/r-trees, I feel safe saying that my data set is not complex enough to require such an engineering heavy solution. When it comes down to it, i am fairly sure that any of the three options I outlined would work, even if not the fastest, but I would like to learn a good and relatively efficient method, rather than just relying on the awesome power of modern computers to brute force a problem like I normally do.
Thanks for the replies and suggestions so far. :)

答:
I hope it's ok to answer my own question.
I believe I have found the optimal (without overcomplicating the problem) data structure for my problem. There was at least minor idiocy on my part for not recognising this earlier. The data doesn't need to be accessed by (x,y,z) but instead by (x, y, range of z (say 0 - 3)). This give a C++ struct as follows:

```<code>struct node {
  struct node *next;
  int zGroup;
  int z;
  50 bytes of misc data };
</code>```

I can then address this through a 3D dynamic array (vectors):

```<code>vector< vector < vector < node* > > > Data;
</code>```

Any given Data[x][y][zGroup] points to the first element of a linked list, the entirety of which is needed every time one element of it is needed. No value of this array is NULL, every one contains a linked-list of at least one element.

The third dimension of the array - the zGroup has jagged dimensions, but with dynamic arrays this isn't an issue. Given the data and computations being performed on it, I know that the max x and y values are set when the file is read and do not change, neither does the number of z groups on any given (x,y) line, the actual z-values of nodes may change, but they will remain inside the same z-groups, giving a constant-sized, fully populated array.

With the way that the file is structured it is also easy enough to page it in and out of memory if I am brought to do this with much larger data sets.

Body:
I hope it's ok to answer my own question.
I believe I have found the optimal (without overcomplicating the problem) data structure for my problem. There was at least minor idiocy on my part for not recognising this earlier. The data doesn't need to be accessed by (x,y,z) but instead by (x, y, range of z (say 0 - 3)). This give a C++ struct as follows:

struct node {
  struct node *next;
  int zGroup;
  int z;
  50 bytes of misc data };

I can then address this through a 3D dynamic array (vectors):

vector< vector < vector < node* > > > Data;

Any given Data[x][y][zGroup] points to the first element of a linked list, the entirety of which is needed every time one element of it is needed. No value of this array is NULL, every one contains a linked-list of at least one element.

The third dimension of the array - the zGroup has jagged dimensions, but with dynamic arrays this isn't an issue. Given the data and computations being performed on it, I know that the max x and y values are set when the file is read and do not change, neither does the number of z groups on any given (x,y) line, the actual z-values of nodes may change, but they will remain inside the same z-groups, giving a constant-sized, fully populated array.

With the way that the file is structured it is also easy enough to page it in and out of memory if I am brought to do this with much larger data sets.


答:
Briefly, you can find some kind of discussion in Pattern-Oriented Software Architecture vol.2 - you're asking about (and I'm roughly describing below) the Reactor pattern.

You can also read an implementation of this in Doug Schmidt's ACE library, but like most real-world libraries, it's covered in portability warts and is pretty old-style code now anyway.

So, you have a simple select/poll/whatever event loop, and want to implement I/O callbacks, periodic timers and async I/O.

1: Basic I/O

The generic (that is, reusable in a library sense) way to dispatch the events is to provide some abstract interface a client can implement. If you look at the select/poll/whatever interface, you'll see the events associated with a file descriptor tell you exactly what you need:

```<code>class IOHandler {
public:
  virtual ~IOHandler();

  // lib needs fd for syscall
  virtual int getFD() const = 0;

  // lib needs to know what flags to set
  virtual bool readFlag() const = 0;
  virtual bool writeFlag() const = 0;
  virtual bool errorFlag() const = 0;

  // lib needs to dispatch callbacks
  virtual void onReadable() = 0;
  virtual void onWriteable() = 0;
  virtual void onError() = 0;
};
</code>```

Now, if you have some vector of IOHandler* or whatever, you should be able to write the loop.

Note that error handling, allowing handlers to remove themselves during the loop etc. will take a little more effort.

2: Timers

You'll notice that your syscall of choice has some timeout parameter. We'll provide another interface for timers:

```<code>class Timer {
public:
  virtual ~Timer() {}

  // some kind of period
  virtual unsigned period() const = 0;

  // some kind of callback at the end of each period
  virtual void fire() = 0;
};
</code>```

Now, your library needs an interface to add & remove those timers. Once you have them, you can maintain some container of Timer*, ordered by next absolute firing time (a heap is traditional).

Then, every time you call select/poll/whatever, you just get the next expiry time from the front of the heap and use that for your timeout. If you get ETIMEDOUT, dispatch timers from the front of your heap until you reach one in the future.

We're talking only about periodic timers here, so each time you pull one off the front, you should add the current time to its period, and re-enqueue it.

Again, handling one-shot or variable-frequency, allowing timers to remove themselves etc. is left as an exercise. If your regular I/O callbacks might be slow (compared to the period of your timers), you may run a timer dispatch cycle after handling those callbacks too.

3: Async I/O

The usual POSIX mechanism for this is to make your sockets non-blocking (this generally doesn't work for files). Once you've done that, you also need to add a lot more state management to handle cases where

you couldn't complete writing a buffer, so you need to keep it around somewhere (and make sure you check for the fd to become writeable again)

any future writes will now have to be queued or appended to that buffer until the socket has caught up

you couldn't read as much as you want, so you need to keep a partial message around somewhere (until the fd becomes readable) and you can reassamble the message

This can probably be handled within the I/O framework sketched above, but there's no way I'm going to implement it here.

Title: Deeper understanding of event loops and timers

Body:
I have a basic grasp of accepting clients without creating a thread for each connection using tools such as select and modern equivalents (kqueue, epoll).

But where do I go from here? e.g async I/O and (periodic) timers. I could crack open the source to libev and friends but that's a little overwhelming to me to say the least.

I've looked around for textbooks on this subject but didn't come up with anything useful.

The basic objective is to write a small toy implementation of an evented library with timers and async I/O. Just for getting a better grasp on the subjects.

I'm not looking to reinvent the wheel. This is solely for learning/educational purposes. (not homework either)

Body:
Briefly, you can find some kind of discussion in Pattern-Oriented Software Architecture vol.2 - you're asking about (and I'm roughly describing below) the Reactor pattern.

You can also read an implementation of this in Doug Schmidt's ACE library, but like most real-world libraries, it's covered in portability warts and is pretty old-style code now anyway.

So, you have a simple select/poll/whatever event loop, and want to implement I/O callbacks, periodic timers and async I/O.

1: Basic I/O

The generic (that is, reusable in a library sense) way to dispatch the events is to provide some abstract interface a client can implement. If you look at the select/poll/whatever interface, you'll see the events associated with a file descriptor tell you exactly what you need:

class IOHandler {
public:
  virtual ~IOHandler();

  // lib needs fd for syscall
  virtual int getFD() const = 0;

  // lib needs to know what flags to set
  virtual bool readFlag() const = 0;
  virtual bool writeFlag() const = 0;
  virtual bool errorFlag() const = 0;

  // lib needs to dispatch callbacks
  virtual void onReadable() = 0;
  virtual void onWriteable() = 0;
  virtual void onError() = 0;
};

Now, if you have some vector of IOHandler* or whatever, you should be able to write the loop.

Note that error handling, allowing handlers to remove themselves during the loop etc. will take a little more effort.

2: Timers

You'll notice that your syscall of choice has some timeout parameter. We'll provide another interface for timers:

class Timer {
public:
  virtual ~Timer() {}

  // some kind of period
  virtual unsigned period() const = 0;

  // some kind of callback at the end of each period
  virtual void fire() = 0;
};

Now, your library needs an interface to add & remove those timers. Once you have them, you can maintain some container of Timer*, ordered by next absolute firing time (a heap is traditional).

Then, every time you call select/poll/whatever, you just get the next expiry time from the front of the heap and use that for your timeout. If you get ETIMEDOUT, dispatch timers from the front of your heap until you reach one in the future.

We're talking only about periodic timers here, so each time you pull one off the front, you should add the current time to its period, and re-enqueue it.

Again, handling one-shot or variable-frequency, allowing timers to remove themselves etc. is left as an exercise. If your regular I/O callbacks might be slow (compared to the period of your timers), you may run a timer dispatch cycle after handling those callbacks too.

3: Async I/O

The usual POSIX mechanism for this is to make your sockets non-blocking (this generally doesn't work for files). Once you've done that, you also need to add a lot more state management to handle cases where

you couldn't complete writing a buffer, so you need to keep it around somewhere (and make sure you check for the fd to become writeable again)

any future writes will now have to be queued or appended to that buffer until the socket has caught up

you couldn't read as much as you want, so you need to keep a partial message around somewhere (until the fd becomes readable) and you can reassamble the message

This can probably be handled within the I/O framework sketched above, but there's no way I'm going to implement it here.


问:
C++ Data Server and J2ME client communication
I am working on a robot that has some AI built in. However, the mandated robot controller does not have the power to do the work onboard. This means that I need to use a co-processor.

I am writing all of my AI in C++. This will also be a TCP server. I have an idea for the protocol. The C++ server receives commands and only sends back values when absolutely required. The String for a basic command would be:

```<code>REQUEST DATA PUT data storename ENDREQ
</code>```

The C++ server would parse the request and store data under the reference of storename.

To read data from the server:

The Java request would be:

```<code>REQUEST DATA GET storename ENDREQ
</code>```

The server will reply with:

```<code>data
</code>```

I will be using TCP for the transmission of data because it seems much more robust and easy to implement using the libraries that I am using.

I am not too knowledgeable when it comes to Java, especially with J2ME. How to implement the Java side?

CHANGE:
It is quite easy for me to implement a web server on the C++ side, so please feel free to use HTTP for the protocol!

答: You may use HttpClient in Java ME.  It's just located under a different namespace (javax.microedition.io.HttpClient).  You can find some sample code in the official MID Profile documentation here</p>


问:
How far can I drift from my original domain model and still have the benefits of an ORM?
I have the following domain models:

```<code>public class User
{
    public int Id { get; set; }
    public ICollection<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public decimal Price { get; set; }
}
</code>```

My User entity has a collection of Products, and no Product can be created without an User.
I am using EntityFramework Code First approach, which requires me to declare the Foreign Key on my Product entity, thus changing it to:

```<code>public class Product
{
    public int Id { get; set; }
    public decimal Price { get; set; }
    public int UserId { get; set; }
}
</code>```

I dont quite like this because, from the domain point of view, it is not interesting to have the User foreign key shown in my Product entity. This, however, does not bring any harm to me and I can live with it. Please, mind that I am using an ORM to simplify my work, so I am okay with it to an extent.

Is it okay to my domain entities having properties or such things only to satisfy my ORM of choice requirements?

答:
If you use the fluent mapping API doing:

```<code>HasMany(x => x.Products);
</code>```

Should be sufficient to create the foreign key relationship between User and Product without needed the UserId property to be specified on Product.

Also note that EF can map data to private properties(and use private ctors and setters) so if a detail like that was absolutely unavoidable you should be able avoid exposing that on your domain.

As a side-note (it may just be your example code); if you want to lazy load Products you will need to specify it as virtual or specify it as an include when performing your queries.

Body:
If you use the fluent mapping API doing:

HasMany(x => x.Products);

Should be sufficient to create the foreign key relationship between User and Product without needed the UserId property to be specified on Product.

Also note that EF can map data to private properties(and use private ctors and setters) so if a detail like that was absolutely unavoidable you should be able avoid exposing that on your domain.

As a side-note (it may just be your example code); if you want to lazy load Products you will need to specify it as virtual or specify it as an include when performing your queries.


问:
simple let binding vs constant function
I understand the reasons why I would prefer let a = f(x) over let a() = f(x), especially when f takes is a long running function.

I also think it is correct to say, that, considering lambda calculus origins of functional programming let a() is truly functional, while let a is not. Please correct me if I'm wrong on this.

However I have no clue which expression will actually be better:

```<code>let a = 4
</code>```

or

```<code>let a() = 4
</code>```

Is there any reason I would prefer one over the other?

答:
There's nothing "unfunctional" about let a = 4 as opposed to let a () = 4.  In fact, in many abstract formulation of type theories, the latter is really syntactic sugar for let a = fun () -> 4.

The main difference is when you want the expression to be evaluated, as you said.  If a will eventually be evaluated anyway, there's no point in wrapping it into a function.  OTOH if you think that there's a good chance that a might not be evaluated, and the evaluation is very expensive (or may even fail if some precondition is not satisfied), then it might be beneficial to keep as a function.  However, in the latter case you still have to be careful to not evaluate the function more than once.

However, I'm not sure if pervasive use of laziness is all that common in a strict language such as F#.

Edit to address your question in the comments:

In many formal mathematical specifications of a language, the let construct binds an expression to a single variable:

```<code>let VARIABLE = EXPRESSION in EXPR
</code>```

The reason is because this is simpler than having a let that binds arbitrary functions such as let f x = 2 * x.  Instead, the latter is treated as a syntactic sugar for the more verbose let f = fun x -> 2 * x.

However, neither is more "functional" (if that word even has a well-defined meaning).  Functional programming does not mean you should attempt to use functions everywhere possible.  Rather, it merely puts functions on equal standing with other values so that you can manipulate both functions and values with equal ease.

The let construct in Haskell looks superficially like the one in F#, but semantically it is very different because it's non-strict ("lazy") by default.  This means let x = 4 in 2 * x in Haskell is more appropriately translated into let x = lazy(4) in 2 * Lazy.force x.

The let construct should not be confused with assignments, which are an entirely different thing as it requires mutation.  By constrast, let does not mutate anything: it merely introduces a new variable.  F# blurs the boundary because it allows pure and impure functions to be mixed, so let bindings can have side-effects as a result and hence the way you bind them (as functions or values) will matter.

In a pure language, let bindings cannot cause any side-effects, but the order of evaluation still matters for two reasons:

Efficiency: because we don't have infinite resources and infinite patience.

Divergence: functions can still fail, or go into an infinite loop.

So even in pure languages, it still matters whether evaluation is done eagerly or lazily.

Title: simple let binding vs constant function

Body:
There's nothing "unfunctional" about let a = 4 as opposed to let a () = 4.  In fact, in many abstract formulation of type theories, the latter is really syntactic sugar for let a = fun () -> 4.

The main difference is when you want the expression to be evaluated, as you said.  If a will eventually be evaluated anyway, there's no point in wrapping it into a function.  OTOH if you think that there's a good chance that a might not be evaluated, and the evaluation is very expensive (or may even fail if some precondition is not satisfied), then it might be beneficial to keep as a function.  However, in the latter case you still have to be careful to not evaluate the function more than once.

However, I'm not sure if pervasive use of laziness is all that common in a strict language such as F#.

Edit to address your question in the comments:

In many formal mathematical specifications of a language, the let construct binds an expression to a single variable:

let VARIABLE = EXPRESSION in EXPR

The reason is because this is simpler than having a let that binds arbitrary functions such as let f x = 2 * x.  Instead, the latter is treated as a syntactic sugar for the more verbose let f = fun x -> 2 * x.

However, neither is more "functional" (if that word even has a well-defined meaning).  Functional programming does not mean you should attempt to use functions everywhere possible.  Rather, it merely puts functions on equal standing with other values so that you can manipulate both functions and values with equal ease.

The let construct in Haskell looks superficially like the one in F#, but semantically it is very different because it's non-strict ("lazy") by default.  This means let x = 4 in 2 * x in Haskell is more appropriately translated into let x = lazy(4) in 2 * Lazy.force x.

The let construct should not be confused with assignments, which are an entirely different thing as it requires mutation.  By constrast, let does not mutate anything: it merely introduces a new variable.  F# blurs the boundary because it allows pure and impure functions to be mixed, so let bindings can have side-effects as a result and hence the way you bind them (as functions or values) will matter.

In a pure language, let bindings cannot cause any side-effects, but the order of evaluation still matters for two reasons:

Efficiency: because we don't have infinite resources and infinite patience.

Divergence: functions can still fail, or go into an infinite loop.

So even in pure languages, it still matters whether evaluation is done eagerly or lazily.


问:
Separate methods or single method with if statement?
I'm working on a .NET application and I'm wondering if I should use separate methods to handle the click events of two different buttons. They essentially do the same thing, just on different objects on the form, in this case two separate maps.

Same method:

```<code>Private Sub SingleButtonHandler(sender As Object, e As EventArgs) Handles btnToggleSatNew.Click, btnToggleSatOld.Click
    If sender Is btnToggleSatNew Then
        Me.NewMap.ToggleSateliteView()
    Else
        Me.OldMap.ToggleSateliteView()
    End If
End Sub
</code>```

Separate Methods:

```<code>Private Sub btnToggleSatOld_Click(sender As Object, e As EventArgs) Handles btnToggleSatOld.Click
    Me.OldMap.ToggleSateliteView()
End Sub

Private Sub btnToggleSatNew_Click(sender As Object, e As EventArgs) Handles btnToggleSatNew.Click
    Me.NewMap.ToggleSateliteView()
End Sub
</code>```

What's the overhead of checking if the two objects are the same? Is one version easier to read than the other? Or should I be doing something completely different?

答:
Use separate methods.  It makes the method easier to read, and makes it clearer what the method does.  The SingleButtonHandler does two things based on a parameter: it toggles the new map if the sender is btnToggleStatNew, or toggles the old map.  While it isn't a horribly messy method right now, it can grow into a large, unwieldy tangle of spaghetti code very quickly.

In addition, it opens up the question of "where should I stick this button's event?"  With 1 click handler for two buttons, it sets a bad precedence.  There will be the temptation to stick other button's click event into the one, because "this button's click is easy.  It doesn't need another whole method" or "this button is kind of related to the others."  Don't open up that temptation.  Each button gets its own even handler.

On the performance overhead:  Don't worry about it.  Unless there's code that's causing major headaches, do not attempt to optimize.  Premature optimization is the root of all evil.  If the profiler says the code isn't the major time sink, then don't try to optimize it.  Make it work.  Make it readable.


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答:
I hv been coding for over 20 years, and currently have 10 programmers working with me. I have to say that those impresses me are those that did their job well, deliver on time and with quality (less bug). communicate frequently, showing passion are all important factors.

thats about it i can share right now. ;)

ContentLicense: CC BY-SA 2.5


答:
Apart from lambda calculus related considerations, there are as well practical considerations. Whether you create a value (let a = 4) or a function value (let a() = 4) has an impact on when your code gets executed, which, at times is of importance. The following F# code shows the effect in a simple way:

```<code>let A = printfn "A invoked"
let B() = printfn "B invoked"

let Run() =
    printfn "Run() invoked"
    A
    B()

Run()
</code>```

The output is:

```<code>A invoked
Run() invoked
B invoked
</code>```

This might come as a surprise once in a while. For simple constant numerical values, less so, than for some functions producing side effects (printfn,...).

Title: simple let binding vs constant function

Body:
I understand the reasons why I would prefer let a = f(x) over let a() = f(x), especially when f takes is a long running function.

I also think it is correct to say, that, considering lambda calculus origins of functional programming let a() is truly functional, while let a is not. Please correct me if I'm wrong on this.

However I have no clue which expression will actually be better:

```<code>let a = 4
</code>```

or

```<code>let a() = 4
</code>```

Is there any reason I would prefer one over the other?

Body:
Apart from lambda calculus related considerations, there are as well practical considerations. Whether you create a value (let a = 4) or a function value (let a() = 4) has an impact on when your code gets executed, which, at times is of importance. The following F# code shows the effect in a simple way:

let A = printfn "A invoked"
let B() = printfn "B invoked"

let Run() =
    printfn "Run() invoked"
    A
    B()

Run()

The output is:

A invoked
Run() invoked
B invoked

This might come as a surprise once in a while. For simple constant numerical values, less so, than for some functions producing side effects (printfn,...).


答: Alternatively, you could add the map to be toggled as a property of the button, and then have one event handler which toggles the map given in the sender's property. This avoids an if/then statement, but gives you one method which does one thing.</p>

Title: Separate methods or single method with if statement?

Body:
I'm working on a .NET application and I'm wondering if I should use separate methods to handle the click events of two different buttons. They essentially do the same thing, just on different objects on the form, in this case two separate maps.

Same method:

```<code>Private Sub SingleButtonHandler(sender As Object, e As EventArgs) Handles btnToggleSatNew.Click, btnToggleSatOld.Click
    If sender Is btnToggleSatNew Then
        Me.NewMap.ToggleSateliteView()
    Else
        Me.OldMap.ToggleSateliteView()
    End If
End Sub
</code>```

Separate Methods:

```<code>Private Sub btnToggleSatOld_Click(sender As Object, e As EventArgs) Handles btnToggleSatOld.Click
    Me.OldMap.ToggleSateliteView()
End Sub

Private Sub btnToggleSatNew_Click(sender As Object, e As EventArgs) Handles btnToggleSatNew.Click
    Me.NewMap.ToggleSateliteView()
End Sub
</code>```

What's the overhead of checking if the two objects are the same? Is one version easier to read than the other? Or should I be doing something completely different?


问:
What constitutes "improper use" of the javascript Eval feature?
Eval is a notoriously controversial language feature.  Douglas Crockford flat out rejects it. I'm wondering what specific risks Eval brings about.  According to this question, Improper use of eval opens up your code for injection attacks.

What are some improper uses of the Eval command, and what security holes do they open up?

答:
I do agree that it should very rarely be used, but I've found a powerful use case for eval.

There is an experimental new feature in Firefox called asm.js I've been working with.  It allows for a limited subset of the Javascript language to be compiled into native code.  Yes, this is very awesome, but it does have limitations.  You can think of the limited subset of Javascript as being a C-like language embedded in Javascript.  It isn't really meant to be read or written by humans.

This limited subset of Javascript does not allow me to inject my runtime-generated code into the compiled code once it's been compiled.

I have written some code that allows a user to write, in familiar notation, a mathematical expression, and have it converted on the fly to asm.js code.  Unless I wanted to have the code processed on the server side (which I don't), eval is the only tool that allows me to have the resulting code processed by the browser in real-time.


问:
REST API design for associations/aggregation
I am building RESTful API that manages persons and lists.
There can be many List and many Person each with its own set of properties. Person can be in zero or more lists, List can contain zero or more Persons.

I have implemented these operations for Persons and Lists:

GET api/Persons/ to get all persons

POST api/Persons/ {..} to create new person

PUT api/Persons/123 {..} to update person by id

DELETE api/Persons/123 to delete person by id

To retrieve Lists person is in I would use GET /api/Persons/123/Lists, to retrieve all persons in List I would use GET /api/Lists/234/Persons.

How do I design API to add Person to Lists, remove them from Lists?

I thought about flattening Person to include Lists but then there will be other associations from Person and it seems unnecessary to transfer that mush information.

I am using asp.net Web API 2 but I am asking in general what are the design principles in this case.

答:
REST isn't carved in stone and this many-to-many relationship of nested resources is a very common problem with mostly two possible approaches. Which of the two is best for your specific case would depend on a few details and maybe how exactly asp.net handles things. But I will just describe both and explain why I mostly prefer the second approach.

Approach one would simply use the nested resources approach you already have. Doing

```<code>POST /api/Lists/234/Persons/123
</code>```

would add Person 123 to list 234. This is simple and easy and you could see this used often enough but has a few disadvantages. (obviously you could mirror this and us POST /api/Persons/123/Lists/234 instead)

The second alternative is to handle it as a resource of its own named ListPersons (as you maybe already named the table holding the relationship information for this).

To create such a resource:

```<code>POST /api/ListPersons?list=234&person=123
</code>```

similar to delete a person from a list or update the relationship. While at first this may seem a bit superficial it is most likely easier to implement and test. Also it keeps the controller actions simpler, since it lets them stay "single responsibility". The main advantage may be that if you later want to add additional data to the relationship adding this information was params will be easy and names can't clash with similar names in the other two tables.

As an example assume a List would be a team and later you decide to add the 'role' the Person (in this case a player) has in this team. You can easily add this like

```<code>POST /api/ListPersons?list=234&person=123&role=captain
</code>```

even if the Person resource has a role (say the preferred role for this Person) by itself.

At least in Rails this has the additional advantage that within the controllers the action names can still reflect the REST verbs, while in approach one since create etc are already taken for the List itself you would have to come up with new names.

For completeness approach three would be to simply update a List with a param that contains a list of Persons. I would totally dislike this for many reasons so I just mention that this too is seen in the wild.

Body:
REST isn't carved in stone and this many-to-many relationship of nested resources is a very common problem with mostly two possible approaches. Which of the two is best for your specific case would depend on a few details and maybe how exactly asp.net handles things. But I will just describe both and explain why I mostly prefer the second approach.

Approach one would simply use the nested resources approach you already have. Doing

POST /api/Lists/234/Persons/123

would add Person 123 to list 234. This is simple and easy and you could see this used often enough but has a few disadvantages. (obviously you could mirror this and us POST /api/Persons/123/Lists/234 instead)

The second alternative is to handle it as a resource of its own named ListPersons (as you maybe already named the table holding the relationship information for this).

To create such a resource:

POST /api/ListPersons?list=234&person=123

similar to delete a person from a list or update the relationship. While at first this may seem a bit superficial it is most likely easier to implement and test. Also it keeps the controller actions simpler, since it lets them stay "single responsibility". The main advantage may be that if you later want to add additional data to the relationship adding this information was params will be easy and names can't clash with similar names in the other two tables.

As an example assume a List would be a team and later you decide to add the 'role' the Person (in this case a player) has in this team. You can easily add this like

POST /api/ListPersons?list=234&person=123&role=captain

even if the Person resource has a role (say the preferred role for this Person) by itself.

At least in Rails this has the additional advantage that within the controllers the action names can still reflect the REST verbs, while in approach one since create etc are already taken for the List itself you would have to come up with new names.

For completeness approach three would be to simply update a List with a param that contains a list of Persons. I would totally dislike this for many reasons so I just mention that this too is seen in the wild.


问:
Does ASCII have a header or footer or anything similar?
I'm working through a problem in Programming Pearls -- specifically, the implementation of a program which sorts a file containing, at most, 10,000,000 integers, each of which is 7 digits long (Column 1, Problem 3).

The problem has some very strict constraints when it comes to memory, so I'm considering reading and writing the integers in ASCII -- 7 bytes at a time. I need to know if ASCII has any headers or footers or anything similar that I should be considering  (I'm putting everything on 1 line without any separators, so new lines aren't an issue).

答: No, text files only contain the bytes of the text nothing more nothing less.</p>


答:
ASCII is a fixed width encoding and only concerns itself with byte<->character mapping. There are no headers or footers in it.

On *nix you should be able to view your bytes using od (eg $ od -h filename to print hex byte representations).

Title: Does ASCII have a header or footer or anything similar?

Body:
I'm working through a problem in Programming Pearls -- specifically, the implementation of a program which sorts a file containing, at most, 10,000,000 integers, each of which is 7 digits long (Column 1, Problem 3).

The problem has some very strict constraints when it comes to memory, so I'm considering reading and writing the integers in ASCII -- 7 bytes at a time. I need to know if ASCII has any headers or footers or anything similar that I should be considering  (I'm putting everything on 1 line without any separators, so new lines aren't an issue).


问:
Implementing a generic/dynamic custom property system in C#
I have an architecture design problem which I think is appropriate for this site.

Note that I have made an EDIT to this post below, reflecting my latest potential solution to this problem.

General problem description:

My primary goal is to design a software library/program (C#) to automate a very particular type of microscopy experiments. Our experimental setups consists of many distinct hardware devices that generally fall into a limited number of categories:

Point detector

XY sample stage

Autofocus device

...

The natural choice is to design an interface IDevice with some basic properties shared by all devices such as e.g. IDevice.Initialize(), IDevice.Name, ...

We can even design an abstract class, inheriting IDevice, e.g. DeviceBase implementing some functionalty common to all devices.

Likewise, we can also design interfaces for specific devices, each time implementing the common stuff (IXYSampleStage might hold e.g. IXYSampleStage.Move(posX, posY) or IXYSampleStage.AxisXStepSize).

Ultimately, I can implement all these interfaces in the final classes representing specific devices. I think I know what to do there.

However, not all devices of a class are exactly the same. Some manufacturers offer rich functionality on top of the standard stuff. An XY Stage might have e.g. any number of optional/non-standard parameters to set such as e.g. channel delays, PID control values or whatever.

To tackle this,

I need a mechanism to add additional properties (not methods,
  properties will suffice) to specific device classes. Higher level
  code, interacting with the devices should understand these added
  properties, be able to get/set them, however many there might be.

So much for the basic design problem.

What exists already

There is an OS software program, Micro Manager, which has such a system implemented, be it in C++ (full source here and no, I cannot use this SW directly for my purposes):

```<code>class PropertyBase
{
public:
   virtual ~PropertyBase() {}

   // property type
   virtual PropertyType GetType() = 0;

   // setting and getting values
   virtual bool Set(double dVal) = 0;
   virtual bool Set(long lVal) = 0;
   virtual bool Set(const char* Val) = 0;

   virtual bool Get(double& dVal) const = 0;
   virtual bool Get(long& lVal) const = 0;
   virtual bool Get(std::string& strVal) const = 0;

   // Limits
   virtual bool HasLimits() const = 0;
   virtual double GetLowerLimit() const = 0;
   virtual double GetUpperLimit() const = 0;
   virtual bool SetLimits(double lowerLimit, double upperLimit) = 0;

   // Some more stuff left out for brevity
   ...
};
</code>```

Subsequently, the Property class implements some of the pure virtual functions related to the limits.

Next, StringProperty, IntegerProperty and FloatProperty implement the Get()/Set() methods. These kinds of properties are defined in an enum which allows only these three kinds of property.

Properties can next be added to a PropertyCollection which is basically a kind of dictionary that is part of a device class.

This all works nicely. We use MM a lot in the lab for other types of experiments but when trying to do similar things in my C# solution I stumbled about a few more fundamental questions. Most of these have to do with not being quite sure how to leverage specific features offered by C#/.NET (generic but definitely also dynamics, ...) to perhaps improve the existing C++ implementation.

The questions:

First question:

To limit the types of properties allowed, MM defines an enum:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```

Whereas C# has reflection and a lot of built-in support for types/generics. I therefore considered this:

```<code>public interface IProperty<T>
{
   public T value { get; set; }

   ...
}
</code>```

I could next do an abstract PropertyBase<T> and ultimately

```<code>IntegerProperty : PropertyBase<int>
StringProperty : PropertyBase<string>
FloatProperty : PropertyBase<double>
</code>```

But this gets me in trouble when trying to put them into a collection because in .NET following is not possible:

```<code>PropertyCollection : Dictionary<string, IProperty<T>>
</code>```

Unless, perhaps, I adopt this strategy, i.e. have a non generic base class that only returns a type and then yet more base classes to actually implement my property system. However, this seems convoluted to me. Is there a better way?

I think that utilising the generic language features might allow me to do away with needing all these Get()/Set() methods in the MM example above, as I would be able to know the backing type of my property value.

I realise this is a very broad question but, there is a big gap between understanding the basics of some language features and being able to fully make the correct design decisions from the outset.

Second question

I am contemplating making my final device classes all inherit from a kind of DynamicDictionary (e.g. similar to the one from here):

```<code>    public class DynamicDictionary : DynamicObject
    {
        internal readonly Dictionary<string, object> SourceItems;

        public DynamicDictionary(Dictionary<string, object> sourceItems)
        {
            SourceItems = sourceItems;
        }
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (SourceItems.ContainsKey(binder.Name))
            {
                SourceItems[binder.Name.ToLower()] = value;
            }
            else
            {
                SourceItems.Add(binder.Name.ToLower(), value);
            }
            return true;
        }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (SourceItems != null)
            {
                if (SourceItems.TryGetValue(binder.Name.ToLower(), out result))
                {
                    return true;
                }
            }
            result = null;
            return true;
        }
    }
}
</code>```

but instead of <string, object> I would then like to use <string, MyPropertyBase> where the string would be the alias for my property (which would correspond to the design choice from Q1).

Would doing such a thing make sense from a design standpoint?

I would actually only need to add custom properties to devices at design time (i.e. when writing a custom device driver). At runtime, I would only need to inspect my custom properties or get/set their values.

the C++ MM solves this by using a bunch of CreateProperty("alias", Property) methods in the device constructor, which again, works so maybe using dynamics here is overkill. But again, I am wondering if somebody could provide insight in possible advantages but certainly also disadvantages of going down the dynamic route.

To summarize

Are there .NET features (4.5) which I could leverage to implement some of the MM concepts in a more elegant way with a focus on the above mentioned specific matters?

Again, I do realise this is a very broad question and perhaps some of the possible answers are more a matter of taste/style than anything els but if so (this making the question unsuited for this platform), please provide feedback/comments such that I can adjust accordingly.

EDIT

I have spent some more thinking about this and tried to solve it in the following way:

First, an enum specifying the allowed propertytypes:

```<code>public enum PropertyType
{
    Undefined,
    String,
    Float,
    Integer
}
</code>```

Second, an interface IPropertyType that is responsible for checking values fed to a property of a specific type:

```<code>public interface IPropertyType
{
    Type BackingType { get; }

    PropertyType TypeAlias { get; }

    bool IsValueTypeValid(object value);
}
</code>```

Then, a base class implementing IPropertyType:

```<code>public bool IsValueTypeValid(object value)
    {
        if (value == null)
        {
            return true;
        }

        Type type = value.GetType();

        if (type == this.BackingType)
        {
            return true;
        }

        return false;
    }

...

public Type BackingType
    {
        get
        {
            switch (this.TypeAlias)
            {
                case PropertyType.Integer:
                    return typeof(long);
                case PropertyType.Float:
                    return typeof(double);
                case PropertyType.String:
                    return typeof(string);
                default:
                    return null;
            }
        }
    }
</code>```

I then have three IPropertyType: StringPropertyType, IntegerPropertyType and FloatPropertyType where each time, the property PropertyTypeAlias is set to one of the enum values.

I can now add my IPropertyType to IProperty types:

```<code>public interface IProperty
{
    string Alias { get; }

    /// If we want to limit the property to discrete values.
    Dictionary<string, object> AllowedValues { get; }

    bool HasLimits { get; }

    bool HasValue { get; }

    bool IsReadOnly { get; }

    /// Callback for HW operations using the property value.
    Func<PropertyFuncType, bool> PropertyFunction { set; }

    PropertyType TypeAlias { get; }

    object Value { get; set; }

    void AddAllowedValue(string alias, object value);

    void ClearAllowedValues();

    // On numeric properties, it might be usefull to limit the range of values.
    void SetLimits(object lowerLimit, object upperLimit);

    // These will do stuff on the HW...
    bool TryApply();

    bool TryUpdate();
}
</code>```

Here, the Value setter will run the validation on input value as defined by the IPropertyType.

IProperty is almost fully implemented in PropertyBase which also has a field of IPropertyType which gets set upon instance creation (and cannot be changed thereafter; a property cannot change type.

From the base class e.g.:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```0

That only leaves specific IProperty classes: StringProperty, IntegerProperty and FloatProperty where there is only one override, SetLimits() because it relies on comparison of values. Everything else can be in the base class:

```<code>    enum PropertyType {
      Undef,
      String,
      Float,
      Integer
    };
</code>```1

This way, I think I have a system that allows me to have a collection of IProperty that can actually hold data of different types (int, float or string) where for each type of IProperty I have the ability to implement value limits etc (i.e. stuff that is different, depending on the data type)...

However, I still have the impression that there are either better ways to do this sort of thing or that I am over engineering things.

Therefore, any feedback on this is still welcome.

EDIT 2

After more searching online I believe the last bits of code posted here in the previous edit are leaning towards the Adaptive Object Model "pattern" (if it really is that).

However, most resources on this topic seem to be quite old and I'm wondering if there are now better ways to achieve these types of things.

答:
You're making a type system on top of the existing type system. There is very little benefit to strongly-typed properties that cannot be referenced in compiled code. I have seen this approach used before and it ends up being a mess.

Just use a key-value store in a single property called ExtendedProperties or some such.

In other words, you are trying to avoid Dictionary<string, object>, but in that effort you are re-inventing the .Net type system.

Attach a property called ExtendedProperties of type Dictionary<string, object> and be done with it. The limitations of loosely-typed data are less costly than the road you're going down.


答:
Two words: Be reliable.

In your position, you weren't hired to be the smartest person on the team. You were hired for the potential you showed and because there are tasks suited for your skill level that need getting done.

Show that you can live up to that trust first, and as you get a feel for the code and the company, find ways to exceed their first impression of you. The latter may take a while, but don't mistake being junior for being inferior.

Title: How can a new programmer impress the software engineer (boss)?

Body:
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.


答:
Don't be concerned about which is more "functional."  You're a programmer, not a mathematician.  Use let a() when you want to evaluate it at the point of use, when you don't care about evaluating it multiple times.  Use let a when you want to evaluate it at the definition point, and only want it to be evaluated once.

Your third choice is let a = lazy(f(x)), which waits until it is needed to evaluate, but only evaluates it once.  This is my preferred choice for expensive functions that may not be needed.  This is kind of ugly in F# though, because it requires an explicit a.Force, unlike most functional languages which force evaluation automatically at the appropriate time.

Remember, let a looks sort of like a mutating assignment, but it isn't.  Pure functional programs can be substituted and expanded out to one big nested expression.  Conceptually, if you expand your program out, you still end up with essentially the same expression with let a, it just eliminates some duplication when you evaluate it.

Title: simple let binding vs constant function